justrun-ws 0.3.5 → 0.3.8

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
@@ -12,14 +12,12 @@ export interface IWrapper<DataT> {
12
12
  get data(): DataT;
13
13
  }
14
14
  declare abstract class DataWrapper<DataT> implements IWrapper<DataT> {
15
- constructor(a: DataT | Uint8Array, needParse?: true);
15
+ constructor(input: DataT | Uint8Array, needParse?: true);
16
16
  get data(): DataT;
17
17
  set data(val: DataT);
18
18
  get buff(): Uint8Array;
19
19
  protected abstract encode(data: DataT): Uint8Array;
20
20
  protected abstract decode(buffer: Uint8Array): DataT;
21
- private z?;
22
- private $?;
23
21
  }
24
22
  declare abstract class PkgWrapper<DataT> extends DataWrapper<DataT> {
25
23
  static context: unknown;
@@ -36,7 +34,7 @@ export declare abstract class EventWrapper<EventT> extends PkgWrapper<EventT> {
36
34
  isEvent(): boolean;
37
35
  }
38
36
  export declare abstract class RequestWrapper<RequestT, ResponseT> extends PkgWrapper<RequestT> {
39
- constructor(a: RequestT | Uint8Array, needParse?: true);
37
+ constructor(input: RequestT | Uint8Array, needParse?: true);
40
38
  isRequest(): boolean;
41
39
  get resp(): ResponseT;
42
40
  set resp(val: ResponseT);
@@ -44,12 +42,10 @@ export declare abstract class RequestWrapper<RequestT, ResponseT> extends PkgWra
44
42
  set respBuff(val: Uint8Array);
45
43
  protected abstract encodeResponse(response: ResponseT): Uint8Array;
46
44
  protected abstract decodeResponse(buffer: Uint8Array): ResponseT;
47
- private _?;
48
- private A?;
49
45
  }
50
46
  export type ErrorWrapperCtor<ErrorT, WrapperT extends ErrorWrapper<ErrorT> = ErrorWrapper<ErrorT>> = new (error: ErrorT | Uint8Array, needParse?: true) => WrapperT;
51
47
  export type MessageWrapperCtor<MessageT, WrapperT extends MessageWrapper<MessageT> = MessageWrapper<MessageT>> = new (message: MessageT | Uint8Array, needParse?: true) => WrapperT;
52
- export type RequestWrapperCtor<RequestT, ResponseT, WrapperT extends RequestWrapper<RequestT, ResponseT> = RequestWrapper<RequestT, ResponseT>> = new (request: RequestT | Uint8Array, needParse?: true, _response?: ResponseT) => WrapperT;
48
+ export type RequestWrapperCtor<RequestT, ResponseT, WrapperT extends RequestWrapper<RequestT, ResponseT> = RequestWrapper<RequestT, ResponseT>> = new (request: RequestT | Uint8Array, needParse?: true, response?: ResponseT) => WrapperT;
53
49
  export interface IConn<ConnContextT = void> {
54
50
  context?: ConnContextT | undefined;
55
51
  readonly id: number;
@@ -73,26 +69,16 @@ declare class ListNode {
73
69
  insertBefore<SelfT extends ListNode>(this: SelfT, node: SelfT): void;
74
70
  insertAfter<SelfT extends ListNode>(this: SelfT, node: SelfT): void;
75
71
  remove(): void;
76
- private j;
77
- private k;
78
72
  }
79
73
  declare abstract class MonitorItem extends ListNode {
80
74
  abstract warnTimeout(): void;
81
75
  abstract onTimeout(): void;
82
76
  }
83
77
  export declare class TimeoutMonitor {
84
- constructor(c: number, h: number, d: number);
78
+ constructor(tickMilSec: number, warningTick: number, timeoutTick: number);
85
79
  insert(item: MonitorItem): void;
86
80
  update(item: MonitorItem): void;
87
81
  remove(item: MonitorItem): void;
88
- private ab;
89
- private Z;
90
- private L;
91
- private H;
92
- private p;
93
- private I;
94
- private a0?;
95
- private t;
96
82
  }
97
83
  export type TypedPkgHubOpts<PkgTypeT extends number | string> = {
98
84
  readonly responsePkgType: PkgTypeT;
@@ -120,26 +106,25 @@ export interface DoneResp<ResultT extends string | number | boolean = boolean> {
120
106
  result: ResultT;
121
107
  }
122
108
  export declare const handleUncaughtErrorWith: (handler: (conn: IConn<unknown>, err: Error) => ErrorWrapper<unknown>) => void;
123
- export declare enum NetErrorString {
124
- AuthTimeout = "AuthTimeout",
125
- BadRequest = "BadRequest",
126
- ConnectFailed = "ConnectFailed",
127
- ConnectionClosed = "ConnectionClosed",
128
- InvalidConnString = "InvalidConnString",
129
- InvalidConnection = "InvalidConnection",
130
- InvalidPackage = "InvalidPackage",
131
- NotAuthenticated = "NotAuthenticated",
132
- NotFound = "NotFound",
133
- Timeout = "Timeout",
134
- UnknownError = "UnknownError"
135
- }
109
+ export declare const NetErrorString: {
110
+ readonly AuthTimeout: "Auth Timeout";
111
+ readonly BadRequest: "Bad Request";
112
+ readonly ConnectFailed: "Connect Failed";
113
+ readonly ConnectionClosed: "Connection Closed";
114
+ readonly InvalidConnString: "Invalid Connection String";
115
+ readonly InvalidConnection: "Invalid Connection";
116
+ readonly InvalidPackage: "Invalid Package";
117
+ readonly NotAuthenticated: "Not Authenticated";
118
+ readonly NotFound: "Not Found";
119
+ readonly Timeout: "Timeout";
120
+ readonly UnknownError: "Unknown Error";
121
+ };
122
+ export type NetErrorString = typeof NetErrorString[keyof typeof NetErrorString];
136
123
  export declare class TimeoutCache<KeyT extends number | string, ValT> {
137
- constructor(c: number, d: number);
124
+ constructor(tickMilSec: number, timeoutTick: number);
138
125
  get(key: KeyT): ValT | undefined;
139
126
  set(key: KeyT, val: ValT): void;
140
127
  delete(key: KeyT): boolean;
141
- private b;
142
- private q;
143
128
  }
144
129
  export interface IAuthProvider {
145
130
  init<PkgTypeT extends number | string>(proxyPrivatePkgType: PkgTypeT, client: WsClient<PkgTypeT>): Promise<void>;
@@ -152,7 +137,7 @@ declare enum ClientConnState {
152
137
  Connected = 2
153
138
  }
154
139
  export declare class WsClient<PkgTypeT extends number | string> {
155
- constructor(connUrl: string, t: TypedPkgHubOpts<PkgTypeT>);
140
+ constructor(connUrl: string, opts: TypedPkgHubOpts<PkgTypeT>);
156
141
  getConnState(): ClientConnState;
157
142
  enableAuthenticate(proxyPrivatePkgType: PkgTypeT, authProvider: IAuthProvider): void;
158
143
  registerError<ErrorT>(pkgType: PkgTypeT, wrapperCtor: ErrorWrapperCtor<ErrorT>): void;
@@ -163,38 +148,15 @@ export declare class WsClient<PkgTypeT extends number | string> {
163
148
  sendMessage<MessageT>(message: MessageWrapper<MessageT>): Promise<void>;
164
149
  sendRequest<RequestT, ResponseT>(request: RequestWrapper<RequestT, ResponseT>): Promise<ResponseT>;
165
150
  onConnectionStatus(listener: (isOpen: boolean, conn: IConn<string>, active: boolean, err?: Error) => void): void;
166
- private g;
167
- private N;
168
- private J;
169
- private aa;
170
- private m;
171
- private a;
172
- private K;
173
- private P?;
174
- private b?;
175
151
  }
176
152
  export declare class JustrunAuthProvider implements IAuthProvider {
177
- constructor(w: string, x: (b: string, k: string, o?: boolean) => string, y: (g: string, k: string, s?: string) => void);
153
+ constructor(authUrl: string, getConnUrl: (address: string, sid: string, kick?: boolean) => string, authStateCb: (cid: string, sid: string, connErr?: string) => void);
178
154
  init<PkgTypeT extends number | string>(proxyPrivatePkgType: PkgTypeT, client: WsClient<PkgTypeT>): Promise<void>;
179
155
  preConnect(): Promise<string>;
180
156
  authWithCredential(type: "signin" | "signup", id: string, hash: string, extra: string): Promise<void>;
181
157
  authWithOAuth2(returnTo: string, oauthUrl: string, clientId: string, scope: string): void;
182
158
  resetAuthState(): Promise<void>;
183
159
  resetConnState(forceKick: boolean): void;
184
- private an;
185
- private R;
186
- private ao;
187
- private W;
188
- private S;
189
- private c;
190
- private d;
191
- private V;
192
- private Q;
193
- private a?;
194
- private h?;
195
- private F?;
196
- private E;
197
- private f;
198
160
  }
199
161
 
200
162
  export {};
@@ -0,0 +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};
package/package.json CHANGED
@@ -1,18 +1,12 @@
1
1
  {
2
2
  "name": "justrun-ws",
3
- "version": "0.3.5",
4
- "scripts": {
5
- "start": "webpack serve"
6
- },
7
- "files": [
8
- "./lib/*"
9
- ],
10
- "module": "./lib/index.min.mjs",
3
+ "version": "0.3.8",
4
+ "module": "./lib/index.min.js",
11
5
  "typings": "./lib/index.d.ts",
12
6
  "exports": {
13
7
  ".": {
14
- "default": "./lib/index.min.mjs",
15
- "types": "./lib/index.d.ts"
8
+ "types": "./lib/index.d.ts",
9
+ "default": "./lib/index.min.js"
16
10
  }
17
11
  },
18
12
  "keywords": [
@@ -21,16 +15,22 @@
21
15
  ],
22
16
  "author": "Andy Deng",
23
17
  "license": "MIT",
18
+ "files": [
19
+ "./lib/*"
20
+ ],
24
21
  "devDependencies": {
25
22
  "@eslint/eslintrc": "^3.2.0",
26
23
  "@eslint/js": "^9.19.0",
24
+ "@rollup/plugin-terser": "^0.4.4",
27
25
  "@typescript-eslint/eslint-plugin": "^8.25.0",
28
26
  "@typescript-eslint/parser": "^8.25.0",
29
27
  "dts-bundle-generator": "^9.5.1",
30
28
  "eslint": "^9.21.0",
31
29
  "eslint-plugin-import": "^2.31.0",
32
30
  "globals": "^16.5.0",
33
- "minify-ts": "^1.2.7",
31
+ "minify-ts": "^1.3.1",
32
+ "rollup": "^4.54.0",
33
+ "terser": "^5.44.1",
34
34
  "ts-loader": "^9.5.2",
35
35
  "webpack": "^5.98.0",
36
36
  "webpack-cli": "^6.0.1"
package/lib/index.min.mjs DELETED
@@ -1 +0,0 @@
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 u 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 d extends a{}let l=(t,e)=>new d(e.message);const g=t=>{l=t};var p;!function(t){t.AuthTimeout="AuthTimeout",t.BadRequest="BadRequest",t.ConnectFailed="ConnectFailed",t.ConnectionClosed="ConnectionClosed",t.InvalidConnString="InvalidConnString",t.InvalidConnection="InvalidConnection",t.InvalidPackage="InvalidPackage",t.NotAuthenticated="NotAuthenticated",t.NotFound="NotFound",t.Timeout="Timeout",t.UnknownError="UnknownError"}(p||(p={}));class f{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}class w{constructor(){this.B=new f}get g(){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 f{}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.g;!r.X(t);t=t.getNext())t.warnTimeout()}const i=s[this.p];for(let t=i.g;!i.X(t);t=t.getNext())t.onTimeout()};Z;L;H;p;I;a0;t}class b extends v{constructor(t,e,s){super(),this.b=t,this.a7=e,this.val=s}val;warnTimeout(){}onTimeout(){this.b.delete(this.a7)}b;a7}class T{constructor(t,e){this.b=new Map,this.q=new m(t,0,e)}get(t){const{b:e,q:s}=this,i=e.get(t);if(i)return s.update(i),i.val}set(t,e){const{b:s,q:i}=this;let r=s.get(t);r?(r.val=e,i.update(r)):(r=new b(s,t,e),s.set(t,r),i.insert(r))}delete(t){const{b:e,q:s}=this,i=e.get(t);return!!i&&(s.remove(i),e.delete(t))}b;q}class E{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}class P extends c{}class x{constructor(t,e,s){let i=sessionStorage.getItem("jrSession");i||(i=crypto.randomUUID(),sessionStorage.setItem("jrSession",i)),this.c="",this.d=i,this.V=t,this.Q="",this.E=e,this.f=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{d:i,f:r}=this,n=this.W();if(n){const{g:t,j:e}=n;if(Math.round(Date.now()/1e3)<=e)return void r(t,i)}r("","")}async preConnect(){const{c:t,d:e,h:s,f:i,E:r}=this;if(s)return i(t,e,s),"";const n=""===s;this.h=void 0;let o=this.W();if(o){const{g:t,b:s,i,j:h}=o,a=Math.round(Date.now()/1e3);if(a<=i)return this.Q=o.b,r(s,e,n);if(a<=h&&(o=await this.S("refresh",""),o))return this.Q=o.b,r(o.b,e,n)}return this.h="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.d}~${s}~${encodeURI(t)}`}async resetAuthState(){await this.S("signout","")}resetConnState(t){if(this.h){this.h=t?"":void 0;const{c:e,d:s,f:i}=this;i(e,s)}}an(t,e,s,i){if(t){this.a=e;const t=this.W();if(t){const{i:e}=t;this.F=new E(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.h=i?.message||"unknown error",{c:e,d:s,f:r}=this;r(e,s,t)}}async R(){this.F=void 0;const{d:t,E:e}=this,s=await this.S("refresh","");if(s&&this.a){const{b:i,i: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 E(1e3*r-Date.now(),this.R)}else this.a&&(this.a.close(),this.a=void 0)}}async ao(t){const{c:e,d:s,a:i}=this,{type:r,n}=t;"kick"===r&&i&&(i.close(),this.a=void 0,n&&(this.h=n,this.f(e,s,n)))}W(){const t=localStorage.getItem("jrAuth")||void 0;if(t){const[e,s,i,r]=t.split(","),{c:n,a:o}=this;return n&&e!==n&&o&&(o.close(),this.a=void 0),this.c=e,{g:e,b:s,i:parseInt(i),j:parseInt(r)}}}async S(t,e){const s=await fetch(this.V,{method:"POST",body:`${t}:${e}`}).catch(t=>{throw new d(t.message)}),i=await s.text();if(!s.ok)throw new d(i);if(i.startsWith("auth:")){const t=i.substring(5);localStorage.setItem("jrAuth",t);const[e,s,r,n]=t.split(","),{c:o,a:h}=this;return o!==e&&(o&&h&&(h.close(),this.a=void 0),this.c=e,this.f(e,this.d,this.h)),{g:e,b:s,i:parseInt(r),j:parseInt(n)}}if(i.startsWith("clear:"))localStorage.removeItem("jrAuth"),this.c="",this.h=void 0,this.f("",""),this.a&&(this.a.close(),this.a=void 0);else if(i.startsWith("error:")){"refresh"!==t&&"signout"!==t||(localStorage.removeItem("jrAuth"),this.c="",this.h=void 0,this.f("",""),this.a&&(this.a.close(),this.a=void 0));const e=i.substring(6);throw new d(e)}}c;d;V;Q;a;h;F;E;f}const C=new Error(p.NotAuthenticated);class S{constructor(t,e,s){this.o=t,this.x=e,this.y=!s}get pkgType(){return this.o.pkgType}get k(){return this.o.name}async w(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}class A{constructor(t,e,s){this.o=t,this.x=e,this.y=!s}get pkgType(){return this.o.pkgType}get k(){return this.o.name}async w(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}class R{b(){return null}init(t){this.G=t}async F(t){return!1}async H(){return!1}async g(t){const e=new WebSocket(t);return new Promise((t,s)=>{e.onerror=t=>{s(new Error(p.UnknownError))},e.onopen=()=>{t(this.al(e,!0))}})}al=(t,e)=>{const s=new I(t),{conn:i,$: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(p.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 B(t){if(this.i)return this.i.send(t);throw new Error(p.InvalidConnection)}async m(t){if(this.i){const e=k(t);return this.i.send(e)}throw new Error(p.InvalidConnection)}async close(t){const{i:e}=this;e&&(this.i=void 0,t?e.close(1006,t.message):e.readyState<=WebSocket.OPEN&&e.close(1e3))}E(){return!this.i}i}const $=(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)},W=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 j{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.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);this.r&&await this.r.then(e=>{this.a=void 0,e.close(t)},()=>this.a=void 0)}async au(){this.a||await this.g()}am(){this.a=void 0}async g(){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 M{constructor(t,e){const{responsePkgType:s,timeoutMonitor:i,makePkgBuff:r,parsePkgBuff:n}=e;this.responsePkgType=s,this.u=0,this.v=new Map,this.h=new Map,this.T=new Map,this.a1=r,this.a2=n,this.C=t,this.M=i,this.w=this.ac;const o=[];this.a1(s,2097152,o),this.a3={makePkgBuff:r,responsePkgType:s,q:k(o)},this.h.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,$:t=>this.ad(s,t),s:t=>this.ae(s,t)};return this.N?.(this,s,!!e),i})}responsePkgType;context;N;J;b(){return this.C.b()}P(t){return this.v.get(t)}g(t){return this.C.g(t)}async Q(){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 R(t){return this.C.F(t)}async S(){return this.C.H()}af(t,e){const s=e.constructor.pkgType,i=this.h.get(s);if(i)return i?.p(t,e);throw new Error(p.InvalidPackage)}ag(t,e){const s=e.constructor.pkgType,i=this.h.get(s);if(i)return i?.p(t,e);throw new Error(p.InvalidPackage)}registerError(t,e){e.registerPkgType(t),this.T.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.k} has an incompatible pkgType ${typeof e}`);if(this.h.has(e))throw new Error(`Wrapper ${t.k} 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.k} has an incompatible pkgType ${typeof e}`);if(this.h.has(e))throw new Error(`Wrapper ${t.k} is already handled by another handler`);return this.h.set(e,t),t}aq(t){const e=t.pkgType;return this.h.get(e)===t&&(this.h.delete(e),!0)}ad(t,e){this.M?.update(t);const s=this.a2(e),i=this.h.get(s.pkgType);i?i.w(t,s):t.close(new Error(p.InvalidPackage))}ae(t,e){this.v.delete(t.id),this.M?.remove(t),t.s(e),this.J?.(this,t,t.e.E(),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(p.InvalidPackage))}}a3;u;a1;a2;C;v;h;T;M}class B extends v{constructor(t,e,s){super(),this.id=s,this.e=e,this.D=t,this.a5=0}context;id;e;get socket(){return this.e.socket}sendMessage(t){const e=t.constructor.pkgType,s=[t.buff];return this.D.makePkgBuff(e,0,s),this.e.m(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.e.m(i)}sendResponse(t,e){const s=[t.respBuff],{makePkgBuff:i,responsePkgType:r}=this.D;return i(r,e,s),this.e.m(s)}async close(t){await this.e.close(t)}a4(t,e){2097152===t&&void 0===this.context&&this.close(new Error(p.AuthTimeout))}ah(t,e){const s=this.n.get(t);if(s)return this.n.delete(t),s.j(e)}warnTimeout(){this.e.B(this.D.q).catch(y)}onTimeout(){this.close(new Error(p.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={d:t,j:s};this.n.set(e,r),this.e.m(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.d(e);2097152===t&&void 0===this.context&&this.close(new Error(p.AuthTimeout))}aj(t){const e=this.n;if(e.size>0){t||(t=new Error(p.ConnectionClosed));for(const[s,i]of e)e.delete(s),i.j(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 F(t,{responsePkgType:0,makePkgBuff:$,parsePkgBuff:W,timeoutMonitor:e});var O;!function(t){t[t.NotConnected=0]="NotConnected",t[t.Connecting=1]="Connecting",t[t.Connected=2]="Connected"}(O||(O={}));class F{constructor(t,e){const s=new R,i=this.m=new M(s,e);this.K=O.NotConnected,this.aa=t,this.a=new j(()=>this.g()),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 S(t,(t,s)=>e(s.data),!0))}handleRequestWith(t,e){this.m.handleRequestWith(new A(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{b:e}=this;e||(this.b=e=[]),e.push(t)}async g(){const{m:t,P:e}=this;this.K=O.Connecting;try{const s=e?await e.preConnect():this.aa;if(!s)throw new Error(p.UnknownError);return await t.g(s)}catch(e){const s=e instanceof Error?e:new Error(p.UnknownError);this.J(t,this.a,!0,s)}}N(t,e,s){if(this.K=O.Connected,e.context="",this.b)for(const t of this.b)t(!0,e,s)}J(t,e,s,i){if(this.K=O.NotConnected,this.a.am(),this.b)for(const t of this.b)t(!1,e,s,i)}aa;m;a;K;P;b}export{d as CommonError,s as ErrorWrapper,r as EventWrapper,a as JsonError,c as JsonMessage,u as JsonRequest,x as JustrunAuthProvider,i as MessageWrapper,p as NetErrorString,n as RequestWrapper,T as TimeoutCache,m as TimeoutMonitor,F as WsClient,q as createNumPkgTypeClient,g as handleUncaughtErrorWith};