@kodiak-finance/orderly-net 2.7.4

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/dist/index.js ADDED
@@ -0,0 +1,759 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ // If the importer is in node compatibility mode or this is not an ESM
39
+ // file that has been converted to a CommonJS file using a Babel-
40
+ // compatible transform (i.e. "__esModule" has not been set), then set
41
+ // "default" to the CommonJS "module.exports" for node compatibility.
42
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
+ mod
44
+ ));
45
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+ var __async = (__this, __arguments, generator) => {
47
+ return new Promise((resolve, reject) => {
48
+ var fulfilled = (value) => {
49
+ try {
50
+ step(generator.next(value));
51
+ } catch (e) {
52
+ reject(e);
53
+ }
54
+ };
55
+ var rejected = (value) => {
56
+ try {
57
+ step(generator.throw(value));
58
+ } catch (e) {
59
+ reject(e);
60
+ }
61
+ };
62
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
63
+ step((generator = generator.apply(__this, __arguments)).next());
64
+ });
65
+ };
66
+
67
+ // src/index.ts
68
+ var src_exports = {};
69
+ __export(src_exports, {
70
+ WS: () => WS,
71
+ WebSocketEvent: () => WebSocketEvent,
72
+ __ORDERLY_API_URL_KEY__: () => __ORDERLY_API_URL_KEY__,
73
+ del: () => del,
74
+ get: () => get,
75
+ mutate: () => mutate,
76
+ post: () => post,
77
+ put: () => put,
78
+ version: () => version_default
79
+ });
80
+ module.exports = __toCommonJS(src_exports);
81
+
82
+ // src/version.ts
83
+ if (typeof window !== "undefined") {
84
+ window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};
85
+ window.__ORDERLY_VERSION__["@kodiak-finance/orderly-net"] = "2.7.4";
86
+ }
87
+ var version_default = "2.7.4";
88
+
89
+ // src/errors/apiError.ts
90
+ var ApiError = class extends Error {
91
+ constructor(message, code) {
92
+ super(message);
93
+ this.code = code;
94
+ this.name = "ApiError";
95
+ }
96
+ };
97
+
98
+ // src/fetch/index.ts
99
+ function request(url, options) {
100
+ return __async(this, null, function* () {
101
+ if (!url.startsWith("http")) {
102
+ throw new Error("url must start with http(s)");
103
+ }
104
+ const response = yield fetch(url, __spreadProps(__spreadValues({}, options), {
105
+ // mode: "cors",
106
+ // credentials: "include",
107
+ headers: _createHeaders(options.headers, options.method)
108
+ }));
109
+ if (response.ok) {
110
+ const res = yield response.json();
111
+ return res;
112
+ } else {
113
+ try {
114
+ const errorMsg = yield response.json();
115
+ if (response.status === 400) {
116
+ throw new ApiError(
117
+ errorMsg.message || errorMsg.code || response.statusText,
118
+ errorMsg.code
119
+ );
120
+ }
121
+ throw new Error(errorMsg.message || errorMsg.code || response.statusText);
122
+ } catch (e) {
123
+ throw e;
124
+ }
125
+ }
126
+ });
127
+ }
128
+ function _createHeaders(headers = {}, method) {
129
+ const _headers = new Headers(headers);
130
+ if (!_headers.has("Content-Type")) {
131
+ if (method !== "DELETE") {
132
+ _headers.append("Content-Type", "application/json;charset=utf-8");
133
+ } else {
134
+ _headers.append("Content-Type", "application/x-www-form-urlencoded");
135
+ }
136
+ }
137
+ return _headers;
138
+ }
139
+ function get(url, options, formatter) {
140
+ return __async(this, null, function* () {
141
+ const res = yield request(url, __spreadValues({
142
+ method: "GET"
143
+ }, options));
144
+ if (res.success) {
145
+ if (typeof formatter === "function") {
146
+ return formatter(res.data);
147
+ }
148
+ if (Array.isArray(res.data["rows"])) {
149
+ return res.data["rows"];
150
+ }
151
+ return res.data;
152
+ }
153
+ throw new Error(res.message);
154
+ });
155
+ }
156
+ function post(url, data, options) {
157
+ return __async(this, null, function* () {
158
+ const res = yield request(url, __spreadValues({
159
+ method: "POST",
160
+ body: JSON.stringify(data)
161
+ }, options));
162
+ return res;
163
+ });
164
+ }
165
+ function put(url, data, options) {
166
+ return __async(this, null, function* () {
167
+ const res = yield request(url, __spreadValues({
168
+ method: "PUT",
169
+ body: JSON.stringify(data)
170
+ }, options));
171
+ return res;
172
+ });
173
+ }
174
+ function del(url, options) {
175
+ return __async(this, null, function* () {
176
+ const res = yield request(url, __spreadValues({
177
+ method: "DELETE"
178
+ }, options));
179
+ return res;
180
+ });
181
+ }
182
+ function mutate(url, init) {
183
+ return __async(this, null, function* () {
184
+ const res = yield request(url, init);
185
+ return res;
186
+ });
187
+ }
188
+
189
+ // src/constants.ts
190
+ var __ORDERLY_API_URL_KEY__ = "__ORDERLY_API_URL__";
191
+
192
+ // src/ws/ws.ts
193
+ var import_eventemitter3 = __toESM(require("eventemitter3"));
194
+
195
+ // src/ws/handler/baseHandler.ts
196
+ var BaseHandler = class {
197
+ handle(message, webSocket) {
198
+ throw new Error("Method not implemented.");
199
+ }
200
+ };
201
+
202
+ // src/ws/handler/ping.ts
203
+ var PingHandler = class extends BaseHandler {
204
+ handle(_, webSocket) {
205
+ webSocket.send(JSON.stringify({ event: "pong", ts: Date.now() }));
206
+ }
207
+ };
208
+
209
+ // src/ws/handler/handler.ts
210
+ var messageHandlers = /* @__PURE__ */ new Map([
211
+ ["ping", new PingHandler()]
212
+ ]);
213
+
214
+ // src/ws/ws.ts
215
+ var WebSocketEvent = /* @__PURE__ */ ((WebSocketEvent2) => {
216
+ WebSocketEvent2["OPEN"] = "open";
217
+ WebSocketEvent2["CLOSE"] = "close";
218
+ WebSocketEvent2["ERROR"] = "error";
219
+ WebSocketEvent2["MESSAGE"] = "message";
220
+ WebSocketEvent2["CONNECTING"] = "connecting";
221
+ WebSocketEvent2["RECONNECTING"] = "reconnecting";
222
+ return WebSocketEvent2;
223
+ })(WebSocketEvent || {});
224
+ var defaultMessageFormatter = (message) => message.data;
225
+ var COMMON_ID = "OqdphuyCtYWxwzhxyLLjOWNdFP7sQt8RPWzmb5xY";
226
+ var TIME_OUT = 1e3 * 60 * 2;
227
+ var CONNECT_LIMIT = 5;
228
+ var WS = class extends import_eventemitter3.default {
229
+ constructor(options) {
230
+ super();
231
+ this.options = options;
232
+ this._eventContainer = /* @__PURE__ */ new Map();
233
+ this.publicIsReconnecting = false;
234
+ this.privateIsReconnecting = false;
235
+ this.reconnectInterval = 1e3;
236
+ this.authenticated = false;
237
+ this._pendingPrivateSubscribe = [];
238
+ this._pendingPublicSubscribe = [];
239
+ // all message handlers
240
+ this._eventHandlers = /* @__PURE__ */ new Map();
241
+ this._eventPrivateHandlers = /* @__PURE__ */ new Map();
242
+ this._publicRetryCount = 0;
243
+ this._privateRetryCount = 0;
244
+ this.send = (message) => {
245
+ var _a, _b;
246
+ if (typeof message !== "string") {
247
+ message = JSON.stringify(message);
248
+ }
249
+ if (typeof message === "undefined")
250
+ return;
251
+ if (((_a = this._publicSocket) == null ? void 0 : _a.readyState) === WebSocket.OPEN) {
252
+ (_b = this._publicSocket) == null ? void 0 : _b.send(message);
253
+ } else {
254
+ console.warn("WebSocket connection is not open. Cannot send message.");
255
+ }
256
+ };
257
+ this.createPublicSC(options);
258
+ if (!!options.accountId) {
259
+ this.createPrivateSC(options);
260
+ }
261
+ this.bindEvents();
262
+ }
263
+ bindEvents() {
264
+ var _a, _b;
265
+ if (typeof document !== "undefined") {
266
+ (_a = document.addEventListener) == null ? void 0 : _a.call(
267
+ document,
268
+ "visibilitychange",
269
+ this.onVisibilityChange.bind(this)
270
+ );
271
+ }
272
+ if (typeof window !== "undefined") {
273
+ (_b = window.addEventListener) == null ? void 0 : _b.call(
274
+ window,
275
+ "online",
276
+ this.onNetworkStatusChange.bind(this)
277
+ );
278
+ }
279
+ }
280
+ onVisibilityChange() {
281
+ if (document.visibilityState === "visible") {
282
+ this.checkSocketStatus();
283
+ }
284
+ }
285
+ onNetworkStatusChange() {
286
+ if (navigator.onLine) {
287
+ this.checkSocketStatus();
288
+ }
289
+ }
290
+ /**
291
+ * Determine the current connection status,
292
+ * 1. If it is disconnected, reconnect
293
+ * 2. If no message is received for too long, disconnect and reconnect actively
294
+ * 3. When returning from the background and the network status changes, the following process is followed
295
+ */
296
+ checkSocketStatus() {
297
+ var _a, _b, _c, _d;
298
+ const now = Date.now();
299
+ if (document.visibilityState !== "visible")
300
+ return;
301
+ if (!navigator.onLine)
302
+ return;
303
+ if (!this.publicIsReconnecting) {
304
+ if (((_a = this._publicSocket) == null ? void 0 : _a.readyState) === WebSocket.CLOSED) {
305
+ this.reconnectPublic();
306
+ } else {
307
+ if (now - this._publicHeartbeatTime > TIME_OUT) {
308
+ (_b = this._publicSocket) == null ? void 0 : _b.close(3888);
309
+ }
310
+ }
311
+ }
312
+ if (!this.privateIsReconnecting) {
313
+ if (((_c = this.privateSocket) == null ? void 0 : _c.readyState) === WebSocket.CLOSED) {
314
+ this.reconnectPrivate();
315
+ } else {
316
+ if (this._privateHeartbeatTime && now - this._privateHeartbeatTime > TIME_OUT) {
317
+ (_d = this.privateSocket) == null ? void 0 : _d.close(3888);
318
+ }
319
+ }
320
+ }
321
+ }
322
+ openPrivate(accountId) {
323
+ var _a;
324
+ if (((_a = this.privateSocket) == null ? void 0 : _a.readyState) === WebSocket.OPEN) {
325
+ return;
326
+ }
327
+ this.createPrivateSC(__spreadProps(__spreadValues({}, this.options), {
328
+ accountId
329
+ }));
330
+ }
331
+ closePrivate(code, reason) {
332
+ var _a, _b;
333
+ if (((_a = this.privateSocket) == null ? void 0 : _a.readyState) !== WebSocket.OPEN) {
334
+ return;
335
+ }
336
+ this.authenticated = false;
337
+ this._pendingPrivateSubscribe = [];
338
+ this._eventPrivateHandlers.clear();
339
+ (_b = this.privateSocket) == null ? void 0 : _b.close(code, reason);
340
+ }
341
+ createPublicSC(options) {
342
+ if (!options.publicUrl) {
343
+ return;
344
+ }
345
+ if (this._publicSocket && this._publicSocket.readyState === WebSocket.OPEN) {
346
+ return;
347
+ }
348
+ this._publicSocket = new WebSocket(
349
+ `${options.publicUrl}/ws/stream/${COMMON_ID}`
350
+ );
351
+ this._publicSocket.onopen = this.onOpen.bind(this);
352
+ this._publicSocket.addEventListener(
353
+ "message",
354
+ this.onPublicMessage.bind(this)
355
+ );
356
+ this._publicSocket.addEventListener("close", this.onPublicClose.bind(this));
357
+ this._publicSocket.addEventListener("error", this.onPublicError.bind(this));
358
+ }
359
+ createPrivateSC(options) {
360
+ if (this.privateSocket && this.privateSocket.readyState === WebSocket.OPEN) {
361
+ return;
362
+ }
363
+ this.options = options;
364
+ this.privateSocket = new WebSocket(
365
+ `${this.options.privateUrl}/v2/ws/private/stream/${options.accountId}`
366
+ );
367
+ this.privateSocket.onopen = this.onPrivateOpen.bind(this);
368
+ this.privateSocket.onmessage = this.onPrivateMessage.bind(this);
369
+ this.privateSocket.onclose = this.onPrivateClose.bind(this);
370
+ this.privateSocket.onerror = this.onPrivateError.bind(this);
371
+ }
372
+ onOpen(event) {
373
+ if (this._pendingPublicSubscribe.length > 0) {
374
+ this._pendingPublicSubscribe.forEach(([params, cb, isOnce]) => {
375
+ this.subscribe(params, cb, isOnce);
376
+ });
377
+ this._pendingPublicSubscribe = [];
378
+ }
379
+ this.publicIsReconnecting = false;
380
+ this.emit("status:change", {
381
+ type: "open" /* OPEN */,
382
+ isPrivate: false,
383
+ isReconnect: this._publicRetryCount > 0
384
+ });
385
+ this._publicRetryCount = 0;
386
+ }
387
+ onPrivateOpen(event) {
388
+ this.authenticate(this.options.accountId).then(() => {
389
+ this.privateIsReconnecting = false;
390
+ this.emit("status:change", {
391
+ type: "open" /* OPEN */,
392
+ isPrivate: true,
393
+ isReconnect: this._privateRetryCount > 0
394
+ });
395
+ this._privateRetryCount = 0;
396
+ }).catch((e) => {
397
+ console.log("ws authenticate failed", e);
398
+ });
399
+ }
400
+ onMessage(event, socket, handlerMap) {
401
+ try {
402
+ const message = JSON.parse(event.data);
403
+ const commoneHandler = messageHandlers.get(message.event);
404
+ if (message.event === "auth" && message.success) {
405
+ this.authenticated = true;
406
+ this.handlePendingPrivateTopic();
407
+ return;
408
+ }
409
+ if (commoneHandler) {
410
+ commoneHandler.handle(message, socket);
411
+ } else {
412
+ const topicKey = this.getTopicKeyFromMessage(message);
413
+ const eventhandler = handlerMap.get(topicKey);
414
+ if (eventhandler == null ? void 0 : eventhandler.callback) {
415
+ eventhandler.callback.forEach((cb) => {
416
+ const data = cb.formatter ? cb.formatter(message) : defaultMessageFormatter(message);
417
+ if (data) {
418
+ cb.onMessage(data);
419
+ }
420
+ });
421
+ }
422
+ this._eventContainer.forEach((_, key) => {
423
+ const reg = new RegExp(key);
424
+ if (reg.test(topicKey)) {
425
+ this.emit(key, message);
426
+ }
427
+ });
428
+ }
429
+ } catch (e) {
430
+ }
431
+ }
432
+ onPublicMessage(event) {
433
+ this.onMessage(event, this._publicSocket, this._eventHandlers);
434
+ this._publicHeartbeatTime = Date.now();
435
+ }
436
+ onPrivateMessage(event) {
437
+ this.onMessage(event, this.privateSocket, this._eventPrivateHandlers);
438
+ this._privateHeartbeatTime = Date.now();
439
+ }
440
+ handlePendingPrivateTopic() {
441
+ if (this._pendingPrivateSubscribe.length > 0) {
442
+ this._pendingPrivateSubscribe.forEach(([params, cb]) => {
443
+ this.privateSubscribe(params, cb);
444
+ });
445
+ this._pendingPrivateSubscribe = [];
446
+ }
447
+ }
448
+ onPublicClose(event) {
449
+ this._eventHandlers.forEach((value, key) => {
450
+ value.callback.forEach((cb) => {
451
+ this._pendingPublicSubscribe.push([value.params, cb, value.isOnce]);
452
+ });
453
+ this._eventHandlers.delete(key);
454
+ });
455
+ this.emit("status:change", {
456
+ type: "close" /* CLOSE */,
457
+ isPrivate: false
458
+ });
459
+ setTimeout(() => this.checkSocketStatus(), 0);
460
+ }
461
+ onPrivateClose(event) {
462
+ if (event.code === 3887)
463
+ return;
464
+ if (this.privateIsReconnecting)
465
+ return;
466
+ this._eventPrivateHandlers.forEach((value, key) => {
467
+ value.callback.forEach((cb) => {
468
+ this._pendingPrivateSubscribe.push([value.params, cb, value.isOnce]);
469
+ });
470
+ this._eventPrivateHandlers.delete(key);
471
+ });
472
+ this.authenticated = false;
473
+ this.emit("status:change", {
474
+ type: "close" /* CLOSE */,
475
+ isPrivate: true,
476
+ event
477
+ });
478
+ setTimeout(() => this.checkSocketStatus(), 0);
479
+ }
480
+ onPublicError(event) {
481
+ var _a, _b;
482
+ console.error("public WebSocket error:", event);
483
+ this.publicIsReconnecting = false;
484
+ if (((_a = this._publicSocket) == null ? void 0 : _a.readyState) === WebSocket.OPEN) {
485
+ (_b = this._publicSocket) == null ? void 0 : _b.close(3888);
486
+ } else {
487
+ if (this._publicRetryCount > CONNECT_LIMIT)
488
+ return;
489
+ setTimeout(() => {
490
+ this.reconnectPublic();
491
+ }, this._publicRetryCount * 1e3);
492
+ }
493
+ this.errorBoardscast(event, this._eventHandlers);
494
+ this.emit("status:change", {
495
+ type: "error" /* ERROR */,
496
+ isPrivate: false
497
+ });
498
+ }
499
+ onPrivateError(event) {
500
+ var _a;
501
+ console.error("Private WebSocket error:", event);
502
+ this.privateIsReconnecting = false;
503
+ if (((_a = this.privateSocket) == null ? void 0 : _a.readyState) === WebSocket.OPEN) {
504
+ this.privateSocket.close(3888);
505
+ } else {
506
+ if (this._privateRetryCount > CONNECT_LIMIT)
507
+ return;
508
+ setTimeout(() => {
509
+ this.reconnectPrivate();
510
+ }, this._privateRetryCount * 1e3);
511
+ }
512
+ this.errorBoardscast(event, this._eventPrivateHandlers);
513
+ this.emit("status:change", { type: "error" /* ERROR */, isPrivate: true });
514
+ }
515
+ errorBoardscast(error, eventHandlers) {
516
+ eventHandlers.forEach((value) => {
517
+ value.callback.forEach((cb) => {
518
+ var _a;
519
+ (_a = cb.onError) == null ? void 0 : _a.call(cb, error);
520
+ });
521
+ });
522
+ }
523
+ close() {
524
+ var _a, _b;
525
+ (_a = this._publicSocket) == null ? void 0 : _a.close();
526
+ (_b = this.privateSocket) == null ? void 0 : _b.close();
527
+ }
528
+ set accountId(accountId) {
529
+ }
530
+ authenticate(accountId) {
531
+ return __async(this, null, function* () {
532
+ var _a, _b;
533
+ if (this.authenticated)
534
+ return;
535
+ if (!this.privateSocket) {
536
+ console.error("private ws not connected");
537
+ return;
538
+ }
539
+ if (this.privateSocket.readyState !== WebSocket.OPEN) {
540
+ return;
541
+ }
542
+ const message = yield (_b = (_a = this.options).onSigntureRequest) == null ? void 0 : _b.call(_a, accountId);
543
+ this.privateSocket.send(
544
+ JSON.stringify({
545
+ id: "auth",
546
+ event: "auth",
547
+ params: {
548
+ orderly_key: message.publicKey,
549
+ sign: message.signature,
550
+ timestamp: message.timestamp
551
+ }
552
+ })
553
+ );
554
+ });
555
+ }
556
+ privateSubscribe(params, callback) {
557
+ var _a;
558
+ const [subscribeMessage, onUnsubscribe] = this.generateMessage(
559
+ params,
560
+ callback.onUnsubscribe
561
+ );
562
+ if (((_a = this.privateSocket) == null ? void 0 : _a.readyState) !== WebSocket.OPEN) {
563
+ this._pendingPrivateSubscribe.push([params, callback]);
564
+ return () => {
565
+ this.unsubscribePrivate(subscribeMessage);
566
+ };
567
+ }
568
+ const topic = subscribeMessage.topic || subscribeMessage.event;
569
+ const handler = this._eventPrivateHandlers.get(topic);
570
+ const callbacks = __spreadProps(__spreadValues({}, callback), {
571
+ onUnsubscribe
572
+ });
573
+ if (!handler) {
574
+ this._eventPrivateHandlers.set(topic, {
575
+ params,
576
+ callback: [callbacks]
577
+ });
578
+ this.privateSocket.send(JSON.stringify(subscribeMessage));
579
+ } else {
580
+ handler.callback.push(callbacks);
581
+ }
582
+ return () => {
583
+ this.unsubscribePrivate(subscribeMessage);
584
+ };
585
+ }
586
+ subscribe(params, callback, once, id) {
587
+ if (!this._publicSocket) {
588
+ return;
589
+ }
590
+ const [subscribeMessage, onUnsubscribe] = this.generateMessage(
591
+ params,
592
+ callback.onUnsubscribe,
593
+ callback.onMessage
594
+ );
595
+ if (this._publicSocket.readyState !== WebSocket.OPEN) {
596
+ this._pendingPublicSubscribe.push([params, callback, once, id]);
597
+ if (!once) {
598
+ return () => {
599
+ this.unsubscribePublic(subscribeMessage);
600
+ };
601
+ }
602
+ return;
603
+ }
604
+ const topic = this.getTopicKeyFromParams(subscribeMessage);
605
+ const handler = this._eventHandlers.get(topic);
606
+ const callbacks = __spreadProps(__spreadValues({}, callback), {
607
+ onUnsubscribe
608
+ });
609
+ if (!handler) {
610
+ this._eventHandlers.set(topic, {
611
+ params,
612
+ isOnce: once,
613
+ callback: [callbacks]
614
+ });
615
+ this._publicSocket.send(JSON.stringify(subscribeMessage));
616
+ } else {
617
+ if (once) {
618
+ handler.callback = [callbacks];
619
+ this._publicSocket.send(JSON.stringify(subscribeMessage));
620
+ } else {
621
+ handler.callback.push(callbacks);
622
+ }
623
+ }
624
+ if (!once) {
625
+ return () => {
626
+ this.unsubscribePublic(subscribeMessage);
627
+ };
628
+ }
629
+ }
630
+ getTopicKeyFromParams(params) {
631
+ let topic;
632
+ if (params.topic) {
633
+ topic = params.topic;
634
+ } else {
635
+ const eventName = params.event;
636
+ topic = params.event;
637
+ if (params.id) {
638
+ topic += `_${params.id}`;
639
+ }
640
+ }
641
+ return topic;
642
+ }
643
+ getTopicKeyFromMessage(message) {
644
+ let topic;
645
+ if (message.topic) {
646
+ topic = message.topic;
647
+ } else {
648
+ if (message.event) {
649
+ topic = `${message.event}`;
650
+ if (message.id) {
651
+ topic += `_${message.id}`;
652
+ }
653
+ }
654
+ }
655
+ return topic;
656
+ }
657
+ // sendPublicMessage(){
658
+ // if(this.publicSocket.readyState !== )
659
+ // }
660
+ onceSubscribe(params, callback) {
661
+ this.subscribe(params, callback, true);
662
+ }
663
+ unsubscribe(parmas, webSocket, handlerMap) {
664
+ const topic = parmas.topic || parmas.event;
665
+ const handler = handlerMap.get(topic);
666
+ if (!!handler && Array.isArray(handler == null ? void 0 : handler.callback)) {
667
+ if (handler.callback.length === 1) {
668
+ const unsubscribeMessage = handler.callback[0].onUnsubscribe(topic);
669
+ webSocket.send(JSON.stringify(unsubscribeMessage));
670
+ handlerMap.delete(topic);
671
+ } else {
672
+ const index = handler.callback.findIndex(
673
+ (cb) => cb.onMessage === parmas.onMessage
674
+ );
675
+ if (index === -1)
676
+ return;
677
+ handler.callback.splice(index, 1);
678
+ }
679
+ }
680
+ }
681
+ unsubscribePrivate(parmas) {
682
+ this.unsubscribe(parmas, this.privateSocket, this._eventPrivateHandlers);
683
+ }
684
+ unsubscribePublic(parmas) {
685
+ this.unsubscribe(parmas, this._publicSocket, this._eventHandlers);
686
+ }
687
+ generateMessage(params, onUnsubscribe, onMessage) {
688
+ let subscribeMessage;
689
+ if (typeof params === "string") {
690
+ subscribeMessage = { event: "subscribe", topic: params };
691
+ } else {
692
+ subscribeMessage = params;
693
+ }
694
+ if (typeof onUnsubscribe !== "function") {
695
+ if (typeof params === "string") {
696
+ onUnsubscribe = () => ({ event: "unsubscribe", topic: params });
697
+ } else {
698
+ onUnsubscribe = () => ({ event: "unsubscribe", topic: params.topic });
699
+ }
700
+ }
701
+ return [__spreadProps(__spreadValues({}, subscribeMessage), { onMessage }), onUnsubscribe];
702
+ }
703
+ reconnectPublic() {
704
+ if (this.publicIsReconnecting)
705
+ return;
706
+ this.publicIsReconnecting = true;
707
+ if (typeof window === "undefined")
708
+ return;
709
+ window.setTimeout(() => {
710
+ this._publicRetryCount++;
711
+ this.createPublicSC(this.options);
712
+ this.emit("status:change", {
713
+ type: "reconnecting" /* RECONNECTING */,
714
+ isPrivate: false,
715
+ count: this._publicRetryCount
716
+ });
717
+ }, this.reconnectInterval);
718
+ }
719
+ reconnectPrivate() {
720
+ if (!this.options.accountId)
721
+ return;
722
+ if (this.privateIsReconnecting)
723
+ return;
724
+ this.privateIsReconnecting = true;
725
+ if (typeof window === "undefined")
726
+ return;
727
+ window.setTimeout(() => {
728
+ this._privateRetryCount++;
729
+ this.createPrivateSC(this.options);
730
+ this.emit("status:change", {
731
+ type: "reconnecting" /* RECONNECTING */,
732
+ isPrivate: true,
733
+ count: this._privateRetryCount
734
+ });
735
+ }, this.reconnectInterval);
736
+ }
737
+ // get publicSocket(): WebSocket {
738
+ // return this._publicSocket;
739
+ // }
740
+ get client() {
741
+ return {
742
+ public: this._publicSocket,
743
+ private: this.privateSocket
744
+ };
745
+ }
746
+ };
747
+ // Annotate the CommonJS export names for ESM import in node:
748
+ 0 && (module.exports = {
749
+ WS,
750
+ WebSocketEvent,
751
+ __ORDERLY_API_URL_KEY__,
752
+ del,
753
+ get,
754
+ mutate,
755
+ post,
756
+ put,
757
+ version
758
+ });
759
+ //# sourceMappingURL=index.js.map