UNPKG

@interopio/gateway-server

Version:

[![npm version](https://img.shields.io/npm/v/@interopio/gateway-server.svg)](https://www.npmjs.com/package/@interopio/gateway-server)

15 lines (14 loc) 36.5 kB
import{isIP as Ze}from"node:net";import{Cookie as ie}from"tough-cookie";function et(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 tt(r){let e=r.one("x-forwarded-ssl");return typeof e=="string"&&e.toLowerCase()==="on"}function rt(r,e){let t=r.get("x-forwarded-proto");return Array.isArray(t)&&(t=t[0]),t!==void 0?t.split(",",1)[0].trim():tt(r)?"https":e}function nt(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:Ze(s)===6?"IPv6":"IPv4"}}var N=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},w=class r extends N{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 st(this.headers)}parseHost(e){return et(this.headers,e)}parseProtocol(e){return rt(this.headers,e)}parseRemoteAddress(e){return nt(this.URL,this.headers,e)}},m=class extends N{get cookies(){return ot(this.headers)}setCookieValue(e){return new ie({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 st(r){return r.list("cookie").map(e=>e.split(";").map(t=>ie.parse(t))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function ot(r){return r.list("set-cookie").map(e=>{let t=ie.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 it}from"node:util";import{MIMEType as ae}from"node:util";var y="*",de=new ae(`${y}/${y}`),ce="application/octet-stream",Mt=new ae(ce);function B(r){return r.type===y}function R(r){return r.subtype===y||r.subtype.startsWith(`${y}+`)}function le(r){return!B(r)&&!R(r)}var q=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 pe(r,e,t){let n=`${r}/${e}`,s;try{s=new ae(n)}catch(o){throw new q(n,void 0,{cause:o})}return t&&s.params.set("charset",t),s}function Ae(r){let e=r.subtype.lastIndexOf("+");return e!==-1&&e<r.subtype.length?r.subtype.substring(e+1):null}function M(r,e){if(!e)return!1;if(B(r)||B(e))return!0;if(r.type===e.type){if(r.subtype===e.subtype)return!0;if(R(r)||R(e)){let t=Ae(r),n=Ae(e);if(r.subtype===y||e.subtype===y)return!0;if(R(r)&&n!==null)return t===e.subtype||t===n;if(R(e)&&t!==null)return r.subtype===n||n===t}}return!1}var at=` application/octet-stream bin dms lrf mar so dist distz pkg bpk dump elc deploy application/json json application/wasm wasm application/x-pkcs12 p12 pfx text/css css text/csv csv text/html html htm text/javascript js mjs text/plain txt text conf def list log in `,u=class r extends it{static ALL=new r("*/*");static APPLICATION_OCTET_STREAM=new r(ce);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),Le(t)||this.#t(t),e===r.#e){let n=Ie(t),s=parseFloat(n);if(isNaN(s)||s<0||s>1)throw new U(`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 U(`Invalid token: ${e}`)}}get quality(){let e=this.params.get(r.#e);return e!==null?parseFloat(Ie(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))}},U=class extends Error{constructor(e){super(e)}},Pt=(function(){let e=new Map;for(let t of at.trim().split(` `)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.split(/\s+/);if(s.length<2)continue;let[o,...i]=s,a=u.parseMediaType(o);for(let c of i){let d="."+c.toLowerCase(),p=e.get(d);p?p.push(a):e.set(d,[a])}}return e})();function Le(r){return r.length>=2&&(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))}function Ie(r){return Le(r)?r.substring(1,r.length-1):r}function dt(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 ct(r){typeof r=="string"&&(r=[r]),typeof r=="number"&&(r=[String(r)]);let e=[];if(r)for(let t of r)t&&e.push(...dt(t));return e}var h=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 ct(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}},It=new h;function We(r){let e=r.one("content-type");return e?u.parseMediaType(e):void 0}var C=class extends w{constructor(e,t){super(new h),this.URL=t,this.method=e}URL;method},D=class extends m{constructor(e,t){super(t),this.statusCode=e}statusCode};var ue=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},x=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 H(r){if(typeof r=="number"){if(r<100||r>999)throw new Error(`status code ${r} should be in range 100-999`);let e=x.resolve(r);return e!==void 0?e:new ue(r)}return r}var he=class extends C{#e;constructor(e,t){super(e,t)}async body(e){return this.#e=e instanceof ReadableStream?e:await e,await this.end()}end(){return Promise.resolve(!0)}getNativeRequest(){let e=this.method,t=new Headers;for(let s of this.headers.keys())if(s.toLowerCase()!=="content-length")for(let o of this.headers.list(s))t.append(s,o);this.headers.has("accept")||t.append("accept","*/*");let n=this.#e;return new Request(this.URL,{method:e,headers:t,body:n})}};function lt(r){let e=new h;for(let[t,n]of r.entries())e.add(t,n);return e}var fe=class extends D{#e;constructor(e){super(H(e.status),lt(e.headers)),this.#e=e}get statusMessage(){return this.#e.statusText}get body(){return this.#e.body??void 0}blob(){return this.#e.blob()}},F=class{#e;constructor(e=globalThis.fetch){this.#e=e}async connect(e,t,n){let s=new he(e,t);await n(s);let o=s.getNativeRequest(),i=await this.#e(o);return new fe(i)}};import*as E from"node:stream/web";var $=class extends C{#e;#t=()=>{throw new Error("Body not set")};constructor(e,t){super(t,e),this.#e=async n=>{let s=[];this.#t=()=>E.ReadableStream.from(s);let o=n.getReader(),i;do{let{value:a,done:c}=await o.read();i=c,a!==void 0&&s.push(a)}while(!i);return!0}}set writeHandler(e){this.#e=e}getNativeRequest(){return this}getBody(){return this.#t()}body(e){let t=(async function*(){if(e instanceof ReadableStream){let n=e.getReader(),s;do{let{value:o,done:i}=await n.read();s=i,o!==void 0&&(yield o)}while(!s)}else{let n=await e;n!==void 0&&(yield n)}})();return this.#e(E.ReadableStream.from(t))}async end(){return await this.body(Promise.resolve())}},V=class extends m{#e;#t=E.ReadableStream.from([]);constructor(e){super(new h),this.#e=H(e)}get statusCode(){return this.#e}addHeader(e,t){return this.headers.add(e,t),this}setHeader(e,t){return this.headers.set(e,t),this}setBody(e,t){return this.#t=E.ReadableStream.from([Buffer.from(e,t)]),this}set body(e){this.#t=e}get body(){return this.#t}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"})}};import Ue from"node:http";function ge(r,e,t){let n=r.elements;if(t=t??n.length,e===0&&t===n.length)return r;if(e===t)return P.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),o=s.map(i=>i.value).join("");return new P(o,s)}var pt={separator:47,decodeAndParseParameters:!0};function z(r,e){return P.createFromUrlPath(r,e??pt)}var P=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 o=[],i;for(e.charCodeAt(0)===n?(i=1,o.push(s)):i=0;i<e.length;){let a=-1;for(let d=i;d<e.length;d++)if(e.charCodeAt(d)===n){a=d;break}let c=a!==-1?e.substring(i,a):e.substring(i);if(c.length>0&&o.push(t.decodeAndParseParameters?r.#n(c):v.from(c,s)),a===-1)break;o.push(s),i=a+1}return new r(e,o)}static#n(e){let t=e.indexOf(";");if(t===-1){let n=decodeURIComponent(e);return v.from(e,n)}else{let n=decodeURIComponent(e.substring(0,t)),s=e.substring(t),o=r.#s(s);return v.from(e,n,o)}}static#s(e){let t=new Map,n=1;for(;n<e.length;){let s=-1;for(let i=n;i<e.length;i++)if(e.charAt(i)===";"){s=i;break}let o=s!==-1?e.substring(n,s):e.substring(n);if(r.#o(o,t),s===-1)break;n=s+1}if(t.size>0)for(let s of t.values())Object.freeze(s);return t}static#o(e,t){if(e){let n=e.indexOf("=");if(n!==-1){let s=decodeURIComponent(e.substring(0,n));if(s.trim()){let o=e.substring(n+1);for(let i of o.split(",")){let a=t.get(s);a!==void 0?a.push(decodeURIComponent(i)):t.set(s,[decodeURIComponent(i)])}}}else{let s=decodeURIComponent(e);if(s.trim()){let o=t.get(s);o!==void 0?o.push(""):t.set(s,[""])}}}}},v=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,o=e.includes(s.encoded)?e.replaceAll(s.encoded,s.value):e;return r.from(e,o,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 Oe(r,e){return typeof r=="string"?me.parse(r,e):Oe(r.href,e)}var me=class r{static#e(e,t){if(!(t&&t.trim())||t.charAt(0)!=="/")return z("");r.#t(e.value,t);let n=t.length,s=0;for(let o=0;o<e.elements.length;o++){let i=e.elements[o];if(s+=i.value.length,n===s)return ge(e,0,o+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 ge(e,n)}static parse(e,t){let n=z(e),s=r.#e(n,t),o=r.#r(n,s);return new r(z(e),s,o)}#n;#s;#o;constructor(e,t,n){this.#n=e,this.#s=t,this.#o=n}get value(){return this.#n.value}get elements(){return this.#n.elements}get contextPath(){return this.#s}get pathWithinApplication(){return this.#o}modifyContextPath(e){let t=r.#e(this,e),n=r.#r(this,t);return new r(this,t,n)}toString(){return this.#n.toString()}},k=class extends w{#e;#t;#r;get requestPath(){return this.#t===void 0&&(this.#t=Oe(this.URL.pathname,this.#r)),this.#t}get sslInfo(){return this.#e===void 0&&(this.#e=this.initSslInfo()),this.#e}};var Ne=class extends Ue.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},Be=class extends Ue.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},A=class extends m{#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:H(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,o)=>s.then(()=>o()),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(){}};var j=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 A)return e.getNativeResponse();if(e instanceof r)return r.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}};var I=class{request;response;#e=new Map;#t;#r="";constructor(e,t,n){this.#e[qe]=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(qe);return this.#t!==e&&(this.#t=e,this.#r=e!==void 0?`[${e}] `:""),this.#r}},qe="io.interop.web.server.exchange.log_id";import*as De from"@interopio/gateway/logging/core";function f(r){return De.getLogger(`gateway.server.${r}`)}function ye(r){return r?.get("io.gateway.logging.suppress")===!0}var Fe="io.gateway.logging.prefix";function be(r){return r?.has(Fe)?r.get(Fe)??"":""}var S=class{#e;logger=f("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(M(t,n))return!0;return!1}},G=class extends S{constructor(){super(de)}canEncode(e,t){return super.canEncode(e,t)}async encode(e,t,n){let s=await e;return this.logger.enabledFor("debug")&&!ye(n)&&this.#e(s),s}#e(e,t){let n=be(t);this.logger.debug(`${n}Encoding value of type ${typeof e} with size ${e.byteLength??e.size??e.length}`)}},Y=class r extends S{constructor(...e){super(...e)}canEncode(e,t){return super.canEncode(e,t)&&e==="string"}async encode(e,t,n){if(e=await e,!ye(n)&&this.logger.enabledFor("debug")){let s=be(n),o=this.logger.enabledFor("trace");this.logger.debug(`${s}Writing ${o?`${e}`:`${e.substring(0,100)}...`}`)}return e}static textPlainOnly(){return new r(pe("text","plain","utf-8"))}static allMimeTypes(){return new r(pe("text","plain","utf-8"),de)}};var b=class{log=f("http.codec");#e=!1;set enableLoggingRequestDetails(e){this.#e=e}get enableLoggingRequestDetails(){return this.#e}};var L=class r extends b{static MEDIA_TYPES=Object.freeze([u.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(M(t,e))return!0;return!1}async readPromise(e,t,n){let s=this.#e.read(e,t,n),o=new FormData;for await(let[i,a]of s)o.append(i,a);return o}read(e,t,n){throw new Error("not implemented yet")}},W=class extends b{getReadableMediaTypes(){return[u.MULTIPART_FORM_DATA]}canRead(e,t){return e==="string"||e.name===File.name&&(t===void 0||M(u.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 O=class r{#e;#t;#r;constructor(e){r.initLogger(e),this.#e=e,this.#t=u.asMediaTypes(...e.encodableMimeTypes()),this.#r=this.#t.find(t=>le(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,o){let i=this.#n(n,s),a=this.#e.encode(e,i,o);await n.body(a)}static initLogger(e){e instanceof S}#n(e,t){let n=We(e.headers);if(n)return n;let s=this.#r;n=ht(t,s)?s:t,n&&(n=ut(n,s),e.headers.set("Content-Type",n.toString()))}};function ut(r,e){if(!r.params.has("charset")&&e!==void 0){let t=e.params.get("charset");if(t){let n=u.parseMediaType(r.toString());return n.params.set("charset",t),n}}return r}function ht(r,e){return(r===void 0||!le(r)||r.essence===u.APPLICATION_OCTET_STREAM.essence)&&e!==void 0}var we=class{#e;#t;#r;#n=!0;#s=Array();#o=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.#o.length=0,!!this.#n)if(this.#e!==void 0)this.addCodec(this.#o,this.#e);else{let e=new W;this.addCodec(this.#o,e),this.addCodec(this.#o,new L(e))}}initWriters(){this.#s.length=0,this.#n&&(this.#s.push(...this.#i()),this.extendWriters(this.#s))}extendWriters(e){}#i(){if(!this.#n)return[];let e=Array();return this.addCodec(e,new O(new G)),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.#o}get catchAllWriters(){if(!this.#n)return[];let e=Array();return this.addCodec(e,new O(Y.allMimeTypes())),e}addCodec(e,t){this.#a(t),e.push(t)}#a(e){if(e instanceof O&&(e=e.encoder),e===void 0)return;let t=this.#t,n=this.#r;n!==void 0&&(e instanceof L&&(e.enableLoggingRequestDetails=n),e instanceof W&&(e.enableLoggingRequestDetails=n))}},Re=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}},Ce=class extends we{},He=class extends Re{constructor(){super(new Ce)}};function ft(){return new He}var Se={serverConfigurer:{create:ft}};import Q from"node:stream/web";var _=class r extends k{#e;#t;#r;upgrade=!1;constructor(e,t){if(super(new h),typeof e=="string")if(URL.canParse(e))e=new URL(e);else if(URL.canParse(e,"http://localhost"))e=new URL(e,"http://localhost");else throw new TypeError("URL cannot parse url");this.#e=e,this.method=t??"GET",this.setHeader("Host",this.#e.hostname),this.path=this.#e.pathname??"/"}static get(e){return new r(e,"GET")}static post(e){return new r(e,"POST")}static options(e){return new r(e,"OPTIONS")}initSslInfo(){return this.#t}getNativeRequest(){throw new Error("This is a mock. No running server, no native request available.")}method;path;get host(){return super.parseHost(this.#e.host)}get protocol(){return super.parseProtocol(this.#e.protocol.slice(0,-1))}get body(){if(this.#r!==void 0){let e=this.#r,t=(async function*(){yield await e.bytes()})();return Q.ReadableStream.from(t)}}blob(){let e=this.#r;return e?Promise.resolve(e):Promise.reject(new Error("no body set"))}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)}async writeBody(e){if(e===void 0){this.#r=new Blob([]);return}if(e instanceof ReadableStream){let t=[],n=e.getReader(),s=!1;for(;!s;){let{value:o,done:i}=await n.read();i?s=!0:t.push(o)}this.#r=new Blob(t)}else e=await e,typeof e=="string"?this.#r=new Blob([e],{type:"text/plain"}):this.#r=new Blob([e]);this.headers.has("content-type")||this.setHeader("Content-Type",this.#r.type||"application/octet-stream")}get URL(){return new URL(this.path+this.#e.search+this.#e.hash,`${this.protocol}://${this.host}`)}addHeader(e,t){return this.headers.add(e,t),this}setHeader(e,t){return this.headers.set(e,t),this}},X=class extends A{#e;#t=()=>{throw new Error("No content was written to the response body nor end was called on this response.")};constructor(){super(new h),this.#e=async e=>{let t=[],n;this.#t=()=>(n??=Q.ReadableStream.from(t),n);let s=e.getReader(),o=!1;do{let{value:i,done:a}=await s.read();a?o=!0:t.push(i)}while(!o);return!0}}get statusCode(){return super.statusCode}set writeHandler(e){this.#t=()=>{throw new Error("Not available with custom write handler")},this.#e=e}getNativeResponse(){throw new Error("This is a mock. No running server, no native response.")}applyStatusCode(){}applyHeaders(){}applyCookies(){for(let e of this.cookies)this.headers.add("Set-Cookie",super.setCookieValue(e))}bodyInternal(e){let t=(async function*(){let n=await e;n!==void 0&&(yield n)})();return this.#e(Q.ReadableStream.from(t))}async end(){return this.doCommit(async()=>await this.#e(Q.ReadableStream.from([])))}getBody(){return this.#t()}};var J=class extends j{};import gt from"node:stream/web";var Te=class extends Error{completedResponse;constructor(e,t={}){super(`error occurred after response was completed: ${e}`,t),this.completedResponse=e}};async function $e(){try{return await new Promise((r,e)=>{let t=new Promise((n,s)=>{Promise.resolve().then(()=>{r({promise:t,resolve:n,reject:s})})})})}catch(r){throw r}}var K=class r{static#e=f("test.http.handler.connector");#t;#r;constructor(e,t){this.#t=e,this.#r=t}async connect(e,t,n){let s=await $e(),o=await $e(),i=[void 0],a=new $(t,e),c=new X;return a.writeHandler=async d=>{this.log("Invoking HttpHandler for ",e,t);let p=await this.adoptRequest(a,d),l=this.prepareResponse(c,p);try{await this.#t(p,l),o.resolve()}catch(g){o.reject(g)}return!0},c.writeHandler=async d=>(this.log("Creating client response for ",e,t),i[0]=this.adoptResponse(c,d),!0),this.log("Writing client request for ",e,t),n(a).then(()=>{s.resolve()}).catch(d=>{s.reject(d)}),Promise.all([s.promise,o.promise]).catch(d=>{let p=i[0];throw p!==void 0?new Te(p,{cause:d}):d}).then(()=>i[0]??this.adoptResponse(c,gt.ReadableStream.from([])))}log(e,t,n){r.#e.enabledFor("debug")&&r.#e.debug(`${e} ${t} "${n.href}"`)}async adoptRequest(e,t){let n=e.method,s=e.URL,o=e.headers,i=e.cookies,a=new _(s,n);for(let c of o.keys()){let d=o.get(c);if(d!==void 0)if(typeof d=="number"&&(d=String(d)),typeof d=="string")a.setHeader(c,d);else for(let p of d)a.addHeader(c,p)}return await a.writeBody(t),a}prepareResponse(e,t){return t.method==="HEAD"?new J(e):e}adoptResponse(e,t){let n=e.statusCode,s=e.headers,o=e.cookies,i=new V(n);for(let a of s.keys()){let c=s.get(a);if(c!==void 0)if(typeof c=="number"&&(c=String(c)),typeof c=="string")i.setHeader(a,c);else for(let d of c)i.addHeader(a,d)}return i.body=t,i}};import{IOGateway as Ve}from"@interopio/gateway";var Ur=f("gateway.ws.client-verify");function ze(r){if(r){let e=(r.block??r.blacklist??[]).map(Ve.Filtering.regexify),t=(r.allow??r.whitelist??[]).map(Ve.Filtering.regexify);return{non_matched:r.non_matched??"allow",missing:r.missing??"allow",allow:t,block:e}}}var mt=async r=>Me();mt.toString=()=>"any-exchange";var je=Object.freeze({}),Z=Object.freeze({match:!1,variables:je}),Me=(r=je)=>({match:!0,variables:r}),Ge=(r,e)=>{let t=e?.method,n=async s=>{let o=s.request,i=o.path;if(t!==void 0&&o.method!==t)return Z;if(typeof r=="string")return i===r?Me():Z;{let a=r.exec(i);return a===null?Z:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${r.toString()}, method=${t??"<any>"})`,n};var yt=async({request:r})=>r.upgrade&&r.headers.one("upgrade")?.toLowerCase()==="websocket"?Me():Z;yt.toString=()=>"websocket upgrade";import{IOGateway as Ye}from"@interopio/gateway";async function Qe(r,e,t){let n=(o,i)=>{if(i?.cors){let a=i.cors===!0?{allowOrigins:i.origins?.allow?.map(Ye.Filtering.regexify),allowMethods:o.method===void 0?["*"]:[o.method],allowCredentials:i.authorize?.access!=="permitted"?!0:void 0}:i.cors,c=o.path;t.cors.push([c,a])}},s=new class{handle(...o){o.forEach(({request:i,options:a,handler:c})=>{let d=Ge(Ye.Filtering.regexify(i.path),{method:i.method});a?.authorize&&t.authorize.push([d,a.authorize]),n(i,a);let p=async(l,g)=>{let{match:T,variables:oe}=await d(l);T?await c(l,oe):await g()};t.middleware.push(p)})}socket(...o){for(let{path:i,factory:a,options:c}of o){let d=i??"/";t.sockets.set(d,{default:i===void 0||i==="/",ping:c?.ping,factory:a,maxConnections:c?.maxConnections,authorize:c?.authorize,originFilters:ze(c?.origins)})}}};await r(s,e)}function _e(...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(o,i)=>{let a=o===e.length?n:e[o];if(a===void 0)return;let c=!1,d=!1,l=await a(i,async g=>{if(c)throw new Error("next() called multiple times");c=!0;try{return await s(o+1,g??i)}finally{d=!0}});if(c&&!d)throw new Error(`middleware resolved before downstream. You are probably missing an await or return statement in your middleware function.`);return l};return s(0,t)}}import{AsyncLocalStorage as Rt}from"node:async_hooks";import{AsyncLocalStorage as wt}from"node:async_hooks";function bt(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 Xe(r,e){return bt(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 ee=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}]`}},te=class extends ee{#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 o=s instanceof Error?s:new Error(String(s));await n.handle(e,o)});return t}},xe=class r{#e;#t;#r;#n;static of(e,...t){let n=[...t],s=new r(t,e),o=r.initChain(t,e);return s.#r=o.#r,s.#n=o.#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)}},re=class extends ee{#e;constructor(e,...t){super(e),this.#e=xe.of(e,...t)}get filters(){return this.#e.filters}handle(e){return this.#e.filter(e)}};var Ee=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=Se.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 b&&t.enableLoggingRequestDetails){this.#r=!0;break}}createExchange(e,t){return new I(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:o}=e;if(s.setStatusCode(x.INTERNAL_SERVER_ERROR)){this.#e.error(`${o}500 Server Error for ${this.formatRequest(n)}`,t);return}else{if(Xe(t,this.#e))return;throw this.#e.error(`${o}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(o=>{this.handleUnresolvedError(n,o)}).then(async()=>{await n.response.end()}));await new Promise((o,i)=>{this.#s!==void 0?this.#s.run({exchange:n},()=>{s().then(()=>o()).catch(a=>i(a))}):s().then(()=>o()).catch(a=>i(a))})}},ne=class r{#e;#t=[];#r=[];#n=[];#s;#o=new wt;#i;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.#o=e,this}codecConfigurer(e){return this.#i=e,this}hasCodecConfigurer(){return this.#i!==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=f("http"),t=new re(this.#e,...this.#t);t=new te(t,...this.#r);let n=new Ee(e,t);this.#o!==void 0&&(n.storage=this.#o),this.#i!==void 0&&(n.codecConfigurer=this.#i);let s=async(o,i)=>n.http(o,i);return this.#s?this.#s(s):s}};function Je(r){return new ke(r)}function Ke(){return new se}var ve=class{#e;#t;constructor(e,t,n){this.#e=e,this.#t=t}fetch=async(e,t)=>{try{let n=t?.method??"GET",s=new URL(e,this.#t),o=await this.#e.connect(n,s,async d=>{let p=new Headers(t?.headers);for(let[g,T]of p.entries())d.headers.add(g,T);let l=t?.body??Promise.resolve();if(l instanceof ReadableStream)throw new Error(`Unsupported body type ${typeof t?.body} in fetch request`);if(l instanceof FormData){let g=Array.from(l.entries());l=new URLSearchParams;for(let[T,oe]of g)l.append(T,oe.toString())}l instanceof URLSearchParams&&(d.headers.has("content-type")||d.headers.set("content-type","application/x-www-form-urlencoded"),l=l.toString()),l instanceof Blob&&(l=await l.bytes()),typeof l=="string"&&(l=Buffer.from(l)),await d.body(l)}),i=new Headers;for(let d of o.headers.keys()){let p=o.headers.get(d);if(p!==void 0){if(typeof p=="string")i.set(d,p);else if(Array.isArray(p))for(let l of p)i.append(d,l)}}let a=o.statusCode?.value,c=await o.blob();return new Response(c,{status:a,headers:i})}catch{return Response.error()}}},se=class{#e;#t;#r;#n="http://localhost:8080";constructor(e,t,n){if(!(e===void 0||t===void 0))throw new Error("You can only set either httpHandlerBuilder or connector, not both.");this.#t=t,this.#r=n,this.#e=e}baseUrl(e){return this.#n=e,this}clientConnector(e){return this.#t=e,this}async build(){let e=this.#t;return e===void 0&&this.#e!==void 0&&(e=new K((await this.#e).build(),this.#r)),e??=new F,new ve(e,this.#n,this)}},Pe=class{#e;#t=[];middleware(...e){return this.#t=[...this.#t,...e],this}sslInfo(e){return this.#e=e,this}configureClient(){let e=this.initHttpHandlerBuilder(...this.#t);return new se(e,void 0,this.#e)}async build(){return await this.configureClient().build()}},ke=class extends Pe{#e;constructor(e){super(),this.#e=e}async initHttpHandlerBuilder(...e){let t={middleware:e,corsConfig:{allowOrigin:["http://localhost:8086"]},resourcesConfig:{locations:[]},cors:[],authConfig:{type:"none"},authorize:[],storage:new Rt,sockets:new Map};await Qe(this.#e,{},t);let n={handle:_e(...t.middleware)};return ne.webHandler(n)}};var fn={bindToApp:Je,bindToServer:Ke};export{fn as TestClient}; //# sourceMappingURL=test.js.map