@interopio/gateway-server 0.19.2 → 0.19.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/web/test.js CHANGED
@@ -1,3 +1,3 @@
1
- import{isIP as ue}from"node:net";import{Cookie as W}from"tough-cookie";function le(r,e){let t=r.get("x-forwarded-host");if(Array.isArray(t)&&(t=t[0]),t){let s=r.one("x-forwarded-port");s&&(t=`${t}:${s}`)}return t??=r.one("host"),Array.isArray(t)&&(t=t[0]),t?t.split(",",1)[0].trim():e}function pe(r){let e=r.one("x-forwarded-ssl");return typeof e=="string"&&e.toLowerCase()==="on"}function he(r,e){let t=r.get("x-forwarded-proto");return Array.isArray(t)&&(t=t[0]),t!==void 0?t.split(",",1)[0].trim():pe(r)?"https":e}function me(r,e,t){let s=t?t.port:r.protocol==="https:"?443:80,n=e.one("x-forwarded-for");if(Array.isArray(n)&&(n=n[0]),n!==void 0)return n=n.split(",",1)[0].trim(),{address:n,port:Number(s),family:ue(n)===6?"IPv6":"IPv4"}}var v=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},f=class r extends v{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 ye(this.headers)}parseHost(e){return le(this.headers,e)}parseProtocol(e){return he(this.headers,e)}parseRemoteAddress(e){return me(this.URL,this.headers,e)}},m=class extends v{get cookies(){return be(this.headers)}setCookieValue(e){return new W({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 fe(r){let e=[];{let t=0,s=0;for(let n=0;n<r.length;n++)switch(r.charCodeAt(n)){case 32:t===s&&(t=s=n+1);break;case 44:e.push(r.slice(t,s)),t=s=n+1;break;default:s=s+1;break}e.push(r.slice(t,s))}return e}function ge(r){typeof r=="string"&&(r=[r]),typeof r=="number"&&(r=[String(r)]);let e=[];if(r)for(let t of r)t&&e.push(...fe(t));return e}function ye(r){return r.list("cookie").map(e=>e.split(";").map(t=>W.parse(t))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function be(r){return r.list("set-cookie").map(e=>{let t=W.parse(e);if(t){let s={name:t.key,value:t.value,maxAge:Number(t.maxAge??-1)};return t.httpOnly&&(s.httpOnly=!0),t.domain&&(s.domain=t.domain),t.path&&(s.path=t.path),t.secure&&(s.secure=!0),t.httpOnly&&(s.httpOnly=!0),t.sameSite&&(s.sameSite=t.sameSite),Object.freeze(s)}}).filter(e=>e!==void 0)}var p=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 ge(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 s=super.get(e.toLowerCase());return typeof t=="string"&&(t=[t]),s&&(t=s.concat(t)),this.set(e,t),this}};var y=class extends f{constructor(e,t){super(new p),this.URL=t,this.method=e}URL;method},x=class extends m{constructor(e,t){super(t),this.statusCode=e}statusCode};var $=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},H=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 b(r){if(typeof r=="number"){if(r<100||r>999)throw new Error(`status code ${r} should be in range 100-999`);let e=H.resolve(r);return e!==void 0?e:new $(r)}return r}var D=class extends y{#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 n of this.headers.keys())if(n.toLowerCase()!=="content-length")for(let o of this.headers.list(n))t.append(n,o);this.headers.has("accept")||t.append("accept","*/*");let s=this.#e;return new Request(this.URL,{method:e,headers:t,body:s})}};function Re(r){let e=new p;for(let[t,s]of r.entries())e.add(t,s);return e}var V=class extends x{#e;constructor(e){super(b(e.status),Re(e.headers)),this.#e=e}get statusMessage(){return this.#e.statusText}get body(){return this.#e.body??void 0}blob(){return this.#e.blob()}},E=class{#e;constructor(e=globalThis.fetch){this.#e=e}async connect(e,t,s){let n=new D(e,t);await s(n);let o=n.getNativeRequest(),a=await this.#e(o);return new V(a)}};import*as w from"node:stream/web";var k=class extends y{#e;#t=()=>{throw new Error("Body not set")};constructor(e,t){super(t,e),this.#e=async s=>{let n=[];this.#t=()=>w.ReadableStream.from(n);let o=s.getReader(),a;do{let{value:i,done:c}=await o.read();a=c,i!==void 0&&n.push(i)}while(!a);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 s=e.getReader(),n;do{let{value:o,done:a}=await s.read();n=a,o!==void 0&&(yield o)}while(!n)}else{let s=await e;s!==void 0&&(yield s)}})();return this.#e(w.ReadableStream.from(t))}async end(){return await this.body(Promise.resolve())}},T=class extends m{#e;#t=w.ReadableStream.from([]);constructor(e){super(new p),this.#e=b(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=w.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 M from"node:stream/web";import Z from"node:http";var K=class extends Z.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},J=class extends Z.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}};var S=class extends m{#e=[];#t;#r="new";#s=[];setStatusCode(e){return this.#r==="committed"?!1:(this.#t=e,!0)}setRawStatusCode(e){return this.setStatusCode(e===void 0?void 0:b(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.#s.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(s=>{throw s})}catch(s){throw s}}async end(){return this.commited?Promise.resolve(!1):this.doCommit(async()=>await this.bodyInternal(Promise.resolve()))}doCommit(e){let t=this.#r,s=Promise.resolve();if(t==="new")this.#r="committing",this.#s.length>0&&(s=this.#s.reduce((n,o)=>n.then(()=>o()),Promise.resolve()).catch(n=>{this.#r==="committing"&&(this.#r="commit-action-failed")}));else if(t==="commit-action-failed")this.#r="committing";else return Promise.resolve(!1);return s=s.then(()=>{this.applyStatusCode(),this.applyHeaders(),this.applyCookies(),this.#r="committed"}),s.then(async()=>e!==void 0?await e():!0)}applyStatusCode(){}applyHeaders(){}applyCookies(){}};var P=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 S)return e.getNativeResponse();if(e instanceof r)return r.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}};var C=class{request;response;#e={};#t;#r="";constructor(e,t){this.#e[X]=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[e]}principal(){return Promise.resolve(void 0)}get logPrefix(){let e=this.attribute(X);return this.#t!==e&&(this.#t=e,this.#r=e!==void 0?`[${e}] `:""),this.#r}},X="io.interop.gateway.server.log_id";var A=class extends f{#e;#t;upgrade=!1;constructor(e,t){if(super(new p),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??"/"}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.#t!==void 0){let e=this.#t,t=(async function*(){yield await e.bytes()})();return M.ReadableStream.from(t)}}blob(){let e=this.#t;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.#t=new Blob([]);return}if(e instanceof ReadableStream){let t=[],s=e.getReader(),n=!1;for(;!n;){let{value:o,done:a}=await s.read();a?n=!0:t.push(o)}this.#t=new Blob(t)}else e=await e,typeof e=="string"?this.#t=new Blob([e],{type:"text/plain"}):this.#t=new Blob([e]);this.headers.has("content-type")||this.setHeader("Content-Type",this.#t.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}},L=class extends S{#e;#t=()=>{throw new Error("No content was written to the response body nor end was called on this response.")};constructor(){super(new p),this.#e=async e=>{let t=[],s;this.#t=()=>(s??=M.ReadableStream.from(t),s);let n=e.getReader(),o=!1;do{let{value:a,done:i}=await n.read();i?o=!0:t.push(a)}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 s=await e;s!==void 0&&(yield s)})();return this.#e(M.ReadableStream.from(t))}async end(){return this.doCommit(async()=>await new Promise((e,t)=>{this.#e(M.ReadableStream.from([]))}))}getBody(){return this.#t()}};import*as G from"@interopio/gateway/logging/core";function g(r){return G.getLogger(`gateway.server.${r}`)}import{AsyncLocalStorage as He}from"node:async_hooks";var O=class extends P{},F=class{#e;#t=!1;#r;#s;constructor(e,t){this.#e=e,this.#r=t}createExchange(e,t){return new C(e,t)}set storage(e){this.#s=e}set enableLoggingRequestDetails(e){this.#t=e}formatHeaders(e){let t="{";for(let s of e.keys())if(this.#t){let n=e.get(s);t+=`"${s}": "${n}", `}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"),s=e.response.statusCode;this.#e.debug(`${e.logPrefix}Completed ${s??"200 OK"}${t?`, headers: ${this.formatHeaders(e.response.headers)}`:""}"`)}}handleUnresolvedError(e,t){let{request:s,response:n,logPrefix:o}=e;if(n.setStatusCode(H.INTERNAL_SERVER_ERROR)){this.#e.error(`${o}500 Server Error for ${this.formatRequest(s)}`,t);return}throw this.#e.error(`${o}Error [${t.message} for ${this.formatRequest(s)}, but already ended (${n.statusCode})`,t),t}async web(e){return await this.#r(e)}async http(e,t){let s=this.createExchange(e,t),n=()=>(this.logRequest(s),this.web(s).then(()=>{this.logResponse(s)}).catch(o=>{this.handleUnresolvedError(s,o)}).then(async()=>{await s.response.end()}));await new Promise((o,a)=>{this.#s!==void 0?this.#s.run({exchange:s},()=>{n().then(()=>o()).catch(i=>a(i))}):n().then(()=>o()).catch(i=>a(i))})}},B=class{#e;#t=new He;#r;storage(e){return this.#t=e,this}httpHandlerDecorator(e){if(this.#r===void 0)this.#r=e;else{let t=this.#r;this.#r=s=>(s=t(s),e(s))}return this}constructor(e){this.#e=e}build(){let e=g("http"),t=new F(e,this.#e);this.#t!==void 0&&(t.storage=this.#t),t.enableLoggingRequestDetails=!1;let s=async(n,o)=>t.http(n,o);return this.#r?this.#r(s):s}};import we from"node:stream/web";var j=class extends Error{completedResponse;constructor(e,t={}){super(`error occurred after response was completed: ${e}`,t),this.completedResponse=e}};async function ee(){try{return await new Promise((r,e)=>{let t=new Promise((s,n)=>{Promise.resolve().then(()=>{r({promise:t,resolve:s,reject:n})})})})}catch(r){throw r}}var I=class r{static#e=g("test.http.handler.connector");#t;constructor(e){this.#t=e}async connect(e,t,s){let n=await ee(),o=await ee(),a=[void 0],i=new k(t,e),c=new L;return i.writeHandler=async d=>{this.log("Invoking HttpHandler for ",e,t);let l=await this.adoptRequest(i,d),u=this.prepareResponse(c,l);try{await this.#t(l,u),o.resolve()}catch(h){o.reject(h)}return!0},c.writeHandler=async d=>(this.log("Creating client response for ",e,t),a[0]=this.adoptResponse(c,d),!0),this.log("Writing client request for ",e,t),s(i).then(()=>{n.resolve()}).catch(d=>{n.reject(d)}),Promise.all([n.promise,o.promise]).catch(d=>{let l=a[0];throw l!==void 0?new j(l,{cause:d}):d}).then(()=>a[0]??this.adoptResponse(c,we.ReadableStream.from([])))}log(e,t,s){r.#e.enabledFor("debug")&&r.#e.debug(`${e} ${t} "${s.href}"`)}async adoptRequest(e,t){let s=e.method,n=e.URL,o=e.headers,a=e.cookies,i=new A(n,s);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")i.setHeader(c,d);else for(let l of d)i.addHeader(c,l)}return await i.writeBody(t),i}prepareResponse(e,t){return t.method==="HEAD"?new O(e):e}adoptResponse(e,t){let s=e.statusCode,n=e.headers,o=e.cookies,a=new T(s);for(let i of n.keys()){let c=n.get(i);if(c!==void 0)if(typeof c=="number"&&(c=String(c)),typeof c=="string")a.setHeader(i,c);else for(let d of c)a.addHeader(i,d)}return a.body=t,a}};import{IOGateway as te}from"@interopio/gateway";var dt=g("gateway.ws.client-verify");function re(r){if(r){let e=(r.block??r.blacklist??[]).map(te.Filtering.regexify),t=(r.allow??r.whitelist??[]).map(te.Filtering.regexify);return{non_matched:r.non_matched??"allow",missing:r.missing??"allow",allow:t,block:e}}}var Se=async r=>z();Se.toString=()=>"any-exchange";var se=Object.freeze({}),N=Object.freeze({match:!1,variables:se}),z=(r=se)=>({match:!0,variables:r}),ne=(r,e)=>{let t=e?.method,s=async n=>{let o=n.request,a=o.path;if(t!==void 0&&o.method!==t)return N;if(typeof r=="string")return a===r?z():N;{let i=r.exec(a);return i===null?N:{match:!0,variables:{...i.groups}}}};return s.toString=()=>`pattern(${r.toString()}, method=${t??"<any>"})`,s};var Ce=async({request:r})=>r.upgrade&&r.headers.one("upgrade")?.toLowerCase()==="websocket"?z():N;Ce.toString=()=>"websocket upgrade";import{IOGateway as oe}from"@interopio/gateway";async function ae(r,e,t){let s=(o,a)=>{if(a?.cors){let i=a.cors===!0?{allowOrigins:a.origins?.allow?.map(oe.Filtering.regexify),allowMethods:o.method===void 0?["*"]:[o.method],allowCredentials:a.authorize?.access!=="permitted"?!0:void 0}:a.cors,c=o.path;t.cors.push([c,i])}},n=new class{handle(...o){o.forEach(({request:a,options:i,handler:c})=>{let d=ne(oe.Filtering.regexify(a.path),{method:a.method});i?.authorize&&t.authorize.push([d,i.authorize]),s(a,i);let l=async(u,h)=>{let{match:R,variables:q}=await d(u);R?await c(u,q):await h()};t.middleware.push(l)})}socket(...o){for(let{path:a,factory:i,options:c}of o){let d=a??"/";t.sockets.set(d,{default:a===void 0,ping:c?.ping,factory:i,maxConnections:c?.maxConnections,authorize:c?.authorize,originFilters:re(c?.origins)})}}};await r(n,e)}function ie(...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,s){let n=async(o,a)=>{let i=o===e.length?s:e[o];if(i===void 0)return;let c=!1,d=!1,u=await i(a,async h=>{if(c)throw new Error("next() called multiple times");c=!0;try{return await n(o+1,h??a)}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 u};return n(0,t)}}import{AsyncLocalStorage as ve}from"node:async_hooks";function de(r){return new Q(r)}function ce(){return new U}var Y=class{#e;#t;#r;constructor(e,t,s){this.#e=e,this.#t=t,this.#r=s}fetch=async(e,t)=>{try{let s=t?.method??"GET",n=new URL(e,this.#t),o=await this.#e.connect(s,n,async d=>{let l=new Headers(t?.headers);for(let[h,R]of l.entries())d.headers.add(h,R);let u=t?.body??Promise.resolve();if(u instanceof ReadableStream)throw new Error(`Unsupported body type ${typeof t?.body} in fetch request`);if(u instanceof FormData){let h=Array.from(u.entries());u=new URLSearchParams;for(let[R,q]of h)u.append(R,q.toString())}u instanceof URLSearchParams&&(d.headers.has("content-type")||d.headers.set("content-type","application/x-www-form-urlencoded"),u=u.toString()),u instanceof Blob&&(u=await u.bytes()),typeof u=="string"&&(u=Buffer.from(u)),await d.body(u)}),a=new Headers;for(let d of o.headers.keys()){let l=o.headers.list(d);for(let u of l)a.append(d,u)}let i=o.statusCode?.value,c=await o.blob();return new Response(c,{status:i,headers:a})}catch{return Response.error()}}},U=class{#e;#t;#r="http://localhost:8080";constructor(e,t){if(!(e===void 0||t===void 0))throw new Error("You can only set either httpHandlerBuilder or connector, not both.");this.#t=t,this.#e=e}baseUrl(e){return this.#r=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 I((await this.#e).build())),e??=new E,new Y(e,this.#r,this)}},_=class{configureClient(){let e=this.initHttpHandlerBuilder();return new U(e)}async build(){return await this.configureClient().build()}},Q=class extends _{#e;constructor(e){super(),this.#e=e}async initHttpHandlerBuilder(){let e={middleware:[],corsConfig:{allowOrigin:["http://localhost:8086"]},cors:[],authConfig:{type:"none"},authorize:[],storage:new ve,sockets:new Map};await ae(this.#e,{},e);let t=ie(...e.middleware);return new B(t)}};var kt={bindToApp:de,bindToServer:ce};export{kt as TestClient};
1
+ import{isIP as ue}from"node:net";import{Cookie as W}from"tough-cookie";function le(r,e){let t=r.get("x-forwarded-host");if(Array.isArray(t)&&(t=t[0]),t){let s=r.one("x-forwarded-port");s&&(t=`${t}:${s}`)}return t??=r.one("host"),Array.isArray(t)&&(t=t[0]),t?t.split(",",1)[0].trim():e}function pe(r){let e=r.one("x-forwarded-ssl");return typeof e=="string"&&e.toLowerCase()==="on"}function he(r,e){let t=r.get("x-forwarded-proto");return Array.isArray(t)&&(t=t[0]),t!==void 0?t.split(",",1)[0].trim():pe(r)?"https":e}function me(r,e,t){let s=t?t.port:r.protocol==="https:"?443:80,n=e.one("x-forwarded-for");if(Array.isArray(n)&&(n=n[0]),n!==void 0)return n=n.split(",",1)[0].trim(),{address:n,port:Number(s),family:ue(n)===6?"IPv6":"IPv4"}}var v=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},f=class r extends v{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 ye(this.headers)}parseHost(e){return le(this.headers,e)}parseProtocol(e){return he(this.headers,e)}parseRemoteAddress(e){return me(this.URL,this.headers,e)}},m=class extends v{get cookies(){return be(this.headers)}setCookieValue(e){return new W({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 fe(r){let e=[];{let t=0,s=0;for(let n=0;n<r.length;n++)switch(r.charCodeAt(n)){case 32:t===s&&(t=s=n+1);break;case 44:e.push(r.slice(t,s)),t=s=n+1;break;default:s=s+1;break}e.push(r.slice(t,s))}return e}function ge(r){typeof r=="string"&&(r=[r]),typeof r=="number"&&(r=[String(r)]);let e=[];if(r)for(let t of r)t&&e.push(...fe(t));return e}function ye(r){return r.list("cookie").map(e=>e.split(";").map(t=>W.parse(t))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function be(r){return r.list("set-cookie").map(e=>{let t=W.parse(e);if(t){let s={name:t.key,value:t.value,maxAge:Number(t.maxAge??-1)};return t.httpOnly&&(s.httpOnly=!0),t.domain&&(s.domain=t.domain),t.path&&(s.path=t.path),t.secure&&(s.secure=!0),t.httpOnly&&(s.httpOnly=!0),t.sameSite&&(s.sameSite=t.sameSite),Object.freeze(s)}}).filter(e=>e!==void 0)}var p=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 ge(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 s=super.get(e.toLowerCase());return typeof t=="string"&&(t=[t]),s&&(t=s.concat(t)),this.set(e,t),this}};var y=class extends f{constructor(e,t){super(new p),this.URL=t,this.method=e}URL;method},x=class extends m{constructor(e,t){super(t),this.statusCode=e}statusCode};var $=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},H=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 b(r){if(typeof r=="number"){if(r<100||r>999)throw new Error(`status code ${r} should be in range 100-999`);let e=H.resolve(r);return e!==void 0?e:new $(r)}return r}var D=class extends y{#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 n of this.headers.keys())if(n.toLowerCase()!=="content-length")for(let o of this.headers.list(n))t.append(n,o);this.headers.has("accept")||t.append("accept","*/*");let s=this.#e;return new Request(this.URL,{method:e,headers:t,body:s})}};function Re(r){let e=new p;for(let[t,s]of r.entries())e.add(t,s);return e}var V=class extends x{#e;constructor(e){super(b(e.status),Re(e.headers)),this.#e=e}get statusMessage(){return this.#e.statusText}get body(){return this.#e.body??void 0}blob(){return this.#e.blob()}},E=class{#e;constructor(e=globalThis.fetch){this.#e=e}async connect(e,t,s){let n=new D(e,t);await s(n);let o=n.getNativeRequest(),a=await this.#e(o);return new V(a)}};import*as w from"node:stream/web";var k=class extends y{#e;#t=()=>{throw new Error("Body not set")};constructor(e,t){super(t,e),this.#e=async s=>{let n=[];this.#t=()=>w.ReadableStream.from(n);let o=s.getReader(),a;do{let{value:i,done:c}=await o.read();a=c,i!==void 0&&n.push(i)}while(!a);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 s=e.getReader(),n;do{let{value:o,done:a}=await s.read();n=a,o!==void 0&&(yield o)}while(!n)}else{let s=await e;s!==void 0&&(yield s)}})();return this.#e(w.ReadableStream.from(t))}async end(){return await this.body(Promise.resolve())}},T=class extends m{#e;#t=w.ReadableStream.from([]);constructor(e){super(new p),this.#e=b(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=w.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 M from"node:stream/web";import X from"node:http";var Q=class extends X.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},K=class extends X.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}};var S=class extends m{#e=[];#t;#r="new";#s=[];setStatusCode(e){return this.#r==="committed"?!1:(this.#t=e,!0)}setRawStatusCode(e){return this.setStatusCode(e===void 0?void 0:b(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.#s.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(s=>{throw s})}catch(s){throw s}}async end(){return this.commited?Promise.resolve(!1):this.doCommit(async()=>await this.bodyInternal(Promise.resolve()))}doCommit(e){let t=this.#r,s=Promise.resolve();if(t==="new")this.#r="committing",this.#s.length>0&&(s=this.#s.reduce((n,o)=>n.then(()=>o()),Promise.resolve()).catch(n=>{this.#r==="committing"&&(this.#r="commit-action-failed")}));else if(t==="commit-action-failed")this.#r="committing";else return Promise.resolve(!1);return s=s.then(()=>{this.applyStatusCode(),this.applyHeaders(),this.applyCookies(),this.#r="committed"}),s.then(async()=>e!==void 0?await e():!0)}applyStatusCode(){}applyHeaders(){}applyCookies(){}};var P=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 S)return e.getNativeResponse();if(e instanceof r)return r.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}};var C=class{request;response;#e={};#t;#r="";constructor(e,t){this.#e[J]=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[e]}principal(){return Promise.resolve(void 0)}get logPrefix(){let e=this.attribute(J);return this.#t!==e&&(this.#t=e,this.#r=e!==void 0?`[${e}] `:""),this.#r}},J="io.interop.gateway.server.log_id";var A=class extends f{#e;#t;upgrade=!1;constructor(e,t){if(super(new p),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??"/"}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.#t!==void 0){let e=this.#t,t=(async function*(){yield await e.bytes()})();return M.ReadableStream.from(t)}}blob(){let e=this.#t;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.#t=new Blob([]);return}if(e instanceof ReadableStream){let t=[],s=e.getReader(),n=!1;for(;!n;){let{value:o,done:a}=await s.read();a?n=!0:t.push(o)}this.#t=new Blob(t)}else e=await e,typeof e=="string"?this.#t=new Blob([e],{type:"text/plain"}):this.#t=new Blob([e]);this.headers.has("content-type")||this.setHeader("Content-Type",this.#t.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}},L=class extends S{#e;#t=()=>{throw new Error("No content was written to the response body nor end was called on this response.")};constructor(){super(new p),this.#e=async e=>{let t=[],s;this.#t=()=>(s??=M.ReadableStream.from(t),s);let n=e.getReader(),o=!1;do{let{value:a,done:i}=await n.read();i?o=!0:t.push(a)}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 s=await e;s!==void 0&&(yield s)})();return this.#e(M.ReadableStream.from(t))}async end(){return this.doCommit(async()=>await new Promise((e,t)=>{this.#e(M.ReadableStream.from([]))}))}getBody(){return this.#t()}};import*as Z from"@interopio/gateway/logging/core";function g(r){return Z.getLogger(`gateway.server.${r}`)}import{AsyncLocalStorage as He}from"node:async_hooks";var O=class extends P{},G=class{#e;#t=!1;#r;#s;constructor(e,t){this.#e=e,this.#r=t}createExchange(e,t){return new C(e,t)}set storage(e){this.#s=e}set enableLoggingRequestDetails(e){this.#t=e}formatHeaders(e){let t="{";for(let s of e.keys())if(this.#t){let n=e.get(s);t+=`"${s}": "${n}", `}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"),s=e.response.statusCode;this.#e.debug(`${e.logPrefix}Completed ${s??"200 OK"}${t?`, headers: ${this.formatHeaders(e.response.headers)}`:""}"`)}}handleUnresolvedError(e,t){let{request:s,response:n,logPrefix:o}=e;if(n.setStatusCode(H.INTERNAL_SERVER_ERROR)){this.#e.error(`${o}500 Server Error for ${this.formatRequest(s)}`,t);return}throw this.#e.error(`${o}Error [${t.message} for ${this.formatRequest(s)}, but already ended (${n.statusCode})`,t),t}async web(e){return await this.#r(e)}async http(e,t){let s=this.createExchange(e,t),n=()=>(this.logRequest(s),this.web(s).then(()=>{this.logResponse(s)}).catch(o=>{this.handleUnresolvedError(s,o)}).then(async()=>{await s.response.end()}));await new Promise((o,a)=>{this.#s!==void 0?this.#s.run({exchange:s},()=>{n().then(()=>o()).catch(i=>a(i))}):n().then(()=>o()).catch(i=>a(i))})}},B=class{#e;#t=new He;#r;storage(e){return this.#t=e,this}httpHandlerDecorator(e){if(this.#r===void 0)this.#r=e;else{let t=this.#r;this.#r=s=>(s=t(s),e(s))}return this}constructor(e){this.#e=e}build(){let e=g("http"),t=new G(e,this.#e);this.#t!==void 0&&(t.storage=this.#t),t.enableLoggingRequestDetails=!1;let s=async(n,o)=>t.http(n,o);return this.#r?this.#r(s):s}};import we from"node:stream/web";var F=class extends Error{completedResponse;constructor(e,t={}){super(`error occurred after response was completed: ${e}`,t),this.completedResponse=e}};async function ee(){try{return await new Promise((r,e)=>{let t=new Promise((s,n)=>{Promise.resolve().then(()=>{r({promise:t,resolve:s,reject:n})})})})}catch(r){throw r}}var I=class r{static#e=g("test.http.handler.connector");#t;constructor(e){this.#t=e}async connect(e,t,s){let n=await ee(),o=await ee(),a=[void 0],i=new k(t,e),c=new L;return i.writeHandler=async d=>{this.log("Invoking HttpHandler for ",e,t);let l=await this.adoptRequest(i,d),u=this.prepareResponse(c,l);try{await this.#t(l,u),o.resolve()}catch(h){o.reject(h)}return!0},c.writeHandler=async d=>(this.log("Creating client response for ",e,t),a[0]=this.adoptResponse(c,d),!0),this.log("Writing client request for ",e,t),s(i).then(()=>{n.resolve()}).catch(d=>{n.reject(d)}),Promise.all([n.promise,o.promise]).catch(d=>{let l=a[0];throw l!==void 0?new F(l,{cause:d}):d}).then(()=>a[0]??this.adoptResponse(c,we.ReadableStream.from([])))}log(e,t,s){r.#e.enabledFor("debug")&&r.#e.debug(`${e} ${t} "${s.href}"`)}async adoptRequest(e,t){let s=e.method,n=e.URL,o=e.headers,a=e.cookies,i=new A(n,s);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")i.setHeader(c,d);else for(let l of d)i.addHeader(c,l)}return await i.writeBody(t),i}prepareResponse(e,t){return t.method==="HEAD"?new O(e):e}adoptResponse(e,t){let s=e.statusCode,n=e.headers,o=e.cookies,a=new T(s);for(let i of n.keys()){let c=n.get(i);if(c!==void 0)if(typeof c=="number"&&(c=String(c)),typeof c=="string")a.setHeader(i,c);else for(let d of c)a.addHeader(i,d)}return a.body=t,a}};import{IOGateway as te}from"@interopio/gateway";var dt=g("gateway.ws.client-verify");function re(r){if(r){let e=(r.block??r.blacklist??[]).map(te.Filtering.regexify),t=(r.allow??r.whitelist??[]).map(te.Filtering.regexify);return{non_matched:r.non_matched??"allow",missing:r.missing??"allow",allow:t,block:e}}}var Se=async r=>z();Se.toString=()=>"any-exchange";var se=Object.freeze({}),N=Object.freeze({match:!1,variables:se}),z=(r=se)=>({match:!0,variables:r}),ne=(r,e)=>{let t=e?.method,s=async n=>{let o=n.request,a=o.path;if(t!==void 0&&o.method!==t)return N;if(typeof r=="string")return a===r?z():N;{let i=r.exec(a);return i===null?N:{match:!0,variables:{...i.groups}}}};return s.toString=()=>`pattern(${r.toString()}, method=${t??"<any>"})`,s};var Ce=async({request:r})=>r.upgrade&&r.headers.one("upgrade")?.toLowerCase()==="websocket"?z():N;Ce.toString=()=>"websocket upgrade";import{IOGateway as oe}from"@interopio/gateway";async function ae(r,e,t){let s=(o,a)=>{if(a?.cors){let i=a.cors===!0?{allowOrigins:a.origins?.allow?.map(oe.Filtering.regexify),allowMethods:o.method===void 0?["*"]:[o.method],allowCredentials:a.authorize?.access!=="permitted"?!0:void 0}:a.cors,c=o.path;t.cors.push([c,i])}},n=new class{handle(...o){o.forEach(({request:a,options:i,handler:c})=>{let d=ne(oe.Filtering.regexify(a.path),{method:a.method});i?.authorize&&t.authorize.push([d,i.authorize]),s(a,i);let l=async(u,h)=>{let{match:R,variables:q}=await d(u);R?await c(u,q):await h()};t.middleware.push(l)})}socket(...o){for(let{path:a,factory:i,options:c}of o){let d=a??"/";t.sockets.set(d,{default:a===void 0,ping:c?.ping,factory:i,maxConnections:c?.maxConnections,authorize:c?.authorize,originFilters:re(c?.origins)})}}};await r(n,e)}function ie(...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,s){let n=async(o,a)=>{let i=o===e.length?s:e[o];if(i===void 0)return;let c=!1,d=!1,u=await i(a,async h=>{if(c)throw new Error("next() called multiple times");c=!0;try{return await n(o+1,h??a)}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 u};return n(0,t)}}import{AsyncLocalStorage as ve}from"node:async_hooks";function de(r){return new _(r)}function ce(){return new U}var j=class{#e;#t;#r;constructor(e,t,s){this.#e=e,this.#t=t,this.#r=s}fetch=async(e,t)=>{try{let s=t?.method??"GET",n=new URL(e,this.#t),o=await this.#e.connect(s,n,async d=>{let l=new Headers(t?.headers);for(let[h,R]of l.entries())d.headers.add(h,R);let u=t?.body??Promise.resolve();if(u instanceof ReadableStream)throw new Error(`Unsupported body type ${typeof t?.body} in fetch request`);if(u instanceof FormData){let h=Array.from(u.entries());u=new URLSearchParams;for(let[R,q]of h)u.append(R,q.toString())}u instanceof URLSearchParams&&(d.headers.has("content-type")||d.headers.set("content-type","application/x-www-form-urlencoded"),u=u.toString()),u instanceof Blob&&(u=await u.bytes()),typeof u=="string"&&(u=Buffer.from(u)),await d.body(u)}),a=new Headers;for(let d of o.headers.keys()){let l=o.headers.list(d);for(let u of l)a.append(d,u)}let i=o.statusCode?.value,c=await o.blob();return new Response(c,{status:i,headers:a})}catch{return Response.error()}}},U=class{#e;#t;#r="http://localhost:8080";constructor(e,t){if(!(e===void 0||t===void 0))throw new Error("You can only set either httpHandlerBuilder or connector, not both.");this.#t=t,this.#e=e}baseUrl(e){return this.#r=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 I((await this.#e).build())),e??=new E,new j(e,this.#r,this)}},Y=class{configureClient(){let e=this.initHttpHandlerBuilder();return new U(e)}async build(){return await this.configureClient().build()}},_=class extends Y{#e;constructor(e){super(),this.#e=e}async initHttpHandlerBuilder(){let e={middleware:[],corsConfig:{allowOrigin:["http://localhost:8086"]},cors:[],authConfig:{type:"none"},authorize:[],storage:new ve,sockets:new Map};await ae(this.#e,{},e);let t=ie(...e.middleware);return new B(t)}};var xt={bindToApp:de,bindToServer:ce};export{xt as TestClient};
3
3
  //# sourceMappingURL=test.js.map