justrun-ws 0.3.8 → 0.4.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/lib/index.d.ts CHANGED
@@ -62,27 +62,17 @@ export type ParseResult<PkgTypeT extends number | string> = {
62
62
  requestId: number;
63
63
  bodyOffset: number;
64
64
  };
65
- declare class ListNode {
66
- constructor();
67
- getPrev<SelfT extends ListNode>(this: SelfT): SelfT;
68
- getNext<SelfT extends ListNode>(this: SelfT): SelfT;
69
- insertBefore<SelfT extends ListNode>(this: SelfT, node: SelfT): void;
70
- insertAfter<SelfT extends ListNode>(this: SelfT, node: SelfT): void;
71
- remove(): void;
72
- }
73
- declare abstract class MonitorItem extends ListNode {
74
- abstract warnTimeout(): void;
75
- abstract onTimeout(): void;
65
+ export interface IConnMonitorHandle {
66
+ onReceive(bytes: number): void;
67
+ onSend(bytes: number): void;
76
68
  }
77
- export declare class TimeoutMonitor {
78
- constructor(tickMilSec: number, warningTick: number, timeoutTick: number);
79
- insert(item: MonitorItem): void;
80
- update(item: MonitorItem): void;
81
- remove(item: MonitorItem): void;
69
+ export interface IConnMonitor {
70
+ insert(forceClose: (reason?: string) => void, keepAlive?: () => void): IConnMonitorHandle;
71
+ remove(handle: IConnMonitorHandle): void;
82
72
  }
83
73
  export type TypedPkgHubOpts<PkgTypeT extends number | string> = {
84
74
  readonly responsePkgType: PkgTypeT;
85
- readonly timeoutMonitor?: TimeoutMonitor;
75
+ readonly connMonitor?: IConnMonitor;
86
76
  makePkgBuff: (pkgType: PkgTypeT, requestId: number, encoded: Uint8Array[]) => void;
87
77
  parsePkgBuff: (buff: Uint8Array) => ParseResult<PkgTypeT>;
88
78
  };
@@ -106,6 +96,11 @@ export interface DoneResp<ResultT extends string | number | boolean = boolean> {
106
96
  result: ResultT;
107
97
  }
108
98
  export declare const handleUncaughtErrorWith: (handler: (conn: IConn<unknown>, err: Error) => ErrorWrapper<unknown>) => void;
99
+ export declare class ConnAliveMonitor implements IConnMonitor {
100
+ constructor(tickMilSec: number, timeoutTick: number, aliveTick: number);
101
+ insert(forceClose: (reason?: string) => void, keepAlive?: () => void): IConnMonitorHandle;
102
+ remove(handle: IConnMonitorHandle): void;
103
+ }
109
104
  export declare const NetErrorString: {
110
105
  readonly AuthTimeout: "Auth Timeout";
111
106
  readonly BadRequest: "Bad Request";
@@ -126,11 +121,20 @@ export declare class TimeoutCache<KeyT extends number | string, ValT> {
126
121
  set(key: KeyT, val: ValT): void;
127
122
  delete(key: KeyT): boolean;
128
123
  }
124
+ export interface ITimeoutHandle {
125
+ onTimeout: () => void;
126
+ }
127
+ export declare class TimeoutMonitor {
128
+ constructor(tickMilSec: number, timeoutTick: number);
129
+ insert(onTimeout: () => void): ITimeoutHandle;
130
+ update(handle: ITimeoutHandle): void;
131
+ remove(handle: ITimeoutHandle): void;
132
+ }
129
133
  export interface IAuthProvider {
130
134
  init<PkgTypeT extends number | string>(proxyPrivatePkgType: PkgTypeT, client: WsClient<PkgTypeT>): Promise<void>;
131
135
  preConnect(): Promise<string>;
132
136
  }
133
- export declare const createNumPkgTypeClient: (connUrl: string, timeoutMonitor?: TimeoutMonitor) => WsClient<number>;
137
+ export declare const createNumPkgTypeClient: (connUrl: string, connMonitor?: IConnMonitor) => WsClient<number>;
134
138
  declare enum ClientConnState {
135
139
  NotConnected = 0,
136
140
  Connecting = 1,
package/lib/index.min.js CHANGED
@@ -1 +1 @@
1
- class t{constructor(t,e){e?this.z=t:this.$=t}get data(){return this.$||(this.$=this.decode(this.z)),this.$}set data(t){this.$=t,this.z=void 0}get buff(){return this.z||(this.z=this.encode(this.$)),this.z}z;$}class e extends t{static context;static registerPkgType(t){let e;try{e=this.pkgType}catch{return void Object.defineProperty(this,"pkgType",{value:t,writable:!1,enumerable:!1})}if(e!==t)throw new Error(`Wrapper ${this.name} is already registered with type ${e}`)}static get pkgType(){throw new Error(`Wrapper ${this.name} need to be registered`)}}class s extends e{isError(){return!0}}class i extends e{isMessage(){return!0}}class r extends e{isEvent(){return!0}}class n extends e{constructor(t,e){super(t,e)}isRequest(){return!0}get resp(){return this._||(this._=this.decodeResponse(this.A)),this._}set resp(t){this._=t,this.A=void 0}get respBuff(){return this.A||(this.A=this.encodeResponse(this._)),this.A}set respBuff(t){this._=void 0,this.A=t}_;A}const o=new TextEncoder,h=new TextDecoder;class a extends s{encode(t){const e=JSON.stringify(t);return o.encode(e)}decode(t){const e=h.decode(t);return JSON.parse(e)}}class c extends i{encode(t){const e=JSON.stringify(t);return o.encode(e)}decode(t){const e=h.decode(t);return JSON.parse(e)}}class d extends n{encode(t){const e=JSON.stringify(t);return o.encode(e)}decode(t){const e=h.decode(t);return JSON.parse(e)}encodeResponse(t){const e=JSON.stringify(t);return o.encode(e)}decodeResponse(t){const e=h.decode(t);return JSON.parse(e)}}class u extends a{}let l=(t,e)=>new u(e.message);const g=t=>{l=t},f={AuthTimeout:"Auth Timeout",BadRequest:"Bad Request",ConnectFailed:"Connect Failed",ConnectionClosed:"Connection Closed",InvalidConnString:"Invalid Connection String",InvalidConnection:"Invalid Connection",InvalidPackage:"Invalid Package",NotAuthenticated:"Not Authenticated",NotFound:"Not Found",Timeout:"Timeout",UnknownError:"Unknown Error"};class p{constructor(){this.j=this,this.k=this}getPrev(){return this.j}getNext(){return this.k}insertBefore(t){this.k=t,this.j=t.j,t.j=this,this.j.k=this}insertAfter(t){this.j=t,this.k=t.k,t.k=this,this.k.j=this}remove(){this.j.k=this.k,this.k.j=this.j}j;k}let w=class{constructor(){this.B=new p}get e(){return this.B.getNext()}get a(){return this.B.getPrev()}X(t){return t===this.B}Y(t){t.insertAfter(this.B)}ap(t){t.insertBefore(this.B)}B};const y=()=>{},k=t=>{let e=0,s=0;for(;e<t.length;)s+=t[e++].length;const i=new Uint8Array(s);for(s=0;e>0;){const r=t[--e];i.set(r,s),s+=r.length}return i};class v extends p{}class m{constructor(t,e,s){if(this.Z=t,this.L=e,this.H=s,this.p=0,this.I=0,this.t=[],0===t)return this.insert=y,this.update=y,void(this.remove=y);for(let t=0;t<s;t++)this.t.push(new w)}insert(t){this.I||(this.a0=setInterval(this.ab,this.Z)),this.I++,this.t[this.p].Y(t)}update(t){t.remove(),this.t[this.p].Y(t)}remove(t){t.remove(),this.I--,this.I||clearInterval(this.a0)}ab=()=>{const{L:t,H:e,t:s}=this;if(this.p++,this.p===e&&(this.p=0),t){let i=this.p+t;i>=e&&(i-=e);const r=s[i];for(let t=r.e;!r.X(t);t=t.getNext())t.warnTimeout()}const i=s[this.p];for(let t=i.e;!i.X(t);t=t.getNext())t.onTimeout()};Z;L;H;p;I;a0;t}class T extends v{constructor(t,e,s){super(),this.h=t,this.a7=e,this.val=s}val;warnTimeout(){}onTimeout(){this.h.delete(this.a7)}h;a7}class E{constructor(t,e){this.h=new Map,this.q=new m(t,0,e)}get(t){const{h:e,q:s}=this,i=e.get(t);if(i)return s.update(i),i.val}set(t,e){const{h:s,q:i}=this;let r=s.get(t);r?(r.val=e,i.update(r)):(r=new T(s,t,e),s.set(t,r),i.insert(r))}delete(t){const{h:e,q:s}=this,i=e.get(t);return!!i&&(s.remove(i),e.delete(t))}h;q}class b{constructor(t,e){this.a8=new Promise(t=>{this.w=t}),this.O=e,t>0?this.l=setTimeout(()=>{this.l=void 0,this.w(!0),e?.()},t):(this.w(!0),e?.())}ar(t){const{l:e,w:s,O:i}=this;e&&clearTimeout(e),t>0?this.l=setTimeout(()=>{this.l=void 0,i?.(),s(!0)},t):(this.l=void 0,s(!0),i?.())}ak(){this.l&&(clearTimeout(this.l),this.l=void 0,this.w(!1))}at(){return this.a8}w;a8;l;O}let P=class extends c{};class x{constructor(t,e,s){let i=sessionStorage.getItem("jrSession");i||(i=crypto.randomUUID(),sessionStorage.setItem("jrSession",i)),this.b="",this.c=i,this.V=t,this.Q="",this.E=e,this.e=s,this.R=this.R.bind(this);const r=()=>{throw new Error("JustrunAuthProvider shall be enabled before use")};this.authWithCredential=r,this.authWithOAuth2=r,this.resetAuthState=r,this.resetConnState=r}async init(t,e){const s=x.prototype;this.authWithCredential=s.authWithCredential,this.authWithOAuth2=s.authWithOAuth2,this.resetAuthState=s.resetAuthState,this.resetConnState=s.resetConnState,e.onConnectionStatus(this.an.bind(this)),e.registerMessage(t,P),e.handleMessageWith(P,this.ao.bind(this));const{c:i,e:r}=this,n=this.W();if(n){const{cid:t,h:e}=n;if(Math.round(Date.now()/1e3)<=e)return void r(t,i)}r("","")}async preConnect(){const{b:t,c:e,f:s,e:i,E:r}=this;if(s)return i(t,e,s),"";const n=""===s;this.f=void 0;let o=this.W();if(o){const{cid:t,address:s,g:i,h:h}=o,a=Math.round(Date.now()/1e3);if(a<=i)return this.Q=o.address,r(s,e,n);if(a<=h&&(o=await this.S("refresh",""),o))return this.Q=o.address,r(o.address,e,n)}return this.f="unknown error",i("",""),""}async authWithCredential(t,e,s,i){await this.S(t,`${e},${s},${i}`)}authWithOAuth2(t,e,s,i){const r=`${e}?client_id=${s}&redirect_uri=${this.V}&scope=${i}&response_type=code`;window.location.href=`${r}&state=${this.c}~${s}~${encodeURI(t)}`}async resetAuthState(){await this.S("signout","")}resetConnState(t){if(this.f){this.f=t?"":void 0;const{b:e,c:s,e:i}=this;i(e,s)}}an(t,e,s,i){if(t){this.a=e;const t=this.W();if(t){const{g:e}=t;this.F=new b(1e3*e-Date.now(),this.R)}}else if(this.a=void 0,this.F&&(this.F.ak(),this.F=void 0),!s){const t=this.f=i?.message||"unknown error",{b:e,c:s,e:r}=this;r(e,s,t)}}async R(){this.F=void 0;const{c:t,E:e}=this,s=await this.S("refresh","");if(s&&this.a){const{address:i,g:r}=s;if(i===this.Q){const s=e(i,t),[n,o]=s.split("://");await fetch(`${n.replace("ws","http")}://${o}`),this.F=new b(1e3*r-Date.now(),this.R)}else this.a&&(this.a.close(),this.a=void 0)}}async ao(t){const{b:e,c:s,a:i}=this,{type:r,k:n}=t;"kick"===r&&i&&(i.close(),this.a=void 0,n&&(this.f=n,this.e(e,s,n)))}W(){const t=localStorage.getItem("jrAuth")||void 0;if(t){const[e,s,i,r]=t.split(","),{b:n,a:o}=this;return n&&e!==n&&o&&(o.close(),this.a=void 0),this.b=e,{cid:e,address:s,g:parseInt(i),h:parseInt(r)}}}async S(t,e){const s=await fetch(this.V,{method:"POST",body:`${t}:${e}`}).catch(t=>{throw new u(t.message)}),i=await s.text();if(!s.ok)throw new u(i);if(i.startsWith("auth:")){const t=i.substring(5);localStorage.setItem("jrAuth",t);const[e,s,r,n]=t.split(","),{b:o,a:h}=this;return o!==e&&(o&&h&&(h.close(),this.a=void 0),this.b=e,this.e(e,this.c,this.f)),{cid:e,address:s,g:parseInt(r),h:parseInt(n)}}if(i.startsWith("clear:"))localStorage.removeItem("jrAuth"),this.b="",this.f=void 0,this.e("",""),this.a&&(this.a.close(),this.a=void 0);else if(i.startsWith("error:")){"refresh"!==t&&"signout"!==t||(localStorage.removeItem("jrAuth"),this.b="",this.f=void 0,this.e("",""),this.a&&(this.a.close(),this.a=void 0));const e=i.substring(6);throw new u(e)}}b;c;V;Q;a;f;F;E;e}const C=new Error(f.NotAuthenticated);class A{constructor(t,e,s){this.o=t,this.x=e,this.y=!s}get pkgType(){return this.o.pkgType}get j(){return this.o.name}async r(t,e){const{buff:s,bodyOffset:i}=e,r=s.subarray(i),n=new this.o(r,!0);if(void 0===t.context&&this.y)l(t,C);else try{await this.x(t,n)}catch(e){e.isError||l(t,e)}void 0===t.context&&await t.close()}async p(t,e){if(void 0===t.context&&this.y)l(t,C);else try{return await this.x(t,e)}catch(e){e.isError||l(t,e)}}o;x;y}let S=class{constructor(t,e,s){this.o=t,this.x=e,this.y=!s}get pkgType(){return this.o.pkgType}get j(){return this.o.name}async r(t,e){const{buff:s,requestId:i,bodyOffset:r}=e,n=s.subarray(r),o=new this.o(n,!0);let h;if(void 0===t.context&&this.y)h=l(t,C);else try{await this.x(t,o)}catch(e){h=e.isError?e:l(t,e)}try{h?await t.sendErrorResponse(h,i):await t.sendResponse(o,i),void 0===t.context&&await t.close()}catch{return}}async p(t,e){if(void 0!==t.context||!this.y)try{return await this.x(t,e)}catch(e){throw e.isError?e:l(t,e)}throw l(t,C)}o;x;y},R=class{address(){return null}init(t){this.G=t}async B(t){return!1}async E(){return!1}async f(t){const e=new WebSocket(t);return new Promise((t,s)=>{e.onerror=t=>{s(new Error(f.UnknownError))},e.onopen=()=>{t(this.al(e,!0))}})}al=(t,e)=>{const s=new I(t),{conn:i,y:r,s:n}=this.G(s,e);t.onmessage=t=>{t.data.arrayBuffer().then(t=>{r(new Uint8Array(t))})};let o=!0;return t.onerror=t=>{o=!1,n(new Error(f.UnknownError))},t.onclose=t=>{o&&n(1e3===t.code?void 0:new Error(t.reason||"unknown error"))},i};G(t,e){throw new Error('Need to call "setConnWrapperMaker" before using')}};class I{constructor(t){this.i=t}get socket(){return{localAddress:"",localPort:0,remoteAddress:"",remoteFamily:"",remotePort:0}}async _(t){if(this.i)return this.i.send(t);throw new Error(f.InvalidConnection)}async l(t){if(this.i){const e=k(t);return this.i.send(e)}throw new Error(f.InvalidConnection)}async close(t){const{i:e}=this;e&&(this.i=void 0,t?e.close(1e3,t.message):e.readyState<=WebSocket.OPEN&&e.close())}A(){return!this.i}i}const W=(t,e,s)=>{const i=[e,t],r=(t=>{let e,s=0,i=0;for(;s<t.length;)for(i++,e=t[s++];e>>>=7;)i++;return i})(i),n=new Uint8Array(r);((t,e,s=0)=>{let i,r,n=s;for(i=0;i<t.length;i++){r=t[i];let s=127&r;for(;r>>>=7;)e[n++]=128|s,s=127&r;e[n++]=s}if(n<=e.length)return n-s;throw new Error("Buffer overflow")})(i,n),s.push(n)},$=t=>{const{g:[e,s],j:i}=((t,e,s=0)=>{let i,r,n=s,o=0,h=0;const a=[];for(i=0;i<t;i++){do{r=e[n++],o|=(127&r)<<h,h+=7}while(128&r);if(!(void 0!==r&&h<=35))throw new Error("Parsing failed");a.push(o),o=0,h=0}return{g:a,j:n-s}})(2,t);return{buff:t,pkgType:s,requestId:e,bodyOffset:i}};class M{constructor(t){this.a9=t}get id(){return this.a?.id??-1}get context(){return this.a?.context}set context(t){this.a&&(this.a.context=t)}localAddress;localPort;remoteAddress;remoteFamily;remotePort;async sendErrorResponse(t,e){return(this.a??await this.f()).sendErrorResponse(t,e)}async sendResponse(t,e){return(this.a??await this.f()).sendResponse(t,e)}async sendMessage(t){return(this.a??await this.f()).sendMessage(t)}async sendRequest(t){return(this.a??await this.f()).sendRequest(t)}async close(t){const{a:e}=this;if(e)return this.a=void 0,void await e.close(t);this.r&&await this.r.then(e=>{this.a=void 0,e.close(t)},()=>this.a=void 0)}async au(){this.a||await this.f()}am(){this.a=void 0}async f(){let{r:t}=this;return t||(t=this.r=new Promise((t,e)=>{this.a9().then(s=>{s?(t(s),this.a=s,this.r=void 0):e(new Error("Connect failed"))})})),await t}a9;a;r}class j{constructor(t,e){const{responsePkgType:s,timeoutMonitor:i,makePkgBuff:r,parsePkgBuff:n}=e;this.responsePkgType=s,this.u=0,this.v=new Map,this.g=new Map,this.T=new Map,this.a1=r,this.a2=n,this.C=t,this.M=i;this.r=this.ac;const o=[];this.a1(s,2097152,o),this.a3={makePkgBuff:r,responsePkgType:s,o:k(o)},this.g.set(s,this),this.C.init((t,e)=>{do{this.u++}while(this.v.has(2097151&this.u));const s=new B(this.a3,t,2097151&this.u);this.v.set(s.id,s),this.M?.insert(s);const i={conn:s,y:t=>this.ad(s,t),s:t=>this.ae(s,t)};return this.N?.(this,s,!!e),i})}responsePkgType;context;N;J;address(){return this.C.address()}L(t){return this.v.get(t)}f(t){return this.C.f(t)}async O(){do{this.u++}while(this.v.has(2097151&this.u));const t=new N(2097151&this.u,this);return this.v.set(t.id,t),t}async P(t){return this.C.B(t)}async Q(){return this.C.E()}af(t,e){const s=e.constructor.pkgType,i=this.g.get(s);if(i)return i?.p(t,e);throw new Error(f.InvalidPackage)}ag(t,e){const s=e.constructor.pkgType,i=this.g.get(s);if(i)return i?.p(t,e);throw new Error(f.InvalidPackage)}registerError(t,e){e.registerPkgType(t),this.T.set(t,e);const s=this.g.get(this.responsePkgType);this.g.set(t,s)}registerMessage(t,e){e.registerPkgType(t)}registerRequest(t,e){e.registerPkgType(t)}handleMessageWith(t){const e=t.pkgType;if(typeof e!=typeof this.responsePkgType)throw new Error(`Wrapper ${t.j} has an incompatible pkgType ${typeof e}`);if(this.g.has(e))throw new Error(`Wrapper ${t.j} is already handled by another handler`);return this.g.set(e,t),t}handleRequestWith(t){const e=t.pkgType;if(typeof e!=typeof this.responsePkgType)throw new Error(`Wrapper ${t.j} has an incompatible pkgType ${typeof e}`);if(this.g.has(e))throw new Error(`Wrapper ${t.j} is already handled by another handler`);return this.g.set(e,t),t}aq(t){const e=t.pkgType;return this.g.get(e)===t&&(this.g.delete(e),!0)}ad(t,e){this.M?.update(t);const s=this.a2(e),i=this.g.get(s.pkgType);i?i.r(t,s):t.close(new Error(f.InvalidPackage))}ae(t,e){this.v.delete(t.id),this.M?.remove(t),t.s(e),this.J?.(this,t,t.d.A(),e)}ac(t,e){try{const{buff:s,pkgType:i,requestId:r,bodyOffset:n}=e;if(i===this.responsePkgType){const e=s.subarray(n);t.a4(r,e)}else{const e=this.T.get(i);if(e){const i=new e(s.subarray(n),!0);t.ah(r,i)}}}catch{t.close(new Error(f.InvalidPackage))}}a3;u;a1;a2;C;v;g;T;M}class B extends v{constructor(t,e,s){super(),this.id=s,this.d=e,this.D=t,this.a5=0}context;id;d;get socket(){return this.d.socket}sendMessage(t){const e=t.constructor.pkgType,s=[t.buff];return this.D.makePkgBuff(e,0,s),this.d.l(s)}sendRequest(t){return this.n=new Map,this.sendRequest=this.a6,this.a4=this.ai,this.s=this.aj,this.a6(t)}sendErrorResponse(t,e){const s=t.constructor.pkgType,i=[t.buff];return this.D.makePkgBuff(s,e,i),this.d.l(i)}sendResponse(t,e){const s=[t.respBuff],{makePkgBuff:i,responsePkgType:r}=this.D;return i(r,e,s),this.d.l(s)}async close(t){await this.d.close(t)}a4(t,e){2097152===t&&void 0===this.context&&this.close(new Error(f.AuthTimeout))}ah(t,e){const s=this.n.get(t);if(s)return this.n.delete(t),s.h(e)}warnTimeout(){this.d._(this.D.o).catch(y)}onTimeout(){this.close(new Error(f.Timeout))}s(t){}async a6(t){const e=2097151&this.a5++,s=t.constructor.pkgType,i=[t.buff];this.D.makePkgBuff(s,e,i);const r=new Promise((t,s)=>{const r={c:t,h:s};this.n.set(e,r),this.d.l(i).catch(t=>{this.n.delete(e),s(t)})});t.respBuff=await r}ai(t,e){const s=this.n.get(t);if(s)return this.n.delete(t),void s.c(e);2097152===t&&void 0===this.context&&this.close(new Error(f.AuthTimeout))}aj(t){const e=this.n;if(e.size>0){t||(t=new Error(f.ConnectionClosed));for(const[s,i]of e)e.delete(s),i.h(t)}this.n=void 0}D;n;a5}class N{constructor(t,e){this.id=t,this.U=e}context;id;socket;get remoteFamily(){return"Local"}async sendMessage(t){return this.U.af(this,t)}async sendRequest(t){return this.U.ag(this,t)}sendErrorResponse(t,e){throw null}sendResponse(t,e){throw null}async close(t){}U}const q=(t,e)=>new U(t,{responsePkgType:0,makePkgBuff:W,parsePkgBuff:$,timeoutMonitor:e});var O;!function(t){t[t.NotConnected=0]="NotConnected",t[t.Connecting=1]="Connecting",t[t.Connected=2]="Connected"}(O||(O={}));class U{constructor(t,e){const s=new R,i=this.m=new j(s,e);this.K=O.NotConnected,this.aa=t,this.a=new M(()=>this.f()),i.N=this.N.bind(this),i.J=this.J.bind(this)}getConnState(){return this.K}enableAuthenticate(t,e){this.P=e,e.init(t,this)}registerError(t,e){return this.m.registerError(t,e)}registerMessage(t,e){return this.m.registerMessage(t,e)}registerRequest(t,e){return this.m.registerRequest(t,e)}handleMessageWith(t,e){this.m.handleMessageWith(new A(t,(t,s)=>e(s.data),!0))}handleRequestWith(t,e){this.m.handleRequestWith(new S(t,async(t,s)=>{s.resp=await e(s.data)},!0))}sendMessage(t){return this.a.sendMessage(t)}async sendRequest(t){return await this.a.sendRequest(t),t.resp}onConnectionStatus(t){let{c:e}=this;e||(this.c=e=[]),e.push(t)}async f(){const{m:t,P:e}=this;this.K=O.Connecting;try{const s=e?await e.preConnect():this.aa;if(!s)throw new Error(f.UnknownError);return await t.f(s)}catch(e){const s=e instanceof Error?e:new Error(f.UnknownError);this.J(t,this.a,!0,s)}}N(t,e,s){if(this.K=O.Connected,e.context="",this.c)for(const t of this.c)t(!0,e,s)}J(t,e,s,i){if(this.K=O.NotConnected,this.a.am(),this.c)for(const t of this.c)t(!1,e,s,i)}aa;m;a;K;P;c}export{u as CommonError,s as ErrorWrapper,r as EventWrapper,a as JsonError,c as JsonMessage,d as JsonRequest,x as JustrunAuthProvider,i as MessageWrapper,f as NetErrorString,n as RequestWrapper,E as TimeoutCache,m as TimeoutMonitor,U as WsClient,q as createNumPkgTypeClient,g as handleUncaughtErrorWith};
1
+ class t{constructor(t,e){e?this.u=t:this.v=t}get data(){return this.v||(this.v=this.decode(this.u)),this.v}set data(t){this.v=t,this.u=void 0}get buff(){return this.u||(this.u=this.encode(this.v)),this.u}u;v}class e extends t{static context;static registerPkgType(t){let e;try{e=this.pkgType}catch{return void Object.defineProperty(this,"pkgType",{value:t,writable:!1,enumerable:!1})}if(e!==t)throw new Error(`Wrapper ${this.name} is already registered with type ${e}`)}static get pkgType(){throw new Error(`Wrapper ${this.name} need to be registered`)}}class s extends e{isError(){return!0}}class n extends e{isMessage(){return!0}}class i extends e{isEvent(){return!0}}class r extends e{constructor(t,e){super(t,e)}isRequest(){return!0}get resp(){return this.w||(this.w=this.decodeResponse(this.x)),this.w}set resp(t){this.w=t,this.x=void 0}get respBuff(){return this.x||(this.x=this.encodeResponse(this.w)),this.x}set respBuff(t){this.w=void 0,this.x=t}w;x}const o=new TextEncoder,h=new TextDecoder;class a extends s{encode(t){const e=JSON.stringify(t);return o.encode(e)}decode(t){const e=h.decode(t);return JSON.parse(e)}}class c extends n{encode(t){const e=JSON.stringify(t);return o.encode(e)}decode(t){const e=h.decode(t);return JSON.parse(e)}}class d extends r{encode(t){const e=JSON.stringify(t);return o.encode(e)}decode(t){const e=h.decode(t);return JSON.parse(e)}encodeResponse(t){const e=JSON.stringify(t);return o.encode(e)}decodeResponse(t){const e=h.decode(t);return JSON.parse(e)}}class u extends a{}let l=(t,e)=>new u(e.message);const g=t=>{l=t},p=Object.freeze({}),f=()=>p,w=t=>{let e=0,s=0;for(;e<t.length;)s+=t[e++].length;const n=new Uint8Array(s);for(s=0;e>0;){const i=t[--e];n.set(i,s),s+=i.length}return n};class y{constructor(t,e){if(this.a0=t,this.R=e,this.z=0,this.I=0,this.$=[],0===t)return this.insert=f,this.update=f,void(this.remove=f);for(let t=0;t<e;t++){const t={onTimeout:f,e:p,c:p};t.e=t.c=t,this.$.push(t)}}insert(t){this.I||(this.a1=setInterval(this.ad,this.a0)),this.I++;const e=this.$[this.z],{c:s}=e,n={onTimeout:t,e:e,c:s};return s.e=n,e.c=n,n}update(t){const e=t,{e:s,c:n}=e;s.c=n,n.e=s;const i=this.$[this.z];e.e=i,e.c=i.c,i.c.e=e,i.c=e}remove(t){const{e:e,c:s}=t;e.c=s,s.e=e,--this.I||clearInterval(this.a1)}ad=()=>{const{R:t,$:e}=this;++this.z===t&&(this.z=0);const s=e[this.z];let n=s.c;for(;n!==s;){const{onTimeout:t}=n;n=n.c,t()}};a0;R;z;I;a1;$}const v={AuthTimeout:"Auth Timeout",BadRequest:"Bad Request",ConnectFailed:"Connect Failed",ConnectionClosed:"Connection Closed",InvalidConnString:"Invalid Connection String",InvalidConnection:"Invalid Connection",InvalidPackage:"Invalid Package",NotAuthenticated:"Not Authenticated",NotFound:"Not Found",Timeout:"Timeout",UnknownError:"Unknown Error"};class k{constructor(t,e,s){this._=new y(t,e),this.A=new y(t,s)}insert(t,e){const{_:s,A:n}=this,i=s.insert(()=>t(v.Timeout)),r=e&&n.insert(e);return{onReceive:()=>s.update(i),onSend:r?()=>n.update(r):f,c:i,b:r}}remove(t){const{_:e,A:s}=this,{c:n,b:i}=t;e.remove(n),i&&s.remove(i)}_;A}class m{constructor(t,e){this.i=new Map,this.m=new y(t,e)}get(t){const{i:e,m:s}=this,n=e.get(t);if(n)return s.update(n.handle),n.val}set(t,e){const{i:s,m:n}=this,i=s.get(t);if(i)i.val=e,n.update(i.handle);else{const i=n.insert(()=>{const e=s.get(t);e&&(n.remove(e.handle),s.delete(t))});s.set(t,{handle:i,key:t,val:e})}}delete(t){const{i:e,m:s}=this,n=e.get(t);return!!n&&(s.remove(n.handle),e.delete(t))}i;m}let b=class{constructor(t,e){this.a2=new Promise(t=>{this.r=t}),this.J=e,t>0?this.j=setTimeout(()=>{this.j=void 0,this.r(!0),e?.()},t):(this.r(!0),e?.())}ak(t){const{j:e,r:s,J:n}=this;e&&clearTimeout(e),t>0?this.j=setTimeout(()=>{this.j=void 0,n?.(),s(!0)},t):(this.j=void 0,s(!0),n?.())}ae(){this.j&&(clearTimeout(this.j),this.j=void 0,this.r(!1))}al(){return this.a2}r;a2;j;J};class E extends c{}class T{constructor(t,e,s){let n=sessionStorage.getItem("jrSession");n||(n=crypto.randomUUID(),sessionStorage.setItem("jrSession",n)),this.b="",this.c=n,this.S=t,this.L="",this.B=e,this.f=s,this.M=this.M.bind(this);const i=()=>{throw new Error("JustrunAuthProvider shall be enabled before use")};this.authWithCredential=i,this.authWithOAuth2=i,this.resetAuthState=i,this.resetConnState=i}async init(t,e){const s=T.prototype;this.authWithCredential=s.authWithCredential,this.authWithOAuth2=s.authWithOAuth2,this.resetAuthState=s.resetAuthState,this.resetConnState=s.resetConnState,e.onConnectionStatus(this.ah.bind(this)),e.registerMessage(t,E),e.handleMessageWith(E,this.ai.bind(this));const{c:n,f:i}=this,r=this.T();if(r){const{cid:t,h:e}=r;if(Math.round(Date.now()/1e3)<=e)return void i(t,n)}i("","")}async preConnect(){const{b:t,c:e,e:s,f:n,B:i}=this;if(s)return n(t,e,s),"";const r=""===s;this.e=void 0;let o=this.T();if(o){const{cid:t,address:s,g:n,h:h}=o,a=Math.round(Date.now()/1e3);if(a<=n)return this.L=o.address,i(s,e,r);if(a<=h&&(o=await this.N("refresh",""),o))return this.L=o.address,i(o.address,e,r)}return this.e="unknown error",n("",""),""}async authWithCredential(t,e,s,n){await this.N(t,`${e},${s},${n}`)}authWithOAuth2(t,e,s,n){const i=`${e}?client_id=${s}&redirect_uri=${this.S}&scope=${n}&response_type=code`;window.location.href=`${i}&state=${this.c}~${s}~${encodeURI(t)}`}async resetAuthState(){await this.N("signout","")}resetConnState(t){if(this.e){this.e=t?"":void 0;const{b:e,c:s,f:n}=this;n(e,s)}}ah(t,e,s,n){if(t){this.a=e;const t=this.T();if(t){const{g:e}=t;this.C=new b(1e3*e-Date.now(),this.M)}}else{this.a=void 0,this.C&&(this.C.ae(),this.C=void 0);const t=this.e=n?.message||v.UnknownError,{b:e,c:s,f:i}=this;i(e,s,t)}}async M(){this.C=void 0;const{c:t,B:e}=this,s=await this.N("refresh","");if(s&&this.a){const{address:n,g:i}=s;if(n===this.L){const s=e(n,t),[r,o]=s.split("://");await fetch(`${r.replace("ws","http")}://${o}`),this.C=new b(1e3*i-Date.now(),this.M)}else this.a&&(this.a.close(),this.a=void 0)}}async ai(t){const{b:e,c:s,a:n}=this,{type:i,j:r}=t;"kick"===i&&n&&(n.close(),this.a=void 0,r&&(this.e=r,this.f(e,s,r)))}T(){const t=localStorage.getItem("jrAuth")||void 0;if(t){const[e,s,n,i]=t.split(","),{b:r,a:o}=this;return r&&e!==r&&o&&(o.close(),this.a=void 0),this.b=e,{cid:e,address:s,g:parseInt(n),h:parseInt(i)}}}async N(t,e){const s=await fetch(this.S,{method:"POST",body:`${t}:${e}`}).catch(t=>{throw new u(t.message)}),n=await s.text();if(!s.ok)throw new u(n);if(n.startsWith("auth:")){const t=n.substring(5);localStorage.setItem("jrAuth",t);const[e,s,i,r]=t.split(","),{b:o,a:h}=this;return o!==e&&(o&&h&&(h.close(),this.a=void 0),this.b=e,this.f(e,this.c,this.e)),{cid:e,address:s,g:parseInt(i),h:parseInt(r)}}if(n.startsWith("clear:"))localStorage.removeItem("jrAuth"),this.b="",this.e=void 0,this.f("",""),this.a&&(this.a.close(),this.a=void 0);else if(n.startsWith("error:")){"refresh"!==t&&"signout"!==t||(localStorage.removeItem("jrAuth"),this.b="",this.e=void 0,this.f("",""),this.a&&(this.a.close(),this.a=void 0));const e=n.substring(6);throw new u(e)}}b;c;S;L;a;e;C;B;f}const C=new Error(v.NotAuthenticated);class P{constructor(t,e,s){this.n=t,this.s=e,this.t=!s}get pkgType(){return this.n.pkgType}get m(){return this.n.name}async v(t,e){const{buff:s,bodyOffset:n}=e,i=s.subarray(n),r=new this.n(i,!0);if(void 0===t.context&&this.t)l(t,C);else try{await this.s(t,r)}catch(e){e.isError||l(t,e)}void 0===t.context&&await t.close()}async u(t,e){if(void 0===t.context&&this.t)l(t,C);else try{return await this.s(t,e)}catch(e){e.isError||l(t,e)}}n;s;t}let S=class{constructor(t,e,s){this.n=t,this.s=e,this.t=!s}get pkgType(){return this.n.pkgType}get m(){return this.n.name}async v(t,e){const{buff:s,requestId:n,bodyOffset:i}=e,r=s.subarray(i),o=new this.n(r,!0);let h;if(void 0===t.context&&this.t)h=l(t,C);else try{await this.s(t,o)}catch(e){h=e.isError?e:l(t,e)}try{h?await t.sendErrorResponse(h,n):await t.sendResponse(o,n),void 0===t.context&&await t.close()}catch{return}}async u(t,e){if(void 0!==t.context||!this.t)try{return await this.s(t,e)}catch(e){throw e.isError?e:l(t,e)}throw l(t,C)}n;s;t},x=class{address(){return null}init(t){this.D=t}async C(t){return!1}async G(){return!1}async g(t){const e=new WebSocket(t);return new Promise((t,s)=>{e.onerror=t=>{s(new Error(v.UnknownError))},e.onopen=()=>{t(this.af(e,!0))}})}af=(t,e)=>{const s=new R(t),{conn:n,$:i,o:r}=this.D(s,e);t.onmessage=t=>{t.data.arrayBuffer().then(t=>{i(new Uint8Array(t))})};let o=!0;return t.onerror=t=>{o=!1,r(new Error(t.message||v.UnknownError))},t.onclose=t=>{o&&r(1e3===t.code?void 0:new Error(t.reason||"unknown error"))},n};D(t,e){throw new Error('Need to call "setConnWrapperMaker" before using')}},R=class{constructor(t){this.e=t}get socket(){return{localAddress:"",localPort:0,remoteAddress:"",remoteFamily:"",remotePort:0}}async A(t){if(this.e)return this.e.send(t),t.byteLength;throw new Error(v.InvalidConnection)}async n(t){if(this.e){const e=w(t);return this.e.send(e),e.byteLength}throw new Error(v.InvalidConnection)}async close(t){const{e:e}=this;e&&(this.e=void 0,t?(e.close(1e3,t.message),e.onerror(new ErrorEvent("error",{message:t.message})),e.onerror=e.onclose=null):e.readyState<=WebSocket.OPEN&&e.close())}B(){return!this.e}e};const A=(t,e,s)=>{const n=[e,t],i=(t=>{let e,s=0,n=0;for(;s<t.length;)for(n++,e=t[s++];e>>>=7;)n++;return n})(n),r=new Uint8Array(i);((t,e,s=0)=>{let n,i,r=s;for(n=0;n<t.length;n++){i=t[n];let s=127&i;for(;i>>>=7;)e[r++]=128|s,s=127&i;e[r++]=s}if(r<=e.length)return r-s;throw new Error("Buffer overflow")})(n,r),s.push(r)},I=t=>{const{g:[e,s],j:n}=((t,e,s=0)=>{let n,i,r=s,o=0,h=0;const a=[];for(n=0;n<t;n++){do{i=e[r++],o|=(127&i)<<h,h+=7}while(128&i);if(!(void 0!==i&&h<=35))throw new Error("Parsing failed");a.push(o),o=0,h=0}return{g:a,j:r-s}})(2,t);return{buff:t,pkgType:s,requestId:e,bodyOffset:n}};class ${constructor(t){this.a3=t}get id(){return this.a?.id??-1}get context(){return this.a?.context}set context(t){this.a&&(this.a.context=t)}localAddress;localPort;remoteAddress;remoteFamily;remotePort;async sendErrorResponse(t,e){return(this.a??await this.g()).sendErrorResponse(t,e)}async sendResponse(t,e){return(this.a??await this.g()).sendResponse(t,e)}async sendMessage(t){return(this.a??await this.g()).sendMessage(t)}async sendRequest(t){return(this.a??await this.g()).sendRequest(t)}async close(t){const{a:e}=this;if(e)return this.a=void 0,void await e.close(t);const{b:s}=this;s&&await s.then(e=>{s===this.b&&(this.b=void 0,this.a=void 0,e.close(t))},()=>{s===this.b&&(this.b=s,this.a=void 0)})}async am(){this.a||await this.g()}ag(){this.a=void 0,this.b=void 0}async g(){let{b:t}=this;return t||(t=this.b=new Promise((e,s)=>{this.a3().then(n=>{if(t===this.b&&(this.b=void 0,n))return e(n),void(this.a=n);n&&n.close(),s(new Error("Connect failed"))})})),await t}a3;a;b}class M{constructor(t,e){const{responsePkgType:s,connMonitor:n,makePkgBuff:i,parsePkgBuff:r}=e;this.responsePkgType=s,this.p=0,this.q=new Map,this.h=new Map,this.O=new Map,this.U=i,this.V=r,this.E=t,this.P=n;this.v=this.a5;const o=[];this.U(s,2097152,o),this.W={makePkgBuff:i,responsePkgType:s,j:w(o)},this.h.set(s,this),t.init((t,e)=>{do{this.p++}while(this.q.has(2097151&this.p));const s=new W(this.W,t,2097151&this.p);this.q.set(s.id,s),s.handle=this.P?.insert(s.forceClose.bind(s),s.keepAlive.bind(s));const n={conn:s,$:t=>this.a6(s,t),o:t=>this.a7(s,t)};return this.H?.(this,s,!!e),n})}responsePkgType;context;H;F;address(){return this.E.address()}M(t){return this.q.get(t)}g(t){return this.E.g(t)}async N(){do{this.p++}while(this.q.has(2097151&this.p));const t=new q(2097151&this.p,this);return this.q.set(t.id,t),t}async R(t){return this.E.C(t)}async S(){return this.E.G()}a8(t,e){const s=e.constructor.pkgType,n=this.h.get(s);if(n)return n?.u(t,e);throw new Error(v.InvalidPackage)}a9(t,e){const s=e.constructor.pkgType,n=this.h.get(s);if(n)return n?.u(t,e);throw new Error(v.InvalidPackage)}registerError(t,e){e.registerPkgType(t),this.O.set(t,e);const s=this.h.get(this.responsePkgType);this.h.set(t,s)}registerMessage(t,e){e.registerPkgType(t)}registerRequest(t,e){e.registerPkgType(t)}handleMessageWith(t){const e=t.pkgType;if(typeof e!=typeof this.responsePkgType)throw new Error(`Wrapper ${t.m} has an incompatible pkgType ${typeof e}`);if(this.h.has(e))throw new Error(`Wrapper ${t.m} is already handled by another handler`);return this.h.set(e,t),t}handleRequestWith(t){const e=t.pkgType;if(typeof e!=typeof this.responsePkgType)throw new Error(`Wrapper ${t.m} has an incompatible pkgType ${typeof e}`);if(this.h.has(e))throw new Error(`Wrapper ${t.m} is already handled by another handler`);return this.h.set(e,t),t}aj(t){const e=t.pkgType;return this.h.get(e)===t&&(this.h.delete(e),!0)}a6(t,e){t.handle?.onReceive(e.byteLength);const s=this.V(e),n=this.h.get(s.pkgType);n?n.v(t,s):t.close(new Error(v.InvalidPackage))}a7(t,e){this.q.delete(t.id),this.P?.remove(t.handle),t.o(e),this.F?.(this,t,t.d.B(),e)}a5(t,e){try{const{buff:s,pkgType:n,requestId:i,bodyOffset:r}=e;if(n===this.responsePkgType){const e=s.subarray(r);t.X(i,e)}else{const e=this.O.get(n);if(e){const n=new e(s.subarray(r),!0);t.aa(i,n)}}}catch{t.close(new Error(v.InvalidPackage))}}W;p;U;V;E;q;h;O;P}class W{constructor(t,e,s){this.id=s,this.d=e,this.y=t,this.Y=0}context;handle;id;d;get socket(){return this.d.socket}async sendMessage(t){const e=t.constructor.pkgType,s=[t.buff];this.y.makePkgBuff(e,0,s);const n=await this.d.n(s);this.handle?.onSend(n)}sendRequest(t){return this.l=new Map,this.sendRequest=this.Z,this.X=this.ab,this.o=this.ac,this.Z(t)}async sendErrorResponse(t,e){const s=t.constructor.pkgType,n=[t.buff];this.y.makePkgBuff(s,e,n);const i=await this.d.n(n);this.handle?.onSend(i)}async sendResponse(t,e){const s=[t.respBuff],{makePkgBuff:n,responsePkgType:i}=this.y;n(i,e,s);const r=await this.d.n(s);this.handle?.onSend(r)}async close(t){await this.d.close(t)}X(t,e){2097152===t&&void 0===this.context&&this.close(new Error(v.AuthTimeout))}aa(t,e){const s=this.l.get(t);if(s)return this.l.delete(t),s.i(e)}keepAlive(){const{j:t}=this.y;this.d.A(t).catch(f),this.handle?.onSend(t.byteLength)}forceClose(t){this.close(new Error(t??v.UnknownError))}o(t){}async Z(t){const e=2097151&this.Y++,s=t.constructor.pkgType,n=[t.buff];this.y.makePkgBuff(s,e,n);const i=new Promise((t,s)=>{const i={c:t,i:s};this.l.set(e,i),this.d.n(n).then(t=>{this.handle?.onSend(t)},t=>{this.l.delete(e),s(t)})});t.respBuff=await i}ab(t,e){const s=this.l.get(t);if(s)return this.l.delete(t),void s.c(e);2097152===t&&void 0===this.context&&this.close(new Error(v.AuthTimeout))}ac(t){const e=this.l;if(e.size>0){t||(t=new Error(v.ConnectionClosed));for(const[s,n]of e)e.delete(s),n.i(t)}this.l=void 0}y;l;Y}class q{constructor(t,e){this.id=t,this.Q=e}context;id;socket;get remoteFamily(){return"Local"}async sendMessage(t){return this.Q.a8(this,t)}async sendRequest(t){return this.Q.a9(this,t)}sendErrorResponse(t,e){throw null}sendResponse(t,e){throw null}async close(t){}Q}const N=(t,e)=>new O(t,{responsePkgType:0,makePkgBuff:A,parsePkgBuff:I,connMonitor:e});var j;!function(t){t[t.NotConnected=0]="NotConnected",t[t.Connecting=1]="Connecting",t[t.Connected=2]="Connected"}(j||(j={}));class O{constructor(t,e){const s=new x,n=this.k=new M(s,e);this.G=j.NotConnected,this.a4=t,this.a=new $(()=>this.g()),n.H=this.H.bind(this),n.F=this.F.bind(this)}getConnState(){return this.G}enableAuthenticate(t,e){this.K=e,e.init(t,this)}registerError(t,e){return this.k.registerError(t,e)}registerMessage(t,e){return this.k.registerMessage(t,e)}registerRequest(t,e){return this.k.registerRequest(t,e)}handleMessageWith(t,e){this.k.handleMessageWith(new P(t,(t,s)=>e(s.data),!0))}handleRequestWith(t,e){this.k.handleRequestWith(new S(t,async(t,s)=>{s.resp=await e(s.data)},!0))}sendMessage(t){return this.a.sendMessage(t)}async sendRequest(t){return await this.a.sendRequest(t),t.resp}onConnectionStatus(t){let{c:e}=this;e||(this.c=e=[]),e.push(t)}async g(){const{k:t,K:e}=this;this.G=j.Connecting;try{const s=e?await e.preConnect():this.a4;if(!s)throw new Error(v.UnknownError);return await t.g(s)}catch(e){const s=e instanceof Error?e:new Error(v.UnknownError);this.F(t,this.a,!0,s)}}H(t,e,s){if(this.G=j.Connected,e.context="",this.c)for(const t of this.c)t(!0,e,s)}F(t,e,s,n){if(this.G=j.NotConnected,this.a.ag(),this.c)for(const t of this.c)t(!1,e,s,n)}a4;k;a;G;K;c}export{u as CommonError,k as ConnAliveMonitor,s as ErrorWrapper,i as EventWrapper,a as JsonError,c as JsonMessage,d as JsonRequest,T as JustrunAuthProvider,n as MessageWrapper,v as NetErrorString,r as RequestWrapper,m as TimeoutCache,y as TimeoutMonitor,O as WsClient,N as createNumPkgTypeClient,g as handleUncaughtErrorWith};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "justrun-ws",
3
- "version": "0.3.8",
3
+ "version": "0.4.0",
4
4
  "module": "./lib/index.min.js",
5
5
  "typings": "./lib/index.d.ts",
6
6
  "exports": {