@interopio/gateway-server 0.21.0 → 0.23.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/{gateway-server → bin/gateway-server.cjs} +203 -49
- package/changelog.md +20 -0
- package/dist/config.cjs +2 -0
- package/dist/config.cjs.map +7 -0
- package/dist/config.js +2 -0
- package/dist/config.js.map +7 -0
- package/dist/index.cjs +17 -3
- package/dist/index.cjs.map +4 -4
- package/dist/index.js +17 -3
- package/dist/index.js.map +4 -4
- package/dist/metrics/publisher/rest.js +1 -1
- package/dist/metrics/publisher/rest.js.map +3 -3
- package/dist/tools.cjs +2 -0
- package/dist/tools.cjs.map +7 -0
- package/dist/tools.js +2 -0
- package/dist/tools.js.map +7 -0
- package/dist/web/test.js +13 -2
- package/dist/web/test.js.map +4 -4
- package/gateway-server.d.ts +3 -126
- package/package.json +14 -5
- package/readme.md +53 -0
- package/types/config.d.ts +147 -0
- package/types/manage.d.ts +46 -0
- package/types/path.d.ts +20 -0
- package/types/tools.d.ts +1 -2
- package/types/web/server.d.ts +11 -3
- package/types/web/test.d.ts +3 -3
- package/dist/metrics/publisher/rest.cjs +0 -2
- package/dist/metrics/publisher/rest.cjs.map +0 -7
- package/dist/tools/index.js +0 -2
- package/dist/tools/index.js.map +0 -7
package/dist/index.js
CHANGED
|
@@ -1,8 +1,22 @@
|
|
|
1
|
-
var
|
|
2
|
-
You are probably missing an await or return statement in your middleware function.`);return l};return o(0,r)}}import{isIP as Jr}from"node:net";import{Cookie as st}from"tough-cookie";function Kr(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 Yr(t){let e=t.one("x-forwarded-ssl");return typeof e=="string"&&e.toLowerCase()==="on"}function Qr(t,e){let r=t.get("x-forwarded-proto");return Array.isArray(r)&&(r=r[0]),r!==void 0?r.split(",",1)[0].trim():Yr(t)?"https":e}function Zr(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:Jr(o)===6?"IPv6":"IPv4"}}var xe=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},Ee=class t extends xe{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 tn(this.headers)}parseHost(e){return Kr(this.headers,e)}parseProtocol(e){return Qr(this.headers,e)}parseRemoteAddress(e){return Zr(this.URL,this.headers,e)}},Ae=class extends xe{get cookies(){return rn(this.headers)}setCookieValue(e){return new st({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 en(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 Bt(t){typeof t=="string"&&(t=[t]),typeof t=="number"&&(t=[String(t)]);let e=[];if(t)for(let r of t)r&&e.push(...en(r));return e}function tn(t){return t.list("cookie").map(e=>e.split(";").map(r=>st.parse(r))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function rn(t){return t.list("set-cookie").map(e=>{let r=st.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 Bt(r)}},x=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 Bt(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 at=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},w=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 _t(t){if(typeof t=="number"){if(t<100||t>999)throw new Error(`status code ${t} should be in range 100-999`);let e=w.resolve(t);return e!==void 0?e:new at(t)}return t}import lt from"node:http";var Ce=class extends lt.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},Y=class extends lt.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},Pe=class extends Ee{#e;get sslInfo(){return this.#e===void 0&&(this.#e=this.initSslInfo()),this.#e}},He=class extends Ae{#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:_t(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 Pe{#e;#r;#t;constructor(e){super(new dt(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 ct(this.#t.socket)}get cookies(){return this.#r??=super.cookies,this.#r}get body(){return lt.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}`}},ct=class{peerCertificate;constructor(e){this.peerCertificate=e.getPeerX509Certificate()}},dt=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()}},ut=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)}},ke=class extends He{#e;constructor(e){super(new ut(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}`))}})}}},Re=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 Pe)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 He)return e.getNativeResponse();if(e instanceof t)return t.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},Te=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}]`}},Oe=class{request;response;#e={};#r;#t="";constructor(e,r){this.#e[qt]=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(qt);return this.#r!==e&&(this.#r=e,this.#t=e!==void 0?`[${e}] `:""),this.#t}},qt="io.interop.gateway.server.log_id";import{getHeapStatistics as nn,writeHeapSnapshot as on}from"node:v8";import{access as sn,mkdir as an,rename as zt,unlink as cn}from"node:fs/promises";var b=y("monitoring"),dn={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function un(){return nn()}async function jt(t){let e=t.dumpPrefix??"Heap",r=`${t.dumpLocation}/${e}.heapsnapshot`;b.enabledFor("debug")&&b.debug(`starting heap dump in ${r}`),await pt(t.dumpLocation).catch(async o=>{b.enabledFor("debug")&&b.debug(`dump location ${t.dumpLocation} does not exists. Will try to create it`);try{await an(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=on(r);b.info("heap dumped");try{b.debug("rolling snapshot backups");let o=`${t.dumpLocation}/${e}.${t.maxBackups}.heapsnapshot`;await pt(o).then(async()=>{b.enabledFor("debug")&&b.debug(`deleting ${o}`);try{await cn(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 pt(a).then(async()=>{try{await zt(a,c)}catch(d){b.warn(`failed to rename ${a} to ${c}`,d)}}).catch(()=>{})}let i=`${t.dumpLocation}/${e}.1.heapsnapshot`;try{await zt(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 pt(t){b.enabledFor("trace")&&b.debug(`checking file ${t}`),await sn(t)}async function ln(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 jt(r)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function Vt(t){let e={...dn,...t},r=!1,n={memoryLimitExceeded:!1},o=async()=>{let a=un();await ln(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 jt(e);break}case"stop":{r=!0,clearInterval(i),b.info("exit memory diagnostic");break}}return r}}}async function pn({channel:t},e){await t(e)||b.warn(`cannot execute command "${e}" already closed`)}async function Xt(t){return await pn(t,"stop")}var fn=(t,e)=>(e??=t,async({response:r},n)=>{e!==!1&&!r.headers.has("server")&&r.headers.set("Server",e),await n()}),Jt=(t,e)=>fn(t,e);import{IOGateway as Me}from"@interopio/gateway";var ht=y("gateway.ws.client-verify");function gn(t){switch(t.missing){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function mn(t,e){let r=t.block??t.blacklist,n=t.allow??t.whitelist;if(r.length>0&&Me.Filtering.valuesMatch(r,e))return ht.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&Me.Filtering.valuesMatch(n,e))return ht.enabledFor("debug")&&ht.debug(`origin ${e} matches allow filter`),!0}function yn(t){switch(t.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Kt(t,e){if(!e)return!0;if(t){let r=mn(e,t);return r||yn(e)}else return gn(e)}function Yt(t){if(t){let e=(t.block??t.blacklist??[]).map(Me.Filtering.regexify),r=(t.allow??t.whitelist??[]).map(Me.Filtering.regexify);return{non_matched:t.non_matched??"allow",missing:t.missing??"allow",allow:r,block:e}}}var Qt=t=>async e=>{for(let r of t)if((await r(e)).match)return T();return C},ee=t=>{let e=async r=>{for(let n of t)if(!(await n(r)).match)return C;return T()};return e.toString=()=>`and(${t.map(r=>r.toString()).join(", ")})`,e},Zt=t=>async e=>(await t(e)).match?C:T(),pe=async t=>T();pe.toString=()=>"any-exchange";var er=Object.freeze({}),C=Object.freeze({match:!1,variables:er}),T=(t=er)=>({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 C;if(typeof t=="string")return s===t?T():C;{let a=t.exec(s);return a===null?C:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${t.toString()}, method=${r??"<any>"})`,n},he=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 C}for(let i of o)if(!e(i)){for(let s of t.mediaTypes)if(i.startsWith(s))return T()}return C}},V=async({request:t})=>t.upgrade&&t.headers.one("upgrade")?.toLowerCase()==="websocket"?T():C;V.toString=()=>"websocket upgrade";import{IOGateway as tr}from"@interopio/gateway";async function ft(t,e,r){let n=(i,s)=>{if(s?.cors){let a=s.cors===!0?{allowOrigins:s.origins?.allow?.map(tr.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(tr.Filtering.regexify(s.path),{method:s.method});a?.authorize&&r.authorize.push([d,a.authorize]),n(s,a);let u=async(l,g)=>{let{match:v,variables:p}=await d(l);v?await c(l,p):await g()};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||s==="/",ping:c?.ping,factory:a,maxConnections:c?.maxConnections,authorize:c?.authorize,originFilters:Yt(c?.origins)})}}};await t(o,e)}import{IOGateway as mt}from"@interopio/gateway";function bn(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 Sn(t){return t.headers.has("origin")&&!bn(t)}function nr(t){return t.method==="OPTIONS"&&t.headers.has("origin")&&t.headers.has("access-control-request-method")}var rr=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],vn=(t,e)=>{let{request:r,response:n}=t,o=n.headers;if(!o.has("Vary"))o.set("Vary",rr.join(", "));else{let s=o.list("Vary");for(let a of rr)s.find(c=>c===a)||s.push(a);o.set("Vary",s.join(", "))}try{if(!Sn(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=nr(r);return e?En(t,e,i):i?(fe(n),!1):!0},Le=["*"],gt=["GET","HEAD","POST"],or={allowOrigins:Le,allowMethods:gt,allowHeaders:Le,maxAge:1800};function De(t){if(t){let e=t.allowHeaders;e&&e!==S&&(t={...t,allowHeaders:e.map(n=>n.toLowerCase())});let r=t.allowOrigins;return r&&(r==="*"?(sr(t),ar(t)):t={...t,allowOrigins:r.map(n=>typeof n=="string"&&n!==S&&(n=mt.Filtering.regexify(n),typeof n=="string")?cr(n).toLowerCase():n)}),t}}function Ie(t,e){if(e===void 0)return t!==void 0?t===S?[S]:t:[];if(t===void 0)return e===S?[S]:e;if(t==Le||t===gt)return e===S?[S]:e;if(e==Le||e===gt)return t===S?[S]:t;if(t===S||t.includes(S)||e===S||e.includes(S))return[S];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:Ie(t.allowOrigins,e?.allowOrigins),allowMethods:Ie(t.allowMethods,e?.allowMethods),allowHeaders:Ie(t.allowHeaders,e?.allowHeaders),exposeHeaders:Ie(t.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??t.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??t.allowPrivateNetwork,maxAge:e?.maxAge??t.maxAge},xn=t=>{let e=t.corsConfigSource,r=t.corsProcessor??vn;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)||nr(n.request)||await o()}},ir=xn,M=y("cors");function fe(t){t.setStatusCode(w.FORBIDDEN)}function En(t,e,r){let{request:n,response:o}=t,i=o.headers,s=n.headers.one("origin"),a=Cn(e,s);if(a===void 0)return M.enabledFor("debug")&&M.debug(`reject: '${s}' origin is not allowed`),fe(o),!1;let c=kn(n,r),d=Pn(e,c);if(d===void 0)return M.enabledFor("debug")&&M.debug(`reject: HTTP '${c}' is not allowed`),fe(o),!1;let u=Rn(n,r),l=Hn(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 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"),r&&e.maxAge!==void 0&&i.set("Access-Control-Max-Age",e.maxAge.toString()),!0}var S="*",An=["GET","HEAD"];function sr(t){if(t.allowCredentials===!0&&t.allowOrigins===S)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function ar(t){if(t.allowPrivateNetwork===!0&&t.allowOrigins===S)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function Cn(t,e){if(e){let r=t.allowOrigins;if(r){if(r===S)return sr(t),ar(t),S;let n=cr(e.toLowerCase());for(let o of r)if(o===S||mt.Filtering.valueMatches(o,n))return e}}}function Pn(t,e){if(e){let r=t.allowMethods??An;if(r===S)return[e];if(mt.Filtering.valuesMatch(r,e))return r}}function Hn(t,e){if(e===void 0)return;if(e.length==0)return[];let r=t.allowHeaders;if(r===void 0)return;let n=r===S||r.includes(S),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 cr(t){return t.endsWith("/")?t.slice(0,-1):t}function kn(t,e){return e?t.headers.one("access-control-request-method"):t.method}function Rn(t,e){let r=t.headers;return e?r.list("access-control-request-headers"):Array.from(r.keys())}var dr=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};import{IOGateway as Tn}from"@interopio/gateway";function ur(t){let{sockets:e,cors:r}=t,n=t.corsConfig===!1?void 0:ge(or,t.corsConfig),o=[];for(let[s,a]of e){let c=n;for(let[u,l]of r)Tn.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)]),De(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),De(a)]);return o.push([O(/\/api\/.*/),De(n)]),dr({mappings:o})}function lr(t){return t!==void 0&&typeof t.type=="string"&&typeof t.authenticated=="boolean"}var A=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}},$e=class extends A{},te=class extends A{},re=class extends A{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)}},be=class extends re{constructor(e){super(e)}};var X=class extends Error{},N=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 A{};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)},On=()=>I(new x().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),Mn=()=>I(new x().add("x-content-type-options","nosniff")),In=(t,e,r)=>{let n=`max-age=${t}`;e&&(n+=" ; includeSubDomains"),r&&(n+=" ; preload");let o=I(new x().add("strict-transport-security",n)),i=s=>s.request.URL.protocol==="https:";return async s=>{i(s)&&await o(s)}},Ln=t=>I(new x().add("x-frame-options",t)),Dn=t=>I(new x().add("x-xss-protection",t)),$n=t=>{let e=t===void 0?void 0:I(new x().add("permissions-policy",t));return async r=>{e!==void 0&&await e(r)}},Wn=(t,e)=>{let r=e?"content-security-policy-report-only":"content-security-policy",n=t===void 0?void 0:I(new x().add(r,t));return async o=>{n!==void 0&&await n(o)}},Un=(t="no-referrer")=>I(new x().add("referer-policy",t)),Fn=t=>{let e=t===void 0?void 0:I(new x().add("cross-origin-opener-policy",t));return async r=>{e!==void 0&&await e(r)}},Nn=t=>{let e=t===void 0?void 0:I(new x().add("cross-origin-embedder-policy",t));return async r=>{e!==void 0&&await e(r)}},Gn=t=>{let e=t===void 0?void 0:I(new x().add("cross-origin-resource-policy",t));return async r=>{e!==void 0&&await e(r)}},Bn=(...t)=>async e=>{for(let r of t)await r(e)};function yt(t){let e=[];t?.cache?.disabled||e.push(On()),t?.contentType?.disabled||e.push(Mn()),t?.hsts?.disabled||e.push(In(t?.hsts?.maxAge??365*24*60*60,t?.hsts?.includeSubDomains??!0,t?.hsts?.preload??!1)),t?.frameOptions?.disabled||e.push(Ln(t?.frameOptions?.mode??"DENY")),t?.xss?.disabled||e.push(Dn(t?.xss?.headerValue??"0")),t?.permissionsPolicy?.disabled||e.push($n(t?.permissionsPolicy?.policyDirectives)),t?.contentSecurityPolicy?.disabled||e.push(Wn(t?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",t?.contentSecurityPolicy?.reportOnly)),t?.refererPolicy?.disabled||e.push(Un(t?.refererPolicy?.policy??"no-referrer")),t?.crossOriginOpenerPolicy?.disabled||e.push(Fn(t?.crossOriginOpenerPolicy?.policy)),t?.crossOriginEmbedderPolicy?.disabled||e.push(Nn(t?.crossOriginEmbedderPolicy?.policy)),t?.crossOriginResourcePolicy?.disabled||e.push(Gn(t?.crossOriginResourcePolicy?.policy)),t?.writers&&e.push(...t.writers);let r=Bn(...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 _n="Realm",qn=t=>`Basic realm="${t}"`,ie=t=>{let e=qn(t?.realm??_n);return async(r,n)=>{let{response:o}=r;o.setStatusCode(w.UNAUTHORIZED),o.headers.set("WWW-Authenticate",e)}};var pr="Basic ",We=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<=pr.length?"":o.substring(pr.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}}}};import{AsyncLocalStorage as zn}from"node:async_hooks";var 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 zn)=>(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 jn(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 Vn(a,{exchange:t,next:e},o,i)}catch(c){throw c instanceof A,c}}async function Vn(t,e,r,n){q.withAuthentication(t)(n),await r(e,t)}function z(t){let e={matcher:pe,successHandler:async({next:n})=>{await n()},converter:We({}),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 jn(n,o,s,r,e.successHandler,e.storage)}catch(a){if(a instanceof A){await e.failureHandler({exchange:n,next:o},a);return}throw a}}}var hr=t=>async(e,r)=>{e.response.setStatusCode(t.httpStatus)};var se=y("auth.entry-point"),Ue=t=>{let e=t.defaultEntryPoint??(async({response:r},n)=>{r.setStatusCode(w.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 fr=t=>async({exchange:e,next:r},n)=>{for(let o of t)await o({exchange:e,next:r},n)};function wt(t){let e=async g=>g.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?T():C,r=Ue({entryPoints:[[e,hr({httpStatus:w.UNAUTHORIZED})]],defaultEntryPoint:ie({})}),n=t.entryPoint??r,o=t.manager,i=he({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),s=Zt(he({mediaTypes:["text/html"]})),a=ee([s,i]),c=Qt([e,a]);t.defaultEntryPoints.push([c,n]);let d=t.failureHandler??oe({entryPoint:n}),u=fr(t.successHandlers??t.defaultSuccessHandlers),l=We({});return z({storage:t.storage,manager:o,failureHandler:d,successHandler:u,converter:l})}var gr={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},mr="https://tools.ietf.org/html/rfc6750#section-3.1";function Fe(t){return{errorCode:gr.invalid_token,httpStatus:w.UNAUTHORIZED,description:t,uri:mr}}function bt(t){return{errorCode:gr.invalid_request,httpStatus:w.BAD_REQUEST,description:t,uri:mr}}var Xn="access_token",Jn=/^Bearer\s+(?<token>[a-zA-Z0-9-._~+/]+=*)$/i,D=class extends A{error;constructor(e,r,n){super(r??(typeof e=="string"?void 0:e.description),n),this.error=typeof e=="string"?{errorCode:e}:e}},yr=t=>t.type==="BearerToken",Kn=t=>async e=>{let{request:r}=e;return Promise.all([Qn(r.headers,t?.headerName).then(n=>n!==void 0?[n]:void 0),Zn(r,t?.uriQueryParameter),eo(e,t?.formEncodedBodyParameter)]).then(n=>n.filter(o=>o!==void 0).flat(1)).then(Yn).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function Yn(t){if(t.length===0)return;if(t.length>1){let r=bt("Found multiple access tokens in the request");throw new D(r)}let e=t[0];if(!e||e.length===0){let r=bt("The requested access token parameter is an empty string");throw new D(r)}return e}async function Qn(t,e="authorization"){let r=t.one(e);if(!r||!/bearer/i.test(r.substring(0)))return;let n=Jn.exec(r);if(n===null){let o=Fe("Bearer token is malformed");throw new D(o)}return n.groups?.token}async function wr(t){let e=t.getAll(Xn);if(e.length!==0)return e}async function Zn(t,e=!1){if(!(!e||t.method!=="GET"))return wr(t.URL.searchParams)}async function eo(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 wr(n)}var Ne=Kn;function to(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 br=t=>t.httpStatus!==void 0;function ro(t){if(t instanceof D){let{error:e}=t;if(br(e))return e.httpStatus}return w.UNAUTHORIZED}function no(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),br(n)&&n.scope&&r.set("scope",n.scope)}return r}var oo=t=>async(e,r)=>{let n=ro(r),o=no(r,t?.realmName),i=to(o),{response:s}=e;s.headers.set("WWW-Authenticate",i),s.setStatusCode(n),await s.end()},Ge=oo;var io=t=>{let e=t?.principalClaimName??"sub";return r=>({type:"JwtToken",authenticated:!0,name:r.getClaimAsString(e)})},so=t=>async e=>t(e),ae=class extends Error{},Se=class extends ae{};function ao(t){if(t instanceof Se)return new D(Fe(t.message),t.message,{cause:t});throw new ne(t.message,{cause:t})}function St(t){let e=t.decoder,r=t.authConverter??so(io({}));return async n=>{if(yr(n)){let o=n.token;try{let i=await e(o);return await r(i)}catch(i){throw i instanceof ae?ao(i):i}}}}function vt(t){let e=t.entryPoint??Ge({}),r=t?.converter??Ne({}),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??St(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")}import{jwtVerifier as fo,JwtVerifyError as go}from"@interopio/gateway/jose/jwt";async function Sr(t,e,r){let n=new $e("Full authentication is required to access this resource."),o=new A("Access Denied",{cause:n});e&&(o.authentication=e),await r(t,o)}function co(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 vr=t=>{let e=co(w.FORBIDDEN),r=t.authenticationEntryPoint??ie();return async(n,o)=>{try{await o()}catch(i){if(i instanceof X){let s=await n.principal();lr(s)?(s.authenticated||await e(n,i),await Sr(n,s,r)):await Sr(n,void 0,r);return}throw i}}};var uo=y("security.auth");function xt(t){let e=async(r,n)=>{let o;for(let[i,s]of t.mappings)if((await i(n))?.match){uo.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 N(!1),o};return new _(e)}var Be=y("security.auth");function Et(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),Be.enabledFor("debug")&&Be.debug("authorization successful")}catch(s){throw s instanceof X&&Be.enabledFor("debug")&&Be.debug(`authorization failed: ${s.message}`),s}await o()}}var At=class extends Te{#e;constructor(e,r){super(e),this.#e=r}async principal(){return(await this.#e())?.authentication}},xr=t=>{let e=t.storage;return async(r,n)=>{await n(new At(r,async()=>await q.getContext(e)))}};var Er=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 _e=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)}},qe=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}};import{argon2 as H,keygen as lo}from"@interopio/gateway-server/tools";function po(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 ze=class extends J{#e;#r;#t;#n;#i;constructor(e=H.DEFAULT_SALT_LENGTH,r=H.DEFAULT_HASH_LENGTH,n=H.DEFAULT_PARALLELISM,o=H.DEFAULT_MEMORY,i=H.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=H.decode(r),o=await H.createHash(n.algorithm,e,n.hash.length,n.parameters);return po(n.hash,o)}catch{return!1}}async encodeDefinedPassword(e){let r=lo.createSalt(this.#e),n={memory:this.#n,passes:this.#i,parallelism:this.#t,nonce:r},o=await H.createHash("argon2id",e,this.#r,n);return H.encode({algorithm:"argon2id",version:H.ARGON2_VERSION,parameters:n,hash:o})}upgradeEncodingDefined(e){let r=H.decode(e);return r.version<H.ARGON2_VERSION||r.parameters.memory<this.#n||r.parameters.passes<this.#i}};var Ct=4096;function Ar(){let t="argon2id",e=new Map([[t,new ze],["noop",qe.instance]]);return new ce(t,e,ce.DEFAULT_ID_PREFIX,ce.DEFAULT_ID_SUFFIX)}var Cr={async updatePassword(t,e){return t}},je=class extends A{username;constructor(e,r,n){super(e,n),this.username=r}},Ve=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=y("security.users");function Pr(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 be("User credentials have expired")}),o=e?.passwordEncoder??Ar(),i=e?.userDetailsPasswordService??Cr,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 g=l.password;return{type:"UsernamePassword",principal:l,credentials:g,authorities:l.authorities,authenticated:!0,name:l.username,eraseCredentials(){g=null}}}}function ho(){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 be("User credentials have expired")}}function Hr(t){let e=t.userDetailsService,r=t.userDetailsChecker??ho(),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 je("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 Pt(t){let e=t.manager??Hr({userDetailsService:t.getService("UserDetailsService")}),r=t.extractor??_e(),n=t.converter??Er({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"),kr=(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 Pr(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]:Ue({entryPoints:this.#r,defaultEntryPoint:this.#r[this.#r.length-1][1]})}build(){if(t.headers!==void 0&&t.headers.disabled!==!0){let d=yt(t.headers);d[W]=$.http_headers,o.push(d)}if(t.x509!==void 0&&t.x509.disabled!==!0){let d=Pt({storage:e.storage,getService:r,extractor:_e({principalAltName:t.x509.principalAltName})});d[W]=$.authentication,o.push(d)}if(t.cors?.disabled!==!0&&e.corsConfigSource!==void 0){let d=ir({corsConfigSource:e.corsConfigSource});d[W]=$.cors,o.push(d)}if(t.basic!==void 0&&t.basic?.disabled!==!0){let d=[async({exchange:l,next:g},v)=>g()],u=wt({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=fo({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(m){return h[m]}}}catch(h){throw h instanceof go?new Se(h.message,{cause:h}):new ae("error occurred while attempting to decoding jwt",{cause:h})}},l=Ne({uriQueryParameter:!0}),g=async f=>{try{return await l(f)===void 0?C:T()}catch{return C}},v=Ge({});this.#r.push([g,v]);let p=vt({storage:e.storage,entryPoint:v,converter:l,jwt:{decoder:u}});p[W]=$.authentication,o.push(p)}let c=xr({storage:e.storage});if(o.push(c),c[W]=$.security_context_server_web_exchange,t.authorize!==void 0){let d=vr({authenticationEntryPoint:this.authenticationEntryPoint});d[W]=$.error_translation,o.push(d);let l=(v=>{let p=[],f=!1;for(let[h,m]of v??[]){let k;if(h==="any-exchange")f=!0,k=pe;else{if(f)throw new Error("Cannot register other matchers after 'any-exchange' matcher");k=h}let R;if(m.access==="permitted")R=new _(async()=>new N(!0)),R.toString=()=>"AuthorizationManager[permitted]";else if(m.access==="denied")R=new _(async()=>new N(!1)),R.toString=()=>"AuthorizationManager[denied]";else if(m.access==="authenticated")R=new _(async K=>{let Ot=await K;return Ot!==void 0?new N(Ot.authenticated):new N(!1)}),R.toString=()=>"AuthorizationManager[authenticated]";else throw new Error(`Unknown access type: ${JSON.stringify(m)}`);p.push([k,R])}return xt({mappings:p})})(t.authorize),g=Et({manager:l,storage:e.storage});g[W]=$.authorization,o.push(g)}o.sort((d,u)=>{let l=d[W]??$.last,g=u[W]??$.last;return l-g})}}let s=new i;return s.authenticationManager=n(),s.build(),o};var Xe=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()}};import{randomUUID as mo}from"node:crypto";var Je=y("auth");function yo(t){let e=[],r=t.authConfig?.type,n={access:r!=="none"?"authenticated":"permitted"};Je.enabledFor("info")&&Je.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 wo(t){if(t.authConfig?.type==="none")return;function e(s,a){if(t.authConfig?.type==="x509")return null;let c=s.password;if(c===void 0){let d=mo().replaceAll("-","");Je.enabledFor("info")&&Je.info(`
|
|
1
|
+
var Ms=Object.defineProperty;var ks=(r,e)=>{for(var t in e)Ms(r,t,{get:e[t],enumerable:!0})};var Hs={};ks(Hs,{Factory:()=>cn,VERSION:()=>Ts});import Rs from"node:http";import Go from"node:https";import{AsyncLocalStorage as Vo}from"node:async_hooks";import{networkInterfaces as Ws}from"node:os";var Is=/^(\d+|(0x[\da-f]+))(-(\d+|(0x[\da-f]+)))?$/i;function dr(r){if(r>65535)throw new Error(`bad port ${r}`);return r}function*dn(r){if(typeof r=="string")for(let e of r.split(",")){let t=e.trim(),n=Is.exec(t);if(n){let s=parseInt(n[1]),i=parseInt(n[4]??n[1]);for(let o=dr(s);o<dr(i)+1;o++)yield o}else throw new Error(`'${e}' is not a valid port or range.`)}else yield dr(r)}var un=(()=>{function r(t){return t.length>0?t[0]:void 0}let e=Object.values(Ws()).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}`}import*as ln from"@interopio/gateway/logging/core";function w(r){return ln.getLogger(`gateway.server.${r}`)}function hn(r,e){return e instanceof RegExp?e.toString():e}import{IOGateway as Os}from"@interopio/gateway";import{AsyncLocalStorage as Ls}from"node:async_hooks";var V=w("ws"),Fs=Os.Encoding.json();function Ds(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 $s(r,e,t,n){let s=ee(n),i=n?.address??"<unknown>",o={key:s,host:i,codec:Fs,onAuthenticate:async()=>{let a=await t();if(a?.authenticated)return{type:"success",user:Ds(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 Us(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=$s(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?Ls.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 pn=Us;import{IOGateway as mn}from"@interopio/gateway";import{IOGateway as Ie}from"@interopio/gateway";function ur(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]=Ie.Filtering.regexify(s));if(e.identity!==void 0){t.identity={};for(let[n,s]of Object.entries(e.identity))t.identity[n]=Ie.Filtering.regexify(s)}return t})}function fn(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]=Ie.Filtering.regexify(c);if(o.metrics={},n){let a=(n.allow??n.whitelist??[]).map(d=>Ie.Filtering.regexify(d)),c=(n.block??n.blacklist??[]).map(d=>Ie.Filtering.regexify(d));a.length>0&&(o.metrics.allow=a),c.length>0&&(o.metrics.block=c)}return o})),e}function lr(r){if(!r)return;let e={...r};return r.filters&&(e.filters=fn(r.filters)),e}function Ns(r){if(r?.enabled!==!1)return r}function qs(r){if(r===void 0||r?.enabled===!1)return;let e={...r};return r.filters&&(e.filters=fn(r.filters)),r.file&&(e.file=lr(r.file)),r.rest&&(e.rest=lr(r.rest)),r.publishers&&(e.publishers=r.publishers.map(t=>{if(typeof t=="string")return[t];let n=lr(t);return n!==void 0?[n]:[]}).flat()),e}function gn(r){let e={...r};return r.contexts&&(e.contexts={...r.contexts,visibility:ur(r.contexts.visibility)}),r.methods&&(e.methods={...r.methods,visibility:ur(r.methods.visibility)}),r.peers&&(e.peers={...r.peers,visibility:ur(r.peers.visibility)}),r.metrics&&(e.metrics=qs(r.metrics)),r.mesh&&(e.mesh=Ns(r.mesh)),e}var M=w("gateway-manager");function yn(){return globalThis.crypto.randomUUID().replaceAll("-","")}var rt=class{#e;#t;#r=new Map;#n=new Map;#s;#i=!1;#o;constructor(e){this.#s={baseConfig:gn(e.baseConfig),scope:e.scope??"principal"},this.#e=e.baseConfig.node??yn(),M.enabledFor("debug")&&M.debug(`creating default gateway with gateway id: ${this.#e}`),this.#t=mn.Factory({...this.#s.baseConfig,node:this.#e})}async start(e){return this.#i?this:(this.#o=e,M.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?M.enabledFor("debug")&&M.debug(`reusing existing gateway for principal '${e}'`):(M.enabledFor("debug")&&M.debug(`no existing gateway for principal '${e}', creating new one`),n=await this.#c(e)),n}async#c(e){let t=yn(),n={...this.#s.baseConfig,node:t};M.enabledFor("debug")&&M.debug(`creating gateway for principal '${e}' with gateway id: ${n.node}`);let s=mn.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){M.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 M.debug("stopping default gateway (managed gateways will continue running)"),await this.#t.stop(),this.#i=!1,this.#t;M.info(`stopping all gateways (1 default + ${this.#r.size} managed)`);for(let[t,n]of this.#r.entries())M.enabledFor("debug")&&M.debug(`stopping gateway with ID: ${t}`),await n.stop();return this.#r.clear(),this.#n.clear(),M.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 bn(...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)}}import{isIP as _s}from"node:net";import{Cookie as hr}from"tough-cookie";function Bs(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 Gs(r){let e=r.one("x-forwarded-ssl");return typeof e=="string"&&e.toLowerCase()==="on"}function Vs(r,e){let t=r.get("x-forwarded-proto");return Array.isArray(t)&&(t=t[0]),t!==void 0?t.split(",",1)[0].trim():Gs(r)?"https":e}function zs(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:_s(s)===6?"IPv6":"IPv4"}}var nt=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},st=class r extends nt{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 js(this.headers)}parseHost(e){return Bs(this.headers,e)}parseProtocol(e){return Vs(this.headers,e)}parseRemoteAddress(e){return zs(this.URL,this.headers,e)}},it=class extends nt{get cookies(){return Xs(this.headers)}setCookieValue(e){return new hr({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 js(r){return r.list("cookie").map(e=>e.split(";").map(t=>hr.parse(t))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function Xs(r){return r.list("set-cookie").map(e=>{let t=hr.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)}import{MIMEType as Js}from"node:util";import{MIMEType as pr}from"node:util";var ae="*",Le=new pr(`${ae}/${ae}`),fr="application/octet-stream",ma=new pr(fr);function pe(r){return r.type===ae}function te(r){return r.subtype===ae||r.subtype.startsWith(`${ae}+`)}function gr(r){return!pe(r)&&!te(r)}var Oe=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 mr(r,e,t){let n=`${r}/${e}`,s;try{s=new pr(n)}catch(i){throw new Oe(n,void 0,{cause:i})}return t&&s.params.set("charset",t),s}function wn(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(pe(r)||pe(e))return!0;if(r.type===e.type){if(r.subtype===e.subtype)return!0;if(te(r)||te(e)){let t=wn(r),n=wn(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 Ys=`
|
|
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
|
+
`,A=class r extends Js{static ALL=new r("*/*");static APPLICATION_OCTET_STREAM=new r(fr);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),En(t)||this.#t(t),e===r.#e){let n=Sn(t),s=parseFloat(n);if(isNaN(s)||s<0||s>1)throw new ot(`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 ot(`Invalid token: ${e}`)}}get quality(){let e=this.params.get(r.#e);return e!==null?parseFloat(Sn(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))}},ot=class extends Error{constructor(e){super(e)}},Sa=(function(){let e=new Map;for(let t of Ys.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=A.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 En(r){return r.length>=2&&(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))}function Sn(r){return En(r)?r.substring(1,r.length-1):r}function Ks(r,e){if(r instanceof A&&e instanceof A){let s=r.quality,i=e.quality;if(s>i)return!0;if(s<i)return!1}let t=pe(r),n=pe(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 Qs(r,e){return Ks(e,r)}function Zs(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 vn(r){if(r===void 0)throw new Error("mimeTypes must not be undefined");if(r.length>100)throw new Oe("too many elements");Zs(r,Qs)}function ei(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 Pn(r){typeof r=="string"&&(r=[r]),typeof r=="number"&&(r=[String(r)]);let e=[];if(r)for(let t of r)t&&e.push(...ei(t));return e}var Fe=class{constructor(){}toList(e){let t=this.get(e);return Pn(t)}},x=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 Pn(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}},Cn=new x;function fe(r){let e=r.one("content-type");return e?A.parseMediaType(e):void 0}var yr=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 at(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 yr(r)}return r}import Pr from"node:http";function Ue(r,e,t){let n=r.elements;if(t=t??n.length,e===0&&t===n.length)return r;if(e===t)return $e.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 $e(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 br={separator:47,decodeAndParseParameters:!0};function j(r,e){return $e.createFromUrlPath(r,e??br)}var $e=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):De.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 De.from(e,n)}else{let n=decodeURIComponent(e.substring(0,t)),s=e.substring(t),i=r.#s(s);return De.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,[""])}}}}},De=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 xn(r,e){return typeof r=="string"?wr.parse(r,e):xn(r.href,e)}var wr=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 Ue(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 Ue(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()}},Ne=class extends st{#e;#t;#r;get requestPath(){return this.#t===void 0&&(this.#t=xn(this.URL.pathname,this.#r)),this.#t}get sslInfo(){return this.#e===void 0&&(this.#e=this.initSslInfo()),this.#e}};var ct=class extends Pr.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},ge=class extends Pr.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},dt=class extends it{#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:at(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(){}},me=class extends Ne{#e;#t;#r;constructor(e){super(new Er(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 Sr(this.#r.socket)}get cookies(){return this.#t??=super.cookies,this.#t}get body(){return Pr.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}`}},Sr=class{peerCertificate;constructor(e){this.peerCertificate=e.getPeerX509Certificate()}},Er=class extends Fe{#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()}},vr=class extends Fe{#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)}},ut=class extends dt{#e;constructor(e){super(new vr(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}`))}})}}},lt=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 Ne)return e.getNativeRequest();if(e instanceof r)return r.getNativeRequest(e.delegate);throw new Error(`Cannot get native request from ${e.constructor.name}`)}},ye=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 dt)return e.getNativeResponse();if(e instanceof r)return r.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},ht=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}]`}},pt=class{request;response;#e=new Map;#t;#r="";constructor(e,t,n){this.#e[An]=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(An);return this.#t!==e&&(this.#t=e,this.#r=e!==void 0?`[${e}] `:""),this.#r}},An="io.interop.web.server.exchange.log_id";import{getHeapStatistics as ti,writeHeapSnapshot as ri}from"node:v8";import{access as ni,mkdir as si,rename as Rn,unlink as ii}from"node:fs/promises";var P=w("monitoring"),oi={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function ai(){return ti()}async function Tn(r){let e=r.dumpPrefix??"Heap",t=`${r.dumpLocation}/${e}.heapsnapshot`;P.enabledFor("debug")&&P.debug(`starting heap dump in ${t}`),await Cr(r.dumpLocation).catch(async s=>{P.enabledFor("debug")&&P.debug(`dump location ${r.dumpLocation} does not exists. Will try to create it`);try{await si(r.dumpLocation,{recursive:!0}),P.info(`dump location dir ${r.dumpLocation} successfully created`)}catch{P.error(`failed to create dump location ${r.dumpLocation}`)}});let n=ri(t);P.info("heap dumped");try{P.debug("rolling snapshot backups");let s=`${r.dumpLocation}/${e}.${r.maxBackups}.heapsnapshot`;await Cr(s).then(async()=>{P.enabledFor("debug")&&P.debug(`deleting ${s}`);try{await ii(s)}catch(o){P.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 Cr(a).then(async()=>{try{await Rn(a,c)}catch(d){P.warn(`failed to rename ${a} to ${c}`,d)}}).catch(()=>{})}let i=`${r.dumpLocation}/${e}.1.heapsnapshot`;try{await Rn(n,i)}catch(o){P.warn(`failed to rename ${n} to ${i}`,o)}P.debug("snapshots rolled")}catch(s){throw P.error("error rolling backups",s),s}}async function Cr(r){P.enabledFor("trace")&&P.debug(`checking file ${r}`),await ni(r)}async function ci(r,e,t){P.enabledFor("debug")&&P.debug(`processing heap stats ${JSON.stringify(r)}`);let n=Math.min(t.memoryLimit,.95*r.heap_size_limit),s=r.used_heap_size;P.info(`heap stats ${JSON.stringify(r)}`),s>=n?(P.warn(`used heap ${s} bytes exceeds memory limit ${n} bytes`),e.memoryLimitExceeded?delete e.snapshot:(e.memoryLimitExceeded=!0,e.snapshot=!0),await Tn(t)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function Hn(r){let e={...oi,...r},t=!1,n={memoryLimitExceeded:!1},s=async()=>{let a=ai();await ci(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 Tn(e);break}case"stop":{t=!0,clearInterval(i),P.info("exit memory diagnostic");break}}return t}}}async function di({channel:r},e){await r(e)||P.warn(`cannot execute command "${e}" already closed`)}async function Mn(r){return await di(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()}),kn=(r,e)=>li(r,e);import{IOGateway as ft}from"@interopio/gateway";var xr=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 pi(r,e){let t=r.block??r.blacklist,n=r.allow??r.whitelist;if(t.length>0&&ft.Filtering.valuesMatch(t,e))return xr.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&ft.Filtering.valuesMatch(n,e))return xr.enabledFor("debug")&&xr.debug(`origin ${e} matches allow filter`),!0}function fi(r){switch(r.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Wn(r,e){if(!e)return!0;if(r){let t=pi(e,r);return t||fi(e)}else return hi(e)}function In(r){if(r){let e=(r.block??r.blacklist??[]).map(ft.Filtering.regexify),t=(r.allow??r.whitelist??[]).map(ft.Filtering.regexify);return{non_matched:r.non_matched??"allow",missing:r.missing??"allow",allow:t,block:e}}}var On=r=>async e=>{for(let t of r)if((await t(e)).match)return D();return W},be=r=>{let e=async t=>{for(let n of r)if(!(await n(t)).match)return W;return D()};return e.toString=()=>`and(${r.map(t=>t.toString()).join(", ")})`,e},Ln=r=>async e=>(await r(e)).match?W:D(),we=async r=>D();we.toString=()=>"any-exchange";var Fn=Object.freeze({}),W=Object.freeze({match:!1,variables:Fn}),D=(r=Fn)=>({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 W;if(typeof r=="string")return o===r?D():W;{let a=r.exec(o);return a===null?W:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${r.toString()}, method=${t??"<any>"})`,n},qe=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 W}for(let i of s)if(!e(i)){for(let o of r.mediaTypes)if(i.startsWith(o))return D()}return W}},ce=async({request:r})=>r.upgrade&&r.headers.one("upgrade")?.toLowerCase()==="websocket"?D():W;ce.toString=()=>"websocket upgrade";import{IOGateway as Dn}from"@interopio/gateway";async function Ar(r,e,t){let n=(i,o)=>{if(o?.cors){let a=o.cors===!0?{allowOrigins:o.origins?.allow?.map(Dn.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=$(Dn.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:v,variables:l}=await d(f);v?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:In(c?.origins)})}}};await r(s,e)}import{IOGateway as Tr}from"@interopio/gateway";function mi(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 $n(r){return r.headers.has("origin")&&!mi(r)}function X(r){return r.method==="OPTIONS"&&r.headers.has("origin")&&r.headers.has("access-control-request-method")}var Un=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],yi=(r,e)=>{let{request:t,response:n}=r,s=n.headers;if(!s.has("Vary"))s.set("Vary",Un.join(", "));else{let o=s.list("Vary");for(let a of Un)o.find(c=>c===a)||o.push(a);s.set("Vary",o.join(", "))}try{if(!$n(t))return!0}catch{return U.enabledFor("debug")&&U.debug("reject: origin is malformed"),_e(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=X(t);return e?wi(r,e,i):i?(_e(n),!1):!0},mt=["*"],Rr=["GET","HEAD","POST"],Nn={allowOrigins:mt,allowMethods:Rr,allowHeaders:mt,maxAge:1800};function yt(r){if(r){let e=r.allowHeaders;e&&e!==C&&(r={...r,allowHeaders:e.map(n=>n.toLowerCase())});let t=r.allowOrigins;return t&&(t==="*"?(_n(r),Bn(r)):r={...r,allowOrigins:t.map(n=>typeof n=="string"&&n!==C&&(n=Tr.Filtering.regexify(n),typeof n=="string")?Gn(n).toLowerCase():n)}),r}}function gt(r,e){if(e===void 0)return r!==void 0?r===C?[C]:r:[];if(r===void 0)return e===C?[C]:e;if(r==mt||r===Rr)return e===C?[C]:e;if(e==mt||e===Rr)return r===C?[C]:r;if(r===C||r.includes(C)||e===C||e.includes(C))return[C];let t=new Set;return r.forEach(n=>t.add(n)),e.forEach(n=>t.add(n)),Array.from(t)}var Be=(r,e)=>e===void 0?r:{allowOrigins:gt(r.allowOrigins,e?.allowOrigins),allowMethods:gt(r.allowMethods,e?.allowMethods),allowHeaders:gt(r.allowHeaders,e?.allowHeaders),exposeHeaders:gt(r.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??r.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??r.allowPrivateNetwork,maxAge:e?.maxAge??r.maxAge},bi=r=>{let e=r.corsConfigSource,t=r.corsProcessor??yi;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)||X(n.request)||await s.filter(n)}}},qn=bi,U=w("cors");function _e(r){r.setStatusCode(y.FORBIDDEN)}function wi(r,e,t){let{request:n,response:s}=r,i=s.headers,o=n.headers.one("origin"),a=Ei(e,o);if(a===void 0)return U.enabledFor("debug")&&U.debug(`reject: '${o}' origin is not allowed`),_e(s),!1;let c=Ci(n,t),d=vi(e,c);if(d===void 0)return U.enabledFor("debug")&&U.debug(`reject: HTTP '${c}' is not allowed`),_e(s),!1;let u=xi(n,t),f=Pi(e,u);if(t&&f===void 0)return U.enabledFor("debug")&&U.debug(`reject: headers '${u}' are not allowed`),_e(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 C="*",Si=["GET","HEAD"];function _n(r){if(r.allowCredentials===!0&&r.allowOrigins===C)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function Bn(r){if(r.allowPrivateNetwork===!0&&r.allowOrigins===C)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function Ei(r,e){if(e){let t=r.allowOrigins;if(t){if(t===C)return _n(r),Bn(r),C;let n=Gn(e.toLowerCase());for(let s of t)if(s===C||Tr.Filtering.valueMatches(s,n))return e}}}function vi(r,e){if(e){let t=r.allowMethods??Si;if(t===C)return[e];if(Tr.Filtering.valuesMatch(t,e))return t}}function Pi(r,e){if(e===void 0)return;if(e.length==0)return[];let t=r.allowHeaders;if(t===void 0)return;let n=t===C||t.includes(C),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 Gn(r){return r.endsWith("/")?r.slice(0,-1):r}function Ci(r,e){return e?r.headers.one("access-control-request-method"):r.method}function xi(r,e){let t=r.headers;return e?t.list("access-control-request-headers"):Array.from(t.keys())}var Vn=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};import{IOGateway as Ai}from"@interopio/gateway";function zn(r){let{sockets:e,cors:t}=r,n=r.corsConfig===!1?void 0:Be(Nn,r.corsConfig),s=[];for(let[o,a]of e){let c=n;for(let[u,f]of t)Ai.Filtering.valueMatches(u,o)&&(f===void 0?c=void 0:c=c===void 0?f:Be(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:Be(c,d),s.push([be([ce,$(o)]),yt(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:Be(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),yt(a)]);return s.push([$(/\/api\/.*/),yt(n)]),Vn({mappings:s})}function jn(r){return r!==void 0&&typeof r.type=="string"&&typeof r.authenticated=="boolean"}var k=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}},bt=class extends k{},Se=class extends k{},Ee=class extends k{constructor(e){super(e)}},Ge=class extends Ee{constructor(e){super(e)}},Ve=class extends Ee{constructor(e){super(e)}},ze=class extends Ee{constructor(e){super(e)}},je=class extends Ee{constructor(e){super(e)}};var de=class extends Error{},J=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)}},ve=class extends k{};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)},Ri=()=>N(new x().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),Ti=()=>N(new x().add("x-content-type-options","nosniff")),Hi=(r,e,t)=>{let n=`max-age=${r}`;e&&(n+=" ; includeSubDomains"),t&&(n+=" ; preload");let s=N(new x().add("strict-transport-security",n)),i=o=>o.request.URL.protocol==="https:";return async o=>{i(o)&&await s(o)}},Mi=r=>N(new x().add("x-frame-options",r)),ki=r=>N(new x().add("x-xss-protection",r)),Wi=r=>{let e=r===void 0?void 0:N(new x().add("permissions-policy",r));return async t=>{e!==void 0&&await e(t)}},Ii=(r,e)=>{let t=e?"content-security-policy-report-only":"content-security-policy",n=r===void 0?void 0:N(new x().add(t,r));return async s=>{n!==void 0&&await n(s)}},Oi=(r="no-referrer")=>N(new x().add("referer-policy",r)),Li=r=>{let e=r===void 0?void 0:N(new x().add("cross-origin-opener-policy",r));return async t=>{e!==void 0&&await e(t)}},Fi=r=>{let e=r===void 0?void 0:N(new x().add("cross-origin-embedder-policy",r));return async t=>{e!==void 0&&await e(t)}},Di=r=>{let e=r===void 0?void 0:N(new x().add("cross-origin-resource-policy",r));return async t=>{e!==void 0&&await e(t)}},$i=(...r)=>async e=>{for(let t of r)await t(e)};function Hr(r){let e=[];r?.cache?.disabled||e.push(Ri()),r?.contentType?.disabled||e.push(Ti()),r?.hsts?.disabled||e.push(Hi(r?.hsts?.maxAge??365*24*60*60,r?.hsts?.includeSubDomains??!0,r?.hsts?.preload??!1)),r?.frameOptions?.disabled||e.push(Mi(r?.frameOptions?.mode??"DENY")),r?.xss?.disabled||e.push(ki(r?.xss?.headerValue??"0")),r?.permissionsPolicy?.disabled||e.push(Wi(r?.permissionsPolicy?.policyDirectives)),r?.contentSecurityPolicy?.disabled||e.push(Ii(r?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",r?.contentSecurityPolicy?.reportOnly)),r?.refererPolicy?.disabled||e.push(Oi(r?.refererPolicy?.policy??"no-referrer")),r?.crossOriginOpenerPolicy?.disabled||e.push(Li(r?.crossOriginOpenerPolicy?.policy)),r?.crossOriginEmbedderPolicy?.disabled||e.push(Fi(r?.crossOriginEmbedderPolicy?.policy)),r?.crossOriginResourcePolicy?.disabled||e.push(Di(r?.crossOriginResourcePolicy?.policy)),r?.writers&&e.push(...r.writers);let t=$i(...e);return{filter:async(n,s)=>(await t(n),s.filter(n))}}var Pe=r=>{let e=r.entryPoint,t=r?.rethrowAuthenticationServiceError??!0;return async({exchange:n},s)=>{if(!t||!(s instanceof ve))return e(n,s);throw s}};var Ui="Realm",Ni=r=>`Basic realm="${r}"`,Ce=r=>{let e=Ni(r?.realm??Ui);return async(t,n)=>{let{response:s}=t;s.setStatusCode(y.UNAUTHORIZED),s.headers.set("WWW-Authenticate",e)}};var Xn="Basic ",wt=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<=Xn.length?"":s.substring(Xn.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}}}};import{AsyncLocalStorage as qi}from"node:async_hooks";var 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 qi)=>(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 _i(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 Bi(a,{exchange:r,chain:e},s,i)}catch(c){throw c instanceof k,c}}async function Bi(r,e,t,n){se.withAuthentication(r)(n),await t(e,r)}function ie(r){let e={matcher:we,successHandler:async({exchange:n,chain:s})=>{await s.filter(n)},converter:wt({}),failureHandler:Pe({entryPoint:Ce({})}),...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 _i(n,s,o,t,e.successHandler,e.storage)}catch(a){if(a instanceof k){await e.failureHandler({exchange:n,chain:s},a);return}throw a}}}}var Jn=r=>async(e,t)=>{e.response.setStatusCode(r.httpStatus)};var xe=w("auth.entry-point"),St=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(xe.enabledFor("debug")&&xe.debug(`trying to match using: ${s}`),(await s(t)).match)return xe.enabledFor("debug")&&xe.debug(`match found. using default entry point ${i}`),i(t,n);return xe.enabledFor("debug")&&xe.debug(`no match found. using default entry point ${e}`),e(t,n)}};var Yn=r=>async({exchange:e,chain:t},n)=>{for(let s of r)await s({exchange:e,chain:t},n)};function Mr(r){let e=async m=>m.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?D():W,t=St({entryPoints:[[e,Jn({httpStatus:y.UNAUTHORIZED})]],defaultEntryPoint:Ce({})}),n=r.entryPoint??t,s=r.manager,i=qe({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),o=Ln(qe({mediaTypes:["text/html"]})),a=be([o,i]),c=On([e,a]);r.defaultEntryPoints.push([c,n]);let d=r.failureHandler??Pe({entryPoint:n}),u=Yn(r.successHandlers??r.defaultSuccessHandlers),f=wt({});return ie({storage:r.storage,manager:s,failureHandler:d,successHandler:u,converter:f})}var Kn={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},Qn="https://tools.ietf.org/html/rfc6750#section-3.1";function Et(r){return{errorCode:Kn.invalid_token,httpStatus:y.UNAUTHORIZED,description:r,uri:Qn}}function kr(r){return{errorCode:Kn.invalid_request,httpStatus:y.BAD_REQUEST,description:r,uri:Qn}}var Gi="access_token",Vi=/^Bearer\s+(?<token>[a-zA-Z0-9-._~+/]+=*)$/i,_=class extends k{error;constructor(e,t,n){super(t??(typeof e=="string"?void 0:e.description),n),this.error=typeof e=="string"?{errorCode:e}:e}},Zn=r=>r.type==="BearerToken",zi=r=>async e=>{let{request:t}=e;return Promise.all([Xi(t.headers,r?.headerName).then(n=>n!==void 0?[n]:void 0),Ji(t,r?.uriQueryParameter),Yi(e,r?.formEncodedBodyParameter)]).then(n=>n.filter(s=>s!==void 0).flat(1)).then(ji).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function ji(r){if(r.length===0)return;if(r.length>1){let t=kr("Found multiple access tokens in the request");throw new _(t)}let e=r[0];if(!e||e.length===0){let t=kr("The requested access token parameter is an empty string");throw new _(t)}return e}async function Xi(r,e="authorization"){let t=r.one(e);if(!t||!/bearer/i.test(t.substring(0)))return;let n=Vi.exec(t);if(n===null){let s=Et("Bearer token is malformed");throw new _(s)}return n.groups?.token}async function es(r){let e=r.getAll(Gi);if(e.length!==0)return e}async function Ji(r,e=!1){if(!(!e||r.method!=="GET"))return es(r.URL.searchParams)}async function Yi(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 es(n)}var vt=zi;function Ki(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 ts=r=>r.httpStatus!==void 0;function Qi(r){if(r instanceof _){let{error:e}=r;if(ts(e))return e.httpStatus}return y.UNAUTHORIZED}function Zi(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),ts(n)&&n.scope&&t.set("scope",n.scope)}return t}var eo=r=>async(e,t)=>{let n=Qi(t),s=Zi(t,r?.realmName),i=Ki(s),{response:o}=e;o.headers.set("WWW-Authenticate",i),o.setStatusCode(n),await o.end()},Pt=eo;var to=r=>{let e=r?.principalClaimName??"sub";return t=>({type:"JwtToken",authenticated:!0,name:t.getClaimAsString(e)})},ro=r=>async e=>r(e),Ae=class extends Error{},Xe=class extends Ae{};function no(r){if(r instanceof Xe)return new _(Et(r.message),r.message,{cause:r});throw new ve(r.message,{cause:r})}function Wr(r){let e=r.decoder,t=r.authConverter??ro(to({}));return async n=>{if(Zn(n)){let s=n.token;try{let i=await e(s);return await t(i)}catch(i){throw i instanceof Ae?no(i):i}}}}function Ir(r){let e=r.entryPoint??Pt({}),t=r?.converter??vt({}),n=r.failureHandler??Pe({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??Wr(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")}import{jwtVerifier as uo,JwtVerifyError as lo}from"@interopio/gateway/jose/jwt";async function rs(r,e,t){let n=new bt("Full authentication is required to access this resource."),s=new k("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 ns=r=>{let e=so(y.FORBIDDEN),t=r.authenticationEntryPoint??Ce();return{filter:async(n,s)=>{try{await s.filter(n)}catch(i){if(i instanceof de){let o=await n.principal();jn(o)?(o.authenticated||await e(n,i),await rs(n,o,t)):await rs(n,void 0,t);return}throw i}}}};var io=w("security.auth");function Or(r){let e=async(t,n)=>{let s;for(let[i,o]of r.mappings)if((await i(n))?.match){io.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 J(!1),s};return new ne(e)}var Ct=w("security.auth");function Lr(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),Ct.enabledFor("debug")&&Ct.debug("authorization successful")}catch(o){throw o instanceof de&&Ct.enabledFor("debug")&&Ct.debug(`authorization failed: ${o.message}`),o}await s.filter(n)}}}var Fr=class extends ht{#e;constructor(e,t){super(e),this.#e=t}async principal(){return(await this.#e())?.authentication}},ss=r=>{let e=r.storage;return{filter:async(t,n)=>{await n.filter(new Fr(t,async()=>await se.getContext(e)))}}};var is=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 xt=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 Se(`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}},Re=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)}},At=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}};import{argon2 as O,keygen as oo}from"@interopio/gateway-server/tools";function ao(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 Rt=class extends ue{#e;#t;#r;#n;#s;constructor(e=O.DEFAULT_SALT_LENGTH,t=O.DEFAULT_HASH_LENGTH,n=O.DEFAULT_PARALLELISM,s=O.DEFAULT_MEMORY,i=O.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=O.decode(t),s=await O.createHash(n.algorithm,e,n.hash.length,n.parameters);return ao(n.hash,s)}catch{return!1}}async encodeDefinedPassword(e){let t=oo.createSalt(this.#e),n={memory:this.#n,passes:this.#s,parallelism:this.#r,nonce:t},s=await O.createHash("argon2id",e,this.#t,n);return O.encode({algorithm:"argon2id",version:O.ARGON2_VERSION,parameters:n,hash:s})}upgradeEncodingDefined(e){let t=O.decode(e);return t.version<O.ARGON2_VERSION||t.parameters.memory<this.#n||t.parameters.passes<this.#s}};var Dr=4096;function os(){let r="argon2id",e=new Map([[r,new Rt],["noop",At.instance]]);return new Re(r,e,Re.DEFAULT_ID_PREFIX,Re.DEFAULT_ID_SUFFIX)}var as={async updatePassword(r,e){return r}},Tt=class extends k{username;constructor(e,t,n){super(e,n),this.username=t}},Ht=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 cs(r,e){let t=e?.preAuthenticationChecks??(a=>{if(a.accountLocked)throw oe.debug("user account is locked"),new Ge("User account is locked");if(a.disabled)throw oe.debug("user account is disabled"),new Ve("User is disabled");if(a.accountExpired)throw oe.debug("user account is expired"),new ze("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??os(),i=e?.userDetailsPasswordService??as,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 Se("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 co(){return r=>{if(r.accountLocked)throw oe.debug("failed to authenticate since user account is locked"),new Ge("User account is locked");if(r.disabled)throw oe.debug("failed to authenticate user account is disabled"),new Ve("User is disabled");if(r.accountExpired)throw oe.debug("failed to authenticate since user account is expired"),new ze("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 ds(r){let e=r.userDetailsService,t=r.userDetailsChecker??co(),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 Tt("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 $r(r){let e=r.manager??ds({userDetailsService:r.getService("UserDetailsService")}),t=r.extractor??xt(),n=r.converter??is({principalExtractor:t});return ie({storage:r.storage,manager:e,converter:n})}var Mt=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}]`}},kt=class extends Mt{#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}},Je=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)}},Wt=class extends Mt{#e;constructor(e,...t){super(e),this.#e=Je.of(e,...t)}get filters(){return this.#e.filters}handle(e){return this.#e.filter(e)}};var It=class{#e;#t=new Nr;#r=new Ur;#n=new _r;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 qr)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}},Ur=class{decorate(e,t){return t=t||[],Je.of({handle:n=>e.filter(n)},...t)}},Ot=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}},Nr=class{async firewalledExchange(e){return e}},qr=class extends Error{constructor(e){super(e),this.name="ServerExchangeRejectedError"}},_r=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"),us=(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 cs(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]:St({entryPoints:this.#t,defaultEntryPoint:this.#t[this.#t.length-1][1]})}build(){if(r.headers!==void 0&&r.headers.disabled!==!0){let d=Hr(r.headers);d[G]=B.http_headers,s.push(d)}if(r.x509!==void 0&&r.x509.disabled!==!0){let d=$r({storage:e.storage,getService:t,extractor:xt({principalAltName:r.x509.principalAltName})});d[G]=B.authentication,s.push(d)}if(r.cors?.disabled!==!0&&e.corsConfigSource!==void 0){let d=qn({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},v)=>await m.filter(f)],u=Mr({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=uo({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 lo?new Xe(p.message,{cause:p}):new Ae("error occurred while attempting to decoding jwt",{cause:p})}},f=vt({uriQueryParameter:!0}),m=async h=>{try{return await f(h)===void 0?W:D()}catch{return W}},v=Pt({});this.#t.push([m,v]);let l=Ir({storage:e.storage,entryPoint:v,converter:f,jwt:{decoder:u}});l[G]=B.authentication,s.push(l)}let c=ss({storage:e.storage});if(s.push(c),c[G]=B.security_context_server_web_exchange,r.authorize!==void 0){let d=ns({authenticationEntryPoint:this.authenticationEntryPoint});d[G]=B.error_translation,s.push(d);let f=(v=>{let l=[],h=!1;for(let[p,g]of v??[]){let b;if(p==="any-exchange")h=!0,b=we;else{if(h)throw new Error("Cannot register other matchers after 'any-exchange' matcher");b=p}let S;if(g.access==="permitted")S=new ne(async()=>new J(!0)),S.toString=()=>"AuthorizationManager[permitted]";else if(g.access==="denied")S=new ne(async()=>new J(!1)),S.toString=()=>"AuthorizationManager[denied]";else if(g.access==="authenticated")S=new ne(async T=>{let L=await T;return L!==void 0?new J(L.authenticated):new J(!1)}),S.toString=()=>"AuthorizationManager[authenticated]";else throw new Error(`Unknown access type: ${JSON.stringify(g)}`);l.push([b,S])}return Or({mappings:l})})(r.authorize),m=Lr({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 Ot(we,...s)};var Lt=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()}};import{randomUUID as ho}from"node:crypto";var Ft=w("auth");function po(r){let e=[],t=r.authConfig?.type,n={access:t!=="none"?"authenticated":"permitted"};Ft.enabledFor("info")&&Ft.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=be([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 fo(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=ho().replaceAll("-","");Ft.enabledFor("info")&&Ft.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>Ct)throw new Error(`Password length exceeds maximum length of ${Ct} 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=Ve.ofUsername(r.name).password(n).roles(...o).build();return new Xe(i)}async function Rr(t){let e=ur(t),r=yo(t),n=wo(t),{storage:o}=t;return kr(r,{storage:o,corsConfigSource:e,userDetailsService:n,userDetailsPasswordService:n})}import{AsyncLocalStorage as bo}from"node:async_hooks";var Ke=class extends Z{};function So(t,e){if(t==null)return!1;let{code:r,message:n}=t;return r==="ECONNRESET"||r==="EPIPE"||r==="ERR_STREAM_PREMATURE_CLOSE"||n?.toLowerCase().includes("client aborted")||n?.toLowerCase().includes("socket hang up")||n?.toLowerCase().includes("aborted")?(e.enabledFor("trace")?e.trace("looks like the client has gone away:",t):e.enabledFor("debug")&&e.debug(`looks like the client has gone away: ${t.message} (For full stack trace enable trace logging level.)`),!0):!1}var Ht=class{#e;#r=!1;#t;#n;constructor(e,r){this.#e=e,this.#t=r}createExchange(e,r){return new Oe(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(w.INTERNAL_SERVER_ERROR)){this.#e.error(`${i}500 Server Error for ${this.formatRequest(n)}`,r);return}if(!So(r,this.#e))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))})}},Ye=class{#e;#r=[];#t=new bo;#n;constructor(e){this.#e=e}middleware(e){return e(this.#r),this}storage(e){return this.#t=e,this}httpHandlerDecorator(e){if(this.#n===void 0)this.#n=e;else{let r=this.#n;this.#n=n=>(n=e(n),n=r(n),n)}return this}hasHttpHandlerDecorator(){return this.#n!==void 0}build(){let e=y("http"),r=new Ht(e,this.#e);this.#t!==void 0&&(r.storage=this.#t),r.enableLoggingRequestDetails=!1;let n=async(o,i)=>r.http(o,i);return this.#n?this.#n(n):n}};import{WebSocketServer as xo}from"ws";function Tr(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 x;for(let g of n.headers.keys())a.set(g,n.headers.list(g));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 Or(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(w.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()}]}import{WebSocket as vo}from"ws";var Qe=class extends vo{constructor(e,r,n){super(null,void 0,n)}connected},Ze=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=y("ws");function Eo(t,e,r,n){return o=>{let{logPrefix:i,request:s}=o,a=Re.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(!Kt(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,(g,v)=>{r.emit("connection",g,v)})}}function Ao(t,e){let r=new Set;t.forEach((o,i)=>{if(i===0&&o.startsWith("HTTP/1.1 101 ")){e.setStatusCode(w.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 Mr(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,Dt):"<none>"}, ping: ${typeof e.ping=="number"?e.ping+"ms":e.ping?JSON.stringify(e.ping):"<none>"}`);let i=new xo({noServer:!0,WebSocket:Qe,autoPong:!1}),s=new Ze(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;Ao(c,u)}}).on("connection",(c,d)=>{let u=Tr(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=Eo(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)}}import{existsSync as P,readFileSync as G,writeFileSync as et,mkdirSync as tt}from"node:fs";import{dirname as rt}from"node:path";import{KEYUTIL as Co,X509 as Po}from"jsrsasign";import{mkcert as kt}from"@interopio/gateway-server/tools";var de=y("ssl");function Ir(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&&P(t.key)&&P(t.cert)){de.info(`using SSL/TLS certificate ${t.cert} with private key in ${t.key}${t.passphrase?" (password-protected)":""}`);let p={key:G(t.key),cert:G(t.cert),...r};return t.passphrase&&(p.passphrase=t.passphrase),t.requestCert&&t.ca&&P(t.ca)&&(p.ca=G(t.ca)),p}if(!t.key&&!t.cert){let p="./gateway-server.key",f="./gateway-server.crt";if(P(p)&&P(f)){de.info(`using SSL/TLS certificate ${f} with private key in ${p}${t.passphrase?" (password-protected)":""}`);let h={key:G(p),cert:G(f),...r};return t.passphrase&&(h.passphrase=t.passphrase),t.requestCert&&t.ca&&P(t.ca)&&(h.ca=G(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(!P(n)){if(P(o))throw new Error(`CA key file not found: ${n} (CA certificate exists: ${o})`);let p=kt.generateRootCA({name:kt.DEFAULT_CA_NAME,passphrase:i}),f=rt(n);f&&f!=="."&&!P(f)&&tt(f,{recursive:!0});let h=rt(o);h&&h!=="."&&h!==f&&!P(h)&&tt(h,{recursive:!0}),et(n,p.key,{mode:256}),et(o,p.cert,{mode:420}),de.info(`created new local Root CA in ${o}, ${n}${i?" (password-protected)":""}`)}let s=G(n,"utf8"),a=Co.getKey(s,i),c=G(o,"utf8"),d=new Po;d.readCertPEM(c);let u=d.getSubjectString(),l=e.host;de.debug(`generating server certificate signed by: ${u} for host: ${l}`);let g=kt.generateCert(a,u,[l],!1);if(t.key||t.cert){let p=t.key||"./gateway-server.key",f=t.cert||"./gateway-server.crt",h=rt(p);h&&h!=="."&&!P(h)&&tt(h,{recursive:!0});let m=rt(f);m&&m!=="."&&m!==h&&!P(m)&&tt(m,{recursive:!0}),et(p,g.key,{mode:384}),et(f,g.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 v={key:g.key,cert:g.cert,...r};return t.requestCert&&t.ca&&P(o)&&(v.ca=G(o)),v}import Lr from"@interopio/gateway-server/package.json"with{type:"json"};import{resolve as Ho}from"node:path";import{access as ko,readFile as Ro}from"node:fs/promises";import{constants as To}from"node:fs";async function Oo(t){if(t)for(let e of t){let r=Ho(e,"index.html");try{return await ko(r,To.R_OK),r}catch{}}}async function Rt(t){let e=await Oo(t),r=he({mediaTypes:["text/html"]});return async(n,o)=>{let{request:i,response:s}=n;if(i.method==="GET"&&i.path==="/")if(s.setStatusCode(w.OK),e!==void 0&&(await r(n)).match)s.headers.set("Content-Type","text/html; charset=utf-8"),await s.body(Ro(e));else{s.headers.set("Content-Type","text/plain; charset=utf-8");let a=Buffer.from("io.Gateway Server","utf-8");await s.body(a)}else await o()}}var U=y("app");async function Do(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 ke(i),c=s.method==="HEAD"?new Ke(a):a;await r(s,c)}}function $o(t){return new Promise((e,r)=>{let n=t(o=>{o?r(o):e(n)})})}function Wo(t){if(t)return Vt({memoryLimit:t.memory_limit,dumpLocation:t.dump_location,dumpPrefix:t.dump_prefix,reportInterval:t.report_interval,maxBackups:t.max_backups})}var Dr=`${Lr.name} - v${Lr.version}`;async function Uo(t){let e=t.storage,r=await Rr(t),n=Or(t),o=Gt(Jt(Dr,t.serverHeader),...r,...n,...t.middleware,async({request:i,response:s},a)=>{if(i.method==="GET"&&i.path==="/health"){s.setStatusCode(w.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()},await Rt(t.resourcesConfig?.locations),async({response:i},s)=>{i.setStatusCode(w.NOT_FOUND),await i.end()});return new Ye(o).storage(e)}var Tt=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)=>Io.createServer({...p,...Ir(e,n)},f):(p,f)=>Mo.createServer(p,f),i=Wo(t.memory),s={middleware:[],corsConfig:t.cors,cors:[],authConfig:t.auth,authorize:[],storage:new Lo,sockets:new Map,resourcesConfig:t.resources},a=new ve({baseConfig:{...t.gateway},scope:t.gateway?.scope??"principal"});if(t.gateway){let p=t.gateway.route?t.gateway.route==="/"?void 0:t.gateway.route:void 0;await ft(async f=>{f.socket({path:p,factory:$t.bind(a),options:t.gateway})},t,s)}t.app&&await ft(t.app,t,s);let c=Mt(t.port??0),d=p=>U.error(`socket error: ${p}`,p),u=await Uo(s),l=await Do(u,d),v=await new Promise((p,f)=>{let h=o({IncomingMessage:Ce,ServerResponse:Y,...t.http},l);h.on("error",m=>{if(m.code==="EADDRINUSE"){U.debug(`port ${m.port} already in use on address ${m.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(m))}else U.error(`server error: ${m.message}`,m),f(m)}),h.on("listening",async()=>{let m=h.address();for(let[k,R]of s.sockets){let K=`${e?"wss":"ws"}://${It}:${m.port}${k}`;await Mr(k,R,K,s.storage,d)}U.info(`http server listening on ${e?"https":"http"}://${B(m)}`),p(h)}),h.on("upgrade",(m,k,R)=>{try{l(m,R)}catch(K){U.error(`upgrade error: ${K}`,K)}}).on("close",async()=>{U.info("http server closed.")});try{let{value:m}=c.next();h.listen(m,r)}catch(m){U.error("error starting web socket server",m),f(m instanceof Error?m:new Error(`listen failed: ${m}`))}});return new class{gateway=a;get address(){let p=v.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 $o(p=>{v.closeAllConnections(),v.close(p)}),i&&await Xt(i),await a.stop()}}};var Wc=Tt;export{$r as GatewayServer,Wc as default};
|
|
18
|
+
`),c=d}if(c.length>Dr)throw new Error(`Password length exceeds maximum length of ${Dr} 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=Ht.ofUsername(t.name).password(n).roles(...s).build();return new Lt(i)}async function ls(r){let e=zn(r),t=po(r),n=fo(r),{storage:s}=r;return us(t,{storage:s,corsConfigSource:e,userDetailsService:n,userDetailsPasswordService:n})}var Dt=class extends ye{};import{WebSocketServer as mo}from"ws";function hs(r,e){let t=r?.exchange,n=t?.request??new me(r),s=t?.principal,i=s?s.bind(t):async function(){},o=n.URL,a=new x;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 ps(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()}]}import{WebSocket as go}from"ws";var $t=class extends go{constructor(e,t,n){super(null,void 0,n)}connected},Ut=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 yo(r,e,t,n){return s=>{let{logPrefix:i,request:o}=s,a=lt.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(!Wn(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,v)=>{t.emit("connection",m,v)})}}function bo(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=ye.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 fs(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,hn):"<none>"}, ping: ${typeof e.ping=="number"?e.ping+"ms":e.ping?JSON.stringify(e.ping):"<none>"}`);let i=new mo({noServer:!0,WebSocket:$t,autoPong:!1}),o=new Ut(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;bo(c,u)}}).on("connection",(c,d)=>{let u=hs(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=yo(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)}}import{existsSync as I,readFileSync as Y,writeFileSync as Nt,mkdirSync as qt}from"node:fs";import{dirname as _t}from"node:path";import{KEYUTIL as wo,X509 as So}from"jsrsasign";import{mkcert as Br}from"@interopio/gateway-server/tools";var Te=w("ssl");function gs(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&&I(r.key)&&I(r.cert)){Te.info(`using SSL/TLS certificate ${r.cert} with private key in ${r.key}${r.passphrase?" (password-protected)":""}`);let l={key:Y(r.key),cert:Y(r.cert),...t};return r.passphrase&&(l.passphrase=r.passphrase),r.requestCert&&r.ca&&I(r.ca)&&(l.ca=Y(r.ca)),l}if(!r.key&&!r.cert){let l="./gateway-server.key",h="./gateway-server.crt";if(I(l)&&I(h)){Te.info(`using SSL/TLS certificate ${h} with private key in ${l}${r.passphrase?" (password-protected)":""}`);let p={key:Y(l),cert:Y(h),...t};return r.passphrase&&(p.passphrase=r.passphrase),r.requestCert&&r.ca&&I(r.ca)&&(p.ca=Y(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(!I(n)){if(I(s))throw new Error(`CA key file not found: ${n} (CA certificate exists: ${s})`);let l=Br.generateRootCA({name:Br.DEFAULT_CA_NAME,passphrase:i}),h=_t(n);h&&h!=="."&&!I(h)&&qt(h,{recursive:!0});let p=_t(s);p&&p!=="."&&p!==h&&!I(p)&&qt(p,{recursive:!0}),Nt(n,l.key,{mode:256}),Nt(s,l.cert,{mode:420}),Te.info(`created new local Root CA in ${s}, ${n}${i?" (password-protected)":""}`)}let o=Y(n,"utf8"),a=wo.getKey(o,i),c=Y(s,"utf8"),d=new So;d.readCertPEM(c);let u=d.getSubjectString(),f=e.host;Te.debug(`generating server certificate signed by: ${u} for host: ${f}`);let m=Br.generateCert(a,u,[f],!1);if(r.key||r.cert){let l=r.key||"./gateway-server.key",h=r.cert||"./gateway-server.crt",p=_t(l);p&&p!=="."&&!I(p)&&qt(p,{recursive:!0});let g=_t(h);g&&g!=="."&&g!==p&&!I(g)&&qt(g,{recursive:!0}),Nt(l,m.key,{mode:384}),Nt(h,m.cert,{mode:420}),Te.info(`generated server certificate saved to ${h} with private key in ${l}${i?" (password-protected)":""}`)}else Te.info(`using in-memory server certificate for host: ${f}`);let v={key:m.key,cert:m.cert,...t};return r.requestCert&&r.ca&&I(s)&&(v.ca=Y(s)),v}function Gr(r){return r?.get("io.gateway.logging.suppress")===!0}var Bt="io.gateway.logging.prefix";function Vr(r){return r?.has(Bt)?r.get(Bt)??"":""}var He=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}},Gt=class extends He{constructor(){super(Le)}canEncode(e,t){return super.canEncode(e,t)}async encode(e,t,n){let s=await e;return this.logger.enabledFor("debug")&&!Gr(n)&&this.#e(s),s}#e(e,t){let n=Vr(t);this.logger.debug(`${n}Encoding value of type ${typeof e} with size ${e.byteLength??e.size??e.length}`)}},Vt=class r extends He{constructor(...e){super(...e)}canEncode(e,t){return super.canEncode(e,t)&&e==="string"}async encode(e,t,n){if(e=await e,!Gr(n)&&this.logger.enabledFor("debug")){let s=Vr(n),i=this.logger.enabledFor("trace");this.logger.debug(`${s}Writing ${i?`${e}`:`${e.substring(0,100)}...`}`)}return e}static textPlainOnly(){return new r(mr("text","plain","utf-8"))}static allMimeTypes(){return new r(mr("text","plain","utf-8"),Le)}};var le=class{log=w("http.codec");#e=!1;set enableLoggingRequestDetails(e){this.#e=e}get enableLoggingRequestDetails(){return this.#e}};var Ye=class r extends le{static MEDIA_TYPES=Object.freeze([A.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")}},Ke=class extends le{getReadableMediaTypes(){return[A.MULTIPART_FORM_DATA]}canRead(e,t){return e==="string"||e.name===File.name&&(t===void 0||re(A.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 Qe=class r{#e;#t;#r;constructor(e){r.initLogger(e),this.#e=e,this.#t=A.asMediaTypes(...e.encodableMimeTypes()),this.#r=this.#t.find(t=>gr(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 He}#n(e,t){let n=fe(e.headers);if(n)return n;let s=this.#r;n=vo(t,s)?s:t,n&&(n=Eo(n,s),e.headers.set("Content-Type",n.toString()))}};function Eo(r,e){if(!r.params.has("charset")&&e!==void 0){let t=e.params.get("charset");if(t){let n=A.parseMediaType(r.toString());return n.params.set("charset",t),n}}return r}function vo(r,e){return(r===void 0||!gr(r)||r.essence===A.APPLICATION_OCTET_STREAM.essence)&&e!==void 0}var zr=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 Ke;this.addCodec(this.#i,e),this.addCodec(this.#i,new Ye(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 Qe(new Gt)),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 Qe(Vt.allMimeTypes())),e}addCodec(e,t){this.#c(t),e.push(t)}#c(e){if(e instanceof Qe&&(e=e.encoder),e===void 0)return;let t=this.#t,n=this.#r;n!==void 0&&(e instanceof Ye&&(e.enableLoggingRequestDetails=n),e instanceof Ke&&(e.enableLoggingRequestDetails=n))}},jr=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}},Xr=class extends zr{},Jr=class extends jr{constructor(){super(new Xr)}};function Po(){return new Jr}var Me={serverConfigurer:{create:Po}};import{createServer as Co}from"node:net";function xo({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=Co(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 ms({options:r,logger:e,shutdown:t,info:n}){xo({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()}})}import As from"@interopio/gateway-server/package.json"with{type:"json"};import{resolve as Ao}from"node:path";import{access as Ro,readFile as To}from"node:fs/promises";import{constants as Ho}from"node:fs";async function Mo(r){if(r)for(let e of r){let t=Ao(e,"index.html");try{return await Ro(t,Ho.R_OK),t}catch{}}}async function Yr(r){let e=await Mo(r),t=qe({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(To(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()}}import{AsyncLocalStorage as ko}from"node:async_hooks";function Kr(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 ys(r,e){return Kr(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 Qr=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=Me.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 pt(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(ys(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))})}},zt=class r{#e;#t=[];#r=[];#n=[];#s;#i=new ko;#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 Wt(this.#e,...this.#t);t=new kt(t,...this.#r);let n=new Qr(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 jt={create:(r,e)=>new en(r,e)},Zr=class{#e;constructor(e){this.#e=e}accept(){return A.parseMediaTypes(...this.#e.list("accept"))}contentLength(){let e=this.#e.one("content-length");return e!==void 0?Number.parseInt(e):void 0}contentType(){return fe(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}},en=class{exchange;messageReaders;#e;constructor(e,t){this.exchange=e,this.messageReaders=[...t],this.#e=new Zr(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 E=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 E{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 ke=class extends E{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 E.WILDCARD_WEIGHT}toString(){return"Wildcard(*)"}};var K=class extends E{#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=E.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===E.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 E{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 Xt=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?Ze.EMPTY:new Ze(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:""}},Ze=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})`}},Jt=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 ke&&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 Xt(e,!1);return this.#i.matches(0,t)}matchAndExtract(e){if(this.#i===void 0)return this.#h(e)&&!this.#p(e)?void 0:Ze.EMPTY;if(!this.#h(e))if(this.#i instanceof Q||this.#i instanceof K)e=r.#e;else return;let t=new Xt(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=Ue(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}};import{format as Wo}from"node:util";var 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"},H=class r extends Error{position;messageType;inserts;#e;static formatMessage(e,t){return Wo(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 Yt=class extends E{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 E.CAPTURE_VARIABLE_WEIGHT}toString(){return`CaptureVariable({${this.variableName}${this.#e?":"+this.#e.source:""}})`}};var Kt=class extends E{#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 et=class extends E{#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),v=m.indexOf(":"),l,h;v!==-1?(l=m.substring(0,v),h=m.substring(v+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:E.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*E.CAPTURE_VARIABLE_WEIGHT+this.wildcardCount*E.WILDCARD_WEIGHT}toString(){return`Regex(${String.fromCharCode(...this.#e)})`}};var Qt=class extends E{#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 Zt=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 H.create(this.#n,this.#t,"ILLEGAL_NESTED_CAPTURE");this.#c=!0,this.#u=this.#n}else if(t===125){if(!this.#c)throw H.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 H.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 H.create(this.#n,this.#t,"ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR",String.fromCharCode(t))}}this.#n++}return this.#a!==-1&&this.#m(this.#y()),new Jt(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 H.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 Yt(this.#a,this.#g(),this.#e.caseSensitive,t)}catch(n){throw n instanceof SyntaxError?H.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 H.create(this.#a,this.#t,"CAPTURE_ALL_IS_STANDALONE_CONSTRUCT");let n=new et(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 ke(this.#a,t):e=new et(this.#a,this.#g(),this.#e.caseSensitive,this.#t,t):this.#s!==0?e=new Kt(this.#a,this.#g(),this.#s,this.#e.caseSensitive,t):e=new Qt(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 H.create(this.#n,this.#t,"MISSING_REGEX_CONSTRAINT");return}t--}if(s==this.#e.pathOptions.separator&&!n)throw H.create(this.#n,this.#t,"MISSING_CLOSE_CAPTURE");this.#n++,n=!1}throw H.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 H.create(this.#n,this.#t,"CANNOT_HAVE_MANY_MULTISEGMENT_PATH_ELEMENTS");if(e>1&&t!==this.#r-1)throw H.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 H.create(e,this.#t,"ILLEGAL_DOUBLE_CAPTURE",t);this.#p.push(t)}};var er=class r{#e=!0;#t=br;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 Zt(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 bs=w("web.async.fn.router"),tn="io.interop.web.async.fn.router.request",rn="io.interop.web.async.fn.router.variables",ws="io.interop.web.async.fn.router.pattern";function Ss(r){let e={route:r,and:t=>Fo(e,t)};return e}function Fo(r,e){return Ss(async t=>{let n=r.route(t);return n!==void 0?n:e.route(t)})}function Es(r,e){return Ss(async t=>{if(r.test(t)){if(bs.enabledFor("trace")){let n=t.exchange.logPrefix;bs.debug(`${n}Matched ${r}`)}return e}else return})}var vs=(function(){let r=w("request.predicates");function e(l){if(X(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),S=h.has(b);return u("Method",`[${[...h].join(", ")}]`,b,S),S};return p.toString=()=>`[${l.join(", ")}]`,t(p)}function c(l){let h=er.DEFAULT;return l=h.initFullPathPattern(l),d(h)(l)}function d(l){return h=>{let p=l.parse(h),g=b=>{let S=b.requestPath.pathWithinApplication,T=p.matchAndExtract(S);return u("Pattern",p.patternString,S.value,T!==void 0),T!==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=>X(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=[A.ALL]:vn(g),g}if(l.length===1){let p=l[0],g=b=>{let S=h(b),T=!1;for(let L of S)if(re(L,p)){T=!0;break}return u("Accept",p,S,T),T};return g.toString=()=>`Accept: ${p}`,f(g)}else{let p=g=>{let b=h(g),S=!1;e:for(let T of b)for(let L of l)if(re(T,L)){S=!0;break e}return u("Accept",l,b,S),S};return p.toString=()=>`Accept: ${l.join(", ")}`,f(p)}}function v(l,h){let p=typeof h=="string"?h:void 0,g=typeof h=="string"?S=>S===p:h,b=S=>{let T=S.queryParam(l);return T!=null&&g(T)};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:v}})();async function Do(r){return tr(r.statusCode).headers(e=>{for(let t of r.headers.keys())e.add(t,r.headers.list(t))}).bodyValue(r.body)}function tr(r){return r=typeof r=="number"?at(r):r,new nn(r)}function $o(){return tr(y.OK)}function Uo(r){return tr(y.CREATED).location(r)}var Ps={from:Do,status:tr,ok:$o,created:Uo};function No(r,e,t,n){let s=fe(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 nn=class{#e;#t=new x;#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 on(this.#e,this.#t,new Map(this.#r),e,t,new Map(this.#n)))}build(e){return e?Promise.resolve(new sn(this.#e,this.#t,this.#r,e)):this.build(async(t,n)=>{await t.response.end()})}},We=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 sn=class extends We{#e;constructor(e,t,n,s){super(e,t,n),this.#e=s}async writeInternal(e,t){await this.#e(e,t)}},on=class extends We{#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(Bt,e.logPrefix),await this.inserter(e.response,{messageWriters:t,serverRequest:e.request,hints:this.hints})}};import{MIMEType as _o}from"node:util";var rr=class r extends Error{#e;#t=new x;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 rr{#e;constructor(e,t){super(e,r.problemDetailFor(e,t)),this.#e=t}get reason(){return this.#e}get headers(){return Cn}};var tt=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)}},an=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=jt.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 Kr(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)}},nr=class r extends an{static#e=new tt;static#t={includes:["status"]};constructor(e,t,n,s={}){super(e,t,n)}getRoutingFunction(e){return Es(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,Le),n=this.#s(e,t);return Ps.status(n).contentType(new _o("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 Cs="io.interop.web.async.handler.handler",xs="io.interop.web.async.handler.pattern";var sr=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(X(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}}},ir=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)||X(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 or=class{supports(e){return typeof e=="function"}async handle(e,t){let n=t,s=e.attribute(tn);if(!s)throw new Error("ServerRequest is not found in exchange attributes.");return n(s).then(i=>({handler:t,returnValue:i}))}},ar=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 We}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})}},cr=class extends ir{#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=Me.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=jt.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(tn,t),e.set(Cs,n);let s=e.get(ws);s&&e.set(xs,s);let i=e.get(rn);i!==void 0&&e.set(rn,i)}};var R=w("app");async function zo(r,e){let t=r.build();return async(n,s)=>{n.socket.addListener("error",e);let i;s instanceof ge?i=s:(n.upgradeHead=s,i=new ge(n),i.assignSocket(n.socket));try{let o=new me(n),a=new ut(i),c=o.method==="HEAD"?new Dt(a):a,d=t(o,c);try{await d,R.enabledFor("trace")&&R.debug(`${o.id} handling completed.`)}catch(u){if(u instanceof Error&&u.code==="ERR_INVALID_URL")throw u;R.enabledFor("trace")&&R.debug(`${o.id} failed to complete: ${u instanceof Error?u.message:u}`)}}catch(o){if(o instanceof Error&&o.code==="ERR_INVALID_URL")return R.enabledFor("debug")&&R.debug(`failed to get request URI: ${o.message}`),i.statusCode=400,i.end(Rs.STATUS_CODES[400]),Promise.resolve();throw o}}}function jo(r){return new Promise((e,t)=>{let n=r(s=>{s?t(s):e(n)})})}function Xo(r){if(r)return Hn({memoryLimit:r.memory_limit,dumpLocation:r.dump_location,dumpPrefix:r.dump_prefix,reportInterval:r.report_interval,maxBackups:r.max_backups})}var Ts=`${As.name} - v${As.version}`;async function Jo(r){let e=r.storage,t=await ls(r),n=ps(r),s=Me.serverConfigurer.create();s.defaultCodecs.enableLoggingRequestDetails(!0);let i=new cr,o=new sr([i],[new or],[new ar(s.writers)]),a={handle:bn(kn(Ts,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 Yr(r.resourcesConfig?.locations),async({response:c},d)=>{throw new Z(y.NOT_FOUND)})};return new zt(a).filter(new It(t)).codecConfigurer(s).exceptionHandler(new nr(s.readers,s.writers,new tt)).storage(e)}var cn=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)=>Go.createServer({...h,...gs(e,n)},p):(h,p)=>Rs.createServer(h,p),i=Xo(r.memory),o={middleware:[],corsConfig:r.cors,cors:[],authConfig:r.auth,authorize:[],storage:new Vo,sockets:new Map,resourcesConfig:r.resources},a=new rt({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 Ar(async p=>{p.socket({path:h,factory:pn.bind(a),options:r.gateway})},r,o)}r.app&&await Ar(r.app,r,o);let c=dn(r.port??0),d=h=>R.error(`socket error: ${h}`,h),u=await Jo(o),f=await zo(u,d),v=await new Promise((h,p)=>{let g=s({IncomingMessage:ct,ServerResponse:ge,...r.http},f);g.on("error",b=>{if(b.code==="EADDRINUSE"){R.debug(`port ${b.port} already in use on address ${b.address}`);let{value:S}=c.next();S?(R.info(`retry starting server on port ${S} and host ${t??"<unspecified>"}`),g.close(),g.listen(S,t)):(R.warn(`all configured port(s) ${r.port} are in use. closing...`),g.close(),p(b))}else R.error(`server error: ${b.message}`,b),p(b)}),g.on("listening",async()=>{let b=g.address();for(let[S,T]of o.sockets){let L=`${e?"wss":"ws"}://${un}:${b.port}${S}`;await fs(S,T,L,o.storage,d)}R.info(`http server listening on ${e?"https":"http"}://${ee(b)}`),h(g)}),g.on("upgrade",(b,S,T)=>{try{f(b,T)}catch(L){R.error(`upgrade error: ${L}`,L)}}).on("close",async()=>{R.info("http server closed.")});try{let{value:b}=c.next();g.listen(b,t)}catch(b){R.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=v.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){R.warn(`error closing route ${h}`,g)}await jo(h=>{v.closeAllConnections(),v.close(h)}),i&&await Mn(i),await a.stop()}};return r.management?.server.path&&ms({options:r.management.server,info:async()=>({pid:process.pid,type:"gateway-server",...l.gateway.info()}),logger:R.child("management"),shutdown:r.management.commands?.shutdown.enabled?async()=>{R.enabledFor("info")&&R.info("stopping gateway-server..."),await l.close()}:void 0}),l};var Cp=cn;export{Hs as GatewayServer,Cp as default};
|
|
8
22
|
//# sourceMappingURL=index.js.map
|