justrun-ws 0.2.3 → 0.3.1

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.
@@ -0,0 +1,231 @@
1
+ import { m } from './common/AdjustableTimer';
2
+ import { CommonError } from './handler/common';
3
+ import { JsonMessage } from './net/JsonPackageWrapper';
4
+ class u extends JsonMessage {
5
+ }
6
+ export class JustrunAuthProvider {
7
+ constructor(w, x, y) {
8
+ let k = sessionStorage.getItem('jrSession');
9
+ if (!k) {
10
+ k = crypto.randomUUID();
11
+ sessionStorage.setItem('jrSession', k);
12
+ }
13
+ this.c = '';
14
+ this.d = k;
15
+ this.T = w;
16
+ this.O = '';
17
+ this.C = x;
18
+ this.f = y;
19
+ this.P = this.P.bind(this);
20
+ const p = () => {
21
+ throw new Error('JustrunAuthProvider shall be enabled before use');
22
+ };
23
+ this.authWithCredential = p;
24
+ this.authWithOAuth2 = p;
25
+ this.resetAuthState = p;
26
+ this.resetConnState = p;
27
+ }
28
+ async init(proxyPrivatePkgType, client) {
29
+ const q = JustrunAuthProvider.prototype;
30
+ this.authWithCredential = q.authWithCredential;
31
+ this.authWithOAuth2 = q.authWithOAuth2;
32
+ this.resetAuthState = q.resetAuthState;
33
+ this.resetConnState = q.resetConnState;
34
+ client.onConnectionStatus(this.ak.bind(this));
35
+ client.registerMessage(proxyPrivatePkgType, u);
36
+ client.handleMessageWith(u, this.al.bind(this));
37
+ const { d, f } = this;
38
+ const e = this.U();
39
+ if (e) {
40
+ const { g, j } = e;
41
+ const now = Math.round(Date.now() / 1000);
42
+ if (now <= j) {
43
+ f(g, d);
44
+ return;
45
+ }
46
+ }
47
+ f('', '');
48
+ }
49
+ async preConnect() {
50
+ const { c, d, h, f, C } = this;
51
+ if (h) {
52
+ f(c, d, h);
53
+ return '';
54
+ }
55
+ const o = h === '';
56
+ this.h = undefined;
57
+ let e = this.U();
58
+ if (e) {
59
+ const { g, b, i, j } = e;
60
+ const now = Math.round(Date.now() / 1000);
61
+ if (now <= i) {
62
+ this.O = e.b;
63
+ return C(b, d, o);
64
+ }
65
+ if (now <= j) {
66
+ e = await this.Q('refresh', '');
67
+ if (e) {
68
+ this.O = e.b;
69
+ return C(e.b, d, o);
70
+ }
71
+ }
72
+ }
73
+ this.h = 'unknown error';
74
+ f('', '');
75
+ return '';
76
+ }
77
+ async authWithCredential(type, id, hash, extra) {
78
+ await this.Q(type, `${id},${hash},${extra}`);
79
+ }
80
+ authWithOAuth2(returnTo, oauthUrl, clientId, scope) {
81
+ const z = this.T;
82
+ const t = `${oauthUrl}?client_id=${clientId}&redirect_uri=${z}&scope=${scope}&response_type=code`;
83
+ window.location.href = `${t}&state=${this.d}~${clientId}~${encodeURI(returnTo)}`;
84
+ }
85
+ async resetAuthState() {
86
+ await this.Q('signout', '');
87
+ }
88
+ resetConnState(forceKick) {
89
+ if (this.h) {
90
+ this.h = forceKick ? '' : undefined;
91
+ const { c, d, f } = this;
92
+ f(c, d);
93
+ }
94
+ }
95
+ ak(isOpen, conn, active, err) {
96
+ if (isOpen) {
97
+ this.a = conn;
98
+ const e = this.U();
99
+ if (e) {
100
+ const { i } = e;
101
+ this.D = new m(i * 1000 - Date.now(), this.P);
102
+ }
103
+ }
104
+ else {
105
+ this.a = undefined;
106
+ if (this.D) {
107
+ this.D.ah();
108
+ this.D = undefined;
109
+ }
110
+ if (!active) {
111
+ const s = this.h = err?.message || 'unknown error';
112
+ const { c, d, f } = this;
113
+ f(c, d, s);
114
+ }
115
+ }
116
+ }
117
+ async P() {
118
+ this.D = undefined;
119
+ const { d, C } = this;
120
+ const e = await this.Q('refresh', '');
121
+ if (e && this.a) {
122
+ const { b, i } = e;
123
+ if (b === this.O) {
124
+ const t = C(b, d);
125
+ const [$, _] = t.split('://');
126
+ await fetch(`${$.replace('ws', 'http')}://${_}`);
127
+ this.D = new m(i * 1000 - Date.now(), this.P);
128
+ }
129
+ else if (this.a) {
130
+ this.a.close();
131
+ this.a = undefined;
132
+ }
133
+ }
134
+ }
135
+ async al(message) {
136
+ const { c, d, a } = this;
137
+ const { type, n } = message;
138
+ if (type === 'kick' && a) {
139
+ a.close();
140
+ this.a = undefined;
141
+ if (n) {
142
+ this.h = n;
143
+ this.f(c, d, n);
144
+ }
145
+ }
146
+ }
147
+ U() {
148
+ const v = localStorage.getItem('jrAuth') || undefined;
149
+ if (v) {
150
+ const [g, b, i, j] = v.split(',');
151
+ const { c, a } = this;
152
+ if (c && g !== c && a) {
153
+ a.close();
154
+ this.a = undefined;
155
+ }
156
+ this.c = g;
157
+ return {
158
+ g,
159
+ b,
160
+ i: parseInt(i),
161
+ j: parseInt(j),
162
+ };
163
+ }
164
+ }
165
+ async Q(type, A) {
166
+ const resp = await fetch(this.T, {
167
+ method: 'POST',
168
+ body: `${type}:${A}`,
169
+ }).catch((err) => {
170
+ throw new CommonError(err.message);
171
+ });
172
+ const l = await resp.text();
173
+ if (!resp.ok) {
174
+ throw new CommonError(l);
175
+ }
176
+ if (l.startsWith('auth:')) {
177
+ const r = l.substring(5);
178
+ localStorage.setItem('jrAuth', r);
179
+ const [g, b, i, j] = r.split(',');
180
+ const { c, a } = this;
181
+ if (c !== g) {
182
+ if (c && a) {
183
+ a.close();
184
+ this.a = undefined;
185
+ }
186
+ this.c = g;
187
+ this.f(g, this.d, this.h);
188
+ }
189
+ return {
190
+ g,
191
+ b,
192
+ i: parseInt(i),
193
+ j: parseInt(j),
194
+ };
195
+ }
196
+ else if (l.startsWith('clear:')) {
197
+ localStorage.removeItem('jrAuth');
198
+ this.c = '';
199
+ this.h = undefined;
200
+ this.f('', '');
201
+ if (this.a) {
202
+ this.a.close();
203
+ this.a = undefined;
204
+ }
205
+ }
206
+ else if (l.startsWith('error:')) {
207
+ if (type === 'refresh' || type === 'signout') {
208
+ localStorage.removeItem('jrAuth');
209
+ this.c = '';
210
+ this.h = undefined;
211
+ this.f('', '');
212
+ if (this.a) {
213
+ this.a.close();
214
+ this.a = undefined;
215
+ }
216
+ }
217
+ const r = l.substring(6);
218
+ throw new CommonError(r);
219
+ }
220
+ }
221
+ c;
222
+ d;
223
+ T;
224
+ O;
225
+ a;
226
+ h;
227
+ D;
228
+ C;
229
+ f;
230
+ }
231
+ //# sourceMappingURL=JustRunAuthProvider.js.map
package/lib/WsClient.js CHANGED
@@ -1,55 +1,60 @@
1
- import { b } from './common/AdjustableTimer';
2
- import { CommonError } from './handler/common';
3
- import { n, o } from './handler/SimpleHandler';
4
- import { r } from './net/BrowserWsNet';
5
- import { p, s } from './net/hubPkgSerializer';
6
- import { JsonRequest } from './net/JsonPackageWrapper';
7
- import { g } from './net/LazyConn';
1
+ import { h, i } from './handler/SimpleHandler';
2
+ import { m } from './net/BrowserWsNet';
3
+ import { n, o } from './net/hubPkgSerializer';
4
+ import { e } from './net/LazyConn';
8
5
  import { NetErrorString } from './net/NetErrorString';
9
- import { v } from './net/TypedPkgHub';
10
- class l extends JsonRequest {
11
- }
12
- export const createNumPkgTypeClient = (getConnStr, timeoutMonitor) => {
13
- return new WsClient(getConnStr, {
6
+ import { u } from './net/TypedPkgHub';
7
+ export const createNumPkgTypeClient = (connUrl, timeoutMonitor) => {
8
+ return new WsClient(connUrl, {
14
9
  responsePkgType: 0,
15
- makePkgBuff: p,
16
- parsePkgBuff: s,
10
+ makePkgBuff: n,
11
+ parsePkgBuff: o,
17
12
  timeoutMonitor,
18
13
  });
19
14
  };
15
+ export var ClientConnState;
16
+ (function (ClientConnState) {
17
+ ClientConnState[ClientConnState["NotConnected"] = 0] = "NotConnected";
18
+ ClientConnState[ClientConnState["Connecting"] = 1] = "Connecting";
19
+ ClientConnState[ClientConnState["Connected"] = 2] = "Connected";
20
+ })(ClientConnState || (ClientConnState = {}));
20
21
  export class WsClient {
21
- constructor(getConnStr, w) {
22
- const F = new r();
23
- const D = this.d = new v(F, w);
24
- this.h = '';
25
- this.j = [];
26
- this.q = 0;
27
- this.a = new g(() => this.c());
28
- this.H = getConnStr;
29
- this.O = this.c;
30
- D.K = this.K.bind(this);
31
- D.B = this.B.bind(this);
22
+ constructor(connUrl, v) {
23
+ const C = new m();
24
+ const $ = this.l = new u(C, v);
25
+ this.I = ClientConnState.NotConnected;
26
+ this.a7 = connUrl;
27
+ this.a = new e(() => this.g());
28
+ $.L = this.L.bind(this);
29
+ $.H = this.H.bind(this);
30
+ }
31
+ getConnState() {
32
+ return this.I;
33
+ }
34
+ enableAuthenticate(proxyPrivatePkgType, authProvider) {
35
+ this.N = authProvider;
36
+ authProvider.init(proxyPrivatePkgType, this);
32
37
  }
33
38
  registerError(pkgType, wrapperCtor) {
34
- return this.d.registerError(pkgType, wrapperCtor);
39
+ return this.l.registerError(pkgType, wrapperCtor);
35
40
  }
36
41
  registerMessage(pkgType, wrapperCtor) {
37
- return this.d.registerMessage(pkgType, wrapperCtor);
42
+ return this.l.registerMessage(pkgType, wrapperCtor);
38
43
  }
39
44
  registerRequest(pkgType, wrapperCtor) {
40
- return this.d.registerRequest(pkgType, wrapperCtor);
45
+ return this.l.registerRequest(pkgType, wrapperCtor);
41
46
  }
42
47
  handleMessageWith(wrapperCtor, handler) {
43
- const i = (a, f) => {
44
- return handler(f.data);
48
+ const f = (a, d) => {
49
+ return handler(d.data);
45
50
  };
46
- this.d.handleMessageWith(new n(wrapperCtor, i, false));
51
+ this.l.handleMessageWith(new h(wrapperCtor, f, true));
47
52
  }
48
53
  handleRequestWith(wrapperCtor, handler) {
49
- const i = async (a, f) => {
50
- f.resp = await handler(f.data);
54
+ const f = async (a, d) => {
55
+ d.resp = await handler(d.data);
51
56
  };
52
- this.d.handleRequestWith(new o(wrapperCtor, i, false));
57
+ this.l.handleRequestWith(new i(wrapperCtor, f, true));
53
58
  }
54
59
  sendMessage(message) {
55
60
  return this.a.sendMessage(message);
@@ -58,154 +63,52 @@ export class WsClient {
58
63
  await this.a.sendRequest(request);
59
64
  return request.resp;
60
65
  }
61
- async sendCustomAuthRequest(_request) {
62
- throw new Error('Need to call "enableAuthenticate" before using sendCustomAuthRequest');
63
- }
64
- resetAuthState() {
65
- }
66
- enableAuthenticate(proxyAuthPkgType, authStatusCallback, allowAnonymous) {
67
- const { O, H, d, a } = this;
68
- if (this.c === O) {
69
- d.registerRequest(proxyAuthPkgType, l);
70
- let token = '';
71
- let shard = undefined;
72
- this.c = async () => {
73
- this.q = -1;
74
- if (this.m) {
75
- await this.m.Y();
76
- }
77
- for (;;) {
78
- const e = H(shard);
79
- let conn;
80
- try {
81
- conn = await d.c(e);
82
- }
83
- catch {
84
- this.B(d, this.a, true, new Error(NetErrorString.k));
85
- return;
86
- }
87
- if (this.h || allowAnonymous) {
88
- const request = new l({
89
- cid: this.h,
90
- token,
91
- });
92
- try {
93
- await conn.sendRequest(request);
94
- const { resp } = request;
95
- this.h = resp.cid;
96
- token = resp.token;
97
- shard = resp.shard;
98
- if (shard && shard < 0) {
99
- shard = -shard - 1;
100
- conn.close();
101
- continue;
102
- }
103
- authStatusCallback(this.h);
104
- }
105
- catch (err) {
106
- if (err instanceof CommonError) {
107
- if (err.data === 'HitSessionLimit') {
108
- this.h = '';
109
- token = '';
110
- shard = undefined;
111
- authStatusCallback(this.h);
112
- }
113
- }
114
- conn.close(err);
115
- return;
116
- }
117
- }
118
- return conn;
119
- }
120
- };
121
- this.sendCustomAuthRequest = async (request) => {
122
- await a.sendRequest(request);
123
- const { resp } = request;
124
- this.h = resp.cid;
125
- token = resp.token;
126
- shard = resp.shard;
127
- if (shard && shard < 0) {
128
- shard = -shard - 1;
129
- a.close();
130
- }
131
- authStatusCallback(this.h);
132
- return resp;
133
- };
134
- this.resetAuthState = () => {
135
- if (this.h) {
136
- this.h = '';
137
- token = '';
138
- shard = undefined;
139
- a.close();
140
- authStatusCallback(this.h);
141
- }
142
- };
143
- }
144
- }
145
- reconnect(delay) {
146
- const { a, q } = this;
147
- if (q > 0) {
148
- return;
149
- }
150
- if (this.m) {
151
- this.m.a3(delay ?? 0);
152
- }
153
- else if (delay) {
154
- this.m = new b(delay, () => this.m = undefined);
155
- }
156
- if (!q) {
157
- a.reconnect();
158
- }
159
- }
160
66
  onConnectionStatus(listener) {
161
- let { j } = this;
162
- if (!j) {
163
- this.j = j = [];
67
+ let { b } = this;
68
+ if (!b) {
69
+ this.b = b = [];
164
70
  }
165
- j.push(listener);
71
+ b.push(listener);
166
72
  }
167
- async c() {
168
- const { H, d, m } = this;
169
- this.q = -1;
170
- if (m) {
171
- await m.Y();
172
- }
173
- const e = H();
73
+ async g() {
74
+ const { l, N } = this;
75
+ this.I = ClientConnState.Connecting;
174
76
  try {
175
- return d.c(e);
77
+ const c = N ? await N.preConnect() : this.a7;
78
+ if (!c) {
79
+ throw new Error(NetErrorString.UnknownError);
80
+ }
81
+ const conn = await l.g(c);
82
+ return conn;
176
83
  }
177
- catch {
178
- this.B(d, this.a, true, new Error(NetErrorString.k));
84
+ catch (err) {
85
+ const error = err instanceof Error ? err : new Error(NetErrorString.UnknownError);
86
+ this.H(l, this.a, true, error);
179
87
  }
180
88
  }
181
- K(d, conn, W) {
182
- this.q = 1;
89
+ L(l, conn, M) {
90
+ this.I = ClientConnState.Connected;
183
91
  conn.context = '';
184
- if (this.j) {
185
- for (const listener of this.j) {
186
- listener(true, W);
92
+ if (this.b) {
93
+ for (const listener of this.b) {
94
+ listener(true, conn, M);
187
95
  }
188
96
  }
189
97
  }
190
- B(d, a, G, err) {
191
- this.q = 0;
192
- this.a.a5();
193
- if (!G) {
194
- this.resetAuthState();
195
- }
196
- if (this.j) {
197
- for (const listener of this.j) {
198
- listener(false, G, err);
98
+ H(l, conn, O, err) {
99
+ this.I = ClientConnState.NotConnected;
100
+ this.a.aj();
101
+ if (this.b) {
102
+ for (const listener of this.b) {
103
+ listener(false, conn, O, err);
199
104
  }
200
105
  }
201
106
  }
202
- d;
107
+ a7;
108
+ l;
203
109
  a;
204
- h;
205
- q;
206
- H;
207
- O;
208
- m;
209
- j;
110
+ I;
111
+ N;
112
+ b;
210
113
  }
211
114
  //# sourceMappingURL=WsClient.js.map
package/lib/bundle.min.js CHANGED
@@ -1 +1 @@
1
- class t{constructor(t,e){e?this.x=t:this.y=t}get data(){return this.y||(this.y=this.decode(this.x)),this.y}set data(t){this.y=t,this.x=void 0}get buff(){return this.x||(this.x=this.encode(this.y)),this.x}x;y}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 r extends e{isMessage(){return!0}}class i extends e{isEvent(){return!0}}class n extends e{constructor(t,e){super(t,e)}isRequest(){return!0}get resp(){return this.z||(this.z=this.decodeResponse(this.$)),this.z}set resp(t){this.z=t,this.$=void 0}get respBuff(){return this.$||(this.$=this.encodeResponse(this.z)),this.$}set respBuff(t){this.z=void 0,this.$=t}z;$}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 r{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 p=t=>{l=t};var g;!function(t){t.I="AuthTimeout",t.a="BadRequest",t.k="ConnectFailed",t.a1="ConnectionClosed",t.b="InvalidConnString",t.l="InvalidConnection",t.z="InvalidPackage",t.g="NotAuthenticated",t.a2="Timeout",t.m="UnknownError"}(g||(g={}));class f{constructor(){this.e=this,this.i=this}getPrev(){return this.e}getNext(){return this.i}insertBefore(t){this.i=t,this.e=t.e,t.e=this,this.e.i=this}insertAfter(t){this.e=t,this.i=t.i,t.i=this,this.i.e=this}remove(){this.e.i=this.i,this.i.e=this.e}e;i}class w{constructor(){this._=new f}get f(){return this._.getNext()}get a(){return this._.getPrev()}P(t){return t===this._}Q(t){t.insertAfter(this._)}a6(t){t.insertBefore(this._)}_}const y=()=>{},m=t=>{let e=0,s=0;for(;e<t.length;)s+=t[e++].length;const r=new Uint8Array(s);for(s=0;e>0;){const i=t[--e];r.set(i,s),s+=i.length}return r};class k extends f{}class v{constructor(t,e,s){if(this.R=t,this.I=e,this.E=s,this.o=0,this.F=0,this.r=[],0===t)return this.insert=y,this.update=y,void(this.remove=y);for(let t=0;t<s;t++)this.r.push(new w)}insert(t){this.F||(this.S=setInterval(this.a2,this.R)),this.F++,this.r[this.o].Q(t)}update(t){t.remove(),this.r[this.o].Q(t)}remove(t){t.remove(),this.F--,this.F||clearInterval(this.S)}a2=()=>{const{I:t,E:e,r:s}=this;if(this.o++,this.o===e&&(this.o=0),t){let r=this.o+t;r>=e&&(r-=e);const i=s[r];for(let t=i.f;!i.P(t);t=t.getNext())t.keepAlive()}const r=s[this.o];for(let t=r.f;!r.P(t);t=t.getNext())t.timeout()};R;I;E;o;F;S;r}class b{constructor(t,e){this.W=new Promise((t=>{this.G=t})),this.N=e,t>0?this.u=setTimeout((()=>{this.u=void 0,this.N?.(),this.G()}),t):this.G()}a3(t){this.u&&clearTimeout(this.u),t>0?this.u=setTimeout((()=>{this.u=void 0,this.N?.(),this.G()}),t):(this.u=void 0,this.G())}async Y(){await this.W}G;W;u;N}const E=new Error(g.g);class P{constructor(t,e,s=!0){this.l=t,this.v=e,this.w=s}get pkgType(){return this.l.pkgType}get m(){return this.l.name}async _(t,e){const{buff:s,bodyOffset:r}=e,i=s.subarray(r),n=new this.l(i,!0);if(void 0===t.context&&this.w)l(t,E);else try{await this.v(t,n)}catch(e){e.isError||l(t,e)}void 0===t.context&&await t.close()}async r(t,e){if(void 0===t.context&&this.w)l(t,E);else try{return await this.v(t,e)}catch(e){e.isError||l(t,e)}}l;v;w}class T{constructor(t,e,s=!0){this.l=t,this.v=e,this.w=s}get pkgType(){return this.l.pkgType}get m(){return this.l.name}async _(t,e){const{buff:s,requestId:r,bodyOffset:i}=e,n=s.subarray(i),o=new this.l(n,!0);let h;if(void 0===t.context&&this.w)h=l(t,E);else try{await this.v(t,o)}catch(e){h=e.isError?e:l(t,e)}try{h?await t.sendErrorResponse(h,r):await t.sendResponse(o,r),void 0===t.context&&await t.close()}catch(e){await t.close(e)}}async r(t,e){if(void 0!==t.context||!this.w)try{return await this.v(t,e)}catch(e){throw e.isError?e:l(t,e)}throw l(t,E)}l;v;w}class x{o(){return null}P(t){this.D=t}async Q(t){return!1}async R(){return!1}async c(t){const e=new WebSocket(t);return new Promise(((t,s)=>{e.onerror=t=>{s(new Error(g.m))},e.onopen=()=>{t(this.a4(e,!0))}}))}a4=(t,e)=>{const s=new R(t),{conn:r,E:i,n}=this.D(s,e);return t.onmessage=t=>{t.data.arrayBuffer().then((t=>{i(new Uint8Array(t))}))},t.onerror=t=>{n(new Error(g.m))},t.onclose=t=>{1e3===t.code?n():n(new Error(t.reason))},r};D(t,e){throw new Error('Need to call "setConnWrapperMaker" before using')}}class R{constructor(t){this.g=t}get localAddress(){}get localPort(){}get remoteAddress(){}get remoteFamily(){}get remotePort(){}async N(t){if(this.g)return this.g.send(t);throw new Error(g.l)}async p(t){if(this.g){const e=m(t);return this.g.send(e)}throw new Error(g.l)}async close(t){const{g:e}=this;e&&(this.g=void 0,t?e.close(3e3,t.message):e.readyState===WebSocket.OPEN&&e.close(1e3))}O(){return!this.g}g}const A=(t,e,s)=>{const r=[e,t],i=(t=>{let e,s=0,r=0;for(;s<t.length;)for(r++,e=t[s++];e>>>=7;)r++;return r})(r),n=new Uint8Array(i);((t,e,s=0)=>{let r,i,n=s;for(r=0;r<t.length;r++){i=t[r];let s=127&i;for(;i>>>=7;)e[n++]=128|s,s=127&i;e[n++]=s}if(n<=e.length)return n-s;throw new Error("Buffer overflow")})(r,n),s.push(n)},q=t=>{const{h:[e,s],k:r}=((t,e,s=0)=>{let r,i,n=s,o=0,h=0;const a=[];for(r=0;r<t;r++){do{i=e[n++],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{h:a,k:n-s}})(2,t);return{buff:t,pkgType:s,requestId:e,bodyOffset:r}};class B{constructor(t){this.a1=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.c()).sendErrorResponse(t,e)}async sendResponse(t,e){return(this.a??await this.c()).sendResponse(t,e)}async sendMessage(t){return(this.a??await this.c()).sendMessage(t)}async sendRequest(t){return(this.a??await this.c()).sendRequest(t)}async close(t){const{a:e}=this;if(e)return this.a=void 0,void await e.close(t);this.p&&await this.p.then((e=>{this.a=void 0,e.close(t)}),(()=>this.a=void 0))}async reconnect(){this.a||await this.c()}a5(){this.a=void 0}async c(){let{p:t}=this;return t||(t=this.p=new Promise(((t,e)=>{this.a1().then((s=>{s?(t(s),this.a=s,this.p=void 0):e(new Error("Connect failed"))}))}))),await t}a1;a;p}class M{constructor(t,e){const{responsePkgType:s,timeoutMonitor:r,makePkgBuff:i,parsePkgBuff:n}=e;this.responsePkgType=s,this.s=0,this.t=new Map,this.f=new Map,this.L=new Map,this.T=i,this.U=n,this.A=t,this.J=r,this._=this.a7;const o=[];this.T(s,2097152,o),this.V={makePkgBuff:i,responsePkgType:s,u:m(o)},this.f.set(s,this),this.A.P(((t,e)=>{do{this.s++}while(this.t.has(2097151&this.s));const s=new N(this.V,t,2097151&this.s);this.t.set(s.id,s),this.J?.insert(s);const r={conn:s,E:t=>this.a8(s,t),n:t=>this.a9(s,t)};return this.K?.(this,s,!!e),r}))}responsePkgType;context;K;B;o(){return this.A.o()}a3(t){return this.t.get(t)}c(t){return this.A.c(t)}async a4(){do{this.s++}while(this.t.has(2097151&this.s));const t=new S(2097151&this.s,this);return this.t.set(t.id,t),t}async a5(t){return this.A.Q(t)}async a6(){return this.A.R()}ab(t,e){const s=e.constructor.pkgType,r=this.f.get(s);if(r)return r?.r(t,e);throw new Error(g.z)}ac(t,e){const s=e.constructor.pkgType,r=this.f.get(s);if(r)return r?.r(t,e);throw new Error(g.z)}registerError(t,e){e.registerPkgType(t),this.L.set(t,e);const s=this.f.get(this.responsePkgType);this.f.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.f.has(e))throw new Error(`Wrapper ${t.m} is already handled by another handler`);return this.f.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.f.has(e))throw new Error(`Wrapper ${t.m} is already handled by another handler`);return this.f.set(e,t),t}ao(t){const e=t.pkgType;return this.f.get(e)===t&&(this.f.delete(e),!0)}a8(t,e){this.J?.update(t);const s=this.U(e),r=this.f.get(s.pkgType);r?r._(t,s):t.close(new Error(g.z))}a9(t,e){const s=t.id;this.t.delete(s),this.J?.remove(t),t.n(e),this.B?.(this,t,t.b.O(),e)}a7(t,e){try{const{buff:s,pkgType:r,requestId:i,bodyOffset:n}=e;if(r===this.responsePkgType){const e=s.subarray(n);t.X(i,e)}else{const e=this.L.get(r);if(e){const r=new e(s.subarray(n),!0);t.ag(i,r)}}}catch{t.close(new Error(g.z))}}V;s;T;U;A;t;f;L;J}class N extends k{constructor(t,e,s){super(),this.id=s,this.b=e,this.C=t,this.Z=0}context;id;b;get localAddress(){return this.b.localAddress}get localPort(){return this.b.localPort}get remoteAddress(){return this.b.remoteAddress}get remoteFamily(){return this.b.remoteFamily}get remotePort(){return this.b.remotePort}sendMessage(t){const e=t.constructor.pkgType,s=[t.buff];return this.C.makePkgBuff(e,0,s),this.b.p(s)}sendRequest(t){return this.k=new Map,this.sendRequest=this.a0,this.X=this.ah,this.n=this.ai,this.a0(t)}sendErrorResponse(t,e){const s=t.constructor.pkgType,r=[t.buff];return this.C.makePkgBuff(s,e,r),this.b.p(r)}sendResponse(t,e){const s=[t.respBuff],{makePkgBuff:r,responsePkgType:i}=this.C;return r(i,e,s),this.b.p(s)}async close(t){await this.b.close(t)}X(t,e){2097152===t&&void 0===this.context&&this.close(new Error(g.I))}ag(t,e){const s=this.k.get(t);if(s)return this.k.delete(t),s.i(e)}keepAlive(){this.b.N(this.C.u).catch(y)}timeout(){this.close(new Error(g.a2))}n(t){}async a0(t){const e=2097151&this.Z++,s=t.constructor.pkgType,r=[t.buff];this.C.makePkgBuff(s,e,r);const i=new Promise(((t,s)=>{const i={d:t,i:s};this.k.set(e,i),this.b.p(r).catch((t=>{this.k.delete(e),s(t)}))}));t.respBuff=await i}ah(t,e){const s=this.k.get(t);if(s)return this.k.delete(t),void s.d(e);2097152===t&&void 0===this.context&&this.close(new Error(g.I))}ai(t){const e=this.k;if(e.size>0){t||(t=new Error(g.a1));for(const[s,r]of e)e.delete(s),r.i(t)}this.k=void 0}C;k;Z}class S{constructor(t,e){this.id=t,this.M=e}context;id;localAddress;localPort;remoteAddress;remotePort;get remoteFamily(){return"Local"}async sendMessage(t){return this.M.ab(this,t)}async sendRequest(t){return this.M.ac(this,t)}sendErrorResponse(t,e){throw null}sendResponse(t,e){throw null}async close(t){}M}class O extends d{}const C=(t,e)=>new W(t,{responsePkgType:0,makePkgBuff:A,parsePkgBuff:q,timeoutMonitor:e});class W{constructor(t,e){const s=new x,r=this.d=new M(s,e);this.h="",this.j=[],this.q=0,this.a=new B((()=>this.c())),this.H=t,this.O=this.c,r.K=this.K.bind(this),r.B=this.B.bind(this)}registerError(t,e){return this.d.registerError(t,e)}registerMessage(t,e){return this.d.registerMessage(t,e)}registerRequest(t,e){return this.d.registerRequest(t,e)}handleMessageWith(t,e){this.d.handleMessageWith(new P(t,((t,s)=>e(s.data)),!1))}handleRequestWith(t,e){this.d.handleRequestWith(new T(t,(async(t,s)=>{s.resp=await e(s.data)}),!1))}sendMessage(t){return this.a.sendMessage(t)}async sendRequest(t){return await this.a.sendRequest(t),t.resp}async sendCustomAuthRequest(t){throw new Error('Need to call "enableAuthenticate" before using sendCustomAuthRequest')}resetAuthState(){}enableAuthenticate(t,e,s){const{O:r,H:i,d:n,a:o}=this;if(this.c===r){n.registerRequest(t,O);let r,h="";this.c=async()=>{for(this.q=-1,this.m&&await this.m.Y();;){const t=i(r);let o;try{o=await n.c(t)}catch{return void this.B(n,this.a,!0,new Error(g.k))}if(this.h||s){const t=new O({cid:this.h,token:h});try{await o.sendRequest(t);const{resp:s}=t;if(this.h=s.cid,h=s.token,r=s.shard,r&&r<0){r=-r-1,o.close();continue}e(this.h)}catch(t){return t instanceof u&&"HitSessionLimit"===t.data&&(this.h="",h="",r=void 0,e(this.h)),void o.close(t)}}return o}},this.sendCustomAuthRequest=async t=>{await o.sendRequest(t);const{resp:s}=t;return this.h=s.cid,h=s.token,r=s.shard,r&&r<0&&(r=-r-1,o.close()),e(this.h),s},this.resetAuthState=()=>{this.h&&(this.h="",h="",r=void 0,o.close(),e(this.h))}}}reconnect(t){const{a:e,q:s}=this;s>0||(this.m?this.m.a3(t??0):t&&(this.m=new b(t,(()=>this.m=void 0))),s||e.reconnect())}onConnectionStatus(t){let{j:e}=this;e||(this.j=e=[]),e.push(t)}async c(){const{H:t,d:e,m:s}=this;this.q=-1,s&&await s.Y();const r=t();try{return e.c(r)}catch{this.B(e,this.a,!0,new Error(g.k))}}K(t,e,s){if(this.q=1,e.context="",this.j)for(const t of this.j)t(!0,s)}B(t,e,s,r){if(this.q=0,this.a.a5(),s||this.resetAuthState(),this.j)for(const t of this.j)t(!1,s,r)}d;a;h;q;H;O;m;j}export{u as CommonError,s as ErrorWrapper,i as EventWrapper,a as JsonError,c as JsonMessage,d as JsonRequest,r as MessageWrapper,g as NetErrorString,n as RequestWrapper,v as TimeoutMonitor,W as WsClient,C as createNumPkgTypeClient,p as handleUncaughtErrorWith};
1
+ class t{constructor(t,e){e?this.x=t:this.y=t}get data(){return this.y||(this.y=this.decode(this.x)),this.y}set data(t){this.y=t,this.x=void 0}get buff(){return this.x||(this.x=this.encode(this.y)),this.x}x;y}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.z||(this.z=this.decodeResponse(this.$)),this.z}set resp(t){this.z=t,this.$=void 0}get respBuff(){return this.$||(this.$=this.encodeResponse(this.z)),this.$}set respBuff(t){this.z=void 0,this.$=t}z;$}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};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.b=this,this.j=this}getPrev(){return this.b}getNext(){return this.j}insertBefore(t){this.j=t,this.b=t.b,t.b=this,this.b.j=this}insertAfter(t){this.b=t,this.j=t.j,t.j=this,this.j.b=this}remove(){this.b.j=this.j,this.j.b=this.b}b;j}class w{constructor(){this._=new f}get e(){return this._.getNext()}get a(){return this._.getPrev()}V(t){return t===this._}W(t){t.insertAfter(this._)}am(t){t.insertBefore(this._)}_}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.X=t,this.J=e,this.F=s,this.p=0,this.G=0,this.r=[],0===t)return this.insert=y,this.update=y,void(this.remove=y);for(let t=0;t<s;t++)this.r.push(new w)}insert(t){this.G||(this.Y=setInterval(this.a8,this.X)),this.G++,this.r[this.p].W(t)}update(t){t.remove(),this.r[this.p].W(t)}remove(t){t.remove(),this.G--,this.G||clearInterval(this.Y)}a8=()=>{const{J:t,F:e,r: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.V(t);t=t.getNext())t.warnTimeout()}const i=s[this.p];for(let t=i.e;!i.V(t);t=t.getNext())t.onTimeout()};X;J;F;p;G;Y;r}class b{constructor(t,e){this.a5=new Promise(t=>{this.u=t}),this.M=e,t>0?this.k=setTimeout(()=>{this.k=void 0,this.u(!0),e?.()},t):(this.u(!0),e?.())}ao(t){const{k:e,u:s,M:i}=this;e&&clearTimeout(e),t>0?this.k=setTimeout(()=>{this.k=void 0,i?.(),s(!0)},t):(this.k=void 0,s(!0),i?.())}ah(){this.k&&(clearTimeout(this.k),this.k=void 0,this.u(!1))}ap(){return this.a5}u;a5;k;M}class T extends c{}class E{constructor(t,e,s){let i=sessionStorage.getItem("jrSession");i||(i=crypto.randomUUID(),sessionStorage.setItem("jrSession",i)),this.c="",this.d=i,this.T=t,this.O="",this.C=e,this.f=s,this.P=this.P.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=E.prototype;this.authWithCredential=s.authWithCredential,this.authWithOAuth2=s.authWithOAuth2,this.resetAuthState=s.resetAuthState,this.resetConnState=s.resetConnState,e.onConnectionStatus(this.ak.bind(this)),e.registerMessage(t,T),e.handleMessageWith(T,this.al.bind(this));const{d:i,f:r}=this,n=this.U();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,C:r}=this;if(s)return i(t,e,s),"";const n=""===s;this.h=void 0;let o=this.U();if(o){const{g:t,b:s,i,j:h}=o,a=Math.round(Date.now()/1e3);if(a<=i)return this.O=o.b,r(s,e,n);if(a<=h&&(o=await this.Q("refresh",""),o))return this.O=o.b,r(o.b,e,n)}return this.h="unknown error",i("",""),""}async authWithCredential(t,e,s,i){await this.Q(t,`${e},${s},${i}`)}authWithOAuth2(t,e,s,i){const r=`${e}?client_id=${s}&redirect_uri=${this.T}&scope=${i}&response_type=code`;window.location.href=`${r}&state=${this.d}~${s}~${encodeURI(t)}`}async resetAuthState(){await this.Q("signout","")}resetConnState(t){if(this.h){this.h=t?"":void 0;const{c:e,d:s,f:i}=this;i(e,s)}}ak(t,e,s,i){if(t){this.a=e;const t=this.U();if(t){const{i:e}=t;this.D=new b(1e3*e-Date.now(),this.P)}}else if(this.a=void 0,this.D&&(this.D.ah(),this.D=void 0),!s){const t=this.h=i?.message||"unknown error",{c:e,d:s,f:r}=this;r(e,s,t)}}async P(){this.D=void 0;const{d:t,C:e}=this,s=await this.Q("refresh","");if(s&&this.a){const{b:i,i:r}=s;if(i===this.O){const s=e(i,t),[n,o]=s.split("://");await fetch(`${n.replace("ws","http")}://${o}`),this.D=new b(1e3*r-Date.now(),this.P)}else this.a&&(this.a.close(),this.a=void 0)}}async al(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)))}U(){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 Q(t,e){const s=await fetch(this.T,{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(","),{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 u(e)}}c;d;T;O;a;h;D;C;f}const P=new Error(p.NotAuthenticated);class x{constructor(t,e,s){this.n=t,this.v=e,this.w=!s}get pkgType(){return this.n.pkgType}get k(){return this.n.name}async x(t,e){const{buff:s,bodyOffset:i}=e,r=s.subarray(i),n=new this.n(r,!0);if(void 0===t.context&&this.w)l(t,P);else try{await this.v(t,n)}catch(e){e.isError||l(t,e)}void 0===t.context&&await t.close()}async q(t,e){if(void 0===t.context&&this.w)l(t,P);else try{return await this.v(t,e)}catch(e){e.isError||l(t,e)}}n;v;w}class C{constructor(t,e,s){this.n=t,this.v=e,this.w=!s}get pkgType(){return this.n.pkgType}get k(){return this.n.name}async x(t,e){const{buff:s,requestId:i,bodyOffset:r}=e,n=s.subarray(r),o=new this.n(n,!0);let h;if(void 0===t.context&&this.w)h=l(t,P);else try{await this.v(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 q(t,e){if(void 0!==t.context||!this.w)try{return await this.v(t,e)}catch(e){throw e.isError?e:l(t,e)}throw l(t,P)}n;v;w}class A{b(){return null}init(t){this.E=t}async I(t){return!1}async J(){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.ai(e,!0))}})}ai=(t,e)=>{const s=new I(t),{conn:i,_:r,o:n}=this.E(s,e);return t.onmessage=t=>{t.data.arrayBuffer().then(t=>{r(new Uint8Array(t))})},t.onerror=t=>{n(new Error(p.UnknownError))},t.onclose=t=>{1e3===t.code?n():n(new Error(t.reason))},i};E(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 F(t){if(this.i)return this.i.send(t);throw new Error(p.InvalidConnection)}async n(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))}G(){return!this.i}i}const S=(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)},R=t=>{const{h:[e,s],k: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{h:a,k:n-s}})(2,t);return{buff:t,pkgType:s,requestId:e,bodyOffset:i}};class ${constructor(t){this.a6=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.q&&await this.q.then(e=>{this.a=void 0,e.close(t)},()=>this.a=void 0)}async aq(){this.a||await this.g()}aj(){this.a=void 0}async g(){let{q:t}=this;return t||(t=this.q=new Promise((t,e)=>{this.a6().then(s=>{s?(t(s),this.a=s,this.q=void 0):e(new Error("Connect failed"))})})),await t}a6;a;q}class q{constructor(t,e){const{responsePkgType:s,timeoutMonitor:i,makePkgBuff:r,parsePkgBuff:n}=e;this.responsePkgType=s,this.s=0,this.t=new Map,this.h=new Map,this.R=new Map,this.Z=r,this.a0=n,this.A=t,this.K=i,this.x=this.a9;const o=[];this.Z(s,2097152,o),this.a1={makePkgBuff:r,responsePkgType:s,r:k(o)},this.h.set(s,this),this.A.init((t,e)=>{do{this.s++}while(this.t.has(2097151&this.s));const s=new W(this.a1,t,2097151&this.s);this.t.set(s.id,s),this.K?.insert(s);const i={conn:s,_:t=>this.aa(s,t),o:t=>this.ab(s,t)};return this.L?.(this,s,!!e),i})}responsePkgType;context;L;H;b(){return this.A.b()}P(t){return this.t.get(t)}g(t){return this.A.g(t)}async Q(){do{this.s++}while(this.t.has(2097151&this.s));const t=new j(2097151&this.s,this);return this.t.set(t.id,t),t}async T(t){return this.A.I(t)}async U(){return this.A.J()}ac(t,e){const s=e.constructor.pkgType,i=this.h.get(s);if(i)return i?.q(t,e);throw new Error(p.InvalidPackage)}ad(t,e){const s=e.constructor.pkgType,i=this.h.get(s);if(i)return i?.q(t,e);throw new Error(p.InvalidPackage)}registerError(t,e){e.registerPkgType(t),this.R.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}an(t){const e=t.pkgType;return this.h.get(e)===t&&(this.h.delete(e),!0)}aa(t,e){this.K?.update(t);const s=this.a0(e),i=this.h.get(s.pkgType);i?i.x(t,s):t.close(new Error(p.InvalidPackage))}ab(t,e){const s=t.id;this.t.delete(s),this.K?.remove(t),t.o(e),this.H?.(this,t,t.e.G(),e)}a9(t,e){try{const{buff:s,pkgType:i,requestId:r,bodyOffset:n}=e;if(i===this.responsePkgType){const e=s.subarray(n);t.a2(r,e)}else{const e=this.R.get(i);if(e){const i=new e(s.subarray(n),!0);t.ae(r,i)}}}catch{t.close(new Error(p.InvalidPackage))}}a1;s;Z;a0;A;t;h;R;K}class W extends v{constructor(t,e,s){super(),this.id=s,this.e=e,this.B=t,this.a3=0}context;id;e;get socket(){return this.e.socket}sendMessage(t){const e=t.constructor.pkgType,s=[t.buff];return this.B.makePkgBuff(e,0,s),this.e.n(s)}sendRequest(t){return this.m=new Map,this.sendRequest=this.a4,this.a2=this.af,this.o=this.ag,this.a4(t)}sendErrorResponse(t,e){const s=t.constructor.pkgType,i=[t.buff];return this.B.makePkgBuff(s,e,i),this.e.n(i)}sendResponse(t,e){const s=[t.respBuff],{makePkgBuff:i,responsePkgType:r}=this.B;return i(r,e,s),this.e.n(s)}async close(t){await this.e.close(t)}a2(t,e){2097152===t&&void 0===this.context&&this.close(new Error(p.AuthTimeout))}ae(t,e){const s=this.m.get(t);if(s)return this.m.delete(t),s.j(e)}warnTimeout(){this.e.F(this.B.r).catch(y)}onTimeout(){this.close(new Error(p.Timeout))}o(t){}async a4(t){const e=2097151&this.a3++,s=t.constructor.pkgType,i=[t.buff];this.B.makePkgBuff(s,e,i);const r=new Promise((t,s)=>{const r={d:t,j:s};this.m.set(e,r),this.e.n(i).catch(t=>{this.m.delete(e),s(t)})});t.respBuff=await r}af(t,e){const s=this.m.get(t);if(s)return this.m.delete(t),void s.d(e);2097152===t&&void 0===this.context&&this.close(new Error(p.AuthTimeout))}ag(t){const e=this.m;if(e.size>0){t||(t=new Error(p.ConnectionClosed));for(const[s,i]of e)e.delete(s),i.j(t)}this.m=void 0}B;m;a3}class j{constructor(t,e){this.id=t,this.S=e}context;id;socket;get remoteFamily(){return"Local"}async sendMessage(t){return this.S.ac(this,t)}async sendRequest(t){return this.S.ad(this,t)}sendErrorResponse(t,e){throw null}sendResponse(t,e){throw null}async close(t){}S}const M=(t,e)=>new N(t,{responsePkgType:0,makePkgBuff:S,parsePkgBuff:R,timeoutMonitor:e});var B;!function(t){t[t.NotConnected=0]="NotConnected",t[t.Connecting=1]="Connecting",t[t.Connected=2]="Connected"}(B||(B={}));class N{constructor(t,e){const s=new A,i=this.l=new q(s,e);this.I=B.NotConnected,this.a7=t,this.a=new $(()=>this.g()),i.L=this.L.bind(this),i.H=this.H.bind(this)}getConnState(){return this.I}enableAuthenticate(t,e){this.N=e,e.init(t,this)}registerError(t,e){return this.l.registerError(t,e)}registerMessage(t,e){return this.l.registerMessage(t,e)}registerRequest(t,e){return this.l.registerRequest(t,e)}handleMessageWith(t,e){this.l.handleMessageWith(new x(t,(t,s)=>e(s.data),!0))}handleRequestWith(t,e){this.l.handleRequestWith(new C(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{l:t,N:e}=this;this.I=B.Connecting;try{const s=e?await e.preConnect():this.a7;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.H(t,this.a,!0,s)}}L(t,e,s){if(this.I=B.Connected,e.context="",this.b)for(const t of this.b)t(!0,e,s)}H(t,e,s,i){if(this.I=B.NotConnected,this.a.aj(),this.b)for(const t of this.b)t(!1,e,s,i)}a7;l;a;I;N;b}export{u as CommonError,s as ErrorWrapper,r as EventWrapper,a as JsonError,c as JsonMessage,d as JsonRequest,E as JustrunAuthProvider,i as MessageWrapper,p as NetErrorString,n as RequestWrapper,m as TimeoutMonitor,N as WsClient,M as createNumPkgTypeClient,g as handleUncaughtErrorWith};
@@ -1,42 +1,52 @@
1
- export class b {
2
- constructor(a, c) {
3
- this.W = new Promise((d) => {
4
- this.G = d;
1
+ export class m {
2
+ constructor(a, onTimeout) {
3
+ this.a5 = new Promise((d) => {
4
+ this.u = d;
5
5
  });
6
- this.N = c;
6
+ this.M = onTimeout;
7
7
  if (a > 0) {
8
- this.u = setTimeout(() => {
9
- this.u = undefined;
10
- this.N?.();
11
- this.G();
8
+ this.k = setTimeout(() => {
9
+ this.k = undefined;
10
+ this.u(true);
11
+ onTimeout?.();
12
12
  }, a);
13
13
  }
14
14
  else {
15
- this.G();
15
+ this.u(true);
16
+ onTimeout?.();
16
17
  }
17
18
  }
18
- a3(a) {
19
- if (this.u) {
20
- clearTimeout(this.u);
19
+ ao(a) {
20
+ const { k, u, M } = this;
21
+ if (k) {
22
+ clearTimeout(k);
21
23
  }
22
24
  if (a > 0) {
23
- this.u = setTimeout(() => {
24
- this.u = undefined;
25
- this.N?.();
26
- this.G();
25
+ this.k = setTimeout(() => {
26
+ this.k = undefined;
27
+ M?.();
28
+ u(true);
27
29
  }, a);
28
30
  }
29
31
  else {
30
- this.u = undefined;
31
- this.G();
32
+ this.k = undefined;
33
+ u(true);
34
+ M?.();
32
35
  }
33
36
  }
34
- async Y() {
35
- await this.W;
37
+ ah() {
38
+ if (this.k) {
39
+ clearTimeout(this.k);
40
+ this.k = undefined;
41
+ this.u(false);
42
+ }
43
+ }
44
+ ap() {
45
+ return this.a5;
36
46
  }
37
- G;
38
- W;
39
47
  u;
40
- N;
48
+ a5;
49
+ k;
50
+ M;
41
51
  }
42
52
  //# sourceMappingURL=AdjustableTimer.js.map