swiftbase-admin-sdk 1.0.0

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