swiftbase-sdk 1.0.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.
package/dist/index.js ADDED
@@ -0,0 +1,4744 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __typeError = (msg) => {
12
+ throw TypeError(msg);
13
+ };
14
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
15
+ var __spreadValues = (a, b) => {
16
+ for (var prop in b || (b = {}))
17
+ if (__hasOwnProp.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ if (__getOwnPropSymbols)
20
+ for (var prop of __getOwnPropSymbols(b)) {
21
+ if (__propIsEnum.call(b, prop))
22
+ __defNormalProp(a, prop, b[prop]);
23
+ }
24
+ return a;
25
+ };
26
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
27
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
28
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
29
+ }) : x)(function(x) {
30
+ if (typeof require !== "undefined") return require.apply(this, arguments);
31
+ throw Error('Dynamic require of "' + x + '" is not supported');
32
+ });
33
+ var __esm = (fn, res) => function __init() {
34
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
35
+ };
36
+ var __commonJS = (cb, mod) => function __require2() {
37
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
38
+ };
39
+ var __export = (target, all) => {
40
+ for (var name in all)
41
+ __defProp(target, name, { get: all[name], enumerable: true });
42
+ };
43
+ var __copyProps = (to, from, except, desc) => {
44
+ if (from && typeof from === "object" || typeof from === "function") {
45
+ for (let key of __getOwnPropNames(from))
46
+ if (!__hasOwnProp.call(to, key) && key !== except)
47
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
48
+ }
49
+ return to;
50
+ };
51
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
52
+ // If the importer is in node compatibility mode or this is not an ESM
53
+ // file that has been converted to a CommonJS file using a Babel-
54
+ // compatible transform (i.e. "__esModule" has not been set), then set
55
+ // "default" to the CommonJS "module.exports" for node compatibility.
56
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
57
+ mod
58
+ ));
59
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
60
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
61
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
62
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
63
+ var __async = (__this, __arguments, generator) => {
64
+ return new Promise((resolve, reject) => {
65
+ var fulfilled = (value) => {
66
+ try {
67
+ step(generator.next(value));
68
+ } catch (e) {
69
+ reject(e);
70
+ }
71
+ };
72
+ var rejected = (value) => {
73
+ try {
74
+ step(generator.throw(value));
75
+ } catch (e) {
76
+ reject(e);
77
+ }
78
+ };
79
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
80
+ step((generator = generator.apply(__this, __arguments)).next());
81
+ });
82
+ };
83
+
84
+ // node_modules/ws/lib/stream.js
85
+ var require_stream = __commonJS({
86
+ "node_modules/ws/lib/stream.js"(exports, module) {
87
+ "use strict";
88
+ var { Duplex } = __require("stream");
89
+ function emitClose(stream) {
90
+ stream.emit("close");
91
+ }
92
+ function duplexOnEnd() {
93
+ if (!this.destroyed && this._writableState.finished) {
94
+ this.destroy();
95
+ }
96
+ }
97
+ function duplexOnError(err) {
98
+ this.removeListener("error", duplexOnError);
99
+ this.destroy();
100
+ if (this.listenerCount("error") === 0) {
101
+ this.emit("error", err);
102
+ }
103
+ }
104
+ function createWebSocketStream2(ws, options) {
105
+ let terminateOnDestroy = true;
106
+ const duplex = new Duplex(__spreadProps(__spreadValues({}, options), {
107
+ autoDestroy: false,
108
+ emitClose: false,
109
+ objectMode: false,
110
+ writableObjectMode: false
111
+ }));
112
+ ws.on("message", function message(msg, isBinary) {
113
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
114
+ if (!duplex.push(data)) ws.pause();
115
+ });
116
+ ws.once("error", function error(err) {
117
+ if (duplex.destroyed) return;
118
+ terminateOnDestroy = false;
119
+ duplex.destroy(err);
120
+ });
121
+ ws.once("close", function close() {
122
+ if (duplex.destroyed) return;
123
+ duplex.push(null);
124
+ });
125
+ duplex._destroy = function(err, callback) {
126
+ if (ws.readyState === ws.CLOSED) {
127
+ callback(err);
128
+ process.nextTick(emitClose, duplex);
129
+ return;
130
+ }
131
+ let called = false;
132
+ ws.once("error", function error(err2) {
133
+ called = true;
134
+ callback(err2);
135
+ });
136
+ ws.once("close", function close() {
137
+ if (!called) callback(err);
138
+ process.nextTick(emitClose, duplex);
139
+ });
140
+ if (terminateOnDestroy) ws.terminate();
141
+ };
142
+ duplex._final = function(callback) {
143
+ if (ws.readyState === ws.CONNECTING) {
144
+ ws.once("open", function open() {
145
+ duplex._final(callback);
146
+ });
147
+ return;
148
+ }
149
+ if (ws._socket === null) return;
150
+ if (ws._socket._writableState.finished) {
151
+ callback();
152
+ if (duplex._readableState.endEmitted) duplex.destroy();
153
+ } else {
154
+ ws._socket.once("finish", function finish() {
155
+ callback();
156
+ });
157
+ ws.close();
158
+ }
159
+ };
160
+ duplex._read = function() {
161
+ if (ws.isPaused) ws.resume();
162
+ };
163
+ duplex._write = function(chunk, encoding, callback) {
164
+ if (ws.readyState === ws.CONNECTING) {
165
+ ws.once("open", function open() {
166
+ duplex._write(chunk, encoding, callback);
167
+ });
168
+ return;
169
+ }
170
+ ws.send(chunk, callback);
171
+ };
172
+ duplex.on("end", duplexOnEnd);
173
+ duplex.on("error", duplexOnError);
174
+ return duplex;
175
+ }
176
+ module.exports = createWebSocketStream2;
177
+ }
178
+ });
179
+
180
+ // node_modules/ws/lib/constants.js
181
+ var require_constants = __commonJS({
182
+ "node_modules/ws/lib/constants.js"(exports, module) {
183
+ "use strict";
184
+ module.exports = {
185
+ BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
186
+ EMPTY_BUFFER: Buffer.alloc(0),
187
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
188
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
189
+ kListener: /* @__PURE__ */ Symbol("kListener"),
190
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
191
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
192
+ NOOP: () => {
193
+ }
194
+ };
195
+ }
196
+ });
197
+
198
+ // node_modules/ws/lib/buffer-util.js
199
+ var require_buffer_util = __commonJS({
200
+ "node_modules/ws/lib/buffer-util.js"(exports, module) {
201
+ "use strict";
202
+ var { EMPTY_BUFFER } = require_constants();
203
+ var FastBuffer = Buffer[Symbol.species];
204
+ function concat(list, totalLength) {
205
+ if (list.length === 0) return EMPTY_BUFFER;
206
+ if (list.length === 1) return list[0];
207
+ const target = Buffer.allocUnsafe(totalLength);
208
+ let offset = 0;
209
+ for (let i = 0; i < list.length; i++) {
210
+ const buf = list[i];
211
+ target.set(buf, offset);
212
+ offset += buf.length;
213
+ }
214
+ if (offset < totalLength) {
215
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
216
+ }
217
+ return target;
218
+ }
219
+ function _mask(source, mask, output, offset, length) {
220
+ for (let i = 0; i < length; i++) {
221
+ output[offset + i] = source[i] ^ mask[i & 3];
222
+ }
223
+ }
224
+ function _unmask(buffer, mask) {
225
+ for (let i = 0; i < buffer.length; i++) {
226
+ buffer[i] ^= mask[i & 3];
227
+ }
228
+ }
229
+ function toArrayBuffer(buf) {
230
+ if (buf.length === buf.buffer.byteLength) {
231
+ return buf.buffer;
232
+ }
233
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
234
+ }
235
+ function toBuffer(data) {
236
+ toBuffer.readOnly = true;
237
+ if (Buffer.isBuffer(data)) return data;
238
+ let buf;
239
+ if (data instanceof ArrayBuffer) {
240
+ buf = new FastBuffer(data);
241
+ } else if (ArrayBuffer.isView(data)) {
242
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
243
+ } else {
244
+ buf = Buffer.from(data);
245
+ toBuffer.readOnly = false;
246
+ }
247
+ return buf;
248
+ }
249
+ module.exports = {
250
+ concat,
251
+ mask: _mask,
252
+ toArrayBuffer,
253
+ toBuffer,
254
+ unmask: _unmask
255
+ };
256
+ if (!process.env.WS_NO_BUFFER_UTIL) {
257
+ try {
258
+ const bufferUtil = __require("bufferutil");
259
+ module.exports.mask = function(source, mask, output, offset, length) {
260
+ if (length < 48) _mask(source, mask, output, offset, length);
261
+ else bufferUtil.mask(source, mask, output, offset, length);
262
+ };
263
+ module.exports.unmask = function(buffer, mask) {
264
+ if (buffer.length < 32) _unmask(buffer, mask);
265
+ else bufferUtil.unmask(buffer, mask);
266
+ };
267
+ } catch (e) {
268
+ }
269
+ }
270
+ }
271
+ });
272
+
273
+ // node_modules/ws/lib/limiter.js
274
+ var require_limiter = __commonJS({
275
+ "node_modules/ws/lib/limiter.js"(exports, module) {
276
+ "use strict";
277
+ var kDone = /* @__PURE__ */ Symbol("kDone");
278
+ var kRun = /* @__PURE__ */ Symbol("kRun");
279
+ var Limiter = class {
280
+ /**
281
+ * Creates a new `Limiter`.
282
+ *
283
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
284
+ * to run concurrently
285
+ */
286
+ constructor(concurrency) {
287
+ this[kDone] = () => {
288
+ this.pending--;
289
+ this[kRun]();
290
+ };
291
+ this.concurrency = concurrency || Infinity;
292
+ this.jobs = [];
293
+ this.pending = 0;
294
+ }
295
+ /**
296
+ * Adds a job to the queue.
297
+ *
298
+ * @param {Function} job The job to run
299
+ * @public
300
+ */
301
+ add(job) {
302
+ this.jobs.push(job);
303
+ this[kRun]();
304
+ }
305
+ /**
306
+ * Removes a job from the queue and runs it if possible.
307
+ *
308
+ * @private
309
+ */
310
+ [kRun]() {
311
+ if (this.pending === this.concurrency) return;
312
+ if (this.jobs.length) {
313
+ const job = this.jobs.shift();
314
+ this.pending++;
315
+ job(this[kDone]);
316
+ }
317
+ }
318
+ };
319
+ module.exports = Limiter;
320
+ }
321
+ });
322
+
323
+ // node_modules/ws/lib/permessage-deflate.js
324
+ var require_permessage_deflate = __commonJS({
325
+ "node_modules/ws/lib/permessage-deflate.js"(exports, module) {
326
+ "use strict";
327
+ var zlib = __require("zlib");
328
+ var bufferUtil = require_buffer_util();
329
+ var Limiter = require_limiter();
330
+ var { kStatusCode } = require_constants();
331
+ var FastBuffer = Buffer[Symbol.species];
332
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
333
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
334
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
335
+ var kCallback = /* @__PURE__ */ Symbol("callback");
336
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
337
+ var kError = /* @__PURE__ */ Symbol("error");
338
+ var zlibLimiter;
339
+ var PerMessageDeflate = class {
340
+ /**
341
+ * Creates a PerMessageDeflate instance.
342
+ *
343
+ * @param {Object} [options] Configuration options
344
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
345
+ * for, or request, a custom client window size
346
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
347
+ * acknowledge disabling of client context takeover
348
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
349
+ * calls to zlib
350
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
351
+ * use of a custom server window size
352
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
353
+ * disabling of server context takeover
354
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
355
+ * messages should not be compressed if context takeover is disabled
356
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
357
+ * deflate
358
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
359
+ * inflate
360
+ * @param {Boolean} [isServer=false] Create the instance in either server or
361
+ * client mode
362
+ * @param {Number} [maxPayload=0] The maximum allowed message length
363
+ */
364
+ constructor(options, isServer, maxPayload) {
365
+ this._maxPayload = maxPayload | 0;
366
+ this._options = options || {};
367
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
368
+ this._isServer = !!isServer;
369
+ this._deflate = null;
370
+ this._inflate = null;
371
+ this.params = null;
372
+ if (!zlibLimiter) {
373
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
374
+ zlibLimiter = new Limiter(concurrency);
375
+ }
376
+ }
377
+ /**
378
+ * @type {String}
379
+ */
380
+ static get extensionName() {
381
+ return "permessage-deflate";
382
+ }
383
+ /**
384
+ * Create an extension negotiation offer.
385
+ *
386
+ * @return {Object} Extension parameters
387
+ * @public
388
+ */
389
+ offer() {
390
+ const params = {};
391
+ if (this._options.serverNoContextTakeover) {
392
+ params.server_no_context_takeover = true;
393
+ }
394
+ if (this._options.clientNoContextTakeover) {
395
+ params.client_no_context_takeover = true;
396
+ }
397
+ if (this._options.serverMaxWindowBits) {
398
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
399
+ }
400
+ if (this._options.clientMaxWindowBits) {
401
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
402
+ } else if (this._options.clientMaxWindowBits == null) {
403
+ params.client_max_window_bits = true;
404
+ }
405
+ return params;
406
+ }
407
+ /**
408
+ * Accept an extension negotiation offer/response.
409
+ *
410
+ * @param {Array} configurations The extension negotiation offers/reponse
411
+ * @return {Object} Accepted configuration
412
+ * @public
413
+ */
414
+ accept(configurations) {
415
+ configurations = this.normalizeParams(configurations);
416
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
417
+ return this.params;
418
+ }
419
+ /**
420
+ * Releases all resources used by the extension.
421
+ *
422
+ * @public
423
+ */
424
+ cleanup() {
425
+ if (this._inflate) {
426
+ this._inflate.close();
427
+ this._inflate = null;
428
+ }
429
+ if (this._deflate) {
430
+ const callback = this._deflate[kCallback];
431
+ this._deflate.close();
432
+ this._deflate = null;
433
+ if (callback) {
434
+ callback(
435
+ new Error(
436
+ "The deflate stream was closed while data was being processed"
437
+ )
438
+ );
439
+ }
440
+ }
441
+ }
442
+ /**
443
+ * Accept an extension negotiation offer.
444
+ *
445
+ * @param {Array} offers The extension negotiation offers
446
+ * @return {Object} Accepted configuration
447
+ * @private
448
+ */
449
+ acceptAsServer(offers) {
450
+ const opts = this._options;
451
+ const accepted = offers.find((params) => {
452
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
453
+ return false;
454
+ }
455
+ return true;
456
+ });
457
+ if (!accepted) {
458
+ throw new Error("None of the extension offers can be accepted");
459
+ }
460
+ if (opts.serverNoContextTakeover) {
461
+ accepted.server_no_context_takeover = true;
462
+ }
463
+ if (opts.clientNoContextTakeover) {
464
+ accepted.client_no_context_takeover = true;
465
+ }
466
+ if (typeof opts.serverMaxWindowBits === "number") {
467
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
468
+ }
469
+ if (typeof opts.clientMaxWindowBits === "number") {
470
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
471
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
472
+ delete accepted.client_max_window_bits;
473
+ }
474
+ return accepted;
475
+ }
476
+ /**
477
+ * Accept the extension negotiation response.
478
+ *
479
+ * @param {Array} response The extension negotiation response
480
+ * @return {Object} Accepted configuration
481
+ * @private
482
+ */
483
+ acceptAsClient(response) {
484
+ const params = response[0];
485
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
486
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
487
+ }
488
+ if (!params.client_max_window_bits) {
489
+ if (typeof this._options.clientMaxWindowBits === "number") {
490
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
491
+ }
492
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
493
+ throw new Error(
494
+ 'Unexpected or invalid parameter "client_max_window_bits"'
495
+ );
496
+ }
497
+ return params;
498
+ }
499
+ /**
500
+ * Normalize parameters.
501
+ *
502
+ * @param {Array} configurations The extension negotiation offers/reponse
503
+ * @return {Array} The offers/response with normalized parameters
504
+ * @private
505
+ */
506
+ normalizeParams(configurations) {
507
+ configurations.forEach((params) => {
508
+ Object.keys(params).forEach((key) => {
509
+ let value = params[key];
510
+ if (value.length > 1) {
511
+ throw new Error(`Parameter "${key}" must have only a single value`);
512
+ }
513
+ value = value[0];
514
+ if (key === "client_max_window_bits") {
515
+ if (value !== true) {
516
+ const num = +value;
517
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
518
+ throw new TypeError(
519
+ `Invalid value for parameter "${key}": ${value}`
520
+ );
521
+ }
522
+ value = num;
523
+ } else if (!this._isServer) {
524
+ throw new TypeError(
525
+ `Invalid value for parameter "${key}": ${value}`
526
+ );
527
+ }
528
+ } else if (key === "server_max_window_bits") {
529
+ const num = +value;
530
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
531
+ throw new TypeError(
532
+ `Invalid value for parameter "${key}": ${value}`
533
+ );
534
+ }
535
+ value = num;
536
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
537
+ if (value !== true) {
538
+ throw new TypeError(
539
+ `Invalid value for parameter "${key}": ${value}`
540
+ );
541
+ }
542
+ } else {
543
+ throw new Error(`Unknown parameter "${key}"`);
544
+ }
545
+ params[key] = value;
546
+ });
547
+ });
548
+ return configurations;
549
+ }
550
+ /**
551
+ * Decompress data. Concurrency limited.
552
+ *
553
+ * @param {Buffer} data Compressed data
554
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
555
+ * @param {Function} callback Callback
556
+ * @public
557
+ */
558
+ decompress(data, fin, callback) {
559
+ zlibLimiter.add((done) => {
560
+ this._decompress(data, fin, (err, result) => {
561
+ done();
562
+ callback(err, result);
563
+ });
564
+ });
565
+ }
566
+ /**
567
+ * Compress data. Concurrency limited.
568
+ *
569
+ * @param {(Buffer|String)} data Data to compress
570
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
571
+ * @param {Function} callback Callback
572
+ * @public
573
+ */
574
+ compress(data, fin, callback) {
575
+ zlibLimiter.add((done) => {
576
+ this._compress(data, fin, (err, result) => {
577
+ done();
578
+ callback(err, result);
579
+ });
580
+ });
581
+ }
582
+ /**
583
+ * Decompress data.
584
+ *
585
+ * @param {Buffer} data Compressed data
586
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
587
+ * @param {Function} callback Callback
588
+ * @private
589
+ */
590
+ _decompress(data, fin, callback) {
591
+ const endpoint = this._isServer ? "client" : "server";
592
+ if (!this._inflate) {
593
+ const key = `${endpoint}_max_window_bits`;
594
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
595
+ this._inflate = zlib.createInflateRaw(__spreadProps(__spreadValues({}, this._options.zlibInflateOptions), {
596
+ windowBits
597
+ }));
598
+ this._inflate[kPerMessageDeflate] = this;
599
+ this._inflate[kTotalLength] = 0;
600
+ this._inflate[kBuffers] = [];
601
+ this._inflate.on("error", inflateOnError);
602
+ this._inflate.on("data", inflateOnData);
603
+ }
604
+ this._inflate[kCallback] = callback;
605
+ this._inflate.write(data);
606
+ if (fin) this._inflate.write(TRAILER);
607
+ this._inflate.flush(() => {
608
+ const err = this._inflate[kError];
609
+ if (err) {
610
+ this._inflate.close();
611
+ this._inflate = null;
612
+ callback(err);
613
+ return;
614
+ }
615
+ const data2 = bufferUtil.concat(
616
+ this._inflate[kBuffers],
617
+ this._inflate[kTotalLength]
618
+ );
619
+ if (this._inflate._readableState.endEmitted) {
620
+ this._inflate.close();
621
+ this._inflate = null;
622
+ } else {
623
+ this._inflate[kTotalLength] = 0;
624
+ this._inflate[kBuffers] = [];
625
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
626
+ this._inflate.reset();
627
+ }
628
+ }
629
+ callback(null, data2);
630
+ });
631
+ }
632
+ /**
633
+ * Compress data.
634
+ *
635
+ * @param {(Buffer|String)} data Data to compress
636
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
637
+ * @param {Function} callback Callback
638
+ * @private
639
+ */
640
+ _compress(data, fin, callback) {
641
+ const endpoint = this._isServer ? "server" : "client";
642
+ if (!this._deflate) {
643
+ const key = `${endpoint}_max_window_bits`;
644
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
645
+ this._deflate = zlib.createDeflateRaw(__spreadProps(__spreadValues({}, this._options.zlibDeflateOptions), {
646
+ windowBits
647
+ }));
648
+ this._deflate[kTotalLength] = 0;
649
+ this._deflate[kBuffers] = [];
650
+ this._deflate.on("data", deflateOnData);
651
+ }
652
+ this._deflate[kCallback] = callback;
653
+ this._deflate.write(data);
654
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
655
+ if (!this._deflate) {
656
+ return;
657
+ }
658
+ let data2 = bufferUtil.concat(
659
+ this._deflate[kBuffers],
660
+ this._deflate[kTotalLength]
661
+ );
662
+ if (fin) {
663
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
664
+ }
665
+ this._deflate[kCallback] = null;
666
+ this._deflate[kTotalLength] = 0;
667
+ this._deflate[kBuffers] = [];
668
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
669
+ this._deflate.reset();
670
+ }
671
+ callback(null, data2);
672
+ });
673
+ }
674
+ };
675
+ module.exports = PerMessageDeflate;
676
+ function deflateOnData(chunk) {
677
+ this[kBuffers].push(chunk);
678
+ this[kTotalLength] += chunk.length;
679
+ }
680
+ function inflateOnData(chunk) {
681
+ this[kTotalLength] += chunk.length;
682
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
683
+ this[kBuffers].push(chunk);
684
+ return;
685
+ }
686
+ this[kError] = new RangeError("Max payload size exceeded");
687
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
688
+ this[kError][kStatusCode] = 1009;
689
+ this.removeListener("data", inflateOnData);
690
+ this.reset();
691
+ }
692
+ function inflateOnError(err) {
693
+ this[kPerMessageDeflate]._inflate = null;
694
+ err[kStatusCode] = 1007;
695
+ this[kCallback](err);
696
+ }
697
+ }
698
+ });
699
+
700
+ // node_modules/ws/lib/validation.js
701
+ var require_validation = __commonJS({
702
+ "node_modules/ws/lib/validation.js"(exports, module) {
703
+ "use strict";
704
+ var { isUtf8 } = __require("buffer");
705
+ var tokenChars = [
706
+ 0,
707
+ 0,
708
+ 0,
709
+ 0,
710
+ 0,
711
+ 0,
712
+ 0,
713
+ 0,
714
+ 0,
715
+ 0,
716
+ 0,
717
+ 0,
718
+ 0,
719
+ 0,
720
+ 0,
721
+ 0,
722
+ // 0 - 15
723
+ 0,
724
+ 0,
725
+ 0,
726
+ 0,
727
+ 0,
728
+ 0,
729
+ 0,
730
+ 0,
731
+ 0,
732
+ 0,
733
+ 0,
734
+ 0,
735
+ 0,
736
+ 0,
737
+ 0,
738
+ 0,
739
+ // 16 - 31
740
+ 0,
741
+ 1,
742
+ 0,
743
+ 1,
744
+ 1,
745
+ 1,
746
+ 1,
747
+ 1,
748
+ 0,
749
+ 0,
750
+ 1,
751
+ 1,
752
+ 0,
753
+ 1,
754
+ 1,
755
+ 0,
756
+ // 32 - 47
757
+ 1,
758
+ 1,
759
+ 1,
760
+ 1,
761
+ 1,
762
+ 1,
763
+ 1,
764
+ 1,
765
+ 1,
766
+ 1,
767
+ 0,
768
+ 0,
769
+ 0,
770
+ 0,
771
+ 0,
772
+ 0,
773
+ // 48 - 63
774
+ 0,
775
+ 1,
776
+ 1,
777
+ 1,
778
+ 1,
779
+ 1,
780
+ 1,
781
+ 1,
782
+ 1,
783
+ 1,
784
+ 1,
785
+ 1,
786
+ 1,
787
+ 1,
788
+ 1,
789
+ 1,
790
+ // 64 - 79
791
+ 1,
792
+ 1,
793
+ 1,
794
+ 1,
795
+ 1,
796
+ 1,
797
+ 1,
798
+ 1,
799
+ 1,
800
+ 1,
801
+ 1,
802
+ 0,
803
+ 0,
804
+ 0,
805
+ 1,
806
+ 1,
807
+ // 80 - 95
808
+ 1,
809
+ 1,
810
+ 1,
811
+ 1,
812
+ 1,
813
+ 1,
814
+ 1,
815
+ 1,
816
+ 1,
817
+ 1,
818
+ 1,
819
+ 1,
820
+ 1,
821
+ 1,
822
+ 1,
823
+ 1,
824
+ // 96 - 111
825
+ 1,
826
+ 1,
827
+ 1,
828
+ 1,
829
+ 1,
830
+ 1,
831
+ 1,
832
+ 1,
833
+ 1,
834
+ 1,
835
+ 1,
836
+ 0,
837
+ 1,
838
+ 0,
839
+ 1,
840
+ 0
841
+ // 112 - 127
842
+ ];
843
+ function isValidStatusCode(code) {
844
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
845
+ }
846
+ function _isValidUTF8(buf) {
847
+ const len = buf.length;
848
+ let i = 0;
849
+ while (i < len) {
850
+ if ((buf[i] & 128) === 0) {
851
+ i++;
852
+ } else if ((buf[i] & 224) === 192) {
853
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
854
+ return false;
855
+ }
856
+ i += 2;
857
+ } else if ((buf[i] & 240) === 224) {
858
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
859
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
860
+ return false;
861
+ }
862
+ i += 3;
863
+ } else if ((buf[i] & 248) === 240) {
864
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
865
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
866
+ return false;
867
+ }
868
+ i += 4;
869
+ } else {
870
+ return false;
871
+ }
872
+ }
873
+ return true;
874
+ }
875
+ module.exports = {
876
+ isValidStatusCode,
877
+ isValidUTF8: _isValidUTF8,
878
+ tokenChars
879
+ };
880
+ if (isUtf8) {
881
+ module.exports.isValidUTF8 = function(buf) {
882
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
883
+ };
884
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
885
+ try {
886
+ const isValidUTF8 = __require("utf-8-validate");
887
+ module.exports.isValidUTF8 = function(buf) {
888
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
889
+ };
890
+ } catch (e) {
891
+ }
892
+ }
893
+ }
894
+ });
895
+
896
+ // node_modules/ws/lib/receiver.js
897
+ var require_receiver = __commonJS({
898
+ "node_modules/ws/lib/receiver.js"(exports, module) {
899
+ "use strict";
900
+ var { Writable } = __require("stream");
901
+ var PerMessageDeflate = require_permessage_deflate();
902
+ var {
903
+ BINARY_TYPES,
904
+ EMPTY_BUFFER,
905
+ kStatusCode,
906
+ kWebSocket
907
+ } = require_constants();
908
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
909
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
910
+ var FastBuffer = Buffer[Symbol.species];
911
+ var GET_INFO = 0;
912
+ var GET_PAYLOAD_LENGTH_16 = 1;
913
+ var GET_PAYLOAD_LENGTH_64 = 2;
914
+ var GET_MASK = 3;
915
+ var GET_DATA = 4;
916
+ var INFLATING = 5;
917
+ var DEFER_EVENT = 6;
918
+ var Receiver2 = class extends Writable {
919
+ /**
920
+ * Creates a Receiver instance.
921
+ *
922
+ * @param {Object} [options] Options object
923
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
924
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
925
+ * multiple times in the same tick
926
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
927
+ * @param {Object} [options.extensions] An object containing the negotiated
928
+ * extensions
929
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
930
+ * client or server mode
931
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
932
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
933
+ * not to skip UTF-8 validation for text and close messages
934
+ */
935
+ constructor(options = {}) {
936
+ super();
937
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
938
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
939
+ this._extensions = options.extensions || {};
940
+ this._isServer = !!options.isServer;
941
+ this._maxPayload = options.maxPayload | 0;
942
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
943
+ this[kWebSocket] = void 0;
944
+ this._bufferedBytes = 0;
945
+ this._buffers = [];
946
+ this._compressed = false;
947
+ this._payloadLength = 0;
948
+ this._mask = void 0;
949
+ this._fragmented = 0;
950
+ this._masked = false;
951
+ this._fin = false;
952
+ this._opcode = 0;
953
+ this._totalPayloadLength = 0;
954
+ this._messageLength = 0;
955
+ this._fragments = [];
956
+ this._errored = false;
957
+ this._loop = false;
958
+ this._state = GET_INFO;
959
+ }
960
+ /**
961
+ * Implements `Writable.prototype._write()`.
962
+ *
963
+ * @param {Buffer} chunk The chunk of data to write
964
+ * @param {String} encoding The character encoding of `chunk`
965
+ * @param {Function} cb Callback
966
+ * @private
967
+ */
968
+ _write(chunk, encoding, cb) {
969
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
970
+ this._bufferedBytes += chunk.length;
971
+ this._buffers.push(chunk);
972
+ this.startLoop(cb);
973
+ }
974
+ /**
975
+ * Consumes `n` bytes from the buffered data.
976
+ *
977
+ * @param {Number} n The number of bytes to consume
978
+ * @return {Buffer} The consumed bytes
979
+ * @private
980
+ */
981
+ consume(n) {
982
+ this._bufferedBytes -= n;
983
+ if (n === this._buffers[0].length) return this._buffers.shift();
984
+ if (n < this._buffers[0].length) {
985
+ const buf = this._buffers[0];
986
+ this._buffers[0] = new FastBuffer(
987
+ buf.buffer,
988
+ buf.byteOffset + n,
989
+ buf.length - n
990
+ );
991
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
992
+ }
993
+ const dst = Buffer.allocUnsafe(n);
994
+ do {
995
+ const buf = this._buffers[0];
996
+ const offset = dst.length - n;
997
+ if (n >= buf.length) {
998
+ dst.set(this._buffers.shift(), offset);
999
+ } else {
1000
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
1001
+ this._buffers[0] = new FastBuffer(
1002
+ buf.buffer,
1003
+ buf.byteOffset + n,
1004
+ buf.length - n
1005
+ );
1006
+ }
1007
+ n -= buf.length;
1008
+ } while (n > 0);
1009
+ return dst;
1010
+ }
1011
+ /**
1012
+ * Starts the parsing loop.
1013
+ *
1014
+ * @param {Function} cb Callback
1015
+ * @private
1016
+ */
1017
+ startLoop(cb) {
1018
+ this._loop = true;
1019
+ do {
1020
+ switch (this._state) {
1021
+ case GET_INFO:
1022
+ this.getInfo(cb);
1023
+ break;
1024
+ case GET_PAYLOAD_LENGTH_16:
1025
+ this.getPayloadLength16(cb);
1026
+ break;
1027
+ case GET_PAYLOAD_LENGTH_64:
1028
+ this.getPayloadLength64(cb);
1029
+ break;
1030
+ case GET_MASK:
1031
+ this.getMask();
1032
+ break;
1033
+ case GET_DATA:
1034
+ this.getData(cb);
1035
+ break;
1036
+ case INFLATING:
1037
+ case DEFER_EVENT:
1038
+ this._loop = false;
1039
+ return;
1040
+ }
1041
+ } while (this._loop);
1042
+ if (!this._errored) cb();
1043
+ }
1044
+ /**
1045
+ * Reads the first two bytes of a frame.
1046
+ *
1047
+ * @param {Function} cb Callback
1048
+ * @private
1049
+ */
1050
+ getInfo(cb) {
1051
+ if (this._bufferedBytes < 2) {
1052
+ this._loop = false;
1053
+ return;
1054
+ }
1055
+ const buf = this.consume(2);
1056
+ if ((buf[0] & 48) !== 0) {
1057
+ const error = this.createError(
1058
+ RangeError,
1059
+ "RSV2 and RSV3 must be clear",
1060
+ true,
1061
+ 1002,
1062
+ "WS_ERR_UNEXPECTED_RSV_2_3"
1063
+ );
1064
+ cb(error);
1065
+ return;
1066
+ }
1067
+ const compressed = (buf[0] & 64) === 64;
1068
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
1069
+ const error = this.createError(
1070
+ RangeError,
1071
+ "RSV1 must be clear",
1072
+ true,
1073
+ 1002,
1074
+ "WS_ERR_UNEXPECTED_RSV_1"
1075
+ );
1076
+ cb(error);
1077
+ return;
1078
+ }
1079
+ this._fin = (buf[0] & 128) === 128;
1080
+ this._opcode = buf[0] & 15;
1081
+ this._payloadLength = buf[1] & 127;
1082
+ if (this._opcode === 0) {
1083
+ if (compressed) {
1084
+ const error = this.createError(
1085
+ RangeError,
1086
+ "RSV1 must be clear",
1087
+ true,
1088
+ 1002,
1089
+ "WS_ERR_UNEXPECTED_RSV_1"
1090
+ );
1091
+ cb(error);
1092
+ return;
1093
+ }
1094
+ if (!this._fragmented) {
1095
+ const error = this.createError(
1096
+ RangeError,
1097
+ "invalid opcode 0",
1098
+ true,
1099
+ 1002,
1100
+ "WS_ERR_INVALID_OPCODE"
1101
+ );
1102
+ cb(error);
1103
+ return;
1104
+ }
1105
+ this._opcode = this._fragmented;
1106
+ } else if (this._opcode === 1 || this._opcode === 2) {
1107
+ if (this._fragmented) {
1108
+ const error = this.createError(
1109
+ RangeError,
1110
+ `invalid opcode ${this._opcode}`,
1111
+ true,
1112
+ 1002,
1113
+ "WS_ERR_INVALID_OPCODE"
1114
+ );
1115
+ cb(error);
1116
+ return;
1117
+ }
1118
+ this._compressed = compressed;
1119
+ } else if (this._opcode > 7 && this._opcode < 11) {
1120
+ if (!this._fin) {
1121
+ const error = this.createError(
1122
+ RangeError,
1123
+ "FIN must be set",
1124
+ true,
1125
+ 1002,
1126
+ "WS_ERR_EXPECTED_FIN"
1127
+ );
1128
+ cb(error);
1129
+ return;
1130
+ }
1131
+ if (compressed) {
1132
+ const error = this.createError(
1133
+ RangeError,
1134
+ "RSV1 must be clear",
1135
+ true,
1136
+ 1002,
1137
+ "WS_ERR_UNEXPECTED_RSV_1"
1138
+ );
1139
+ cb(error);
1140
+ return;
1141
+ }
1142
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1143
+ const error = this.createError(
1144
+ RangeError,
1145
+ `invalid payload length ${this._payloadLength}`,
1146
+ true,
1147
+ 1002,
1148
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1149
+ );
1150
+ cb(error);
1151
+ return;
1152
+ }
1153
+ } else {
1154
+ const error = this.createError(
1155
+ RangeError,
1156
+ `invalid opcode ${this._opcode}`,
1157
+ true,
1158
+ 1002,
1159
+ "WS_ERR_INVALID_OPCODE"
1160
+ );
1161
+ cb(error);
1162
+ return;
1163
+ }
1164
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1165
+ this._masked = (buf[1] & 128) === 128;
1166
+ if (this._isServer) {
1167
+ if (!this._masked) {
1168
+ const error = this.createError(
1169
+ RangeError,
1170
+ "MASK must be set",
1171
+ true,
1172
+ 1002,
1173
+ "WS_ERR_EXPECTED_MASK"
1174
+ );
1175
+ cb(error);
1176
+ return;
1177
+ }
1178
+ } else if (this._masked) {
1179
+ const error = this.createError(
1180
+ RangeError,
1181
+ "MASK must be clear",
1182
+ true,
1183
+ 1002,
1184
+ "WS_ERR_UNEXPECTED_MASK"
1185
+ );
1186
+ cb(error);
1187
+ return;
1188
+ }
1189
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1190
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1191
+ else this.haveLength(cb);
1192
+ }
1193
+ /**
1194
+ * Gets extended payload length (7+16).
1195
+ *
1196
+ * @param {Function} cb Callback
1197
+ * @private
1198
+ */
1199
+ getPayloadLength16(cb) {
1200
+ if (this._bufferedBytes < 2) {
1201
+ this._loop = false;
1202
+ return;
1203
+ }
1204
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1205
+ this.haveLength(cb);
1206
+ }
1207
+ /**
1208
+ * Gets extended payload length (7+64).
1209
+ *
1210
+ * @param {Function} cb Callback
1211
+ * @private
1212
+ */
1213
+ getPayloadLength64(cb) {
1214
+ if (this._bufferedBytes < 8) {
1215
+ this._loop = false;
1216
+ return;
1217
+ }
1218
+ const buf = this.consume(8);
1219
+ const num = buf.readUInt32BE(0);
1220
+ if (num > Math.pow(2, 53 - 32) - 1) {
1221
+ const error = this.createError(
1222
+ RangeError,
1223
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1224
+ false,
1225
+ 1009,
1226
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1227
+ );
1228
+ cb(error);
1229
+ return;
1230
+ }
1231
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1232
+ this.haveLength(cb);
1233
+ }
1234
+ /**
1235
+ * Payload length has been read.
1236
+ *
1237
+ * @param {Function} cb Callback
1238
+ * @private
1239
+ */
1240
+ haveLength(cb) {
1241
+ if (this._payloadLength && this._opcode < 8) {
1242
+ this._totalPayloadLength += this._payloadLength;
1243
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1244
+ const error = this.createError(
1245
+ RangeError,
1246
+ "Max payload size exceeded",
1247
+ false,
1248
+ 1009,
1249
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1250
+ );
1251
+ cb(error);
1252
+ return;
1253
+ }
1254
+ }
1255
+ if (this._masked) this._state = GET_MASK;
1256
+ else this._state = GET_DATA;
1257
+ }
1258
+ /**
1259
+ * Reads mask bytes.
1260
+ *
1261
+ * @private
1262
+ */
1263
+ getMask() {
1264
+ if (this._bufferedBytes < 4) {
1265
+ this._loop = false;
1266
+ return;
1267
+ }
1268
+ this._mask = this.consume(4);
1269
+ this._state = GET_DATA;
1270
+ }
1271
+ /**
1272
+ * Reads data bytes.
1273
+ *
1274
+ * @param {Function} cb Callback
1275
+ * @private
1276
+ */
1277
+ getData(cb) {
1278
+ let data = EMPTY_BUFFER;
1279
+ if (this._payloadLength) {
1280
+ if (this._bufferedBytes < this._payloadLength) {
1281
+ this._loop = false;
1282
+ return;
1283
+ }
1284
+ data = this.consume(this._payloadLength);
1285
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1286
+ unmask(data, this._mask);
1287
+ }
1288
+ }
1289
+ if (this._opcode > 7) {
1290
+ this.controlMessage(data, cb);
1291
+ return;
1292
+ }
1293
+ if (this._compressed) {
1294
+ this._state = INFLATING;
1295
+ this.decompress(data, cb);
1296
+ return;
1297
+ }
1298
+ if (data.length) {
1299
+ this._messageLength = this._totalPayloadLength;
1300
+ this._fragments.push(data);
1301
+ }
1302
+ this.dataMessage(cb);
1303
+ }
1304
+ /**
1305
+ * Decompresses data.
1306
+ *
1307
+ * @param {Buffer} data Compressed data
1308
+ * @param {Function} cb Callback
1309
+ * @private
1310
+ */
1311
+ decompress(data, cb) {
1312
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1313
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1314
+ if (err) return cb(err);
1315
+ if (buf.length) {
1316
+ this._messageLength += buf.length;
1317
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1318
+ const error = this.createError(
1319
+ RangeError,
1320
+ "Max payload size exceeded",
1321
+ false,
1322
+ 1009,
1323
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1324
+ );
1325
+ cb(error);
1326
+ return;
1327
+ }
1328
+ this._fragments.push(buf);
1329
+ }
1330
+ this.dataMessage(cb);
1331
+ if (this._state === GET_INFO) this.startLoop(cb);
1332
+ });
1333
+ }
1334
+ /**
1335
+ * Handles a data message.
1336
+ *
1337
+ * @param {Function} cb Callback
1338
+ * @private
1339
+ */
1340
+ dataMessage(cb) {
1341
+ if (!this._fin) {
1342
+ this._state = GET_INFO;
1343
+ return;
1344
+ }
1345
+ const messageLength = this._messageLength;
1346
+ const fragments = this._fragments;
1347
+ this._totalPayloadLength = 0;
1348
+ this._messageLength = 0;
1349
+ this._fragmented = 0;
1350
+ this._fragments = [];
1351
+ if (this._opcode === 2) {
1352
+ let data;
1353
+ if (this._binaryType === "nodebuffer") {
1354
+ data = concat(fragments, messageLength);
1355
+ } else if (this._binaryType === "arraybuffer") {
1356
+ data = toArrayBuffer(concat(fragments, messageLength));
1357
+ } else {
1358
+ data = fragments;
1359
+ }
1360
+ if (this._allowSynchronousEvents) {
1361
+ this.emit("message", data, true);
1362
+ this._state = GET_INFO;
1363
+ } else {
1364
+ this._state = DEFER_EVENT;
1365
+ setImmediate(() => {
1366
+ this.emit("message", data, true);
1367
+ this._state = GET_INFO;
1368
+ this.startLoop(cb);
1369
+ });
1370
+ }
1371
+ } else {
1372
+ const buf = concat(fragments, messageLength);
1373
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1374
+ const error = this.createError(
1375
+ Error,
1376
+ "invalid UTF-8 sequence",
1377
+ true,
1378
+ 1007,
1379
+ "WS_ERR_INVALID_UTF8"
1380
+ );
1381
+ cb(error);
1382
+ return;
1383
+ }
1384
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1385
+ this.emit("message", buf, false);
1386
+ this._state = GET_INFO;
1387
+ } else {
1388
+ this._state = DEFER_EVENT;
1389
+ setImmediate(() => {
1390
+ this.emit("message", buf, false);
1391
+ this._state = GET_INFO;
1392
+ this.startLoop(cb);
1393
+ });
1394
+ }
1395
+ }
1396
+ }
1397
+ /**
1398
+ * Handles a control message.
1399
+ *
1400
+ * @param {Buffer} data Data to handle
1401
+ * @return {(Error|RangeError|undefined)} A possible error
1402
+ * @private
1403
+ */
1404
+ controlMessage(data, cb) {
1405
+ if (this._opcode === 8) {
1406
+ if (data.length === 0) {
1407
+ this._loop = false;
1408
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1409
+ this.end();
1410
+ } else {
1411
+ const code = data.readUInt16BE(0);
1412
+ if (!isValidStatusCode(code)) {
1413
+ const error = this.createError(
1414
+ RangeError,
1415
+ `invalid status code ${code}`,
1416
+ true,
1417
+ 1002,
1418
+ "WS_ERR_INVALID_CLOSE_CODE"
1419
+ );
1420
+ cb(error);
1421
+ return;
1422
+ }
1423
+ const buf = new FastBuffer(
1424
+ data.buffer,
1425
+ data.byteOffset + 2,
1426
+ data.length - 2
1427
+ );
1428
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1429
+ const error = this.createError(
1430
+ Error,
1431
+ "invalid UTF-8 sequence",
1432
+ true,
1433
+ 1007,
1434
+ "WS_ERR_INVALID_UTF8"
1435
+ );
1436
+ cb(error);
1437
+ return;
1438
+ }
1439
+ this._loop = false;
1440
+ this.emit("conclude", code, buf);
1441
+ this.end();
1442
+ }
1443
+ this._state = GET_INFO;
1444
+ return;
1445
+ }
1446
+ if (this._allowSynchronousEvents) {
1447
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1448
+ this._state = GET_INFO;
1449
+ } else {
1450
+ this._state = DEFER_EVENT;
1451
+ setImmediate(() => {
1452
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1453
+ this._state = GET_INFO;
1454
+ this.startLoop(cb);
1455
+ });
1456
+ }
1457
+ }
1458
+ /**
1459
+ * Builds an error object.
1460
+ *
1461
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1462
+ * @param {String} message The error message
1463
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1464
+ * `message`
1465
+ * @param {Number} statusCode The status code
1466
+ * @param {String} errorCode The exposed error code
1467
+ * @return {(Error|RangeError)} The error
1468
+ * @private
1469
+ */
1470
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1471
+ this._loop = false;
1472
+ this._errored = true;
1473
+ const err = new ErrorCtor(
1474
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1475
+ );
1476
+ Error.captureStackTrace(err, this.createError);
1477
+ err.code = errorCode;
1478
+ err[kStatusCode] = statusCode;
1479
+ return err;
1480
+ }
1481
+ };
1482
+ module.exports = Receiver2;
1483
+ }
1484
+ });
1485
+
1486
+ // node_modules/ws/lib/sender.js
1487
+ var require_sender = __commonJS({
1488
+ "node_modules/ws/lib/sender.js"(exports, module) {
1489
+ "use strict";
1490
+ var { Duplex } = __require("stream");
1491
+ var { randomFillSync } = __require("crypto");
1492
+ var PerMessageDeflate = require_permessage_deflate();
1493
+ var { EMPTY_BUFFER } = require_constants();
1494
+ var { isValidStatusCode } = require_validation();
1495
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1496
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1497
+ var maskBuffer = Buffer.alloc(4);
1498
+ var RANDOM_POOL_SIZE = 8 * 1024;
1499
+ var randomPool;
1500
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1501
+ var Sender2 = class _Sender {
1502
+ /**
1503
+ * Creates a Sender instance.
1504
+ *
1505
+ * @param {Duplex} socket The connection socket
1506
+ * @param {Object} [extensions] An object containing the negotiated extensions
1507
+ * @param {Function} [generateMask] The function used to generate the masking
1508
+ * key
1509
+ */
1510
+ constructor(socket, extensions, generateMask) {
1511
+ this._extensions = extensions || {};
1512
+ if (generateMask) {
1513
+ this._generateMask = generateMask;
1514
+ this._maskBuffer = Buffer.alloc(4);
1515
+ }
1516
+ this._socket = socket;
1517
+ this._firstFragment = true;
1518
+ this._compress = false;
1519
+ this._bufferedBytes = 0;
1520
+ this._deflating = false;
1521
+ this._queue = [];
1522
+ }
1523
+ /**
1524
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1525
+ *
1526
+ * @param {(Buffer|String)} data The data to frame
1527
+ * @param {Object} options Options object
1528
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1529
+ * FIN bit
1530
+ * @param {Function} [options.generateMask] The function used to generate the
1531
+ * masking key
1532
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1533
+ * `data`
1534
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1535
+ * key
1536
+ * @param {Number} options.opcode The opcode
1537
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1538
+ * modified
1539
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1540
+ * RSV1 bit
1541
+ * @return {(Buffer|String)[]} The framed data
1542
+ * @public
1543
+ */
1544
+ static frame(data, options) {
1545
+ let mask;
1546
+ let merge = false;
1547
+ let offset = 2;
1548
+ let skipMasking = false;
1549
+ if (options.mask) {
1550
+ mask = options.maskBuffer || maskBuffer;
1551
+ if (options.generateMask) {
1552
+ options.generateMask(mask);
1553
+ } else {
1554
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1555
+ if (randomPool === void 0) {
1556
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1557
+ }
1558
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1559
+ randomPoolPointer = 0;
1560
+ }
1561
+ mask[0] = randomPool[randomPoolPointer++];
1562
+ mask[1] = randomPool[randomPoolPointer++];
1563
+ mask[2] = randomPool[randomPoolPointer++];
1564
+ mask[3] = randomPool[randomPoolPointer++];
1565
+ }
1566
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1567
+ offset = 6;
1568
+ }
1569
+ let dataLength;
1570
+ if (typeof data === "string") {
1571
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1572
+ dataLength = options[kByteLength];
1573
+ } else {
1574
+ data = Buffer.from(data);
1575
+ dataLength = data.length;
1576
+ }
1577
+ } else {
1578
+ dataLength = data.length;
1579
+ merge = options.mask && options.readOnly && !skipMasking;
1580
+ }
1581
+ let payloadLength = dataLength;
1582
+ if (dataLength >= 65536) {
1583
+ offset += 8;
1584
+ payloadLength = 127;
1585
+ } else if (dataLength > 125) {
1586
+ offset += 2;
1587
+ payloadLength = 126;
1588
+ }
1589
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1590
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1591
+ if (options.rsv1) target[0] |= 64;
1592
+ target[1] = payloadLength;
1593
+ if (payloadLength === 126) {
1594
+ target.writeUInt16BE(dataLength, 2);
1595
+ } else if (payloadLength === 127) {
1596
+ target[2] = target[3] = 0;
1597
+ target.writeUIntBE(dataLength, 4, 6);
1598
+ }
1599
+ if (!options.mask) return [target, data];
1600
+ target[1] |= 128;
1601
+ target[offset - 4] = mask[0];
1602
+ target[offset - 3] = mask[1];
1603
+ target[offset - 2] = mask[2];
1604
+ target[offset - 1] = mask[3];
1605
+ if (skipMasking) return [target, data];
1606
+ if (merge) {
1607
+ applyMask(data, mask, target, offset, dataLength);
1608
+ return [target];
1609
+ }
1610
+ applyMask(data, mask, data, 0, dataLength);
1611
+ return [target, data];
1612
+ }
1613
+ /**
1614
+ * Sends a close message to the other peer.
1615
+ *
1616
+ * @param {Number} [code] The status code component of the body
1617
+ * @param {(String|Buffer)} [data] The message component of the body
1618
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1619
+ * @param {Function} [cb] Callback
1620
+ * @public
1621
+ */
1622
+ close(code, data, mask, cb) {
1623
+ let buf;
1624
+ if (code === void 0) {
1625
+ buf = EMPTY_BUFFER;
1626
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1627
+ throw new TypeError("First argument must be a valid error code number");
1628
+ } else if (data === void 0 || !data.length) {
1629
+ buf = Buffer.allocUnsafe(2);
1630
+ buf.writeUInt16BE(code, 0);
1631
+ } else {
1632
+ const length = Buffer.byteLength(data);
1633
+ if (length > 123) {
1634
+ throw new RangeError("The message must not be greater than 123 bytes");
1635
+ }
1636
+ buf = Buffer.allocUnsafe(2 + length);
1637
+ buf.writeUInt16BE(code, 0);
1638
+ if (typeof data === "string") {
1639
+ buf.write(data, 2);
1640
+ } else {
1641
+ buf.set(data, 2);
1642
+ }
1643
+ }
1644
+ const options = {
1645
+ [kByteLength]: buf.length,
1646
+ fin: true,
1647
+ generateMask: this._generateMask,
1648
+ mask,
1649
+ maskBuffer: this._maskBuffer,
1650
+ opcode: 8,
1651
+ readOnly: false,
1652
+ rsv1: false
1653
+ };
1654
+ if (this._deflating) {
1655
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1656
+ } else {
1657
+ this.sendFrame(_Sender.frame(buf, options), cb);
1658
+ }
1659
+ }
1660
+ /**
1661
+ * Sends a ping message to the other peer.
1662
+ *
1663
+ * @param {*} data The message to send
1664
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1665
+ * @param {Function} [cb] Callback
1666
+ * @public
1667
+ */
1668
+ ping(data, mask, cb) {
1669
+ let byteLength;
1670
+ let readOnly;
1671
+ if (typeof data === "string") {
1672
+ byteLength = Buffer.byteLength(data);
1673
+ readOnly = false;
1674
+ } else {
1675
+ data = toBuffer(data);
1676
+ byteLength = data.length;
1677
+ readOnly = toBuffer.readOnly;
1678
+ }
1679
+ if (byteLength > 125) {
1680
+ throw new RangeError("The data size must not be greater than 125 bytes");
1681
+ }
1682
+ const options = {
1683
+ [kByteLength]: byteLength,
1684
+ fin: true,
1685
+ generateMask: this._generateMask,
1686
+ mask,
1687
+ maskBuffer: this._maskBuffer,
1688
+ opcode: 9,
1689
+ readOnly,
1690
+ rsv1: false
1691
+ };
1692
+ if (this._deflating) {
1693
+ this.enqueue([this.dispatch, data, false, options, cb]);
1694
+ } else {
1695
+ this.sendFrame(_Sender.frame(data, options), cb);
1696
+ }
1697
+ }
1698
+ /**
1699
+ * Sends a pong message to the other peer.
1700
+ *
1701
+ * @param {*} data The message to send
1702
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1703
+ * @param {Function} [cb] Callback
1704
+ * @public
1705
+ */
1706
+ pong(data, mask, cb) {
1707
+ let byteLength;
1708
+ let readOnly;
1709
+ if (typeof data === "string") {
1710
+ byteLength = Buffer.byteLength(data);
1711
+ readOnly = false;
1712
+ } else {
1713
+ data = toBuffer(data);
1714
+ byteLength = data.length;
1715
+ readOnly = toBuffer.readOnly;
1716
+ }
1717
+ if (byteLength > 125) {
1718
+ throw new RangeError("The data size must not be greater than 125 bytes");
1719
+ }
1720
+ const options = {
1721
+ [kByteLength]: byteLength,
1722
+ fin: true,
1723
+ generateMask: this._generateMask,
1724
+ mask,
1725
+ maskBuffer: this._maskBuffer,
1726
+ opcode: 10,
1727
+ readOnly,
1728
+ rsv1: false
1729
+ };
1730
+ if (this._deflating) {
1731
+ this.enqueue([this.dispatch, data, false, options, cb]);
1732
+ } else {
1733
+ this.sendFrame(_Sender.frame(data, options), cb);
1734
+ }
1735
+ }
1736
+ /**
1737
+ * Sends a data message to the other peer.
1738
+ *
1739
+ * @param {*} data The message to send
1740
+ * @param {Object} options Options object
1741
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1742
+ * or text
1743
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1744
+ * compress `data`
1745
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1746
+ * last one
1747
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1748
+ * `data`
1749
+ * @param {Function} [cb] Callback
1750
+ * @public
1751
+ */
1752
+ send(data, options, cb) {
1753
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1754
+ let opcode = options.binary ? 2 : 1;
1755
+ let rsv1 = options.compress;
1756
+ let byteLength;
1757
+ let readOnly;
1758
+ if (typeof data === "string") {
1759
+ byteLength = Buffer.byteLength(data);
1760
+ readOnly = false;
1761
+ } else {
1762
+ data = toBuffer(data);
1763
+ byteLength = data.length;
1764
+ readOnly = toBuffer.readOnly;
1765
+ }
1766
+ if (this._firstFragment) {
1767
+ this._firstFragment = false;
1768
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1769
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1770
+ }
1771
+ this._compress = rsv1;
1772
+ } else {
1773
+ rsv1 = false;
1774
+ opcode = 0;
1775
+ }
1776
+ if (options.fin) this._firstFragment = true;
1777
+ if (perMessageDeflate) {
1778
+ const opts = {
1779
+ [kByteLength]: byteLength,
1780
+ fin: options.fin,
1781
+ generateMask: this._generateMask,
1782
+ mask: options.mask,
1783
+ maskBuffer: this._maskBuffer,
1784
+ opcode,
1785
+ readOnly,
1786
+ rsv1
1787
+ };
1788
+ if (this._deflating) {
1789
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1790
+ } else {
1791
+ this.dispatch(data, this._compress, opts, cb);
1792
+ }
1793
+ } else {
1794
+ this.sendFrame(
1795
+ _Sender.frame(data, {
1796
+ [kByteLength]: byteLength,
1797
+ fin: options.fin,
1798
+ generateMask: this._generateMask,
1799
+ mask: options.mask,
1800
+ maskBuffer: this._maskBuffer,
1801
+ opcode,
1802
+ readOnly,
1803
+ rsv1: false
1804
+ }),
1805
+ cb
1806
+ );
1807
+ }
1808
+ }
1809
+ /**
1810
+ * Dispatches a message.
1811
+ *
1812
+ * @param {(Buffer|String)} data The message to send
1813
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1814
+ * `data`
1815
+ * @param {Object} options Options object
1816
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1817
+ * FIN bit
1818
+ * @param {Function} [options.generateMask] The function used to generate the
1819
+ * masking key
1820
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1821
+ * `data`
1822
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1823
+ * key
1824
+ * @param {Number} options.opcode The opcode
1825
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1826
+ * modified
1827
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1828
+ * RSV1 bit
1829
+ * @param {Function} [cb] Callback
1830
+ * @private
1831
+ */
1832
+ dispatch(data, compress, options, cb) {
1833
+ if (!compress) {
1834
+ this.sendFrame(_Sender.frame(data, options), cb);
1835
+ return;
1836
+ }
1837
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1838
+ this._bufferedBytes += options[kByteLength];
1839
+ this._deflating = true;
1840
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1841
+ if (this._socket.destroyed) {
1842
+ const err = new Error(
1843
+ "The socket was closed while data was being compressed"
1844
+ );
1845
+ if (typeof cb === "function") cb(err);
1846
+ for (let i = 0; i < this._queue.length; i++) {
1847
+ const params = this._queue[i];
1848
+ const callback = params[params.length - 1];
1849
+ if (typeof callback === "function") callback(err);
1850
+ }
1851
+ return;
1852
+ }
1853
+ this._bufferedBytes -= options[kByteLength];
1854
+ this._deflating = false;
1855
+ options.readOnly = false;
1856
+ this.sendFrame(_Sender.frame(buf, options), cb);
1857
+ this.dequeue();
1858
+ });
1859
+ }
1860
+ /**
1861
+ * Executes queued send operations.
1862
+ *
1863
+ * @private
1864
+ */
1865
+ dequeue() {
1866
+ while (!this._deflating && this._queue.length) {
1867
+ const params = this._queue.shift();
1868
+ this._bufferedBytes -= params[3][kByteLength];
1869
+ Reflect.apply(params[0], this, params.slice(1));
1870
+ }
1871
+ }
1872
+ /**
1873
+ * Enqueues a send operation.
1874
+ *
1875
+ * @param {Array} params Send operation parameters.
1876
+ * @private
1877
+ */
1878
+ enqueue(params) {
1879
+ this._bufferedBytes += params[3][kByteLength];
1880
+ this._queue.push(params);
1881
+ }
1882
+ /**
1883
+ * Sends a frame.
1884
+ *
1885
+ * @param {Buffer[]} list The frame to send
1886
+ * @param {Function} [cb] Callback
1887
+ * @private
1888
+ */
1889
+ sendFrame(list, cb) {
1890
+ if (list.length === 2) {
1891
+ this._socket.cork();
1892
+ this._socket.write(list[0]);
1893
+ this._socket.write(list[1], cb);
1894
+ this._socket.uncork();
1895
+ } else {
1896
+ this._socket.write(list[0], cb);
1897
+ }
1898
+ }
1899
+ };
1900
+ module.exports = Sender2;
1901
+ }
1902
+ });
1903
+
1904
+ // node_modules/ws/lib/event-target.js
1905
+ var require_event_target = __commonJS({
1906
+ "node_modules/ws/lib/event-target.js"(exports, module) {
1907
+ "use strict";
1908
+ var { kForOnEventAttribute, kListener } = require_constants();
1909
+ var kCode = /* @__PURE__ */ Symbol("kCode");
1910
+ var kData = /* @__PURE__ */ Symbol("kData");
1911
+ var kError = /* @__PURE__ */ Symbol("kError");
1912
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
1913
+ var kReason = /* @__PURE__ */ Symbol("kReason");
1914
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
1915
+ var kType = /* @__PURE__ */ Symbol("kType");
1916
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
1917
+ var Event = class {
1918
+ /**
1919
+ * Create a new `Event`.
1920
+ *
1921
+ * @param {String} type The name of the event
1922
+ * @throws {TypeError} If the `type` argument is not specified
1923
+ */
1924
+ constructor(type) {
1925
+ this[kTarget] = null;
1926
+ this[kType] = type;
1927
+ }
1928
+ /**
1929
+ * @type {*}
1930
+ */
1931
+ get target() {
1932
+ return this[kTarget];
1933
+ }
1934
+ /**
1935
+ * @type {String}
1936
+ */
1937
+ get type() {
1938
+ return this[kType];
1939
+ }
1940
+ };
1941
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1942
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1943
+ var CloseEvent = class extends Event {
1944
+ /**
1945
+ * Create a new `CloseEvent`.
1946
+ *
1947
+ * @param {String} type The name of the event
1948
+ * @param {Object} [options] A dictionary object that allows for setting
1949
+ * attributes via object members of the same name
1950
+ * @param {Number} [options.code=0] The status code explaining why the
1951
+ * connection was closed
1952
+ * @param {String} [options.reason=''] A human-readable string explaining why
1953
+ * the connection was closed
1954
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1955
+ * connection was cleanly closed
1956
+ */
1957
+ constructor(type, options = {}) {
1958
+ super(type);
1959
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1960
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1961
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1962
+ }
1963
+ /**
1964
+ * @type {Number}
1965
+ */
1966
+ get code() {
1967
+ return this[kCode];
1968
+ }
1969
+ /**
1970
+ * @type {String}
1971
+ */
1972
+ get reason() {
1973
+ return this[kReason];
1974
+ }
1975
+ /**
1976
+ * @type {Boolean}
1977
+ */
1978
+ get wasClean() {
1979
+ return this[kWasClean];
1980
+ }
1981
+ };
1982
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1983
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1984
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1985
+ var ErrorEvent = class extends Event {
1986
+ /**
1987
+ * Create a new `ErrorEvent`.
1988
+ *
1989
+ * @param {String} type The name of the event
1990
+ * @param {Object} [options] A dictionary object that allows for setting
1991
+ * attributes via object members of the same name
1992
+ * @param {*} [options.error=null] The error that generated this event
1993
+ * @param {String} [options.message=''] The error message
1994
+ */
1995
+ constructor(type, options = {}) {
1996
+ super(type);
1997
+ this[kError] = options.error === void 0 ? null : options.error;
1998
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1999
+ }
2000
+ /**
2001
+ * @type {*}
2002
+ */
2003
+ get error() {
2004
+ return this[kError];
2005
+ }
2006
+ /**
2007
+ * @type {String}
2008
+ */
2009
+ get message() {
2010
+ return this[kMessage];
2011
+ }
2012
+ };
2013
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
2014
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
2015
+ var MessageEvent = class extends Event {
2016
+ /**
2017
+ * Create a new `MessageEvent`.
2018
+ *
2019
+ * @param {String} type The name of the event
2020
+ * @param {Object} [options] A dictionary object that allows for setting
2021
+ * attributes via object members of the same name
2022
+ * @param {*} [options.data=null] The message content
2023
+ */
2024
+ constructor(type, options = {}) {
2025
+ super(type);
2026
+ this[kData] = options.data === void 0 ? null : options.data;
2027
+ }
2028
+ /**
2029
+ * @type {*}
2030
+ */
2031
+ get data() {
2032
+ return this[kData];
2033
+ }
2034
+ };
2035
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
2036
+ var EventTarget = {
2037
+ /**
2038
+ * Register an event listener.
2039
+ *
2040
+ * @param {String} type A string representing the event type to listen for
2041
+ * @param {(Function|Object)} handler The listener to add
2042
+ * @param {Object} [options] An options object specifies characteristics about
2043
+ * the event listener
2044
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2045
+ * listener should be invoked at most once after being added. If `true`,
2046
+ * the listener would be automatically removed when invoked.
2047
+ * @public
2048
+ */
2049
+ addEventListener(type, handler, options = {}) {
2050
+ for (const listener of this.listeners(type)) {
2051
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2052
+ return;
2053
+ }
2054
+ }
2055
+ let wrapper;
2056
+ if (type === "message") {
2057
+ wrapper = function onMessage(data, isBinary) {
2058
+ const event = new MessageEvent("message", {
2059
+ data: isBinary ? data : data.toString()
2060
+ });
2061
+ event[kTarget] = this;
2062
+ callListener(handler, this, event);
2063
+ };
2064
+ } else if (type === "close") {
2065
+ wrapper = function onClose(code, message) {
2066
+ const event = new CloseEvent("close", {
2067
+ code,
2068
+ reason: message.toString(),
2069
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2070
+ });
2071
+ event[kTarget] = this;
2072
+ callListener(handler, this, event);
2073
+ };
2074
+ } else if (type === "error") {
2075
+ wrapper = function onError(error) {
2076
+ const event = new ErrorEvent("error", {
2077
+ error,
2078
+ message: error.message
2079
+ });
2080
+ event[kTarget] = this;
2081
+ callListener(handler, this, event);
2082
+ };
2083
+ } else if (type === "open") {
2084
+ wrapper = function onOpen() {
2085
+ const event = new Event("open");
2086
+ event[kTarget] = this;
2087
+ callListener(handler, this, event);
2088
+ };
2089
+ } else {
2090
+ return;
2091
+ }
2092
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2093
+ wrapper[kListener] = handler;
2094
+ if (options.once) {
2095
+ this.once(type, wrapper);
2096
+ } else {
2097
+ this.on(type, wrapper);
2098
+ }
2099
+ },
2100
+ /**
2101
+ * Remove an event listener.
2102
+ *
2103
+ * @param {String} type A string representing the event type to remove
2104
+ * @param {(Function|Object)} handler The listener to remove
2105
+ * @public
2106
+ */
2107
+ removeEventListener(type, handler) {
2108
+ for (const listener of this.listeners(type)) {
2109
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2110
+ this.removeListener(type, listener);
2111
+ break;
2112
+ }
2113
+ }
2114
+ }
2115
+ };
2116
+ module.exports = {
2117
+ CloseEvent,
2118
+ ErrorEvent,
2119
+ Event,
2120
+ EventTarget,
2121
+ MessageEvent
2122
+ };
2123
+ function callListener(listener, thisArg, event) {
2124
+ if (typeof listener === "object" && listener.handleEvent) {
2125
+ listener.handleEvent.call(listener, event);
2126
+ } else {
2127
+ listener.call(thisArg, event);
2128
+ }
2129
+ }
2130
+ }
2131
+ });
2132
+
2133
+ // node_modules/ws/lib/extension.js
2134
+ var require_extension = __commonJS({
2135
+ "node_modules/ws/lib/extension.js"(exports, module) {
2136
+ "use strict";
2137
+ var { tokenChars } = require_validation();
2138
+ function push(dest, name, elem) {
2139
+ if (dest[name] === void 0) dest[name] = [elem];
2140
+ else dest[name].push(elem);
2141
+ }
2142
+ function parse(header) {
2143
+ const offers = /* @__PURE__ */ Object.create(null);
2144
+ let params = /* @__PURE__ */ Object.create(null);
2145
+ let mustUnescape = false;
2146
+ let isEscaping = false;
2147
+ let inQuotes = false;
2148
+ let extensionName;
2149
+ let paramName;
2150
+ let start = -1;
2151
+ let code = -1;
2152
+ let end = -1;
2153
+ let i = 0;
2154
+ for (; i < header.length; i++) {
2155
+ code = header.charCodeAt(i);
2156
+ if (extensionName === void 0) {
2157
+ if (end === -1 && tokenChars[code] === 1) {
2158
+ if (start === -1) start = i;
2159
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2160
+ if (end === -1 && start !== -1) end = i;
2161
+ } else if (code === 59 || code === 44) {
2162
+ if (start === -1) {
2163
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2164
+ }
2165
+ if (end === -1) end = i;
2166
+ const name = header.slice(start, end);
2167
+ if (code === 44) {
2168
+ push(offers, name, params);
2169
+ params = /* @__PURE__ */ Object.create(null);
2170
+ } else {
2171
+ extensionName = name;
2172
+ }
2173
+ start = end = -1;
2174
+ } else {
2175
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2176
+ }
2177
+ } else if (paramName === void 0) {
2178
+ if (end === -1 && tokenChars[code] === 1) {
2179
+ if (start === -1) start = i;
2180
+ } else if (code === 32 || code === 9) {
2181
+ if (end === -1 && start !== -1) end = i;
2182
+ } else if (code === 59 || code === 44) {
2183
+ if (start === -1) {
2184
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2185
+ }
2186
+ if (end === -1) end = i;
2187
+ push(params, header.slice(start, end), true);
2188
+ if (code === 44) {
2189
+ push(offers, extensionName, params);
2190
+ params = /* @__PURE__ */ Object.create(null);
2191
+ extensionName = void 0;
2192
+ }
2193
+ start = end = -1;
2194
+ } else if (code === 61 && start !== -1 && end === -1) {
2195
+ paramName = header.slice(start, i);
2196
+ start = end = -1;
2197
+ } else {
2198
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2199
+ }
2200
+ } else {
2201
+ if (isEscaping) {
2202
+ if (tokenChars[code] !== 1) {
2203
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2204
+ }
2205
+ if (start === -1) start = i;
2206
+ else if (!mustUnescape) mustUnescape = true;
2207
+ isEscaping = false;
2208
+ } else if (inQuotes) {
2209
+ if (tokenChars[code] === 1) {
2210
+ if (start === -1) start = i;
2211
+ } else if (code === 34 && start !== -1) {
2212
+ inQuotes = false;
2213
+ end = i;
2214
+ } else if (code === 92) {
2215
+ isEscaping = true;
2216
+ } else {
2217
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2218
+ }
2219
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2220
+ inQuotes = true;
2221
+ } else if (end === -1 && tokenChars[code] === 1) {
2222
+ if (start === -1) start = i;
2223
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2224
+ if (end === -1) end = i;
2225
+ } else if (code === 59 || code === 44) {
2226
+ if (start === -1) {
2227
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2228
+ }
2229
+ if (end === -1) end = i;
2230
+ let value = header.slice(start, end);
2231
+ if (mustUnescape) {
2232
+ value = value.replace(/\\/g, "");
2233
+ mustUnescape = false;
2234
+ }
2235
+ push(params, paramName, value);
2236
+ if (code === 44) {
2237
+ push(offers, extensionName, params);
2238
+ params = /* @__PURE__ */ Object.create(null);
2239
+ extensionName = void 0;
2240
+ }
2241
+ paramName = void 0;
2242
+ start = end = -1;
2243
+ } else {
2244
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2245
+ }
2246
+ }
2247
+ }
2248
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2249
+ throw new SyntaxError("Unexpected end of input");
2250
+ }
2251
+ if (end === -1) end = i;
2252
+ const token = header.slice(start, end);
2253
+ if (extensionName === void 0) {
2254
+ push(offers, token, params);
2255
+ } else {
2256
+ if (paramName === void 0) {
2257
+ push(params, token, true);
2258
+ } else if (mustUnescape) {
2259
+ push(params, paramName, token.replace(/\\/g, ""));
2260
+ } else {
2261
+ push(params, paramName, token);
2262
+ }
2263
+ push(offers, extensionName, params);
2264
+ }
2265
+ return offers;
2266
+ }
2267
+ function format(extensions) {
2268
+ return Object.keys(extensions).map((extension) => {
2269
+ let configurations = extensions[extension];
2270
+ if (!Array.isArray(configurations)) configurations = [configurations];
2271
+ return configurations.map((params) => {
2272
+ return [extension].concat(
2273
+ Object.keys(params).map((k) => {
2274
+ let values = params[k];
2275
+ if (!Array.isArray(values)) values = [values];
2276
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2277
+ })
2278
+ ).join("; ");
2279
+ }).join(", ");
2280
+ }).join(", ");
2281
+ }
2282
+ module.exports = { format, parse };
2283
+ }
2284
+ });
2285
+
2286
+ // node_modules/ws/lib/websocket.js
2287
+ var require_websocket = __commonJS({
2288
+ "node_modules/ws/lib/websocket.js"(exports, module) {
2289
+ "use strict";
2290
+ var EventEmitter = __require("events");
2291
+ var https = __require("https");
2292
+ var http = __require("http");
2293
+ var net = __require("net");
2294
+ var tls = __require("tls");
2295
+ var { randomBytes, createHash } = __require("crypto");
2296
+ var { Duplex, Readable } = __require("stream");
2297
+ var { URL: URL2 } = __require("url");
2298
+ var PerMessageDeflate = require_permessage_deflate();
2299
+ var Receiver2 = require_receiver();
2300
+ var Sender2 = require_sender();
2301
+ var {
2302
+ BINARY_TYPES,
2303
+ EMPTY_BUFFER,
2304
+ GUID,
2305
+ kForOnEventAttribute,
2306
+ kListener,
2307
+ kStatusCode,
2308
+ kWebSocket,
2309
+ NOOP
2310
+ } = require_constants();
2311
+ var {
2312
+ EventTarget: { addEventListener, removeEventListener }
2313
+ } = require_event_target();
2314
+ var { format, parse } = require_extension();
2315
+ var { toBuffer } = require_buffer_util();
2316
+ var closeTimeout = 30 * 1e3;
2317
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
2318
+ var protocolVersions = [8, 13];
2319
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2320
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2321
+ var WebSocket3 = class _WebSocket extends EventEmitter {
2322
+ /**
2323
+ * Create a new `WebSocket`.
2324
+ *
2325
+ * @param {(String|URL)} address The URL to which to connect
2326
+ * @param {(String|String[])} [protocols] The subprotocols
2327
+ * @param {Object} [options] Connection options
2328
+ */
2329
+ constructor(address, protocols, options) {
2330
+ super();
2331
+ this._binaryType = BINARY_TYPES[0];
2332
+ this._closeCode = 1006;
2333
+ this._closeFrameReceived = false;
2334
+ this._closeFrameSent = false;
2335
+ this._closeMessage = EMPTY_BUFFER;
2336
+ this._closeTimer = null;
2337
+ this._extensions = {};
2338
+ this._paused = false;
2339
+ this._protocol = "";
2340
+ this._readyState = _WebSocket.CONNECTING;
2341
+ this._receiver = null;
2342
+ this._sender = null;
2343
+ this._socket = null;
2344
+ if (address !== null) {
2345
+ this._bufferedAmount = 0;
2346
+ this._isServer = false;
2347
+ this._redirects = 0;
2348
+ if (protocols === void 0) {
2349
+ protocols = [];
2350
+ } else if (!Array.isArray(protocols)) {
2351
+ if (typeof protocols === "object" && protocols !== null) {
2352
+ options = protocols;
2353
+ protocols = [];
2354
+ } else {
2355
+ protocols = [protocols];
2356
+ }
2357
+ }
2358
+ initAsClient(this, address, protocols, options);
2359
+ } else {
2360
+ this._autoPong = options.autoPong;
2361
+ this._isServer = true;
2362
+ }
2363
+ }
2364
+ /**
2365
+ * This deviates from the WHATWG interface since ws doesn't support the
2366
+ * required default "blob" type (instead we define a custom "nodebuffer"
2367
+ * type).
2368
+ *
2369
+ * @type {String}
2370
+ */
2371
+ get binaryType() {
2372
+ return this._binaryType;
2373
+ }
2374
+ set binaryType(type) {
2375
+ if (!BINARY_TYPES.includes(type)) return;
2376
+ this._binaryType = type;
2377
+ if (this._receiver) this._receiver._binaryType = type;
2378
+ }
2379
+ /**
2380
+ * @type {Number}
2381
+ */
2382
+ get bufferedAmount() {
2383
+ if (!this._socket) return this._bufferedAmount;
2384
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2385
+ }
2386
+ /**
2387
+ * @type {String}
2388
+ */
2389
+ get extensions() {
2390
+ return Object.keys(this._extensions).join();
2391
+ }
2392
+ /**
2393
+ * @type {Boolean}
2394
+ */
2395
+ get isPaused() {
2396
+ return this._paused;
2397
+ }
2398
+ /**
2399
+ * @type {Function}
2400
+ */
2401
+ /* istanbul ignore next */
2402
+ get onclose() {
2403
+ return null;
2404
+ }
2405
+ /**
2406
+ * @type {Function}
2407
+ */
2408
+ /* istanbul ignore next */
2409
+ get onerror() {
2410
+ return null;
2411
+ }
2412
+ /**
2413
+ * @type {Function}
2414
+ */
2415
+ /* istanbul ignore next */
2416
+ get onopen() {
2417
+ return null;
2418
+ }
2419
+ /**
2420
+ * @type {Function}
2421
+ */
2422
+ /* istanbul ignore next */
2423
+ get onmessage() {
2424
+ return null;
2425
+ }
2426
+ /**
2427
+ * @type {String}
2428
+ */
2429
+ get protocol() {
2430
+ return this._protocol;
2431
+ }
2432
+ /**
2433
+ * @type {Number}
2434
+ */
2435
+ get readyState() {
2436
+ return this._readyState;
2437
+ }
2438
+ /**
2439
+ * @type {String}
2440
+ */
2441
+ get url() {
2442
+ return this._url;
2443
+ }
2444
+ /**
2445
+ * Set up the socket and the internal resources.
2446
+ *
2447
+ * @param {Duplex} socket The network socket between the server and client
2448
+ * @param {Buffer} head The first packet of the upgraded stream
2449
+ * @param {Object} options Options object
2450
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2451
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2452
+ * multiple times in the same tick
2453
+ * @param {Function} [options.generateMask] The function used to generate the
2454
+ * masking key
2455
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2456
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2457
+ * not to skip UTF-8 validation for text and close messages
2458
+ * @private
2459
+ */
2460
+ setSocket(socket, head, options) {
2461
+ const receiver = new Receiver2({
2462
+ allowSynchronousEvents: options.allowSynchronousEvents,
2463
+ binaryType: this.binaryType,
2464
+ extensions: this._extensions,
2465
+ isServer: this._isServer,
2466
+ maxPayload: options.maxPayload,
2467
+ skipUTF8Validation: options.skipUTF8Validation
2468
+ });
2469
+ this._sender = new Sender2(socket, this._extensions, options.generateMask);
2470
+ this._receiver = receiver;
2471
+ this._socket = socket;
2472
+ receiver[kWebSocket] = this;
2473
+ socket[kWebSocket] = this;
2474
+ receiver.on("conclude", receiverOnConclude);
2475
+ receiver.on("drain", receiverOnDrain);
2476
+ receiver.on("error", receiverOnError);
2477
+ receiver.on("message", receiverOnMessage);
2478
+ receiver.on("ping", receiverOnPing);
2479
+ receiver.on("pong", receiverOnPong);
2480
+ if (socket.setTimeout) socket.setTimeout(0);
2481
+ if (socket.setNoDelay) socket.setNoDelay();
2482
+ if (head.length > 0) socket.unshift(head);
2483
+ socket.on("close", socketOnClose);
2484
+ socket.on("data", socketOnData);
2485
+ socket.on("end", socketOnEnd);
2486
+ socket.on("error", socketOnError);
2487
+ this._readyState = _WebSocket.OPEN;
2488
+ this.emit("open");
2489
+ }
2490
+ /**
2491
+ * Emit the `'close'` event.
2492
+ *
2493
+ * @private
2494
+ */
2495
+ emitClose() {
2496
+ if (!this._socket) {
2497
+ this._readyState = _WebSocket.CLOSED;
2498
+ this.emit("close", this._closeCode, this._closeMessage);
2499
+ return;
2500
+ }
2501
+ if (this._extensions[PerMessageDeflate.extensionName]) {
2502
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
2503
+ }
2504
+ this._receiver.removeAllListeners();
2505
+ this._readyState = _WebSocket.CLOSED;
2506
+ this.emit("close", this._closeCode, this._closeMessage);
2507
+ }
2508
+ /**
2509
+ * Start a closing handshake.
2510
+ *
2511
+ * +----------+ +-----------+ +----------+
2512
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2513
+ * | +----------+ +-----------+ +----------+ |
2514
+ * +----------+ +-----------+ |
2515
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2516
+ * +----------+ +-----------+ |
2517
+ * | | | +---+ |
2518
+ * +------------------------+-->|fin| - - - -
2519
+ * | +---+ | +---+
2520
+ * - - - - -|fin|<---------------------+
2521
+ * +---+
2522
+ *
2523
+ * @param {Number} [code] Status code explaining why the connection is closing
2524
+ * @param {(String|Buffer)} [data] The reason why the connection is
2525
+ * closing
2526
+ * @public
2527
+ */
2528
+ close(code, data) {
2529
+ if (this.readyState === _WebSocket.CLOSED) return;
2530
+ if (this.readyState === _WebSocket.CONNECTING) {
2531
+ const msg = "WebSocket was closed before the connection was established";
2532
+ abortHandshake(this, this._req, msg);
2533
+ return;
2534
+ }
2535
+ if (this.readyState === _WebSocket.CLOSING) {
2536
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2537
+ this._socket.end();
2538
+ }
2539
+ return;
2540
+ }
2541
+ this._readyState = _WebSocket.CLOSING;
2542
+ this._sender.close(code, data, !this._isServer, (err) => {
2543
+ if (err) return;
2544
+ this._closeFrameSent = true;
2545
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2546
+ this._socket.end();
2547
+ }
2548
+ });
2549
+ this._closeTimer = setTimeout(
2550
+ this._socket.destroy.bind(this._socket),
2551
+ closeTimeout
2552
+ );
2553
+ }
2554
+ /**
2555
+ * Pause the socket.
2556
+ *
2557
+ * @public
2558
+ */
2559
+ pause() {
2560
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2561
+ return;
2562
+ }
2563
+ this._paused = true;
2564
+ this._socket.pause();
2565
+ }
2566
+ /**
2567
+ * Send a ping.
2568
+ *
2569
+ * @param {*} [data] The data to send
2570
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2571
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2572
+ * @public
2573
+ */
2574
+ ping(data, mask, cb) {
2575
+ if (this.readyState === _WebSocket.CONNECTING) {
2576
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2577
+ }
2578
+ if (typeof data === "function") {
2579
+ cb = data;
2580
+ data = mask = void 0;
2581
+ } else if (typeof mask === "function") {
2582
+ cb = mask;
2583
+ mask = void 0;
2584
+ }
2585
+ if (typeof data === "number") data = data.toString();
2586
+ if (this.readyState !== _WebSocket.OPEN) {
2587
+ sendAfterClose(this, data, cb);
2588
+ return;
2589
+ }
2590
+ if (mask === void 0) mask = !this._isServer;
2591
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2592
+ }
2593
+ /**
2594
+ * Send a pong.
2595
+ *
2596
+ * @param {*} [data] The data to send
2597
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2598
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2599
+ * @public
2600
+ */
2601
+ pong(data, mask, cb) {
2602
+ if (this.readyState === _WebSocket.CONNECTING) {
2603
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2604
+ }
2605
+ if (typeof data === "function") {
2606
+ cb = data;
2607
+ data = mask = void 0;
2608
+ } else if (typeof mask === "function") {
2609
+ cb = mask;
2610
+ mask = void 0;
2611
+ }
2612
+ if (typeof data === "number") data = data.toString();
2613
+ if (this.readyState !== _WebSocket.OPEN) {
2614
+ sendAfterClose(this, data, cb);
2615
+ return;
2616
+ }
2617
+ if (mask === void 0) mask = !this._isServer;
2618
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2619
+ }
2620
+ /**
2621
+ * Resume the socket.
2622
+ *
2623
+ * @public
2624
+ */
2625
+ resume() {
2626
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2627
+ return;
2628
+ }
2629
+ this._paused = false;
2630
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2631
+ }
2632
+ /**
2633
+ * Send a data message.
2634
+ *
2635
+ * @param {*} data The message to send
2636
+ * @param {Object} [options] Options object
2637
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2638
+ * text
2639
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2640
+ * `data`
2641
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2642
+ * last one
2643
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2644
+ * @param {Function} [cb] Callback which is executed when data is written out
2645
+ * @public
2646
+ */
2647
+ send(data, options, cb) {
2648
+ if (this.readyState === _WebSocket.CONNECTING) {
2649
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2650
+ }
2651
+ if (typeof options === "function") {
2652
+ cb = options;
2653
+ options = {};
2654
+ }
2655
+ if (typeof data === "number") data = data.toString();
2656
+ if (this.readyState !== _WebSocket.OPEN) {
2657
+ sendAfterClose(this, data, cb);
2658
+ return;
2659
+ }
2660
+ const opts = __spreadValues({
2661
+ binary: typeof data !== "string",
2662
+ mask: !this._isServer,
2663
+ compress: true,
2664
+ fin: true
2665
+ }, options);
2666
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
2667
+ opts.compress = false;
2668
+ }
2669
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2670
+ }
2671
+ /**
2672
+ * Forcibly close the connection.
2673
+ *
2674
+ * @public
2675
+ */
2676
+ terminate() {
2677
+ if (this.readyState === _WebSocket.CLOSED) return;
2678
+ if (this.readyState === _WebSocket.CONNECTING) {
2679
+ const msg = "WebSocket was closed before the connection was established";
2680
+ abortHandshake(this, this._req, msg);
2681
+ return;
2682
+ }
2683
+ if (this._socket) {
2684
+ this._readyState = _WebSocket.CLOSING;
2685
+ this._socket.destroy();
2686
+ }
2687
+ }
2688
+ };
2689
+ Object.defineProperty(WebSocket3, "CONNECTING", {
2690
+ enumerable: true,
2691
+ value: readyStates.indexOf("CONNECTING")
2692
+ });
2693
+ Object.defineProperty(WebSocket3.prototype, "CONNECTING", {
2694
+ enumerable: true,
2695
+ value: readyStates.indexOf("CONNECTING")
2696
+ });
2697
+ Object.defineProperty(WebSocket3, "OPEN", {
2698
+ enumerable: true,
2699
+ value: readyStates.indexOf("OPEN")
2700
+ });
2701
+ Object.defineProperty(WebSocket3.prototype, "OPEN", {
2702
+ enumerable: true,
2703
+ value: readyStates.indexOf("OPEN")
2704
+ });
2705
+ Object.defineProperty(WebSocket3, "CLOSING", {
2706
+ enumerable: true,
2707
+ value: readyStates.indexOf("CLOSING")
2708
+ });
2709
+ Object.defineProperty(WebSocket3.prototype, "CLOSING", {
2710
+ enumerable: true,
2711
+ value: readyStates.indexOf("CLOSING")
2712
+ });
2713
+ Object.defineProperty(WebSocket3, "CLOSED", {
2714
+ enumerable: true,
2715
+ value: readyStates.indexOf("CLOSED")
2716
+ });
2717
+ Object.defineProperty(WebSocket3.prototype, "CLOSED", {
2718
+ enumerable: true,
2719
+ value: readyStates.indexOf("CLOSED")
2720
+ });
2721
+ [
2722
+ "binaryType",
2723
+ "bufferedAmount",
2724
+ "extensions",
2725
+ "isPaused",
2726
+ "protocol",
2727
+ "readyState",
2728
+ "url"
2729
+ ].forEach((property) => {
2730
+ Object.defineProperty(WebSocket3.prototype, property, { enumerable: true });
2731
+ });
2732
+ ["open", "error", "close", "message"].forEach((method) => {
2733
+ Object.defineProperty(WebSocket3.prototype, `on${method}`, {
2734
+ enumerable: true,
2735
+ get() {
2736
+ for (const listener of this.listeners(method)) {
2737
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2738
+ }
2739
+ return null;
2740
+ },
2741
+ set(handler) {
2742
+ for (const listener of this.listeners(method)) {
2743
+ if (listener[kForOnEventAttribute]) {
2744
+ this.removeListener(method, listener);
2745
+ break;
2746
+ }
2747
+ }
2748
+ if (typeof handler !== "function") return;
2749
+ this.addEventListener(method, handler, {
2750
+ [kForOnEventAttribute]: true
2751
+ });
2752
+ }
2753
+ });
2754
+ });
2755
+ WebSocket3.prototype.addEventListener = addEventListener;
2756
+ WebSocket3.prototype.removeEventListener = removeEventListener;
2757
+ module.exports = WebSocket3;
2758
+ function initAsClient(websocket, address, protocols, options) {
2759
+ const opts = __spreadProps(__spreadValues({
2760
+ allowSynchronousEvents: true,
2761
+ autoPong: true,
2762
+ protocolVersion: protocolVersions[1],
2763
+ maxPayload: 100 * 1024 * 1024,
2764
+ skipUTF8Validation: false,
2765
+ perMessageDeflate: true,
2766
+ followRedirects: false,
2767
+ maxRedirects: 10
2768
+ }, options), {
2769
+ socketPath: void 0,
2770
+ hostname: void 0,
2771
+ protocol: void 0,
2772
+ timeout: void 0,
2773
+ method: "GET",
2774
+ host: void 0,
2775
+ path: void 0,
2776
+ port: void 0
2777
+ });
2778
+ websocket._autoPong = opts.autoPong;
2779
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2780
+ throw new RangeError(
2781
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2782
+ );
2783
+ }
2784
+ let parsedUrl;
2785
+ if (address instanceof URL2) {
2786
+ parsedUrl = address;
2787
+ } else {
2788
+ try {
2789
+ parsedUrl = new URL2(address);
2790
+ } catch (e) {
2791
+ throw new SyntaxError(`Invalid URL: ${address}`);
2792
+ }
2793
+ }
2794
+ if (parsedUrl.protocol === "http:") {
2795
+ parsedUrl.protocol = "ws:";
2796
+ } else if (parsedUrl.protocol === "https:") {
2797
+ parsedUrl.protocol = "wss:";
2798
+ }
2799
+ websocket._url = parsedUrl.href;
2800
+ const isSecure = parsedUrl.protocol === "wss:";
2801
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2802
+ let invalidUrlMessage;
2803
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2804
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`;
2805
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2806
+ invalidUrlMessage = "The URL's pathname is empty";
2807
+ } else if (parsedUrl.hash) {
2808
+ invalidUrlMessage = "The URL contains a fragment identifier";
2809
+ }
2810
+ if (invalidUrlMessage) {
2811
+ const err = new SyntaxError(invalidUrlMessage);
2812
+ if (websocket._redirects === 0) {
2813
+ throw err;
2814
+ } else {
2815
+ emitErrorAndClose(websocket, err);
2816
+ return;
2817
+ }
2818
+ }
2819
+ const defaultPort = isSecure ? 443 : 80;
2820
+ const key = randomBytes(16).toString("base64");
2821
+ const request = isSecure ? https.request : http.request;
2822
+ const protocolSet = /* @__PURE__ */ new Set();
2823
+ let perMessageDeflate;
2824
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2825
+ opts.defaultPort = opts.defaultPort || defaultPort;
2826
+ opts.port = parsedUrl.port || defaultPort;
2827
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2828
+ opts.headers = __spreadProps(__spreadValues({}, opts.headers), {
2829
+ "Sec-WebSocket-Version": opts.protocolVersion,
2830
+ "Sec-WebSocket-Key": key,
2831
+ Connection: "Upgrade",
2832
+ Upgrade: "websocket"
2833
+ });
2834
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2835
+ opts.timeout = opts.handshakeTimeout;
2836
+ if (opts.perMessageDeflate) {
2837
+ perMessageDeflate = new PerMessageDeflate(
2838
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
2839
+ false,
2840
+ opts.maxPayload
2841
+ );
2842
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2843
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2844
+ });
2845
+ }
2846
+ if (protocols.length) {
2847
+ for (const protocol of protocols) {
2848
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2849
+ throw new SyntaxError(
2850
+ "An invalid or duplicated subprotocol was specified"
2851
+ );
2852
+ }
2853
+ protocolSet.add(protocol);
2854
+ }
2855
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2856
+ }
2857
+ if (opts.origin) {
2858
+ if (opts.protocolVersion < 13) {
2859
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2860
+ } else {
2861
+ opts.headers.Origin = opts.origin;
2862
+ }
2863
+ }
2864
+ if (parsedUrl.username || parsedUrl.password) {
2865
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2866
+ }
2867
+ if (isIpcUrl) {
2868
+ const parts = opts.path.split(":");
2869
+ opts.socketPath = parts[0];
2870
+ opts.path = parts[1];
2871
+ }
2872
+ let req;
2873
+ if (opts.followRedirects) {
2874
+ if (websocket._redirects === 0) {
2875
+ websocket._originalIpc = isIpcUrl;
2876
+ websocket._originalSecure = isSecure;
2877
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2878
+ const headers = options && options.headers;
2879
+ options = __spreadProps(__spreadValues({}, options), { headers: {} });
2880
+ if (headers) {
2881
+ for (const [key2, value] of Object.entries(headers)) {
2882
+ options.headers[key2.toLowerCase()] = value;
2883
+ }
2884
+ }
2885
+ } else if (websocket.listenerCount("redirect") === 0) {
2886
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2887
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2888
+ delete opts.headers.authorization;
2889
+ delete opts.headers.cookie;
2890
+ if (!isSameHost) delete opts.headers.host;
2891
+ opts.auth = void 0;
2892
+ }
2893
+ }
2894
+ if (opts.auth && !options.headers.authorization) {
2895
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2896
+ }
2897
+ req = websocket._req = request(opts);
2898
+ if (websocket._redirects) {
2899
+ websocket.emit("redirect", websocket.url, req);
2900
+ }
2901
+ } else {
2902
+ req = websocket._req = request(opts);
2903
+ }
2904
+ if (opts.timeout) {
2905
+ req.on("timeout", () => {
2906
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2907
+ });
2908
+ }
2909
+ req.on("error", (err) => {
2910
+ if (req === null || req[kAborted]) return;
2911
+ req = websocket._req = null;
2912
+ emitErrorAndClose(websocket, err);
2913
+ });
2914
+ req.on("response", (res) => {
2915
+ const location = res.headers.location;
2916
+ const statusCode = res.statusCode;
2917
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2918
+ if (++websocket._redirects > opts.maxRedirects) {
2919
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2920
+ return;
2921
+ }
2922
+ req.abort();
2923
+ let addr;
2924
+ try {
2925
+ addr = new URL2(location, address);
2926
+ } catch (e) {
2927
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2928
+ emitErrorAndClose(websocket, err);
2929
+ return;
2930
+ }
2931
+ initAsClient(websocket, addr, protocols, options);
2932
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2933
+ abortHandshake(
2934
+ websocket,
2935
+ req,
2936
+ `Unexpected server response: ${res.statusCode}`
2937
+ );
2938
+ }
2939
+ });
2940
+ req.on("upgrade", (res, socket, head) => {
2941
+ websocket.emit("upgrade", res);
2942
+ if (websocket.readyState !== WebSocket3.CONNECTING) return;
2943
+ req = websocket._req = null;
2944
+ const upgrade = res.headers.upgrade;
2945
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2946
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2947
+ return;
2948
+ }
2949
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2950
+ if (res.headers["sec-websocket-accept"] !== digest) {
2951
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2952
+ return;
2953
+ }
2954
+ const serverProt = res.headers["sec-websocket-protocol"];
2955
+ let protError;
2956
+ if (serverProt !== void 0) {
2957
+ if (!protocolSet.size) {
2958
+ protError = "Server sent a subprotocol but none was requested";
2959
+ } else if (!protocolSet.has(serverProt)) {
2960
+ protError = "Server sent an invalid subprotocol";
2961
+ }
2962
+ } else if (protocolSet.size) {
2963
+ protError = "Server sent no subprotocol";
2964
+ }
2965
+ if (protError) {
2966
+ abortHandshake(websocket, socket, protError);
2967
+ return;
2968
+ }
2969
+ if (serverProt) websocket._protocol = serverProt;
2970
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2971
+ if (secWebSocketExtensions !== void 0) {
2972
+ if (!perMessageDeflate) {
2973
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2974
+ abortHandshake(websocket, socket, message);
2975
+ return;
2976
+ }
2977
+ let extensions;
2978
+ try {
2979
+ extensions = parse(secWebSocketExtensions);
2980
+ } catch (err) {
2981
+ const message = "Invalid Sec-WebSocket-Extensions header";
2982
+ abortHandshake(websocket, socket, message);
2983
+ return;
2984
+ }
2985
+ const extensionNames = Object.keys(extensions);
2986
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2987
+ const message = "Server indicated an extension that was not requested";
2988
+ abortHandshake(websocket, socket, message);
2989
+ return;
2990
+ }
2991
+ try {
2992
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2993
+ } catch (err) {
2994
+ const message = "Invalid Sec-WebSocket-Extensions header";
2995
+ abortHandshake(websocket, socket, message);
2996
+ return;
2997
+ }
2998
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2999
+ }
3000
+ websocket.setSocket(socket, head, {
3001
+ allowSynchronousEvents: opts.allowSynchronousEvents,
3002
+ generateMask: opts.generateMask,
3003
+ maxPayload: opts.maxPayload,
3004
+ skipUTF8Validation: opts.skipUTF8Validation
3005
+ });
3006
+ });
3007
+ if (opts.finishRequest) {
3008
+ opts.finishRequest(req, websocket);
3009
+ } else {
3010
+ req.end();
3011
+ }
3012
+ }
3013
+ function emitErrorAndClose(websocket, err) {
3014
+ websocket._readyState = WebSocket3.CLOSING;
3015
+ websocket.emit("error", err);
3016
+ websocket.emitClose();
3017
+ }
3018
+ function netConnect(options) {
3019
+ options.path = options.socketPath;
3020
+ return net.connect(options);
3021
+ }
3022
+ function tlsConnect(options) {
3023
+ options.path = void 0;
3024
+ if (!options.servername && options.servername !== "") {
3025
+ options.servername = net.isIP(options.host) ? "" : options.host;
3026
+ }
3027
+ return tls.connect(options);
3028
+ }
3029
+ function abortHandshake(websocket, stream, message) {
3030
+ websocket._readyState = WebSocket3.CLOSING;
3031
+ const err = new Error(message);
3032
+ Error.captureStackTrace(err, abortHandshake);
3033
+ if (stream.setHeader) {
3034
+ stream[kAborted] = true;
3035
+ stream.abort();
3036
+ if (stream.socket && !stream.socket.destroyed) {
3037
+ stream.socket.destroy();
3038
+ }
3039
+ process.nextTick(emitErrorAndClose, websocket, err);
3040
+ } else {
3041
+ stream.destroy(err);
3042
+ stream.once("error", websocket.emit.bind(websocket, "error"));
3043
+ stream.once("close", websocket.emitClose.bind(websocket));
3044
+ }
3045
+ }
3046
+ function sendAfterClose(websocket, data, cb) {
3047
+ if (data) {
3048
+ const length = toBuffer(data).length;
3049
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
3050
+ else websocket._bufferedAmount += length;
3051
+ }
3052
+ if (cb) {
3053
+ const err = new Error(
3054
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3055
+ );
3056
+ process.nextTick(cb, err);
3057
+ }
3058
+ }
3059
+ function receiverOnConclude(code, reason) {
3060
+ const websocket = this[kWebSocket];
3061
+ websocket._closeFrameReceived = true;
3062
+ websocket._closeMessage = reason;
3063
+ websocket._closeCode = code;
3064
+ if (websocket._socket[kWebSocket] === void 0) return;
3065
+ websocket._socket.removeListener("data", socketOnData);
3066
+ process.nextTick(resume, websocket._socket);
3067
+ if (code === 1005) websocket.close();
3068
+ else websocket.close(code, reason);
3069
+ }
3070
+ function receiverOnDrain() {
3071
+ const websocket = this[kWebSocket];
3072
+ if (!websocket.isPaused) websocket._socket.resume();
3073
+ }
3074
+ function receiverOnError(err) {
3075
+ const websocket = this[kWebSocket];
3076
+ if (websocket._socket[kWebSocket] !== void 0) {
3077
+ websocket._socket.removeListener("data", socketOnData);
3078
+ process.nextTick(resume, websocket._socket);
3079
+ websocket.close(err[kStatusCode]);
3080
+ }
3081
+ websocket.emit("error", err);
3082
+ }
3083
+ function receiverOnFinish() {
3084
+ this[kWebSocket].emitClose();
3085
+ }
3086
+ function receiverOnMessage(data, isBinary) {
3087
+ this[kWebSocket].emit("message", data, isBinary);
3088
+ }
3089
+ function receiverOnPing(data) {
3090
+ const websocket = this[kWebSocket];
3091
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3092
+ websocket.emit("ping", data);
3093
+ }
3094
+ function receiverOnPong(data) {
3095
+ this[kWebSocket].emit("pong", data);
3096
+ }
3097
+ function resume(stream) {
3098
+ stream.resume();
3099
+ }
3100
+ function socketOnClose() {
3101
+ const websocket = this[kWebSocket];
3102
+ this.removeListener("close", socketOnClose);
3103
+ this.removeListener("data", socketOnData);
3104
+ this.removeListener("end", socketOnEnd);
3105
+ websocket._readyState = WebSocket3.CLOSING;
3106
+ let chunk;
3107
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
3108
+ websocket._receiver.write(chunk);
3109
+ }
3110
+ websocket._receiver.end();
3111
+ this[kWebSocket] = void 0;
3112
+ clearTimeout(websocket._closeTimer);
3113
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3114
+ websocket.emitClose();
3115
+ } else {
3116
+ websocket._receiver.on("error", receiverOnFinish);
3117
+ websocket._receiver.on("finish", receiverOnFinish);
3118
+ }
3119
+ }
3120
+ function socketOnData(chunk) {
3121
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3122
+ this.pause();
3123
+ }
3124
+ }
3125
+ function socketOnEnd() {
3126
+ const websocket = this[kWebSocket];
3127
+ websocket._readyState = WebSocket3.CLOSING;
3128
+ websocket._receiver.end();
3129
+ this.end();
3130
+ }
3131
+ function socketOnError() {
3132
+ const websocket = this[kWebSocket];
3133
+ this.removeListener("error", socketOnError);
3134
+ this.on("error", NOOP);
3135
+ if (websocket) {
3136
+ websocket._readyState = WebSocket3.CLOSING;
3137
+ this.destroy();
3138
+ }
3139
+ }
3140
+ }
3141
+ });
3142
+
3143
+ // node_modules/ws/lib/subprotocol.js
3144
+ var require_subprotocol = __commonJS({
3145
+ "node_modules/ws/lib/subprotocol.js"(exports, module) {
3146
+ "use strict";
3147
+ var { tokenChars } = require_validation();
3148
+ function parse(header) {
3149
+ const protocols = /* @__PURE__ */ new Set();
3150
+ let start = -1;
3151
+ let end = -1;
3152
+ let i = 0;
3153
+ for (i; i < header.length; i++) {
3154
+ const code = header.charCodeAt(i);
3155
+ if (end === -1 && tokenChars[code] === 1) {
3156
+ if (start === -1) start = i;
3157
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3158
+ if (end === -1 && start !== -1) end = i;
3159
+ } else if (code === 44) {
3160
+ if (start === -1) {
3161
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3162
+ }
3163
+ if (end === -1) end = i;
3164
+ const protocol2 = header.slice(start, end);
3165
+ if (protocols.has(protocol2)) {
3166
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3167
+ }
3168
+ protocols.add(protocol2);
3169
+ start = end = -1;
3170
+ } else {
3171
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3172
+ }
3173
+ }
3174
+ if (start === -1 || end !== -1) {
3175
+ throw new SyntaxError("Unexpected end of input");
3176
+ }
3177
+ const protocol = header.slice(start, i);
3178
+ if (protocols.has(protocol)) {
3179
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3180
+ }
3181
+ protocols.add(protocol);
3182
+ return protocols;
3183
+ }
3184
+ module.exports = { parse };
3185
+ }
3186
+ });
3187
+
3188
+ // node_modules/ws/lib/websocket-server.js
3189
+ var require_websocket_server = __commonJS({
3190
+ "node_modules/ws/lib/websocket-server.js"(exports, module) {
3191
+ "use strict";
3192
+ var EventEmitter = __require("events");
3193
+ var http = __require("http");
3194
+ var { Duplex } = __require("stream");
3195
+ var { createHash } = __require("crypto");
3196
+ var extension = require_extension();
3197
+ var PerMessageDeflate = require_permessage_deflate();
3198
+ var subprotocol = require_subprotocol();
3199
+ var WebSocket3 = require_websocket();
3200
+ var { GUID, kWebSocket } = require_constants();
3201
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3202
+ var RUNNING = 0;
3203
+ var CLOSING = 1;
3204
+ var CLOSED = 2;
3205
+ var WebSocketServer2 = class extends EventEmitter {
3206
+ /**
3207
+ * Create a `WebSocketServer` instance.
3208
+ *
3209
+ * @param {Object} options Configuration options
3210
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3211
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3212
+ * multiple times in the same tick
3213
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3214
+ * automatically send a pong in response to a ping
3215
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3216
+ * pending connections
3217
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3218
+ * track clients
3219
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3220
+ * @param {String} [options.host] The hostname where to bind the server
3221
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3222
+ * size
3223
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3224
+ * @param {String} [options.path] Accept only connections matching this path
3225
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3226
+ * permessage-deflate
3227
+ * @param {Number} [options.port] The port where to bind the server
3228
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3229
+ * server to use
3230
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3231
+ * not to skip UTF-8 validation for text and close messages
3232
+ * @param {Function} [options.verifyClient] A hook to reject connections
3233
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3234
+ * class to use. It must be the `WebSocket` class or class that extends it
3235
+ * @param {Function} [callback] A listener for the `listening` event
3236
+ */
3237
+ constructor(options, callback) {
3238
+ super();
3239
+ options = __spreadValues({
3240
+ allowSynchronousEvents: true,
3241
+ autoPong: true,
3242
+ maxPayload: 100 * 1024 * 1024,
3243
+ skipUTF8Validation: false,
3244
+ perMessageDeflate: false,
3245
+ handleProtocols: null,
3246
+ clientTracking: true,
3247
+ verifyClient: null,
3248
+ noServer: false,
3249
+ backlog: null,
3250
+ // use default (511 as implemented in net.js)
3251
+ server: null,
3252
+ host: null,
3253
+ path: null,
3254
+ port: null,
3255
+ WebSocket: WebSocket3
3256
+ }, options);
3257
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3258
+ throw new TypeError(
3259
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3260
+ );
3261
+ }
3262
+ if (options.port != null) {
3263
+ this._server = http.createServer((req, res) => {
3264
+ const body = http.STATUS_CODES[426];
3265
+ res.writeHead(426, {
3266
+ "Content-Length": body.length,
3267
+ "Content-Type": "text/plain"
3268
+ });
3269
+ res.end(body);
3270
+ });
3271
+ this._server.listen(
3272
+ options.port,
3273
+ options.host,
3274
+ options.backlog,
3275
+ callback
3276
+ );
3277
+ } else if (options.server) {
3278
+ this._server = options.server;
3279
+ }
3280
+ if (this._server) {
3281
+ const emitConnection = this.emit.bind(this, "connection");
3282
+ this._removeListeners = addListeners(this._server, {
3283
+ listening: this.emit.bind(this, "listening"),
3284
+ error: this.emit.bind(this, "error"),
3285
+ upgrade: (req, socket, head) => {
3286
+ this.handleUpgrade(req, socket, head, emitConnection);
3287
+ }
3288
+ });
3289
+ }
3290
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3291
+ if (options.clientTracking) {
3292
+ this.clients = /* @__PURE__ */ new Set();
3293
+ this._shouldEmitClose = false;
3294
+ }
3295
+ this.options = options;
3296
+ this._state = RUNNING;
3297
+ }
3298
+ /**
3299
+ * Returns the bound address, the address family name, and port of the server
3300
+ * as reported by the operating system if listening on an IP socket.
3301
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3302
+ * returned as a string.
3303
+ *
3304
+ * @return {(Object|String|null)} The address of the server
3305
+ * @public
3306
+ */
3307
+ address() {
3308
+ if (this.options.noServer) {
3309
+ throw new Error('The server is operating in "noServer" mode');
3310
+ }
3311
+ if (!this._server) return null;
3312
+ return this._server.address();
3313
+ }
3314
+ /**
3315
+ * Stop the server from accepting new connections and emit the `'close'` event
3316
+ * when all existing connections are closed.
3317
+ *
3318
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3319
+ * @public
3320
+ */
3321
+ close(cb) {
3322
+ if (this._state === CLOSED) {
3323
+ if (cb) {
3324
+ this.once("close", () => {
3325
+ cb(new Error("The server is not running"));
3326
+ });
3327
+ }
3328
+ process.nextTick(emitClose, this);
3329
+ return;
3330
+ }
3331
+ if (cb) this.once("close", cb);
3332
+ if (this._state === CLOSING) return;
3333
+ this._state = CLOSING;
3334
+ if (this.options.noServer || this.options.server) {
3335
+ if (this._server) {
3336
+ this._removeListeners();
3337
+ this._removeListeners = this._server = null;
3338
+ }
3339
+ if (this.clients) {
3340
+ if (!this.clients.size) {
3341
+ process.nextTick(emitClose, this);
3342
+ } else {
3343
+ this._shouldEmitClose = true;
3344
+ }
3345
+ } else {
3346
+ process.nextTick(emitClose, this);
3347
+ }
3348
+ } else {
3349
+ const server = this._server;
3350
+ this._removeListeners();
3351
+ this._removeListeners = this._server = null;
3352
+ server.close(() => {
3353
+ emitClose(this);
3354
+ });
3355
+ }
3356
+ }
3357
+ /**
3358
+ * See if a given request should be handled by this server instance.
3359
+ *
3360
+ * @param {http.IncomingMessage} req Request object to inspect
3361
+ * @return {Boolean} `true` if the request is valid, else `false`
3362
+ * @public
3363
+ */
3364
+ shouldHandle(req) {
3365
+ if (this.options.path) {
3366
+ const index = req.url.indexOf("?");
3367
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3368
+ if (pathname !== this.options.path) return false;
3369
+ }
3370
+ return true;
3371
+ }
3372
+ /**
3373
+ * Handle a HTTP Upgrade request.
3374
+ *
3375
+ * @param {http.IncomingMessage} req The request object
3376
+ * @param {Duplex} socket The network socket between the server and client
3377
+ * @param {Buffer} head The first packet of the upgraded stream
3378
+ * @param {Function} cb Callback
3379
+ * @public
3380
+ */
3381
+ handleUpgrade(req, socket, head, cb) {
3382
+ socket.on("error", socketOnError);
3383
+ const key = req.headers["sec-websocket-key"];
3384
+ const upgrade = req.headers.upgrade;
3385
+ const version = +req.headers["sec-websocket-version"];
3386
+ if (req.method !== "GET") {
3387
+ const message = "Invalid HTTP method";
3388
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3389
+ return;
3390
+ }
3391
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3392
+ const message = "Invalid Upgrade header";
3393
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3394
+ return;
3395
+ }
3396
+ if (key === void 0 || !keyRegex.test(key)) {
3397
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3398
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3399
+ return;
3400
+ }
3401
+ if (version !== 8 && version !== 13) {
3402
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3403
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3404
+ return;
3405
+ }
3406
+ if (!this.shouldHandle(req)) {
3407
+ abortHandshake(socket, 400);
3408
+ return;
3409
+ }
3410
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3411
+ let protocols = /* @__PURE__ */ new Set();
3412
+ if (secWebSocketProtocol !== void 0) {
3413
+ try {
3414
+ protocols = subprotocol.parse(secWebSocketProtocol);
3415
+ } catch (err) {
3416
+ const message = "Invalid Sec-WebSocket-Protocol header";
3417
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3418
+ return;
3419
+ }
3420
+ }
3421
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3422
+ const extensions = {};
3423
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3424
+ const perMessageDeflate = new PerMessageDeflate(
3425
+ this.options.perMessageDeflate,
3426
+ true,
3427
+ this.options.maxPayload
3428
+ );
3429
+ try {
3430
+ const offers = extension.parse(secWebSocketExtensions);
3431
+ if (offers[PerMessageDeflate.extensionName]) {
3432
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
3433
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3434
+ }
3435
+ } catch (err) {
3436
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3437
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3438
+ return;
3439
+ }
3440
+ }
3441
+ if (this.options.verifyClient) {
3442
+ const info = {
3443
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3444
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3445
+ req
3446
+ };
3447
+ if (this.options.verifyClient.length === 2) {
3448
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3449
+ if (!verified) {
3450
+ return abortHandshake(socket, code || 401, message, headers);
3451
+ }
3452
+ this.completeUpgrade(
3453
+ extensions,
3454
+ key,
3455
+ protocols,
3456
+ req,
3457
+ socket,
3458
+ head,
3459
+ cb
3460
+ );
3461
+ });
3462
+ return;
3463
+ }
3464
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3465
+ }
3466
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3467
+ }
3468
+ /**
3469
+ * Upgrade the connection to WebSocket.
3470
+ *
3471
+ * @param {Object} extensions The accepted extensions
3472
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3473
+ * @param {Set} protocols The subprotocols
3474
+ * @param {http.IncomingMessage} req The request object
3475
+ * @param {Duplex} socket The network socket between the server and client
3476
+ * @param {Buffer} head The first packet of the upgraded stream
3477
+ * @param {Function} cb Callback
3478
+ * @throws {Error} If called more than once with the same socket
3479
+ * @private
3480
+ */
3481
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3482
+ if (!socket.readable || !socket.writable) return socket.destroy();
3483
+ if (socket[kWebSocket]) {
3484
+ throw new Error(
3485
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3486
+ );
3487
+ }
3488
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3489
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
3490
+ const headers = [
3491
+ "HTTP/1.1 101 Switching Protocols",
3492
+ "Upgrade: websocket",
3493
+ "Connection: Upgrade",
3494
+ `Sec-WebSocket-Accept: ${digest}`
3495
+ ];
3496
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3497
+ if (protocols.size) {
3498
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3499
+ if (protocol) {
3500
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3501
+ ws._protocol = protocol;
3502
+ }
3503
+ }
3504
+ if (extensions[PerMessageDeflate.extensionName]) {
3505
+ const params = extensions[PerMessageDeflate.extensionName].params;
3506
+ const value = extension.format({
3507
+ [PerMessageDeflate.extensionName]: [params]
3508
+ });
3509
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3510
+ ws._extensions = extensions;
3511
+ }
3512
+ this.emit("headers", headers, req);
3513
+ socket.write(headers.concat("\r\n").join("\r\n"));
3514
+ socket.removeListener("error", socketOnError);
3515
+ ws.setSocket(socket, head, {
3516
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3517
+ maxPayload: this.options.maxPayload,
3518
+ skipUTF8Validation: this.options.skipUTF8Validation
3519
+ });
3520
+ if (this.clients) {
3521
+ this.clients.add(ws);
3522
+ ws.on("close", () => {
3523
+ this.clients.delete(ws);
3524
+ if (this._shouldEmitClose && !this.clients.size) {
3525
+ process.nextTick(emitClose, this);
3526
+ }
3527
+ });
3528
+ }
3529
+ cb(ws, req);
3530
+ }
3531
+ };
3532
+ module.exports = WebSocketServer2;
3533
+ function addListeners(server, map) {
3534
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3535
+ return function removeListeners() {
3536
+ for (const event of Object.keys(map)) {
3537
+ server.removeListener(event, map[event]);
3538
+ }
3539
+ };
3540
+ }
3541
+ function emitClose(server) {
3542
+ server._state = CLOSED;
3543
+ server.emit("close");
3544
+ }
3545
+ function socketOnError() {
3546
+ this.destroy();
3547
+ }
3548
+ function abortHandshake(socket, code, message, headers) {
3549
+ message = message || http.STATUS_CODES[code];
3550
+ headers = __spreadValues({
3551
+ Connection: "close",
3552
+ "Content-Type": "text/html",
3553
+ "Content-Length": Buffer.byteLength(message)
3554
+ }, headers);
3555
+ socket.once("finish", socket.destroy);
3556
+ socket.end(
3557
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3558
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3559
+ );
3560
+ }
3561
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
3562
+ if (server.listenerCount("wsClientError")) {
3563
+ const err = new Error(message);
3564
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3565
+ server.emit("wsClientError", err, socket, req);
3566
+ } else {
3567
+ abortHandshake(socket, code, message);
3568
+ }
3569
+ }
3570
+ }
3571
+ });
3572
+
3573
+ // node_modules/ws/wrapper.mjs
3574
+ var wrapper_exports = {};
3575
+ __export(wrapper_exports, {
3576
+ Receiver: () => import_receiver.default,
3577
+ Sender: () => import_sender.default,
3578
+ WebSocket: () => import_websocket.default,
3579
+ WebSocketServer: () => import_websocket_server.default,
3580
+ createWebSocketStream: () => import_stream.default,
3581
+ default: () => wrapper_default
3582
+ });
3583
+ var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default;
3584
+ var init_wrapper = __esm({
3585
+ "node_modules/ws/wrapper.mjs"() {
3586
+ "use strict";
3587
+ import_stream = __toESM(require_stream(), 1);
3588
+ import_receiver = __toESM(require_receiver(), 1);
3589
+ import_sender = __toESM(require_sender(), 1);
3590
+ import_websocket = __toESM(require_websocket(), 1);
3591
+ import_websocket_server = __toESM(require_websocket_server(), 1);
3592
+ wrapper_default = import_websocket.default;
3593
+ }
3594
+ });
3595
+
3596
+ // src/common/token.ts
3597
+ var _token, _type, _expiration;
3598
+ var Token = class {
3599
+ constructor(token, type, expiration) {
3600
+ __privateAdd(this, _token);
3601
+ __privateAdd(this, _type);
3602
+ __privateAdd(this, _expiration);
3603
+ __privateSet(this, _token, token);
3604
+ __privateSet(this, _type, type);
3605
+ if (expiration) {
3606
+ __privateSet(this, _expiration, expiration);
3607
+ } else {
3608
+ __privateSet(this, _expiration, this.decodeExpiration(token));
3609
+ }
3610
+ }
3611
+ decodeExpiration(token) {
3612
+ try {
3613
+ const payload = JSON.parse(atob(token.split(".")[1]));
3614
+ return payload.exp * 1e3;
3615
+ } catch (e) {
3616
+ return 0;
3617
+ }
3618
+ }
3619
+ /**
3620
+ * Getter for the raw token
3621
+ *
3622
+ * @returns {string} The token
3623
+ */
3624
+ value() {
3625
+ return __privateGet(this, _token);
3626
+ }
3627
+ /**
3628
+ * Checks if the token is valid
3629
+ *
3630
+ * @returns {boolean} True if the API key is valid, false otherwise
3631
+ */
3632
+ isValid() {
3633
+ return __privateGet(this, _expiration) > Date.now();
3634
+ }
3635
+ /**
3636
+ * Checks if the API key is a secret key
3637
+ *
3638
+ * @returns {boolean} True if the API key is a secret key, false otherwise
3639
+ */
3640
+ isAccessToken() {
3641
+ return __privateGet(this, _type) === "access";
3642
+ }
3643
+ /**
3644
+ * Checks if the API key is a public key
3645
+ *
3646
+ * @returns {boolean} True if the API key is a public key, false otherwise
3647
+ */
3648
+ isRefreshToken() {
3649
+ return __privateGet(this, _type) === "refresh";
3650
+ }
3651
+ };
3652
+ _token = new WeakMap();
3653
+ _type = new WeakMap();
3654
+ _expiration = new WeakMap();
3655
+
3656
+ // src/common/app.ts
3657
+ import { UserManager, WebStorageStateStore } from "oidc-client-ts";
3658
+ var app = {
3659
+ projectId: "",
3660
+ baseUrl: "https://api.swiftbase.io",
3661
+ accessToken: null,
3662
+ refreshToken: null,
3663
+ debounceTimeout: 300,
3664
+ cacheArticles: true,
3665
+ searchCacheEnabled: true,
3666
+ searchCacheCapacity: 50,
3667
+ userManager: null
3668
+ };
3669
+ var initializeSdk = (projectId, options) => {
3670
+ app.projectId = projectId;
3671
+ if (options == null ? void 0 : options.baseUrl) {
3672
+ app.baseUrl = options.baseUrl.endsWith("/") ? options.baseUrl.slice(0, -1) : options.baseUrl;
3673
+ }
3674
+ if ((options == null ? void 0 : options.debounceTimeout) !== void 0) {
3675
+ app.debounceTimeout = options.debounceTimeout;
3676
+ }
3677
+ if ((options == null ? void 0 : options.cacheArticles) !== void 0) {
3678
+ app.cacheArticles = options.cacheArticles;
3679
+ }
3680
+ if ((options == null ? void 0 : options.searchCacheEnabled) !== void 0) {
3681
+ app.searchCacheEnabled = options.searchCacheEnabled;
3682
+ }
3683
+ if ((options == null ? void 0 : options.searchCacheCapacity) !== void 0) {
3684
+ app.searchCacheCapacity = options.searchCacheCapacity;
3685
+ }
3686
+ if (typeof window !== "undefined" && window.sessionStorage) {
3687
+ const accessToken = window.sessionStorage.getItem("swiftbase_access_token");
3688
+ const refreshToken = window.sessionStorage.getItem("swiftbase_refresh_token");
3689
+ if (accessToken) {
3690
+ app.accessToken = new Token(accessToken, "access");
3691
+ }
3692
+ if (refreshToken) {
3693
+ app.refreshToken = new Token(refreshToken, "refresh");
3694
+ }
3695
+ }
3696
+ if (typeof window !== "undefined") {
3697
+ app.userManager = new UserManager({
3698
+ authority: app.baseUrl,
3699
+ client_id: app.projectId,
3700
+ redirect_uri: window.location.origin,
3701
+ response_type: "code",
3702
+ scope: "openid profile email",
3703
+ userStore: new WebStorageStateStore({ store: window.sessionStorage }),
3704
+ automaticSilentRenew: true,
3705
+ filterProtocolClaims: true,
3706
+ loadUserInfo: true
3707
+ });
3708
+ app.userManager.events.addUserLoaded((user) => {
3709
+ console.log("[SDK] User loaded from UserManager");
3710
+ setAccessToken(user.access_token, user.expires_at ? user.expires_at * 1e3 : void 0);
3711
+ if (user.refresh_token) {
3712
+ setRefreshToken(user.refresh_token);
3713
+ }
3714
+ });
3715
+ app.userManager.events.addUserUnloaded(() => {
3716
+ console.log("[SDK] User unloaded from UserManager");
3717
+ setAccessToken("");
3718
+ setRefreshToken("");
3719
+ });
3720
+ }
3721
+ };
3722
+ var setAccessToken = (token, expiration) => {
3723
+ console.log("[SDK] setAccessToken called", !!token);
3724
+ if (!token || token === "null" || token === "undefined") {
3725
+ app.accessToken = null;
3726
+ if (typeof window !== "undefined" && window.sessionStorage) {
3727
+ window.sessionStorage.removeItem("swiftbase_access_token");
3728
+ }
3729
+ return;
3730
+ }
3731
+ app.accessToken = new Token(token, "access", expiration);
3732
+ if (typeof window !== "undefined" && window.sessionStorage) {
3733
+ window.sessionStorage.setItem("swiftbase_access_token", token);
3734
+ }
3735
+ };
3736
+ var setRefreshToken = (token, expiration) => {
3737
+ console.log("[SDK] setRefreshToken called", !!token);
3738
+ if (!token || token === "null" || token === "undefined") {
3739
+ app.refreshToken = null;
3740
+ if (typeof window !== "undefined" && window.sessionStorage) {
3741
+ window.sessionStorage.removeItem("swiftbase_refresh_token");
3742
+ }
3743
+ return;
3744
+ }
3745
+ app.refreshToken = new Token(token, "refresh", expiration);
3746
+ if (typeof window !== "undefined" && window.sessionStorage) {
3747
+ window.sessionStorage.setItem("swiftbase_refresh_token", token);
3748
+ }
3749
+ };
3750
+ var refreshTokens = () => __async(null, null, function* () {
3751
+ if (app.userManager) {
3752
+ try {
3753
+ yield app.userManager.signinSilent();
3754
+ return;
3755
+ } catch (e) {
3756
+ console.error("[SDK] signinSilent failed", e);
3757
+ }
3758
+ }
3759
+ if (!app.refreshToken) {
3760
+ throw new Error("No refresh token available");
3761
+ }
3762
+ const tokenUrl = `${app.baseUrl}/oauth2/token`;
3763
+ const response = yield fetch(tokenUrl, {
3764
+ method: "POST",
3765
+ headers: {
3766
+ "Content-Type": "application/x-www-form-urlencoded"
3767
+ },
3768
+ body: new URLSearchParams({
3769
+ grant_type: "refresh_token",
3770
+ client_id: app.projectId,
3771
+ refresh_token: app.refreshToken.value()
3772
+ })
3773
+ });
3774
+ if (!response.ok) {
3775
+ const errorData = yield response.json().catch(() => ({}));
3776
+ throw new Error(errorData.error_description || errorData.error || "Failed to refresh tokens");
3777
+ }
3778
+ const data = yield response.json();
3779
+ const expiresAt = Date.now() + data.expires_in * 1e3;
3780
+ setAccessToken(data.access_token, expiresAt);
3781
+ if (data.refresh_token) {
3782
+ const refreshExpiresAt = Date.now() + 30 * 24 * 60 * 60 * 1e3;
3783
+ setRefreshToken(data.refresh_token, refreshExpiresAt);
3784
+ }
3785
+ });
3786
+
3787
+ // src/auth/getaccesstoken.ts
3788
+ var getAccessToken = (forceRefresh = false) => __async(null, null, function* () {
3789
+ if (typeof window === "undefined" || !app.userManager) {
3790
+ return app.accessToken ? app.accessToken.value() : null;
3791
+ }
3792
+ let user = yield app.userManager.getUser();
3793
+ if (forceRefresh || !user || user.expired) {
3794
+ try {
3795
+ user = yield app.userManager.signinSilent();
3796
+ } catch (e) {
3797
+ console.warn("Failed to silently refresh token during getAccessToken", e);
3798
+ }
3799
+ }
3800
+ return user ? user.access_token : app.accessToken ? app.accessToken.value() : null;
3801
+ });
3802
+
3803
+ // src/common/makerequest.ts
3804
+ var Unauthorized = class _Unauthorized extends Error {
3805
+ constructor(msg) {
3806
+ super(msg);
3807
+ Object.setPrototypeOf(this, _Unauthorized.prototype);
3808
+ }
3809
+ };
3810
+ var Forbidden = class _Forbidden extends Error {
3811
+ constructor(msg) {
3812
+ super(msg);
3813
+ Object.setPrototypeOf(this, _Forbidden.prototype);
3814
+ }
3815
+ };
3816
+ var BadRequest = class _BadRequest extends Error {
3817
+ constructor(msg) {
3818
+ super(msg);
3819
+ Object.setPrototypeOf(this, _BadRequest.prototype);
3820
+ }
3821
+ };
3822
+ var TooManyRequests = class _TooManyRequests extends Error {
3823
+ constructor(msg) {
3824
+ super(msg);
3825
+ Object.setPrototypeOf(this, _TooManyRequests.prototype);
3826
+ }
3827
+ };
3828
+ var handleRequestError = (status) => {
3829
+ if (status === 401) {
3830
+ throw new Unauthorized("Unauthorized");
3831
+ } else if (status === 403) {
3832
+ throw new Forbidden("Forbidden");
3833
+ } else if (status === 400) {
3834
+ throw new BadRequest("Bad Request");
3835
+ } else if (status === 429) {
3836
+ throw new TooManyRequests("Too Many Requests");
3837
+ } else {
3838
+ throw new Error("Unexpected error");
3839
+ }
3840
+ };
3841
+ var _data, _meta;
3842
+ var PaginatedResponse = class {
3843
+ constructor(response) {
3844
+ __privateAdd(this, _data, []);
3845
+ __privateAdd(this, _meta);
3846
+ __privateSet(this, _data, response.data);
3847
+ __privateSet(this, _meta, response.meta);
3848
+ }
3849
+ get items() {
3850
+ return __privateGet(this, _data);
3851
+ }
3852
+ get total() {
3853
+ return __privateGet(this, _meta).total;
3854
+ }
3855
+ get page() {
3856
+ return __privateGet(this, _meta).page;
3857
+ }
3858
+ get limit() {
3859
+ return __privateGet(this, _meta).limit;
3860
+ }
3861
+ get hasNext() {
3862
+ return !!__privateGet(this, _meta).next;
3863
+ }
3864
+ get hasBack() {
3865
+ return !!__privateGet(this, _meta).back;
3866
+ }
3867
+ next() {
3868
+ return __async(this, null, function* () {
3869
+ if (!__privateGet(this, _meta).next) return null;
3870
+ return yield makeRequest("get" /* GET */, __privateGet(this, _meta).next);
3871
+ });
3872
+ }
3873
+ back() {
3874
+ return __async(this, null, function* () {
3875
+ if (!__privateGet(this, _meta).back) return null;
3876
+ return yield makeRequest("get" /* GET */, __privateGet(this, _meta).back);
3877
+ });
3878
+ }
3879
+ };
3880
+ _data = new WeakMap();
3881
+ _meta = new WeakMap();
3882
+ var makeRequest = (method, path, params, body) => __async(null, null, function* () {
3883
+ const token = yield getAccessToken();
3884
+ let url = path.startsWith("http") ? path : `${app.baseUrl}${!path.startsWith("/") ? "/" : ""}${path}`;
3885
+ if (params) {
3886
+ const query = new URLSearchParams();
3887
+ for (const [key, value] of Object.entries(params)) {
3888
+ if (value !== void 0) query.append(key, String(value));
3889
+ }
3890
+ const queryString = query.toString();
3891
+ if (queryString) {
3892
+ url += (url.includes("?") ? "&" : "?") + queryString;
3893
+ }
3894
+ }
3895
+ const headers = {
3896
+ "Content-Type": "application/json"
3897
+ };
3898
+ if (token) {
3899
+ headers["Authorization"] = `Bearer ${token}`;
3900
+ }
3901
+ const options = {
3902
+ method,
3903
+ headers
3904
+ };
3905
+ if (body) {
3906
+ options.body = JSON.stringify(body);
3907
+ }
3908
+ try {
3909
+ const response = yield fetch(url, options);
3910
+ if (!response.ok) {
3911
+ handleRequestError(response.status);
3912
+ }
3913
+ const data = yield response.json();
3914
+ if (data.data !== void 0 && data.meta !== void 0) {
3915
+ return new PaginatedResponse(data);
3916
+ } else {
3917
+ return data;
3918
+ }
3919
+ } catch (error) {
3920
+ console.error(error);
3921
+ throw error;
3922
+ }
3923
+ });
3924
+
3925
+ // src/auth/loginwithpassword.ts
3926
+ var loginWithPassword = (input) => __async(null, null, function* () {
3927
+ const data = yield makeRequest("post" /* POST */, "/api/login", void 0, input);
3928
+ const { token, user } = data;
3929
+ setAccessToken(token);
3930
+ return user;
3931
+ });
3932
+
3933
+ // src/auth/loginservice.ts
3934
+ var loginService = (projectId, serviceId, secretKey) => __async(null, null, function* () {
3935
+ const body = new URLSearchParams({
3936
+ grant_type: "client_credentials",
3937
+ client_id: serviceId,
3938
+ client_secret: secretKey,
3939
+ scope: "all"
3940
+ });
3941
+ const response = yield fetch(`${app.baseUrl}/oauth2/token`, {
3942
+ method: "POST",
3943
+ headers: {
3944
+ "Content-Type": "application/x-www-form-urlencoded"
3945
+ },
3946
+ body
3947
+ });
3948
+ if (!response.ok) {
3949
+ throw new Error("Service login failed");
3950
+ }
3951
+ const data = yield response.json();
3952
+ if (data.access_token) {
3953
+ setAccessToken(data.access_token);
3954
+ }
3955
+ return data;
3956
+ });
3957
+
3958
+ // src/auth/loginwithredirect.ts
3959
+ var loginWithRedirect = (..._0) => __async(null, [..._0], function* (options = {}) {
3960
+ if (typeof window === "undefined" || !app.userManager) {
3961
+ throw new Error("loginWithRedirect can only be used in a browser environment after initializeSdk");
3962
+ }
3963
+ const {
3964
+ redirectUri = window.location.origin,
3965
+ state,
3966
+ scope,
3967
+ prompt
3968
+ } = options;
3969
+ yield app.userManager.signinRedirect({
3970
+ redirect_uri: redirectUri,
3971
+ state,
3972
+ scope,
3973
+ prompt
3974
+ });
3975
+ });
3976
+
3977
+ // src/auth/handleredirectcallback.ts
3978
+ var handleRedirectCallback = (url) => __async(null, null, function* () {
3979
+ if (typeof window === "undefined" || !app.userManager) {
3980
+ throw new Error("handleRedirectCallback can only be used in a browser environment after initializeSdk");
3981
+ }
3982
+ const user = yield app.userManager.signinRedirectCallback(url);
3983
+ if (!user.profile) {
3984
+ throw new Error("User profile not found in token response");
3985
+ }
3986
+ return user.profile;
3987
+ });
3988
+
3989
+ // src/auth/resetpassword.ts
3990
+ var resetPassword = (input) => __async(null, null, function* () {
3991
+ return yield makeRequest("post" /* POST */, "/api/users/reset-password", void 0, input);
3992
+ });
3993
+
3994
+ // src/auth/isloggedin.ts
3995
+ var isLoggedIn = () => {
3996
+ return app.accessToken !== null && app.accessToken.isValid();
3997
+ };
3998
+
3999
+ // src/auth/logout.ts
4000
+ var logout = () => __async(null, null, function* () {
4001
+ if (typeof window === "undefined" || !app.userManager) {
4002
+ app.accessToken = null;
4003
+ app.refreshToken = null;
4004
+ if (typeof window !== "undefined" && window.sessionStorage) {
4005
+ window.sessionStorage.removeItem("swiftbase_access_token");
4006
+ window.sessionStorage.removeItem("swiftbase_refresh_token");
4007
+ }
4008
+ return;
4009
+ }
4010
+ yield app.userManager.signoutRedirect();
4011
+ });
4012
+
4013
+ // src/auth/verifytoken.ts
4014
+ var verifyToken = (token, projectId) => __async(null, null, function* () {
4015
+ const url = `${app.baseUrl}/api/me`;
4016
+ const response = yield fetch(url, {
4017
+ headers: {
4018
+ "Authorization": `Bearer ${token}`
4019
+ }
4020
+ });
4021
+ if (!response.ok) {
4022
+ throw new Error("Invalid token");
4023
+ }
4024
+ return yield response.json();
4025
+ });
4026
+ var verifyServiceToken = (token, projectId, scope) => __async(null, null, function* () {
4027
+ return yield makeRequest("post" /* POST */, "/api/verify-service-token", void 0, {
4028
+ token,
4029
+ scope
4030
+ });
4031
+ });
4032
+
4033
+ // src/profile/getprofile.ts
4034
+ var getProfile = () => __async(null, null, function* () {
4035
+ return yield makeRequest("get" /* GET */, "/api/me");
4036
+ });
4037
+
4038
+ // src/profile/updateprofile.ts
4039
+ var updateProfile = (input) => __async(null, null, function* () {
4040
+ const me = yield makeRequest("get" /* GET */, "/api/me");
4041
+ return yield makeRequest("put" /* PUT */, `/api/users/${me.id}`, void 0, input);
4042
+ });
4043
+
4044
+ // src/profile/updateuser.ts
4045
+ var updateUser = (id, input) => __async(null, null, function* () {
4046
+ return yield makeRequest("put" /* PUT */, `/api/users/${id}`, void 0, input);
4047
+ });
4048
+
4049
+ // src/profile/changepassword.ts
4050
+ var changePassword = (input) => __async(null, null, function* () {
4051
+ return yield makeRequest("post" /* POST */, "/api/users/change-password", void 0, input);
4052
+ });
4053
+
4054
+ // src/identity/index.ts
4055
+ var getUsers = (projectId) => __async(null, null, function* () {
4056
+ const response = yield makeRequest("get" /* GET */, "/api/users", { projectId });
4057
+ return response instanceof PaginatedResponse ? response.items : response;
4058
+ });
4059
+ var getRoles = (projectId) => __async(null, null, function* () {
4060
+ const response = yield makeRequest("get" /* GET */, "/api/roles", { projectId });
4061
+ return response instanceof PaginatedResponse ? response.items : response;
4062
+ });
4063
+ var getServices = (projectId) => __async(null, null, function* () {
4064
+ const response = yield makeRequest("get" /* GET */, "/api/services", { projectId });
4065
+ return response instanceof PaginatedResponse ? response.items : response;
4066
+ });
4067
+ var createRole = (input) => __async(null, null, function* () {
4068
+ return yield makeRequest("post" /* POST */, "/api/roles", void 0, input);
4069
+ });
4070
+ var deleteRole = (id) => __async(null, null, function* () {
4071
+ return yield makeRequest("delete" /* DELETE */, `/api/roles/${id}`);
4072
+ });
4073
+ var createService = (input) => __async(null, null, function* () {
4074
+ return yield makeRequest("post" /* POST */, "/api/services", void 0, input);
4075
+ });
4076
+ var deleteService = (id) => __async(null, null, function* () {
4077
+ return yield makeRequest("delete" /* DELETE */, `/api/services/${id}`);
4078
+ });
4079
+ var assignRole = (userId, roleName) => __async(null, null, function* () {
4080
+ const user = yield makeRequest("get" /* GET */, `/api/users/${userId}`);
4081
+ const roles = [...user.roles || []];
4082
+ if (!roles.includes(roleName)) {
4083
+ roles.push(roleName);
4084
+ }
4085
+ return yield makeRequest("put" /* PUT */, `/api/users/${userId}`, void 0, { roles });
4086
+ });
4087
+ var unassignRole = (userId, roleName) => __async(null, null, function* () {
4088
+ const user = yield makeRequest("get" /* GET */, `/api/users/${userId}`);
4089
+ const roles = (user.roles || []).filter((r) => r !== roleName);
4090
+ return yield makeRequest("put" /* PUT */, `/api/users/${userId}`, void 0, { roles });
4091
+ });
4092
+
4093
+ // src/database/index.ts
4094
+ import { v4 as uuidv4 } from "uuid";
4095
+ var _DatabaseSocketManager = class _DatabaseSocketManager {
4096
+ constructor() {
4097
+ this.socket = null;
4098
+ this.connectionPromise = null;
4099
+ this.pendingQueries = /* @__PURE__ */ new Map();
4100
+ this.activeSubscriptions = /* @__PURE__ */ new Map();
4101
+ }
4102
+ static getInstance() {
4103
+ if (!_DatabaseSocketManager.instance) {
4104
+ _DatabaseSocketManager.instance = new _DatabaseSocketManager();
4105
+ }
4106
+ return _DatabaseSocketManager.instance;
4107
+ }
4108
+ isWebSocketAvailable() {
4109
+ return this.socket !== null && (this.socket.readyState === 0 || this.socket.readyState === 1);
4110
+ }
4111
+ getWebSocketUrl(baseUrl, token) {
4112
+ let wsUrl = baseUrl.replace(/^http/, "ws");
4113
+ wsUrl = wsUrl.endsWith("/") ? wsUrl.slice(0, -1) : wsUrl;
4114
+ wsUrl = `${wsUrl}/ws`;
4115
+ if (token) {
4116
+ wsUrl = `${wsUrl}?token=${encodeURIComponent(token)}`;
4117
+ }
4118
+ return wsUrl;
4119
+ }
4120
+ ensureConnected() {
4121
+ return __async(this, null, function* () {
4122
+ if (this.socket && (this.socket.readyState === 0 || this.socket.readyState === 1)) {
4123
+ return;
4124
+ }
4125
+ if (this.connectionPromise) {
4126
+ return this.connectionPromise;
4127
+ }
4128
+ this.connectionPromise = (() => __async(this, null, function* () {
4129
+ const token = yield getAccessToken();
4130
+ const wsUrl = this.getWebSocketUrl(app.baseUrl, token);
4131
+ let WS = typeof WebSocket !== "undefined" ? WebSocket : globalThis.WebSocket;
4132
+ if (!WS) {
4133
+ try {
4134
+ const wsModule = yield Promise.resolve().then(() => (init_wrapper(), wrapper_exports));
4135
+ WS = wsModule.default || wsModule;
4136
+ } catch (err) {
4137
+ this.connectionPromise = null;
4138
+ throw new Error(
4139
+ "WebSocket constructor not found. Please install the 'ws' package or run in an environment with global WebSocket support."
4140
+ );
4141
+ }
4142
+ }
4143
+ return new Promise((resolve, reject) => {
4144
+ try {
4145
+ const socket = new WS(wsUrl);
4146
+ this.socket = socket;
4147
+ socket.onopen = () => {
4148
+ this.connectionPromise = null;
4149
+ resolve();
4150
+ this.resubscribeAll().catch((err) => {
4151
+ console.error("[DatabaseSocketManager] Re-subscription failed:", err);
4152
+ });
4153
+ };
4154
+ socket.onerror = (err) => {
4155
+ this.connectionPromise = null;
4156
+ reject(err);
4157
+ };
4158
+ socket.onclose = () => {
4159
+ this.socket = null;
4160
+ this.connectionPromise = null;
4161
+ for (const [_, { reject: rejectQuery }] of this.pendingQueries.entries()) {
4162
+ rejectQuery(new Error("WebSocket disconnected"));
4163
+ }
4164
+ this.pendingQueries.clear();
4165
+ };
4166
+ socket.onmessage = (event) => {
4167
+ this.handleMessage(event);
4168
+ };
4169
+ } catch (err) {
4170
+ this.connectionPromise = null;
4171
+ reject(err);
4172
+ }
4173
+ });
4174
+ }))();
4175
+ return this.connectionPromise;
4176
+ });
4177
+ }
4178
+ resubscribeAll() {
4179
+ return __async(this, null, function* () {
4180
+ for (const key of this.activeSubscriptions.keys()) {
4181
+ const [database, table] = key.split(":");
4182
+ yield this.sendListenRequest(database, table);
4183
+ }
4184
+ });
4185
+ }
4186
+ sendListenRequest(database, table) {
4187
+ return __async(this, null, function* () {
4188
+ if (!this.socket || this.socket.readyState !== 1) {
4189
+ throw new Error("WebSocket not open");
4190
+ }
4191
+ const id = uuidv4();
4192
+ this.socket.send(JSON.stringify({
4193
+ id,
4194
+ action: "listen",
4195
+ payload: { database, table }
4196
+ }));
4197
+ return new Promise((resolve, reject) => {
4198
+ this.pendingQueries.set(id, { resolve: () => resolve(), reject });
4199
+ });
4200
+ });
4201
+ }
4202
+ handleMessage(event) {
4203
+ try {
4204
+ const msg = JSON.parse(event.data.toString());
4205
+ if (msg.action === "change") {
4206
+ const { database, table, event: changeEvent, data } = msg.payload;
4207
+ const key = `${database}:${table}`;
4208
+ const callbacks = this.activeSubscriptions.get(key);
4209
+ if (callbacks) {
4210
+ for (const cb of callbacks) {
4211
+ try {
4212
+ cb({ event: changeEvent, data });
4213
+ } catch (err) {
4214
+ console.error("[DatabaseSocketManager] Callback error:", err);
4215
+ }
4216
+ }
4217
+ }
4218
+ } else if (msg.id && this.pendingQueries.has(msg.id)) {
4219
+ const { resolve, reject } = this.pendingQueries.get(msg.id);
4220
+ this.pendingQueries.delete(msg.id);
4221
+ if (msg.status === "success") {
4222
+ resolve(msg.data);
4223
+ } else {
4224
+ reject(new Error(msg.message || "Query failed over WebSocket"));
4225
+ }
4226
+ }
4227
+ } catch (err) {
4228
+ console.error("[DatabaseSocketManager] Message handling error:", err);
4229
+ }
4230
+ }
4231
+ executeQuery(payload) {
4232
+ return __async(this, null, function* () {
4233
+ yield this.ensureConnected();
4234
+ const id = uuidv4();
4235
+ this.socket.send(JSON.stringify({
4236
+ id,
4237
+ action: "query",
4238
+ payload
4239
+ }));
4240
+ return new Promise((resolve, reject) => {
4241
+ this.pendingQueries.set(id, { resolve, reject });
4242
+ });
4243
+ });
4244
+ }
4245
+ subscribe(database, table, callback) {
4246
+ return __async(this, null, function* () {
4247
+ const key = `${database}:${table}`;
4248
+ let cbs = this.activeSubscriptions.get(key);
4249
+ const isNewTable = !cbs || cbs.size === 0;
4250
+ if (!cbs) {
4251
+ cbs = /* @__PURE__ */ new Set();
4252
+ this.activeSubscriptions.set(key, cbs);
4253
+ }
4254
+ cbs.add(callback);
4255
+ yield this.ensureConnected();
4256
+ if (isNewTable) {
4257
+ try {
4258
+ yield this.sendListenRequest(database, table);
4259
+ } catch (err) {
4260
+ cbs.delete(callback);
4261
+ if (cbs.size === 0) {
4262
+ this.activeSubscriptions.delete(key);
4263
+ }
4264
+ throw err;
4265
+ }
4266
+ }
4267
+ return () => {
4268
+ const currentCbs = this.activeSubscriptions.get(key);
4269
+ if (currentCbs) {
4270
+ currentCbs.delete(callback);
4271
+ if (currentCbs.size === 0) {
4272
+ this.activeSubscriptions.delete(key);
4273
+ }
4274
+ }
4275
+ };
4276
+ });
4277
+ }
4278
+ };
4279
+ _DatabaseSocketManager.instance = null;
4280
+ var DatabaseSocketManager = _DatabaseSocketManager;
4281
+ var QueryBuilder = class {
4282
+ constructor(dbName, tableName) {
4283
+ this.dbName = dbName;
4284
+ this.tableName = tableName;
4285
+ this.payload = {
4286
+ database: dbName,
4287
+ table: tableName
4288
+ };
4289
+ }
4290
+ select(...columns) {
4291
+ const flatColumns = columns.flat();
4292
+ if (flatColumns.length > 0) {
4293
+ if (!this.payload.select) {
4294
+ this.payload.select = [];
4295
+ }
4296
+ this.payload.select.push(...flatColumns);
4297
+ }
4298
+ return this;
4299
+ }
4300
+ where(columnOrObj, operatorOrValue, value) {
4301
+ if (!this.payload.where) {
4302
+ this.payload.where = [];
4303
+ }
4304
+ if (typeof columnOrObj === "string") {
4305
+ if (value !== void 0) {
4306
+ this.payload.where.push({
4307
+ column: columnOrObj,
4308
+ operator: operatorOrValue,
4309
+ value
4310
+ });
4311
+ } else if (operatorOrValue !== void 0) {
4312
+ this.payload.where.push({
4313
+ column: columnOrObj,
4314
+ operator: "=",
4315
+ value: operatorOrValue
4316
+ });
4317
+ }
4318
+ } else if (columnOrObj && typeof columnOrObj === "object") {
4319
+ for (const [k, v] of Object.entries(columnOrObj)) {
4320
+ this.payload.where.push({
4321
+ column: k,
4322
+ operator: "=",
4323
+ value: v
4324
+ });
4325
+ }
4326
+ }
4327
+ return this;
4328
+ }
4329
+ limit(value) {
4330
+ this.payload.limit = value;
4331
+ return this;
4332
+ }
4333
+ offset(value) {
4334
+ this.payload.offset = value;
4335
+ return this;
4336
+ }
4337
+ insert(data) {
4338
+ this.payload.insert = data;
4339
+ return this;
4340
+ }
4341
+ update(data) {
4342
+ this.payload.update = data;
4343
+ return this;
4344
+ }
4345
+ delete() {
4346
+ this.payload.delete = true;
4347
+ return this;
4348
+ }
4349
+ listen(callback) {
4350
+ let unsubscribed = false;
4351
+ let unsub = null;
4352
+ DatabaseSocketManager.getInstance().subscribe(this.dbName, this.tableName, callback).then((u) => {
4353
+ if (unsubscribed) {
4354
+ u();
4355
+ } else {
4356
+ unsub = u;
4357
+ }
4358
+ }).catch((err) => {
4359
+ console.error("[QueryBuilder] Subscription failed:", err);
4360
+ });
4361
+ return () => {
4362
+ unsubscribed = true;
4363
+ if (unsub) {
4364
+ unsub();
4365
+ }
4366
+ };
4367
+ }
4368
+ execute() {
4369
+ return __async(this, null, function* () {
4370
+ const socketManager = DatabaseSocketManager.getInstance();
4371
+ if (socketManager.isWebSocketAvailable()) {
4372
+ try {
4373
+ return yield socketManager.executeQuery(this.payload);
4374
+ } catch (err) {
4375
+ console.warn("[QueryBuilder] WebSocket execution failed, falling back to REST:", err);
4376
+ }
4377
+ }
4378
+ return yield makeRequest("post" /* POST */, "/api/db/query", void 0, this.payload);
4379
+ });
4380
+ }
4381
+ then(onfulfilled, onrejected) {
4382
+ return this.execute().then(onfulfilled, onrejected);
4383
+ }
4384
+ };
4385
+ function db(dbName) {
4386
+ return function(tableName) {
4387
+ return new QueryBuilder(dbName, tableName);
4388
+ };
4389
+ }
4390
+
4391
+ // src/storage/sigv4.ts
4392
+ function stringToUint8Array(str) {
4393
+ return new TextEncoder().encode(str);
4394
+ }
4395
+ function bufferToHex(buffer) {
4396
+ return Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
4397
+ }
4398
+ function getCryptoObj() {
4399
+ return __async(this, null, function* () {
4400
+ if (typeof globalThis.crypto !== "undefined") {
4401
+ return globalThis.crypto;
4402
+ }
4403
+ const cryptoModule = yield import("crypto");
4404
+ return cryptoModule.webcrypto;
4405
+ });
4406
+ }
4407
+ function sha256(data) {
4408
+ return __async(this, null, function* () {
4409
+ const cryptoObj = yield getCryptoObj();
4410
+ const dataArr = typeof data === "string" ? stringToUint8Array(data) : data;
4411
+ return yield cryptoObj.subtle.digest("SHA-256", dataArr);
4412
+ });
4413
+ }
4414
+ function hmac(key, data) {
4415
+ return __async(this, null, function* () {
4416
+ const cryptoObj = yield getCryptoObj();
4417
+ const cryptoKey = yield cryptoObj.subtle.importKey(
4418
+ "raw",
4419
+ key,
4420
+ { name: "HMAC", hash: "SHA-256" },
4421
+ false,
4422
+ ["sign"]
4423
+ );
4424
+ const dataArr = typeof data === "string" ? stringToUint8Array(data) : data;
4425
+ return yield cryptoObj.subtle.sign("HMAC", cryptoKey, dataArr);
4426
+ });
4427
+ }
4428
+ function getSigningKey(secretKey, date, region, service) {
4429
+ return __async(this, null, function* () {
4430
+ const kDate = yield hmac(stringToUint8Array("AWS4" + secretKey), date);
4431
+ const kRegion = yield hmac(new Uint8Array(kDate), region);
4432
+ const kService = yield hmac(new Uint8Array(kRegion), service);
4433
+ const kSigning = yield hmac(new Uint8Array(kService), "aws4_request");
4434
+ return new Uint8Array(kSigning);
4435
+ });
4436
+ }
4437
+ function signS3Request(options) {
4438
+ return __async(this, null, function* () {
4439
+ const { method, url, headers, body = "", accessKeyId, secretAccessKey, region } = options;
4440
+ const parsedUrl = new URL(url);
4441
+ const host = parsedUrl.host;
4442
+ const now = /* @__PURE__ */ new Date();
4443
+ const amzDate = now.toISOString().replace(/[:-]/g, "").split(".")[0] + "Z";
4444
+ const dateStamp = amzDate.substring(0, 8);
4445
+ const headersToSign = {};
4446
+ headersToSign["host"] = host;
4447
+ headersToSign["x-amz-date"] = amzDate;
4448
+ const payloadHash = bufferToHex(yield sha256(body));
4449
+ headersToSign["x-amz-content-sha256"] = payloadHash;
4450
+ for (const [key, value] of Object.entries(headers)) {
4451
+ const lowerKey = key.toLowerCase();
4452
+ if (lowerKey !== "authorization" && lowerKey !== "host" && lowerKey !== "x-amz-date" && lowerKey !== "x-amz-content-sha256") {
4453
+ headersToSign[lowerKey] = value.trim().replace(/\s+/g, " ");
4454
+ }
4455
+ }
4456
+ const sortedHeaderKeys = Object.keys(headersToSign).sort();
4457
+ let canonicalHeaders = "";
4458
+ for (const key of sortedHeaderKeys) {
4459
+ canonicalHeaders += `${key}:${headersToSign[key]}
4460
+ `;
4461
+ }
4462
+ const signedHeaders = sortedHeaderKeys.join(";");
4463
+ const queryParams = [];
4464
+ parsedUrl.searchParams.forEach((value, key) => {
4465
+ queryParams.push({ key, value });
4466
+ });
4467
+ queryParams.sort((a, b) => a.key.localeCompare(b.key));
4468
+ const rfc3986Encode = (str) => encodeURIComponent(str).replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
4469
+ const canonicalQueryString = queryParams.map((p) => `${rfc3986Encode(p.key)}=${rfc3986Encode(p.value)}`).join("&");
4470
+ const canonicalUri = parsedUrl.pathname || "/";
4471
+ const canonicalRequest = [
4472
+ method.toUpperCase(),
4473
+ canonicalUri,
4474
+ canonicalQueryString,
4475
+ canonicalHeaders,
4476
+ signedHeaders,
4477
+ payloadHash
4478
+ ].join("\n");
4479
+ const canonicalRequestHash = bufferToHex(yield sha256(canonicalRequest));
4480
+ const algorithm = "AWS4-HMAC-SHA256";
4481
+ const credentialScope = `${dateStamp}/${region}/s3/aws4_request`;
4482
+ const stringToSign = [
4483
+ algorithm,
4484
+ amzDate,
4485
+ credentialScope,
4486
+ canonicalRequestHash
4487
+ ].join("\n");
4488
+ const signingKey = yield getSigningKey(secretAccessKey, dateStamp, region, "s3");
4489
+ const signature = bufferToHex(yield hmac(signingKey, stringToSign));
4490
+ const authorizationHeader = `${algorithm} Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
4491
+ const resultHeaders = __spreadValues({}, headers);
4492
+ resultHeaders["Host"] = host;
4493
+ resultHeaders["x-amz-date"] = amzDate;
4494
+ resultHeaders["x-amz-content-sha256"] = payloadHash;
4495
+ resultHeaders["Authorization"] = authorizationHeader;
4496
+ return resultHeaders;
4497
+ });
4498
+ }
4499
+
4500
+ // src/storage/storage.ts
4501
+ function getDefaultEndpoint() {
4502
+ const base = app.baseUrl || "https://api.swiftbase.io";
4503
+ if (base.includes("localhost") || base.includes("127.0.0.1")) {
4504
+ return "http://localhost:3006";
4505
+ }
4506
+ return base.replace("api.swiftbase", "storage.swiftbase");
4507
+ }
4508
+ function parseListBuckets(xml) {
4509
+ const buckets = [];
4510
+ const bucketMatches = xml.matchAll(/<Bucket>([\s\S]*?)<\/Bucket>/g);
4511
+ for (const match of bucketMatches) {
4512
+ const bucketContent = match[1];
4513
+ const nameMatch = bucketContent.match(/<Name>(.*?)<\/Name>/);
4514
+ const dateMatch = bucketContent.match(/<CreationDate>(.*?)<\/CreationDate>/);
4515
+ if (nameMatch) {
4516
+ buckets.push({
4517
+ name: nameMatch[1],
4518
+ creationDate: dateMatch ? dateMatch[1] : void 0
4519
+ });
4520
+ }
4521
+ }
4522
+ return buckets;
4523
+ }
4524
+ function parseListObjects(xml) {
4525
+ const nameMatch = xml.match(/<Name>(.*?)<\/Name>/);
4526
+ const prefixMatch = xml.match(/<Prefix>(.*?)<\/Prefix>/);
4527
+ const maxKeysMatch = xml.match(/<MaxKeys>(.*?)<\/MaxKeys>/);
4528
+ const isTruncatedMatch = xml.match(/<IsTruncated>(.*?)<\/IsTruncated>/);
4529
+ const contents = [];
4530
+ const contentMatches = xml.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g);
4531
+ for (const match of contentMatches) {
4532
+ const content = match[1];
4533
+ const keyMatch = content.match(/<Key>(.*?)<\/Key>/);
4534
+ const lmMatch = content.match(/<LastModified>(.*?)<\/LastModified>/);
4535
+ const etagMatch = content.match(/<ETag>(.*?)<\/ETag>/);
4536
+ const sizeMatch = content.match(/<Size>(.*?)<\/Size>/);
4537
+ if (keyMatch) {
4538
+ contents.push({
4539
+ key: keyMatch[1],
4540
+ lastModified: lmMatch ? lmMatch[1] : void 0,
4541
+ etag: etagMatch ? etagMatch[1].replace(/"/g, "") : void 0,
4542
+ size: sizeMatch ? parseInt(sizeMatch[1]) : 0
4543
+ });
4544
+ }
4545
+ }
4546
+ const commonPrefixes = [];
4547
+ const cpMatches = xml.matchAll(/<CommonPrefixes>([\s\S]*?)<\/CommonPrefixes>/g);
4548
+ for (const match of cpMatches) {
4549
+ const prefixMatch2 = match[1].match(/<Prefix>(.*?)<\/Prefix>/);
4550
+ if (prefixMatch2) {
4551
+ commonPrefixes.push(prefixMatch2[1]);
4552
+ }
4553
+ }
4554
+ return {
4555
+ name: nameMatch ? nameMatch[1] : "",
4556
+ prefix: prefixMatch ? prefixMatch[1] : "",
4557
+ maxKeys: maxKeysMatch ? parseInt(maxKeysMatch[1]) : 1e3,
4558
+ isTruncated: isTruncatedMatch ? isTruncatedMatch[1] === "true" : false,
4559
+ contents,
4560
+ commonPrefixes
4561
+ };
4562
+ }
4563
+ function parseErrorXml(xml) {
4564
+ const codeMatch = xml.match(/<Code>(.*?)<\/Code>/);
4565
+ const messageMatch = xml.match(/<Message>(.*?)<\/Message>/);
4566
+ if (codeMatch && messageMatch) {
4567
+ return `${codeMatch[1]}: ${messageMatch[1]}`;
4568
+ }
4569
+ return xml;
4570
+ }
4571
+ var Storage = class {
4572
+ constructor(options) {
4573
+ this.bucket = options.bucket;
4574
+ this.endpoint = options.endpoint || getDefaultEndpoint();
4575
+ this.region = options.region || "us-east-1";
4576
+ this.accessKeyId = options.accessKeyId;
4577
+ this.secretAccessKey = options.secretAccessKey;
4578
+ }
4579
+ getHeaders(_0, _1, _2) {
4580
+ return __async(this, arguments, function* (method, url, body, customHeaders = {}) {
4581
+ let headers = __spreadValues({}, customHeaders);
4582
+ if (this.accessKeyId && this.secretAccessKey) {
4583
+ headers = yield signS3Request({
4584
+ method,
4585
+ url,
4586
+ headers,
4587
+ body,
4588
+ accessKeyId: this.accessKeyId,
4589
+ secretAccessKey: this.secretAccessKey,
4590
+ region: this.region
4591
+ });
4592
+ } else {
4593
+ const token = yield getAccessToken();
4594
+ if (token) {
4595
+ headers["Authorization"] = `Bearer ${token}`;
4596
+ }
4597
+ }
4598
+ return headers;
4599
+ });
4600
+ }
4601
+ listBuckets() {
4602
+ return __async(this, null, function* () {
4603
+ const method = "GET";
4604
+ const url = `${this.endpoint.replace(/\/$/, "")}/`;
4605
+ const headers = yield this.getHeaders(method, url);
4606
+ const response = yield fetch(url, { method, headers });
4607
+ const text = yield response.text();
4608
+ if (!response.ok) {
4609
+ throw new Error(parseErrorXml(text) || `Failed to list buckets: ${response.statusText}`);
4610
+ }
4611
+ return parseListBuckets(text);
4612
+ });
4613
+ }
4614
+ listObjects(options) {
4615
+ return __async(this, null, function* () {
4616
+ const method = "GET";
4617
+ const query = new URLSearchParams();
4618
+ if (options == null ? void 0 : options.prefix) query.append("prefix", options.prefix);
4619
+ if (options == null ? void 0 : options.delimiter) query.append("delimiter", options.delimiter);
4620
+ if (options == null ? void 0 : options.maxKeys) query.append("max-keys", String(options.maxKeys));
4621
+ const queryString = query.toString();
4622
+ const url = `${this.endpoint.replace(/\/$/, "")}/${this.bucket}${queryString ? "?" + queryString : ""}`;
4623
+ const headers = yield this.getHeaders(method, url);
4624
+ const response = yield fetch(url, { method, headers });
4625
+ const text = yield response.text();
4626
+ if (!response.ok) {
4627
+ throw new Error(parseErrorXml(text) || `Failed to list objects: ${response.statusText}`);
4628
+ }
4629
+ return parseListObjects(text);
4630
+ });
4631
+ }
4632
+ getObject(key) {
4633
+ return __async(this, null, function* () {
4634
+ const method = "GET";
4635
+ const cleanKey = key.startsWith("/") ? key : "/" + key;
4636
+ const url = `${this.endpoint.replace(/\/$/, "")}/${this.bucket}${cleanKey}`;
4637
+ const headers = yield this.getHeaders(method, url);
4638
+ const response = yield fetch(url, { method, headers });
4639
+ if (!response.ok) {
4640
+ const text = yield response.text();
4641
+ throw new Error(parseErrorXml(text) || `Failed to get object: ${response.statusText}`);
4642
+ }
4643
+ return response;
4644
+ });
4645
+ }
4646
+ getObjectAsText(key) {
4647
+ return __async(this, null, function* () {
4648
+ const res = yield this.getObject(key);
4649
+ return yield res.text();
4650
+ });
4651
+ }
4652
+ getObjectAsJson(key) {
4653
+ return __async(this, null, function* () {
4654
+ const res = yield this.getObject(key);
4655
+ return yield res.json();
4656
+ });
4657
+ }
4658
+ getObjectAsArrayBuffer(key) {
4659
+ return __async(this, null, function* () {
4660
+ const res = yield this.getObject(key);
4661
+ return yield res.arrayBuffer();
4662
+ });
4663
+ }
4664
+ putObject(key, body, options) {
4665
+ return __async(this, null, function* () {
4666
+ const method = "PUT";
4667
+ const cleanKey = key.startsWith("/") ? key : "/" + key;
4668
+ const url = `${this.endpoint.replace(/\/$/, "")}/${this.bucket}${cleanKey}`;
4669
+ let bodyData;
4670
+ if (typeof body === "string") {
4671
+ bodyData = new TextEncoder().encode(body);
4672
+ } else if (body instanceof ArrayBuffer) {
4673
+ bodyData = new Uint8Array(body);
4674
+ } else if (body instanceof Uint8Array) {
4675
+ bodyData = body;
4676
+ } else if (typeof Blob !== "undefined" && body instanceof Blob) {
4677
+ bodyData = new Uint8Array(yield body.arrayBuffer());
4678
+ } else {
4679
+ throw new Error("Unsupported body type. Must be string, ArrayBuffer, Uint8Array, or Blob.");
4680
+ }
4681
+ const customHeaders = {};
4682
+ if (options == null ? void 0 : options.contentType) {
4683
+ customHeaders["Content-Type"] = options.contentType;
4684
+ }
4685
+ const headers = yield this.getHeaders(method, url, bodyData, customHeaders);
4686
+ const response = yield fetch(url, {
4687
+ method,
4688
+ headers,
4689
+ body: bodyData
4690
+ });
4691
+ if (!response.ok) {
4692
+ const text = yield response.text();
4693
+ throw new Error(parseErrorXml(text) || `Failed to put object: ${response.statusText}`);
4694
+ }
4695
+ });
4696
+ }
4697
+ deleteObject(key) {
4698
+ return __async(this, null, function* () {
4699
+ const method = "DELETE";
4700
+ const cleanKey = key.startsWith("/") ? key : "/" + key;
4701
+ const url = `${this.endpoint.replace(/\/$/, "")}/${this.bucket}${cleanKey}`;
4702
+ const headers = yield this.getHeaders(method, url);
4703
+ const response = yield fetch(url, { method, headers });
4704
+ if (!response.ok) {
4705
+ const text = yield response.text();
4706
+ throw new Error(parseErrorXml(text) || `Failed to delete object: ${response.statusText}`);
4707
+ }
4708
+ });
4709
+ }
4710
+ };
4711
+ export {
4712
+ PaginatedResponse,
4713
+ Storage,
4714
+ assignRole,
4715
+ changePassword,
4716
+ createRole,
4717
+ createService,
4718
+ db,
4719
+ deleteRole,
4720
+ deleteService,
4721
+ getAccessToken,
4722
+ getProfile,
4723
+ getRoles,
4724
+ getServices,
4725
+ getUsers,
4726
+ handleRedirectCallback,
4727
+ initializeSdk,
4728
+ isLoggedIn,
4729
+ loginService as login,
4730
+ loginService,
4731
+ loginWithPassword,
4732
+ loginWithRedirect,
4733
+ logout,
4734
+ refreshTokens,
4735
+ resetPassword,
4736
+ setAccessToken,
4737
+ setRefreshToken,
4738
+ unassignRole,
4739
+ updateProfile,
4740
+ updateUser,
4741
+ verifyServiceToken,
4742
+ verifyToken
4743
+ };
4744
+ //# sourceMappingURL=index.js.map