justrun-ws 0.3.7 → 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
@@ -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;
@@ -66,37 +62,17 @@ export type ParseResult<PkgTypeT extends number | string> = {
66
62
  requestId: number;
67
63
  bodyOffset: number;
68
64
  };
69
- declare class ListNode {
70
- constructor();
71
- getPrev<SelfT extends ListNode>(this: SelfT): SelfT;
72
- getNext<SelfT extends ListNode>(this: SelfT): SelfT;
73
- insertBefore<SelfT extends ListNode>(this: SelfT, node: SelfT): void;
74
- insertAfter<SelfT extends ListNode>(this: SelfT, node: SelfT): void;
75
- remove(): void;
76
- private j;
77
- private k;
78
- }
79
- declare abstract class MonitorItem extends ListNode {
80
- abstract warnTimeout(): void;
81
- abstract onTimeout(): void;
65
+ export interface IConnMonitorHandle {
66
+ onReceive(bytes: number): void;
67
+ onSend(bytes: number): void;
82
68
  }
83
- export declare class TimeoutMonitor {
84
- constructor(c: number, h: number, d: number);
85
- insert(item: MonitorItem): void;
86
- update(item: MonitorItem): void;
87
- 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;
69
+ export interface IConnMonitor {
70
+ insert(forceClose: (reason?: string) => void, keepAlive?: () => void): IConnMonitorHandle;
71
+ remove(handle: IConnMonitorHandle): void;
96
72
  }
97
73
  export type TypedPkgHubOpts<PkgTypeT extends number | string> = {
98
74
  readonly responsePkgType: PkgTypeT;
99
- readonly timeoutMonitor?: TimeoutMonitor;
75
+ readonly connMonitor?: IConnMonitor;
100
76
  makePkgBuff: (pkgType: PkgTypeT, requestId: number, encoded: Uint8Array[]) => void;
101
77
  parsePkgBuff: (buff: Uint8Array) => ParseResult<PkgTypeT>;
102
78
  };
@@ -120,39 +96,52 @@ export interface DoneResp<ResultT extends string | number | boolean = boolean> {
120
96
  result: ResultT;
121
97
  }
122
98
  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
- }
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
+ }
104
+ export declare const NetErrorString: {
105
+ readonly AuthTimeout: "Auth Timeout";
106
+ readonly BadRequest: "Bad Request";
107
+ readonly ConnectFailed: "Connect Failed";
108
+ readonly ConnectionClosed: "Connection Closed";
109
+ readonly InvalidConnString: "Invalid Connection String";
110
+ readonly InvalidConnection: "Invalid Connection";
111
+ readonly InvalidPackage: "Invalid Package";
112
+ readonly NotAuthenticated: "Not Authenticated";
113
+ readonly NotFound: "Not Found";
114
+ readonly Timeout: "Timeout";
115
+ readonly UnknownError: "Unknown Error";
116
+ };
117
+ export type NetErrorString = typeof NetErrorString[keyof typeof NetErrorString];
136
118
  export declare class TimeoutCache<KeyT extends number | string, ValT> {
137
- constructor(c: number, d: number);
119
+ constructor(tickMilSec: number, timeoutTick: number);
138
120
  get(key: KeyT): ValT | undefined;
139
121
  set(key: KeyT, val: ValT): void;
140
122
  delete(key: KeyT): boolean;
141
- private b;
142
- private q;
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;
143
132
  }
144
133
  export interface IAuthProvider {
145
134
  init<PkgTypeT extends number | string>(proxyPrivatePkgType: PkgTypeT, client: WsClient<PkgTypeT>): Promise<void>;
146
135
  preConnect(): Promise<string>;
147
136
  }
148
- export declare const createNumPkgTypeClient: (connUrl: string, timeoutMonitor?: TimeoutMonitor) => WsClient<number>;
137
+ export declare const createNumPkgTypeClient: (connUrl: string, connMonitor?: IConnMonitor) => WsClient<number>;
149
138
  declare enum ClientConnState {
150
139
  NotConnected = 0,
151
140
  Connecting = 1,
152
141
  Connected = 2
153
142
  }
154
143
  export declare class WsClient<PkgTypeT extends number | string> {
155
- constructor(connUrl: string, t: TypedPkgHubOpts<PkgTypeT>);
144
+ constructor(connUrl: string, opts: TypedPkgHubOpts<PkgTypeT>);
156
145
  getConnState(): ClientConnState;
157
146
  enableAuthenticate(proxyPrivatePkgType: PkgTypeT, authProvider: IAuthProvider): void;
158
147
  registerError<ErrorT>(pkgType: PkgTypeT, wrapperCtor: ErrorWrapperCtor<ErrorT>): void;
@@ -163,38 +152,15 @@ export declare class WsClient<PkgTypeT extends number | string> {
163
152
  sendMessage<MessageT>(message: MessageWrapper<MessageT>): Promise<void>;
164
153
  sendRequest<RequestT, ResponseT>(request: RequestWrapper<RequestT, ResponseT>): Promise<ResponseT>;
165
154
  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
155
  }
176
156
  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);
157
+ constructor(authUrl: string, getConnUrl: (address: string, sid: string, kick?: boolean) => string, authStateCb: (cid: string, sid: string, connErr?: string) => void);
178
158
  init<PkgTypeT extends number | string>(proxyPrivatePkgType: PkgTypeT, client: WsClient<PkgTypeT>): Promise<void>;
179
159
  preConnect(): Promise<string>;
180
160
  authWithCredential(type: "signin" | "signup", id: string, hash: string, extra: string): Promise<void>;
181
161
  authWithOAuth2(returnTo: string, oauthUrl: string, clientId: string, scope: string): void;
182
162
  resetAuthState(): Promise<void>;
183
163
  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
164
  }
199
165
 
200
166
  export {};
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 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}let w=class{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: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: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}let A=class{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},R=class{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};
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,14 +1,8 @@
1
1
  {
2
2
  "name": "justrun-ws",
3
- "version": "0.3.7",
4
- "scripts": {
5
- "start": "webpack serve"
6
- },
7
- "files": [
8
- "./lib/*"
9
- ],
10
- "typings": "./lib/index.d.ts",
3
+ "version": "0.4.0",
11
4
  "module": "./lib/index.min.js",
5
+ "typings": "./lib/index.d.ts",
12
6
  "exports": {
13
7
  ".": {
14
8
  "types": "./lib/index.d.ts",
@@ -21,6 +15,9 @@
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",
@@ -31,7 +28,7 @@
31
28
  "eslint": "^9.21.0",
32
29
  "eslint-plugin-import": "^2.31.0",
33
30
  "globals": "^16.5.0",
34
- "minify-ts": "^1.2.8",
31
+ "minify-ts": "^1.3.1",
35
32
  "rollup": "^4.54.0",
36
33
  "terser": "^5.44.1",
37
34
  "ts-loader": "^9.5.2",