@hashgraph/sdk
Version:
3 lines (2 loc) • 2.61 kB
JavaScript
import{ALL_WEB_NETWORK_NODES as t}from"../constants/ClientConstants.js";import e from"../grpc/GrpcServiceError.js";import s from"../grpc/GrpcStatus.js";import r from"../http/HttpError.js";import i from"../http/HttpStatus.js";import{SDK_NAME as a,SDK_VERSION as o}from"../version.js";import n,{encodeRequest as h,decodeUnaryResponse as l}from"./Channel.js";class c extends n{constructor(t,e){super(e),this._address=t,this._isReady=!1,this._healthCheckPromise=null}_shouldUseHttps(t){return!(t.includes("localhost")||t.includes("127.0.0.1")||t.includes(".cluster.local"))}_buildUrl(t){if(t.startsWith("http://")||t.startsWith("https://"))return t;return this._shouldUseHttps(t)?`https://${t}`:`http://${t}`}async _waitForReady(t){if(!this._isReady){if(this._healthCheckPromise)return this._healthCheckPromise;this._healthCheckPromise=this._performHealthCheck(t);try{await this._healthCheckPromise}finally{this._healthCheckPromise=null}}}async _performHealthCheck(r){const i=this._buildUrl(this._address),n=r.getTime()-Date.now();if(n<=0)throw new e(s.Timeout,t?.[this._address]?.toString());const h=new AbortController,l=setTimeout(()=>h.abort(),n);try{const r=await fetch(i,{method:"POST",headers:{"content-type":"application/grpc-web+proto","x-user-agent":`${a}/${o}`,"x-grpc-web":"1"},body:new Uint8Array(0),signal:h.signal});if(clearTimeout(l),r.ok||r.status>=300&&r.status<400){const t=r.headers.get("grpc-status"),e=r.headers.get("grpc-message");if(null!=t||null!=e)return void(this._isReady=!0)}throw new e(s.Unavailable,t?.[this._address]?.toString())}catch(r){if(clearTimeout(l),r instanceof Error&&"AbortError"===r.name)throw new e(s.Timeout,t?.[this._address]?.toString());if(r instanceof e)throw r;throw new e(s.Unavailable,t?.[this._address]?.toString())}}close(){}_createUnaryClient(n){return async(c,d,u)=>{const p=new Date,m=this._grpcDeadline;p.setMilliseconds(p.getMilliseconds()+m);try{await this._waitForReady(p);const m=this._buildUrl(this._address),f=await fetch(`${m}/proto.${n}/${c.name}`,{method:"POST",headers:{"content-type":"application/grpc-web+proto","x-user-agent":`${a}/${o}`,"x-grpc-web":"1"},body:h(d)});if(!f.ok){return void u(new r(i._fromValue(f.status)),null)}const _=f.headers.get("grpc-status"),g=f.headers.get("grpc-message");if(null!=_&&null!=g){const r=new e(s._fromValue(parseInt(_)),t?.[this._address]?.toString());return r.message=g,void u(r,null)}const w=await f.arrayBuffer();u(null,l(w))}catch(r){if(r instanceof e)return void u(r,null);u(new e(s._fromValue(18),t?.[this._address]?.toString()),null)}}}}export{c as default};
//# sourceMappingURL=WebChannel.js.map