@oox/ws-client 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/browser.js ADDED
@@ -0,0 +1,2517 @@
1
+ var OOXWebSocketClient = (function (exports, oox) {
2
+ 'use strict';
3
+
4
+ function _interopNamespaceDefault(e) {
5
+ var n = Object.create(null);
6
+ if (e) {
7
+ Object.keys(e).forEach(function (k) {
8
+ if (k !== 'default') {
9
+ var d = Object.getOwnPropertyDescriptor(e, k);
10
+ Object.defineProperty(n, k, d.get ? d : {
11
+ enumerable: true,
12
+ get: function () { return e[k]; }
13
+ });
14
+ }
15
+ });
16
+ }
17
+ n.default = e;
18
+ return Object.freeze(n);
19
+ }
20
+
21
+ var oox__namespace = /*#__PURE__*/_interopNamespaceDefault(oox);
22
+
23
+ function utf8Count(str) {
24
+ const strLength = str.length;
25
+ let byteLength = 0;
26
+ let pos = 0;
27
+ while (pos < strLength) {
28
+ let value = str.charCodeAt(pos++);
29
+ if ((value & 0xffffff80) === 0) {
30
+ // 1-byte
31
+ byteLength++;
32
+ continue;
33
+ }
34
+ else if ((value & 0xfffff800) === 0) {
35
+ // 2-bytes
36
+ byteLength += 2;
37
+ }
38
+ else {
39
+ // handle surrogate pair
40
+ if (value >= 0xd800 && value <= 0xdbff) {
41
+ // high surrogate
42
+ if (pos < strLength) {
43
+ const extra = str.charCodeAt(pos);
44
+ if ((extra & 0xfc00) === 0xdc00) {
45
+ ++pos;
46
+ value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
47
+ }
48
+ }
49
+ }
50
+ if ((value & 0xffff0000) === 0) {
51
+ // 3-byte
52
+ byteLength += 3;
53
+ }
54
+ else {
55
+ // 4-byte
56
+ byteLength += 4;
57
+ }
58
+ }
59
+ }
60
+ return byteLength;
61
+ }
62
+ function utf8EncodeJs(str, output, outputOffset) {
63
+ const strLength = str.length;
64
+ let offset = outputOffset;
65
+ let pos = 0;
66
+ while (pos < strLength) {
67
+ let value = str.charCodeAt(pos++);
68
+ if ((value & 0xffffff80) === 0) {
69
+ // 1-byte
70
+ output[offset++] = value;
71
+ continue;
72
+ }
73
+ else if ((value & 0xfffff800) === 0) {
74
+ // 2-bytes
75
+ output[offset++] = ((value >> 6) & 0x1f) | 0xc0;
76
+ }
77
+ else {
78
+ // handle surrogate pair
79
+ if (value >= 0xd800 && value <= 0xdbff) {
80
+ // high surrogate
81
+ if (pos < strLength) {
82
+ const extra = str.charCodeAt(pos);
83
+ if ((extra & 0xfc00) === 0xdc00) {
84
+ ++pos;
85
+ value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
86
+ }
87
+ }
88
+ }
89
+ if ((value & 0xffff0000) === 0) {
90
+ // 3-byte
91
+ output[offset++] = ((value >> 12) & 0x0f) | 0xe0;
92
+ output[offset++] = ((value >> 6) & 0x3f) | 0x80;
93
+ }
94
+ else {
95
+ // 4-byte
96
+ output[offset++] = ((value >> 18) & 0x07) | 0xf0;
97
+ output[offset++] = ((value >> 12) & 0x3f) | 0x80;
98
+ output[offset++] = ((value >> 6) & 0x3f) | 0x80;
99
+ }
100
+ }
101
+ output[offset++] = (value & 0x3f) | 0x80;
102
+ }
103
+ }
104
+ // TextEncoder and TextDecoder are standardized in whatwg encoding:
105
+ // https://encoding.spec.whatwg.org/
106
+ // and available in all the modern browsers:
107
+ // https://caniuse.com/textencoder
108
+ // They are available in Node.js since v12 LTS as well:
109
+ // https://nodejs.org/api/globals.html#textencoder
110
+ const sharedTextEncoder = new TextEncoder();
111
+ // This threshold should be determined by benchmarking, which might vary in engines and input data.
112
+ // Run `npx ts-node benchmark/encode-string.ts` for details.
113
+ const TEXT_ENCODER_THRESHOLD = 50;
114
+ function utf8EncodeTE(str, output, outputOffset) {
115
+ sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
116
+ }
117
+ function utf8Encode(str, output, outputOffset) {
118
+ if (str.length > TEXT_ENCODER_THRESHOLD) {
119
+ utf8EncodeTE(str, output, outputOffset);
120
+ }
121
+ else {
122
+ utf8EncodeJs(str, output, outputOffset);
123
+ }
124
+ }
125
+ const CHUNK_SIZE = 4096;
126
+ function utf8DecodeJs(bytes, inputOffset, byteLength) {
127
+ let offset = inputOffset;
128
+ const end = offset + byteLength;
129
+ const units = [];
130
+ let result = "";
131
+ while (offset < end) {
132
+ const byte1 = bytes[offset++];
133
+ if ((byte1 & 0x80) === 0) {
134
+ // 1 byte
135
+ units.push(byte1);
136
+ }
137
+ else if ((byte1 & 0xe0) === 0xc0) {
138
+ // 2 bytes
139
+ const byte2 = bytes[offset++] & 0x3f;
140
+ units.push(((byte1 & 0x1f) << 6) | byte2);
141
+ }
142
+ else if ((byte1 & 0xf0) === 0xe0) {
143
+ // 3 bytes
144
+ const byte2 = bytes[offset++] & 0x3f;
145
+ const byte3 = bytes[offset++] & 0x3f;
146
+ units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
147
+ }
148
+ else if ((byte1 & 0xf8) === 0xf0) {
149
+ // 4 bytes
150
+ const byte2 = bytes[offset++] & 0x3f;
151
+ const byte3 = bytes[offset++] & 0x3f;
152
+ const byte4 = bytes[offset++] & 0x3f;
153
+ let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
154
+ if (unit > 0xffff) {
155
+ unit -= 0x10000;
156
+ units.push(((unit >>> 10) & 0x3ff) | 0xd800);
157
+ unit = 0xdc00 | (unit & 0x3ff);
158
+ }
159
+ units.push(unit);
160
+ }
161
+ else {
162
+ units.push(byte1);
163
+ }
164
+ if (units.length >= CHUNK_SIZE) {
165
+ result += String.fromCharCode(...units);
166
+ units.length = 0;
167
+ }
168
+ }
169
+ if (units.length > 0) {
170
+ result += String.fromCharCode(...units);
171
+ }
172
+ return result;
173
+ }
174
+ const sharedTextDecoder = new TextDecoder();
175
+ // This threshold should be determined by benchmarking, which might vary in engines and input data.
176
+ // Run `npx ts-node benchmark/decode-string.ts` for details.
177
+ const TEXT_DECODER_THRESHOLD = 200;
178
+ function utf8DecodeTD(bytes, inputOffset, byteLength) {
179
+ const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
180
+ return sharedTextDecoder.decode(stringBytes);
181
+ }
182
+ function utf8Decode(bytes, inputOffset, byteLength) {
183
+ if (byteLength > TEXT_DECODER_THRESHOLD) {
184
+ return utf8DecodeTD(bytes, inputOffset, byteLength);
185
+ }
186
+ else {
187
+ return utf8DecodeJs(bytes, inputOffset, byteLength);
188
+ }
189
+ }
190
+
191
+ /**
192
+ * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.
193
+ */
194
+ class ExtData {
195
+ type;
196
+ data;
197
+ constructor(type, data) {
198
+ this.type = type;
199
+ this.data = data;
200
+ }
201
+ }
202
+
203
+ class DecodeError extends Error {
204
+ constructor(message) {
205
+ super(message);
206
+ // fix the prototype chain in a cross-platform way
207
+ const proto = Object.create(DecodeError.prototype);
208
+ Object.setPrototypeOf(this, proto);
209
+ Object.defineProperty(this, "name", {
210
+ configurable: true,
211
+ enumerable: false,
212
+ value: DecodeError.name,
213
+ });
214
+ }
215
+ }
216
+
217
+ // Integer Utility
218
+ const UINT32_MAX = 4294967295;
219
+ // DataView extension to handle int64 / uint64,
220
+ // where the actual range is 53-bits integer (a.k.a. safe integer)
221
+ function setUint64(view, offset, value) {
222
+ const high = value / 4294967296;
223
+ const low = value; // high bits are truncated by DataView
224
+ view.setUint32(offset, high);
225
+ view.setUint32(offset + 4, low);
226
+ }
227
+ function setInt64(view, offset, value) {
228
+ const high = Math.floor(value / 4294967296);
229
+ const low = value; // high bits are truncated by DataView
230
+ view.setUint32(offset, high);
231
+ view.setUint32(offset + 4, low);
232
+ }
233
+ function getInt64(view, offset) {
234
+ const high = view.getInt32(offset);
235
+ const low = view.getUint32(offset + 4);
236
+ return high * 4294967296 + low;
237
+ }
238
+ function getUint64(view, offset) {
239
+ const high = view.getUint32(offset);
240
+ const low = view.getUint32(offset + 4);
241
+ return high * 4294967296 + low;
242
+ }
243
+
244
+ // https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
245
+ const EXT_TIMESTAMP = -1;
246
+ const TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int
247
+ const TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int
248
+ function encodeTimeSpecToTimestamp({ sec, nsec }) {
249
+ if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
250
+ // Here sec >= 0 && nsec >= 0
251
+ if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
252
+ // timestamp 32 = { sec32 (unsigned) }
253
+ const rv = new Uint8Array(4);
254
+ const view = new DataView(rv.buffer);
255
+ view.setUint32(0, sec);
256
+ return rv;
257
+ }
258
+ else {
259
+ // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }
260
+ const secHigh = sec / 0x100000000;
261
+ const secLow = sec & 0xffffffff;
262
+ const rv = new Uint8Array(8);
263
+ const view = new DataView(rv.buffer);
264
+ // nsec30 | secHigh2
265
+ view.setUint32(0, (nsec << 2) | (secHigh & 0x3));
266
+ // secLow32
267
+ view.setUint32(4, secLow);
268
+ return rv;
269
+ }
270
+ }
271
+ else {
272
+ // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
273
+ const rv = new Uint8Array(12);
274
+ const view = new DataView(rv.buffer);
275
+ view.setUint32(0, nsec);
276
+ setInt64(view, 4, sec);
277
+ return rv;
278
+ }
279
+ }
280
+ function encodeDateToTimeSpec(date) {
281
+ const msec = date.getTime();
282
+ const sec = Math.floor(msec / 1e3);
283
+ const nsec = (msec - sec * 1e3) * 1e6;
284
+ // Normalizes { sec, nsec } to ensure nsec is unsigned.
285
+ const nsecInSec = Math.floor(nsec / 1e9);
286
+ return {
287
+ sec: sec + nsecInSec,
288
+ nsec: nsec - nsecInSec * 1e9,
289
+ };
290
+ }
291
+ function encodeTimestampExtension(object) {
292
+ if (object instanceof Date) {
293
+ const timeSpec = encodeDateToTimeSpec(object);
294
+ return encodeTimeSpecToTimestamp(timeSpec);
295
+ }
296
+ else {
297
+ return null;
298
+ }
299
+ }
300
+ function decodeTimestampToTimeSpec(data) {
301
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
302
+ // data may be 32, 64, or 96 bits
303
+ switch (data.byteLength) {
304
+ case 4: {
305
+ // timestamp 32 = { sec32 }
306
+ const sec = view.getUint32(0);
307
+ const nsec = 0;
308
+ return { sec, nsec };
309
+ }
310
+ case 8: {
311
+ // timestamp 64 = { nsec30, sec34 }
312
+ const nsec30AndSecHigh2 = view.getUint32(0);
313
+ const secLow32 = view.getUint32(4);
314
+ const sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;
315
+ const nsec = nsec30AndSecHigh2 >>> 2;
316
+ return { sec, nsec };
317
+ }
318
+ case 12: {
319
+ // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
320
+ const sec = getInt64(view, 4);
321
+ const nsec = view.getUint32(0);
322
+ return { sec, nsec };
323
+ }
324
+ default:
325
+ throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);
326
+ }
327
+ }
328
+ function decodeTimestampExtension(data) {
329
+ const timeSpec = decodeTimestampToTimeSpec(data);
330
+ return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
331
+ }
332
+ const timestampExtension = {
333
+ type: EXT_TIMESTAMP,
334
+ encode: encodeTimestampExtension,
335
+ decode: decodeTimestampExtension,
336
+ };
337
+
338
+ // ExtensionCodec to handle MessagePack extensions
339
+ class ExtensionCodec {
340
+ static defaultCodec = new ExtensionCodec();
341
+ // ensures ExtensionCodecType<X> matches ExtensionCodec<X>
342
+ // this will make type errors a lot more clear
343
+ // eslint-disable-next-line @typescript-eslint/naming-convention
344
+ __brand;
345
+ // built-in extensions
346
+ builtInEncoders = [];
347
+ builtInDecoders = [];
348
+ // custom extensions
349
+ encoders = [];
350
+ decoders = [];
351
+ constructor() {
352
+ this.register(timestampExtension);
353
+ }
354
+ register({ type, encode, decode, }) {
355
+ if (type >= 0) {
356
+ // custom extensions
357
+ this.encoders[type] = encode;
358
+ this.decoders[type] = decode;
359
+ }
360
+ else {
361
+ // built-in extensions
362
+ const index = -1 - type;
363
+ this.builtInEncoders[index] = encode;
364
+ this.builtInDecoders[index] = decode;
365
+ }
366
+ }
367
+ tryToEncode(object, context) {
368
+ // built-in extensions
369
+ for (let i = 0; i < this.builtInEncoders.length; i++) {
370
+ const encodeExt = this.builtInEncoders[i];
371
+ if (encodeExt != null) {
372
+ const data = encodeExt(object, context);
373
+ if (data != null) {
374
+ const type = -1 - i;
375
+ return new ExtData(type, data);
376
+ }
377
+ }
378
+ }
379
+ // custom extensions
380
+ for (let i = 0; i < this.encoders.length; i++) {
381
+ const encodeExt = this.encoders[i];
382
+ if (encodeExt != null) {
383
+ const data = encodeExt(object, context);
384
+ if (data != null) {
385
+ const type = i;
386
+ return new ExtData(type, data);
387
+ }
388
+ }
389
+ }
390
+ if (object instanceof ExtData) {
391
+ // to keep ExtData as is
392
+ return object;
393
+ }
394
+ return null;
395
+ }
396
+ decode(data, type, context) {
397
+ const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
398
+ if (decodeExt) {
399
+ return decodeExt(data, type, context);
400
+ }
401
+ else {
402
+ // decode() does not fail, returns ExtData instead.
403
+ return new ExtData(type, data);
404
+ }
405
+ }
406
+ }
407
+
408
+ function isArrayBufferLike(buffer) {
409
+ return (buffer instanceof ArrayBuffer || (typeof SharedArrayBuffer !== "undefined" && buffer instanceof SharedArrayBuffer));
410
+ }
411
+ function ensureUint8Array(buffer) {
412
+ if (buffer instanceof Uint8Array) {
413
+ return buffer;
414
+ }
415
+ else if (ArrayBuffer.isView(buffer)) {
416
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
417
+ }
418
+ else if (isArrayBufferLike(buffer)) {
419
+ return new Uint8Array(buffer);
420
+ }
421
+ else {
422
+ // ArrayLike<number>
423
+ return Uint8Array.from(buffer);
424
+ }
425
+ }
426
+
427
+ const DEFAULT_MAX_DEPTH = 100;
428
+ const DEFAULT_INITIAL_BUFFER_SIZE = 2048;
429
+ class Encoder {
430
+ extensionCodec;
431
+ context;
432
+ useBigInt64;
433
+ maxDepth;
434
+ initialBufferSize;
435
+ sortKeys;
436
+ forceFloat32;
437
+ ignoreUndefined;
438
+ forceIntegerToFloat;
439
+ pos;
440
+ view;
441
+ bytes;
442
+ entered = false;
443
+ constructor(options) {
444
+ this.extensionCodec = options?.extensionCodec ?? ExtensionCodec.defaultCodec;
445
+ this.context = options?.context; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined
446
+ this.useBigInt64 = options?.useBigInt64 ?? false;
447
+ this.maxDepth = options?.maxDepth ?? DEFAULT_MAX_DEPTH;
448
+ this.initialBufferSize = options?.initialBufferSize ?? DEFAULT_INITIAL_BUFFER_SIZE;
449
+ this.sortKeys = options?.sortKeys ?? false;
450
+ this.forceFloat32 = options?.forceFloat32 ?? false;
451
+ this.ignoreUndefined = options?.ignoreUndefined ?? false;
452
+ this.forceIntegerToFloat = options?.forceIntegerToFloat ?? false;
453
+ this.pos = 0;
454
+ this.view = new DataView(new ArrayBuffer(this.initialBufferSize));
455
+ this.bytes = new Uint8Array(this.view.buffer);
456
+ }
457
+ clone() {
458
+ // Because of slightly special argument `context`,
459
+ // type assertion is needed.
460
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
461
+ return new Encoder({
462
+ extensionCodec: this.extensionCodec,
463
+ context: this.context,
464
+ useBigInt64: this.useBigInt64,
465
+ maxDepth: this.maxDepth,
466
+ initialBufferSize: this.initialBufferSize,
467
+ sortKeys: this.sortKeys,
468
+ forceFloat32: this.forceFloat32,
469
+ ignoreUndefined: this.ignoreUndefined,
470
+ forceIntegerToFloat: this.forceIntegerToFloat,
471
+ });
472
+ }
473
+ reinitializeState() {
474
+ this.pos = 0;
475
+ }
476
+ /**
477
+ * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.
478
+ *
479
+ * @returns Encodes the object and returns a shared reference the encoder's internal buffer.
480
+ */
481
+ encodeSharedRef(object) {
482
+ if (this.entered) {
483
+ const instance = this.clone();
484
+ return instance.encodeSharedRef(object);
485
+ }
486
+ try {
487
+ this.entered = true;
488
+ this.reinitializeState();
489
+ this.doEncode(object, 1);
490
+ return this.bytes.subarray(0, this.pos);
491
+ }
492
+ finally {
493
+ this.entered = false;
494
+ }
495
+ }
496
+ /**
497
+ * @returns Encodes the object and returns a copy of the encoder's internal buffer.
498
+ */
499
+ encode(object) {
500
+ if (this.entered) {
501
+ const instance = this.clone();
502
+ return instance.encode(object);
503
+ }
504
+ try {
505
+ this.entered = true;
506
+ this.reinitializeState();
507
+ this.doEncode(object, 1);
508
+ return this.bytes.slice(0, this.pos);
509
+ }
510
+ finally {
511
+ this.entered = false;
512
+ }
513
+ }
514
+ doEncode(object, depth) {
515
+ if (depth > this.maxDepth) {
516
+ throw new Error(`Too deep objects in depth ${depth}`);
517
+ }
518
+ if (object == null) {
519
+ this.encodeNil();
520
+ }
521
+ else if (typeof object === "boolean") {
522
+ this.encodeBoolean(object);
523
+ }
524
+ else if (typeof object === "number") {
525
+ if (!this.forceIntegerToFloat) {
526
+ this.encodeNumber(object);
527
+ }
528
+ else {
529
+ this.encodeNumberAsFloat(object);
530
+ }
531
+ }
532
+ else if (typeof object === "string") {
533
+ this.encodeString(object);
534
+ }
535
+ else if (this.useBigInt64 && typeof object === "bigint") {
536
+ this.encodeBigInt64(object);
537
+ }
538
+ else {
539
+ this.encodeObject(object, depth);
540
+ }
541
+ }
542
+ ensureBufferSizeToWrite(sizeToWrite) {
543
+ const requiredSize = this.pos + sizeToWrite;
544
+ if (this.view.byteLength < requiredSize) {
545
+ this.resizeBuffer(requiredSize * 2);
546
+ }
547
+ }
548
+ resizeBuffer(newSize) {
549
+ const newBuffer = new ArrayBuffer(newSize);
550
+ const newBytes = new Uint8Array(newBuffer);
551
+ const newView = new DataView(newBuffer);
552
+ newBytes.set(this.bytes);
553
+ this.view = newView;
554
+ this.bytes = newBytes;
555
+ }
556
+ encodeNil() {
557
+ this.writeU8(0xc0);
558
+ }
559
+ encodeBoolean(object) {
560
+ if (object === false) {
561
+ this.writeU8(0xc2);
562
+ }
563
+ else {
564
+ this.writeU8(0xc3);
565
+ }
566
+ }
567
+ encodeNumber(object) {
568
+ if (!this.forceIntegerToFloat && Number.isSafeInteger(object)) {
569
+ if (object >= 0) {
570
+ if (object < 0x80) {
571
+ // positive fixint
572
+ this.writeU8(object);
573
+ }
574
+ else if (object < 0x100) {
575
+ // uint 8
576
+ this.writeU8(0xcc);
577
+ this.writeU8(object);
578
+ }
579
+ else if (object < 0x10000) {
580
+ // uint 16
581
+ this.writeU8(0xcd);
582
+ this.writeU16(object);
583
+ }
584
+ else if (object < 0x100000000) {
585
+ // uint 32
586
+ this.writeU8(0xce);
587
+ this.writeU32(object);
588
+ }
589
+ else if (!this.useBigInt64) {
590
+ // uint 64
591
+ this.writeU8(0xcf);
592
+ this.writeU64(object);
593
+ }
594
+ else {
595
+ this.encodeNumberAsFloat(object);
596
+ }
597
+ }
598
+ else {
599
+ if (object >= -32) {
600
+ // negative fixint
601
+ this.writeU8(0xe0 | (object + 0x20));
602
+ }
603
+ else if (object >= -128) {
604
+ // int 8
605
+ this.writeU8(0xd0);
606
+ this.writeI8(object);
607
+ }
608
+ else if (object >= -32768) {
609
+ // int 16
610
+ this.writeU8(0xd1);
611
+ this.writeI16(object);
612
+ }
613
+ else if (object >= -2147483648) {
614
+ // int 32
615
+ this.writeU8(0xd2);
616
+ this.writeI32(object);
617
+ }
618
+ else if (!this.useBigInt64) {
619
+ // int 64
620
+ this.writeU8(0xd3);
621
+ this.writeI64(object);
622
+ }
623
+ else {
624
+ this.encodeNumberAsFloat(object);
625
+ }
626
+ }
627
+ }
628
+ else {
629
+ this.encodeNumberAsFloat(object);
630
+ }
631
+ }
632
+ encodeNumberAsFloat(object) {
633
+ if (this.forceFloat32) {
634
+ // float 32
635
+ this.writeU8(0xca);
636
+ this.writeF32(object);
637
+ }
638
+ else {
639
+ // float 64
640
+ this.writeU8(0xcb);
641
+ this.writeF64(object);
642
+ }
643
+ }
644
+ encodeBigInt64(object) {
645
+ if (object >= BigInt(0)) {
646
+ // uint 64
647
+ this.writeU8(0xcf);
648
+ this.writeBigUint64(object);
649
+ }
650
+ else {
651
+ // int 64
652
+ this.writeU8(0xd3);
653
+ this.writeBigInt64(object);
654
+ }
655
+ }
656
+ writeStringHeader(byteLength) {
657
+ if (byteLength < 32) {
658
+ // fixstr
659
+ this.writeU8(0xa0 + byteLength);
660
+ }
661
+ else if (byteLength < 0x100) {
662
+ // str 8
663
+ this.writeU8(0xd9);
664
+ this.writeU8(byteLength);
665
+ }
666
+ else if (byteLength < 0x10000) {
667
+ // str 16
668
+ this.writeU8(0xda);
669
+ this.writeU16(byteLength);
670
+ }
671
+ else if (byteLength < 0x100000000) {
672
+ // str 32
673
+ this.writeU8(0xdb);
674
+ this.writeU32(byteLength);
675
+ }
676
+ else {
677
+ throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);
678
+ }
679
+ }
680
+ encodeString(object) {
681
+ const maxHeaderSize = 1 + 4;
682
+ const byteLength = utf8Count(object);
683
+ this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
684
+ this.writeStringHeader(byteLength);
685
+ utf8Encode(object, this.bytes, this.pos);
686
+ this.pos += byteLength;
687
+ }
688
+ encodeObject(object, depth) {
689
+ // try to encode objects with custom codec first of non-primitives
690
+ const ext = this.extensionCodec.tryToEncode(object, this.context);
691
+ if (ext != null) {
692
+ this.encodeExtension(ext);
693
+ }
694
+ else if (Array.isArray(object)) {
695
+ this.encodeArray(object, depth);
696
+ }
697
+ else if (ArrayBuffer.isView(object)) {
698
+ this.encodeBinary(object);
699
+ }
700
+ else if (typeof object === "object") {
701
+ this.encodeMap(object, depth);
702
+ }
703
+ else {
704
+ // symbol, function and other special object come here unless extensionCodec handles them.
705
+ throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);
706
+ }
707
+ }
708
+ encodeBinary(object) {
709
+ const size = object.byteLength;
710
+ if (size < 0x100) {
711
+ // bin 8
712
+ this.writeU8(0xc4);
713
+ this.writeU8(size);
714
+ }
715
+ else if (size < 0x10000) {
716
+ // bin 16
717
+ this.writeU8(0xc5);
718
+ this.writeU16(size);
719
+ }
720
+ else if (size < 0x100000000) {
721
+ // bin 32
722
+ this.writeU8(0xc6);
723
+ this.writeU32(size);
724
+ }
725
+ else {
726
+ throw new Error(`Too large binary: ${size}`);
727
+ }
728
+ const bytes = ensureUint8Array(object);
729
+ this.writeU8a(bytes);
730
+ }
731
+ encodeArray(object, depth) {
732
+ const size = object.length;
733
+ if (size < 16) {
734
+ // fixarray
735
+ this.writeU8(0x90 + size);
736
+ }
737
+ else if (size < 0x10000) {
738
+ // array 16
739
+ this.writeU8(0xdc);
740
+ this.writeU16(size);
741
+ }
742
+ else if (size < 0x100000000) {
743
+ // array 32
744
+ this.writeU8(0xdd);
745
+ this.writeU32(size);
746
+ }
747
+ else {
748
+ throw new Error(`Too large array: ${size}`);
749
+ }
750
+ for (const item of object) {
751
+ this.doEncode(item, depth + 1);
752
+ }
753
+ }
754
+ countWithoutUndefined(object, keys) {
755
+ let count = 0;
756
+ for (const key of keys) {
757
+ if (object[key] !== undefined) {
758
+ count++;
759
+ }
760
+ }
761
+ return count;
762
+ }
763
+ encodeMap(object, depth) {
764
+ const keys = Object.keys(object);
765
+ if (this.sortKeys) {
766
+ keys.sort();
767
+ }
768
+ const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
769
+ if (size < 16) {
770
+ // fixmap
771
+ this.writeU8(0x80 + size);
772
+ }
773
+ else if (size < 0x10000) {
774
+ // map 16
775
+ this.writeU8(0xde);
776
+ this.writeU16(size);
777
+ }
778
+ else if (size < 0x100000000) {
779
+ // map 32
780
+ this.writeU8(0xdf);
781
+ this.writeU32(size);
782
+ }
783
+ else {
784
+ throw new Error(`Too large map object: ${size}`);
785
+ }
786
+ for (const key of keys) {
787
+ const value = object[key];
788
+ if (!(this.ignoreUndefined && value === undefined)) {
789
+ this.encodeString(key);
790
+ this.doEncode(value, depth + 1);
791
+ }
792
+ }
793
+ }
794
+ encodeExtension(ext) {
795
+ if (typeof ext.data === "function") {
796
+ const data = ext.data(this.pos + 6);
797
+ const size = data.length;
798
+ if (size >= 0x100000000) {
799
+ throw new Error(`Too large extension object: ${size}`);
800
+ }
801
+ this.writeU8(0xc9);
802
+ this.writeU32(size);
803
+ this.writeI8(ext.type);
804
+ this.writeU8a(data);
805
+ return;
806
+ }
807
+ const size = ext.data.length;
808
+ if (size === 1) {
809
+ // fixext 1
810
+ this.writeU8(0xd4);
811
+ }
812
+ else if (size === 2) {
813
+ // fixext 2
814
+ this.writeU8(0xd5);
815
+ }
816
+ else if (size === 4) {
817
+ // fixext 4
818
+ this.writeU8(0xd6);
819
+ }
820
+ else if (size === 8) {
821
+ // fixext 8
822
+ this.writeU8(0xd7);
823
+ }
824
+ else if (size === 16) {
825
+ // fixext 16
826
+ this.writeU8(0xd8);
827
+ }
828
+ else if (size < 0x100) {
829
+ // ext 8
830
+ this.writeU8(0xc7);
831
+ this.writeU8(size);
832
+ }
833
+ else if (size < 0x10000) {
834
+ // ext 16
835
+ this.writeU8(0xc8);
836
+ this.writeU16(size);
837
+ }
838
+ else if (size < 0x100000000) {
839
+ // ext 32
840
+ this.writeU8(0xc9);
841
+ this.writeU32(size);
842
+ }
843
+ else {
844
+ throw new Error(`Too large extension object: ${size}`);
845
+ }
846
+ this.writeI8(ext.type);
847
+ this.writeU8a(ext.data);
848
+ }
849
+ writeU8(value) {
850
+ this.ensureBufferSizeToWrite(1);
851
+ this.view.setUint8(this.pos, value);
852
+ this.pos++;
853
+ }
854
+ writeU8a(values) {
855
+ const size = values.length;
856
+ this.ensureBufferSizeToWrite(size);
857
+ this.bytes.set(values, this.pos);
858
+ this.pos += size;
859
+ }
860
+ writeI8(value) {
861
+ this.ensureBufferSizeToWrite(1);
862
+ this.view.setInt8(this.pos, value);
863
+ this.pos++;
864
+ }
865
+ writeU16(value) {
866
+ this.ensureBufferSizeToWrite(2);
867
+ this.view.setUint16(this.pos, value);
868
+ this.pos += 2;
869
+ }
870
+ writeI16(value) {
871
+ this.ensureBufferSizeToWrite(2);
872
+ this.view.setInt16(this.pos, value);
873
+ this.pos += 2;
874
+ }
875
+ writeU32(value) {
876
+ this.ensureBufferSizeToWrite(4);
877
+ this.view.setUint32(this.pos, value);
878
+ this.pos += 4;
879
+ }
880
+ writeI32(value) {
881
+ this.ensureBufferSizeToWrite(4);
882
+ this.view.setInt32(this.pos, value);
883
+ this.pos += 4;
884
+ }
885
+ writeF32(value) {
886
+ this.ensureBufferSizeToWrite(4);
887
+ this.view.setFloat32(this.pos, value);
888
+ this.pos += 4;
889
+ }
890
+ writeF64(value) {
891
+ this.ensureBufferSizeToWrite(8);
892
+ this.view.setFloat64(this.pos, value);
893
+ this.pos += 8;
894
+ }
895
+ writeU64(value) {
896
+ this.ensureBufferSizeToWrite(8);
897
+ setUint64(this.view, this.pos, value);
898
+ this.pos += 8;
899
+ }
900
+ writeI64(value) {
901
+ this.ensureBufferSizeToWrite(8);
902
+ setInt64(this.view, this.pos, value);
903
+ this.pos += 8;
904
+ }
905
+ writeBigUint64(value) {
906
+ this.ensureBufferSizeToWrite(8);
907
+ this.view.setBigUint64(this.pos, value);
908
+ this.pos += 8;
909
+ }
910
+ writeBigInt64(value) {
911
+ this.ensureBufferSizeToWrite(8);
912
+ this.view.setBigInt64(this.pos, value);
913
+ this.pos += 8;
914
+ }
915
+ }
916
+
917
+ /**
918
+ * It encodes `value` in the MessagePack format and
919
+ * returns a byte buffer.
920
+ *
921
+ * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.
922
+ */
923
+ function encode(value, options) {
924
+ const encoder = new Encoder(options);
925
+ return encoder.encodeSharedRef(value);
926
+ }
927
+
928
+ function prettyByte(byte) {
929
+ return `${byte < 0 ? "-" : ""}0x${Math.abs(byte).toString(16).padStart(2, "0")}`;
930
+ }
931
+
932
+ const DEFAULT_MAX_KEY_LENGTH = 16;
933
+ const DEFAULT_MAX_LENGTH_PER_KEY = 16;
934
+ class CachedKeyDecoder {
935
+ hit = 0;
936
+ miss = 0;
937
+ caches;
938
+ maxKeyLength;
939
+ maxLengthPerKey;
940
+ constructor(maxKeyLength = DEFAULT_MAX_KEY_LENGTH, maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {
941
+ this.maxKeyLength = maxKeyLength;
942
+ this.maxLengthPerKey = maxLengthPerKey;
943
+ // avoid `new Array(N)`, which makes a sparse array,
944
+ // because a sparse array is typically slower than a non-sparse array.
945
+ this.caches = [];
946
+ for (let i = 0; i < this.maxKeyLength; i++) {
947
+ this.caches.push([]);
948
+ }
949
+ }
950
+ canBeCached(byteLength) {
951
+ return byteLength > 0 && byteLength <= this.maxKeyLength;
952
+ }
953
+ find(bytes, inputOffset, byteLength) {
954
+ const records = this.caches[byteLength - 1];
955
+ FIND_CHUNK: for (const record of records) {
956
+ const recordBytes = record.bytes;
957
+ for (let j = 0; j < byteLength; j++) {
958
+ if (recordBytes[j] !== bytes[inputOffset + j]) {
959
+ continue FIND_CHUNK;
960
+ }
961
+ }
962
+ return record.str;
963
+ }
964
+ return null;
965
+ }
966
+ store(bytes, value) {
967
+ const records = this.caches[bytes.length - 1];
968
+ const record = { bytes, str: value };
969
+ if (records.length >= this.maxLengthPerKey) {
970
+ // `records` are full!
971
+ // Set `record` to an arbitrary position.
972
+ records[(Math.random() * records.length) | 0] = record;
973
+ }
974
+ else {
975
+ records.push(record);
976
+ }
977
+ }
978
+ decode(bytes, inputOffset, byteLength) {
979
+ const cachedValue = this.find(bytes, inputOffset, byteLength);
980
+ if (cachedValue != null) {
981
+ this.hit++;
982
+ return cachedValue;
983
+ }
984
+ this.miss++;
985
+ const str = utf8DecodeJs(bytes, inputOffset, byteLength);
986
+ // Ensure to copy a slice of bytes because the bytes may be a NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.
987
+ const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
988
+ this.store(slicedCopyOfBytes, str);
989
+ return str;
990
+ }
991
+ }
992
+
993
+ const STATE_ARRAY = "array";
994
+ const STATE_MAP_KEY = "map_key";
995
+ const STATE_MAP_VALUE = "map_value";
996
+ const mapKeyConverter = (key) => {
997
+ if (typeof key === "string" || typeof key === "number") {
998
+ return key;
999
+ }
1000
+ throw new DecodeError("The type of key must be string or number but " + typeof key);
1001
+ };
1002
+ class StackPool {
1003
+ stack = [];
1004
+ stackHeadPosition = -1;
1005
+ get length() {
1006
+ return this.stackHeadPosition + 1;
1007
+ }
1008
+ top() {
1009
+ return this.stack[this.stackHeadPosition];
1010
+ }
1011
+ pushArrayState(size) {
1012
+ const state = this.getUninitializedStateFromPool();
1013
+ state.type = STATE_ARRAY;
1014
+ state.position = 0;
1015
+ state.size = size;
1016
+ state.array = new Array(size);
1017
+ }
1018
+ pushMapState(size) {
1019
+ const state = this.getUninitializedStateFromPool();
1020
+ state.type = STATE_MAP_KEY;
1021
+ state.readCount = 0;
1022
+ state.size = size;
1023
+ state.map = {};
1024
+ }
1025
+ getUninitializedStateFromPool() {
1026
+ this.stackHeadPosition++;
1027
+ if (this.stackHeadPosition === this.stack.length) {
1028
+ const partialState = {
1029
+ type: undefined,
1030
+ size: 0,
1031
+ array: undefined,
1032
+ position: 0,
1033
+ readCount: 0,
1034
+ map: undefined,
1035
+ key: null,
1036
+ };
1037
+ this.stack.push(partialState);
1038
+ }
1039
+ return this.stack[this.stackHeadPosition];
1040
+ }
1041
+ release(state) {
1042
+ const topStackState = this.stack[this.stackHeadPosition];
1043
+ if (topStackState !== state) {
1044
+ throw new Error("Invalid stack state. Released state is not on top of the stack.");
1045
+ }
1046
+ if (state.type === STATE_ARRAY) {
1047
+ const partialState = state;
1048
+ partialState.size = 0;
1049
+ partialState.array = undefined;
1050
+ partialState.position = 0;
1051
+ partialState.type = undefined;
1052
+ }
1053
+ if (state.type === STATE_MAP_KEY || state.type === STATE_MAP_VALUE) {
1054
+ const partialState = state;
1055
+ partialState.size = 0;
1056
+ partialState.map = undefined;
1057
+ partialState.readCount = 0;
1058
+ partialState.type = undefined;
1059
+ }
1060
+ this.stackHeadPosition--;
1061
+ }
1062
+ reset() {
1063
+ this.stack.length = 0;
1064
+ this.stackHeadPosition = -1;
1065
+ }
1066
+ }
1067
+ const HEAD_BYTE_REQUIRED = -1;
1068
+ const EMPTY_VIEW = new DataView(new ArrayBuffer(0));
1069
+ const EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);
1070
+ try {
1071
+ // IE11: The spec says it should throw RangeError,
1072
+ // IE11: but in IE11 it throws TypeError.
1073
+ EMPTY_VIEW.getInt8(0);
1074
+ }
1075
+ catch (e) {
1076
+ if (!(e instanceof RangeError)) {
1077
+ throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access");
1078
+ }
1079
+ }
1080
+ const MORE_DATA = new RangeError("Insufficient data");
1081
+ const sharedCachedKeyDecoder = new CachedKeyDecoder();
1082
+ class Decoder {
1083
+ extensionCodec;
1084
+ context;
1085
+ useBigInt64;
1086
+ rawStrings;
1087
+ maxStrLength;
1088
+ maxBinLength;
1089
+ maxArrayLength;
1090
+ maxMapLength;
1091
+ maxExtLength;
1092
+ keyDecoder;
1093
+ mapKeyConverter;
1094
+ totalPos = 0;
1095
+ pos = 0;
1096
+ view = EMPTY_VIEW;
1097
+ bytes = EMPTY_BYTES;
1098
+ headByte = HEAD_BYTE_REQUIRED;
1099
+ stack = new StackPool();
1100
+ entered = false;
1101
+ constructor(options) {
1102
+ this.extensionCodec = options?.extensionCodec ?? ExtensionCodec.defaultCodec;
1103
+ this.context = options?.context; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined
1104
+ this.useBigInt64 = options?.useBigInt64 ?? false;
1105
+ this.rawStrings = options?.rawStrings ?? false;
1106
+ this.maxStrLength = options?.maxStrLength ?? UINT32_MAX;
1107
+ this.maxBinLength = options?.maxBinLength ?? UINT32_MAX;
1108
+ this.maxArrayLength = options?.maxArrayLength ?? UINT32_MAX;
1109
+ this.maxMapLength = options?.maxMapLength ?? UINT32_MAX;
1110
+ this.maxExtLength = options?.maxExtLength ?? UINT32_MAX;
1111
+ this.keyDecoder = options?.keyDecoder !== undefined ? options.keyDecoder : sharedCachedKeyDecoder;
1112
+ this.mapKeyConverter = options?.mapKeyConverter ?? mapKeyConverter;
1113
+ }
1114
+ clone() {
1115
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
1116
+ return new Decoder({
1117
+ extensionCodec: this.extensionCodec,
1118
+ context: this.context,
1119
+ useBigInt64: this.useBigInt64,
1120
+ rawStrings: this.rawStrings,
1121
+ maxStrLength: this.maxStrLength,
1122
+ maxBinLength: this.maxBinLength,
1123
+ maxArrayLength: this.maxArrayLength,
1124
+ maxMapLength: this.maxMapLength,
1125
+ maxExtLength: this.maxExtLength,
1126
+ keyDecoder: this.keyDecoder,
1127
+ });
1128
+ }
1129
+ reinitializeState() {
1130
+ this.totalPos = 0;
1131
+ this.headByte = HEAD_BYTE_REQUIRED;
1132
+ this.stack.reset();
1133
+ // view, bytes, and pos will be re-initialized in setBuffer()
1134
+ }
1135
+ setBuffer(buffer) {
1136
+ const bytes = ensureUint8Array(buffer);
1137
+ this.bytes = bytes;
1138
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1139
+ this.pos = 0;
1140
+ }
1141
+ appendBuffer(buffer) {
1142
+ if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {
1143
+ this.setBuffer(buffer);
1144
+ }
1145
+ else {
1146
+ const remainingData = this.bytes.subarray(this.pos);
1147
+ const newData = ensureUint8Array(buffer);
1148
+ // concat remainingData + newData
1149
+ const newBuffer = new Uint8Array(remainingData.length + newData.length);
1150
+ newBuffer.set(remainingData);
1151
+ newBuffer.set(newData, remainingData.length);
1152
+ this.setBuffer(newBuffer);
1153
+ }
1154
+ }
1155
+ hasRemaining(size) {
1156
+ return this.view.byteLength - this.pos >= size;
1157
+ }
1158
+ createExtraByteError(posToShow) {
1159
+ const { view, pos } = this;
1160
+ return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);
1161
+ }
1162
+ /**
1163
+ * @throws {@link DecodeError}
1164
+ * @throws {@link RangeError}
1165
+ */
1166
+ decode(buffer) {
1167
+ if (this.entered) {
1168
+ const instance = this.clone();
1169
+ return instance.decode(buffer);
1170
+ }
1171
+ try {
1172
+ this.entered = true;
1173
+ this.reinitializeState();
1174
+ this.setBuffer(buffer);
1175
+ const object = this.doDecodeSync();
1176
+ if (this.hasRemaining(1)) {
1177
+ throw this.createExtraByteError(this.pos);
1178
+ }
1179
+ return object;
1180
+ }
1181
+ finally {
1182
+ this.entered = false;
1183
+ }
1184
+ }
1185
+ *decodeMulti(buffer) {
1186
+ if (this.entered) {
1187
+ const instance = this.clone();
1188
+ yield* instance.decodeMulti(buffer);
1189
+ return;
1190
+ }
1191
+ try {
1192
+ this.entered = true;
1193
+ this.reinitializeState();
1194
+ this.setBuffer(buffer);
1195
+ while (this.hasRemaining(1)) {
1196
+ yield this.doDecodeSync();
1197
+ }
1198
+ }
1199
+ finally {
1200
+ this.entered = false;
1201
+ }
1202
+ }
1203
+ async decodeAsync(stream) {
1204
+ if (this.entered) {
1205
+ const instance = this.clone();
1206
+ return instance.decodeAsync(stream);
1207
+ }
1208
+ try {
1209
+ this.entered = true;
1210
+ let decoded = false;
1211
+ let object;
1212
+ for await (const buffer of stream) {
1213
+ if (decoded) {
1214
+ this.entered = false;
1215
+ throw this.createExtraByteError(this.totalPos);
1216
+ }
1217
+ this.appendBuffer(buffer);
1218
+ try {
1219
+ object = this.doDecodeSync();
1220
+ decoded = true;
1221
+ }
1222
+ catch (e) {
1223
+ if (!(e instanceof RangeError)) {
1224
+ throw e; // rethrow
1225
+ }
1226
+ // fallthrough
1227
+ }
1228
+ this.totalPos += this.pos;
1229
+ }
1230
+ if (decoded) {
1231
+ if (this.hasRemaining(1)) {
1232
+ throw this.createExtraByteError(this.totalPos);
1233
+ }
1234
+ return object;
1235
+ }
1236
+ const { headByte, pos, totalPos } = this;
1237
+ throw new RangeError(`Insufficient data in parsing ${prettyByte(headByte)} at ${totalPos} (${pos} in the current buffer)`);
1238
+ }
1239
+ finally {
1240
+ this.entered = false;
1241
+ }
1242
+ }
1243
+ decodeArrayStream(stream) {
1244
+ return this.decodeMultiAsync(stream, true);
1245
+ }
1246
+ decodeStream(stream) {
1247
+ return this.decodeMultiAsync(stream, false);
1248
+ }
1249
+ async *decodeMultiAsync(stream, isArray) {
1250
+ if (this.entered) {
1251
+ const instance = this.clone();
1252
+ yield* instance.decodeMultiAsync(stream, isArray);
1253
+ return;
1254
+ }
1255
+ try {
1256
+ this.entered = true;
1257
+ let isArrayHeaderRequired = isArray;
1258
+ let arrayItemsLeft = -1;
1259
+ for await (const buffer of stream) {
1260
+ if (isArray && arrayItemsLeft === 0) {
1261
+ throw this.createExtraByteError(this.totalPos);
1262
+ }
1263
+ this.appendBuffer(buffer);
1264
+ if (isArrayHeaderRequired) {
1265
+ arrayItemsLeft = this.readArraySize();
1266
+ isArrayHeaderRequired = false;
1267
+ this.complete();
1268
+ }
1269
+ try {
1270
+ while (true) {
1271
+ yield this.doDecodeSync();
1272
+ if (--arrayItemsLeft === 0) {
1273
+ break;
1274
+ }
1275
+ }
1276
+ }
1277
+ catch (e) {
1278
+ if (!(e instanceof RangeError)) {
1279
+ throw e; // rethrow
1280
+ }
1281
+ // fallthrough
1282
+ }
1283
+ this.totalPos += this.pos;
1284
+ }
1285
+ }
1286
+ finally {
1287
+ this.entered = false;
1288
+ }
1289
+ }
1290
+ doDecodeSync() {
1291
+ DECODE: while (true) {
1292
+ const headByte = this.readHeadByte();
1293
+ let object;
1294
+ if (headByte >= 0xe0) {
1295
+ // negative fixint (111x xxxx) 0xe0 - 0xff
1296
+ object = headByte - 0x100;
1297
+ }
1298
+ else if (headByte < 0xc0) {
1299
+ if (headByte < 0x80) {
1300
+ // positive fixint (0xxx xxxx) 0x00 - 0x7f
1301
+ object = headByte;
1302
+ }
1303
+ else if (headByte < 0x90) {
1304
+ // fixmap (1000 xxxx) 0x80 - 0x8f
1305
+ const size = headByte - 0x80;
1306
+ if (size !== 0) {
1307
+ this.pushMapState(size);
1308
+ this.complete();
1309
+ continue DECODE;
1310
+ }
1311
+ else {
1312
+ object = {};
1313
+ }
1314
+ }
1315
+ else if (headByte < 0xa0) {
1316
+ // fixarray (1001 xxxx) 0x90 - 0x9f
1317
+ const size = headByte - 0x90;
1318
+ if (size !== 0) {
1319
+ this.pushArrayState(size);
1320
+ this.complete();
1321
+ continue DECODE;
1322
+ }
1323
+ else {
1324
+ object = [];
1325
+ }
1326
+ }
1327
+ else {
1328
+ // fixstr (101x xxxx) 0xa0 - 0xbf
1329
+ const byteLength = headByte - 0xa0;
1330
+ object = this.decodeString(byteLength, 0);
1331
+ }
1332
+ }
1333
+ else if (headByte === 0xc0) {
1334
+ // nil
1335
+ object = null;
1336
+ }
1337
+ else if (headByte === 0xc2) {
1338
+ // false
1339
+ object = false;
1340
+ }
1341
+ else if (headByte === 0xc3) {
1342
+ // true
1343
+ object = true;
1344
+ }
1345
+ else if (headByte === 0xca) {
1346
+ // float 32
1347
+ object = this.readF32();
1348
+ }
1349
+ else if (headByte === 0xcb) {
1350
+ // float 64
1351
+ object = this.readF64();
1352
+ }
1353
+ else if (headByte === 0xcc) {
1354
+ // uint 8
1355
+ object = this.readU8();
1356
+ }
1357
+ else if (headByte === 0xcd) {
1358
+ // uint 16
1359
+ object = this.readU16();
1360
+ }
1361
+ else if (headByte === 0xce) {
1362
+ // uint 32
1363
+ object = this.readU32();
1364
+ }
1365
+ else if (headByte === 0xcf) {
1366
+ // uint 64
1367
+ if (this.useBigInt64) {
1368
+ object = this.readU64AsBigInt();
1369
+ }
1370
+ else {
1371
+ object = this.readU64();
1372
+ }
1373
+ }
1374
+ else if (headByte === 0xd0) {
1375
+ // int 8
1376
+ object = this.readI8();
1377
+ }
1378
+ else if (headByte === 0xd1) {
1379
+ // int 16
1380
+ object = this.readI16();
1381
+ }
1382
+ else if (headByte === 0xd2) {
1383
+ // int 32
1384
+ object = this.readI32();
1385
+ }
1386
+ else if (headByte === 0xd3) {
1387
+ // int 64
1388
+ if (this.useBigInt64) {
1389
+ object = this.readI64AsBigInt();
1390
+ }
1391
+ else {
1392
+ object = this.readI64();
1393
+ }
1394
+ }
1395
+ else if (headByte === 0xd9) {
1396
+ // str 8
1397
+ const byteLength = this.lookU8();
1398
+ object = this.decodeString(byteLength, 1);
1399
+ }
1400
+ else if (headByte === 0xda) {
1401
+ // str 16
1402
+ const byteLength = this.lookU16();
1403
+ object = this.decodeString(byteLength, 2);
1404
+ }
1405
+ else if (headByte === 0xdb) {
1406
+ // str 32
1407
+ const byteLength = this.lookU32();
1408
+ object = this.decodeString(byteLength, 4);
1409
+ }
1410
+ else if (headByte === 0xdc) {
1411
+ // array 16
1412
+ const size = this.readU16();
1413
+ if (size !== 0) {
1414
+ this.pushArrayState(size);
1415
+ this.complete();
1416
+ continue DECODE;
1417
+ }
1418
+ else {
1419
+ object = [];
1420
+ }
1421
+ }
1422
+ else if (headByte === 0xdd) {
1423
+ // array 32
1424
+ const size = this.readU32();
1425
+ if (size !== 0) {
1426
+ this.pushArrayState(size);
1427
+ this.complete();
1428
+ continue DECODE;
1429
+ }
1430
+ else {
1431
+ object = [];
1432
+ }
1433
+ }
1434
+ else if (headByte === 0xde) {
1435
+ // map 16
1436
+ const size = this.readU16();
1437
+ if (size !== 0) {
1438
+ this.pushMapState(size);
1439
+ this.complete();
1440
+ continue DECODE;
1441
+ }
1442
+ else {
1443
+ object = {};
1444
+ }
1445
+ }
1446
+ else if (headByte === 0xdf) {
1447
+ // map 32
1448
+ const size = this.readU32();
1449
+ if (size !== 0) {
1450
+ this.pushMapState(size);
1451
+ this.complete();
1452
+ continue DECODE;
1453
+ }
1454
+ else {
1455
+ object = {};
1456
+ }
1457
+ }
1458
+ else if (headByte === 0xc4) {
1459
+ // bin 8
1460
+ const size = this.lookU8();
1461
+ object = this.decodeBinary(size, 1);
1462
+ }
1463
+ else if (headByte === 0xc5) {
1464
+ // bin 16
1465
+ const size = this.lookU16();
1466
+ object = this.decodeBinary(size, 2);
1467
+ }
1468
+ else if (headByte === 0xc6) {
1469
+ // bin 32
1470
+ const size = this.lookU32();
1471
+ object = this.decodeBinary(size, 4);
1472
+ }
1473
+ else if (headByte === 0xd4) {
1474
+ // fixext 1
1475
+ object = this.decodeExtension(1, 0);
1476
+ }
1477
+ else if (headByte === 0xd5) {
1478
+ // fixext 2
1479
+ object = this.decodeExtension(2, 0);
1480
+ }
1481
+ else if (headByte === 0xd6) {
1482
+ // fixext 4
1483
+ object = this.decodeExtension(4, 0);
1484
+ }
1485
+ else if (headByte === 0xd7) {
1486
+ // fixext 8
1487
+ object = this.decodeExtension(8, 0);
1488
+ }
1489
+ else if (headByte === 0xd8) {
1490
+ // fixext 16
1491
+ object = this.decodeExtension(16, 0);
1492
+ }
1493
+ else if (headByte === 0xc7) {
1494
+ // ext 8
1495
+ const size = this.lookU8();
1496
+ object = this.decodeExtension(size, 1);
1497
+ }
1498
+ else if (headByte === 0xc8) {
1499
+ // ext 16
1500
+ const size = this.lookU16();
1501
+ object = this.decodeExtension(size, 2);
1502
+ }
1503
+ else if (headByte === 0xc9) {
1504
+ // ext 32
1505
+ const size = this.lookU32();
1506
+ object = this.decodeExtension(size, 4);
1507
+ }
1508
+ else {
1509
+ throw new DecodeError(`Unrecognized type byte: ${prettyByte(headByte)}`);
1510
+ }
1511
+ this.complete();
1512
+ const stack = this.stack;
1513
+ while (stack.length > 0) {
1514
+ // arrays and maps
1515
+ const state = stack.top();
1516
+ if (state.type === STATE_ARRAY) {
1517
+ state.array[state.position] = object;
1518
+ state.position++;
1519
+ if (state.position === state.size) {
1520
+ object = state.array;
1521
+ stack.release(state);
1522
+ }
1523
+ else {
1524
+ continue DECODE;
1525
+ }
1526
+ }
1527
+ else if (state.type === STATE_MAP_KEY) {
1528
+ if (object === "__proto__") {
1529
+ throw new DecodeError("The key __proto__ is not allowed");
1530
+ }
1531
+ state.key = this.mapKeyConverter(object);
1532
+ state.type = STATE_MAP_VALUE;
1533
+ continue DECODE;
1534
+ }
1535
+ else {
1536
+ // it must be `state.type === State.MAP_VALUE` here
1537
+ state.map[state.key] = object;
1538
+ state.readCount++;
1539
+ if (state.readCount === state.size) {
1540
+ object = state.map;
1541
+ stack.release(state);
1542
+ }
1543
+ else {
1544
+ state.key = null;
1545
+ state.type = STATE_MAP_KEY;
1546
+ continue DECODE;
1547
+ }
1548
+ }
1549
+ }
1550
+ return object;
1551
+ }
1552
+ }
1553
+ readHeadByte() {
1554
+ if (this.headByte === HEAD_BYTE_REQUIRED) {
1555
+ this.headByte = this.readU8();
1556
+ // console.log("headByte", prettyByte(this.headByte));
1557
+ }
1558
+ return this.headByte;
1559
+ }
1560
+ complete() {
1561
+ this.headByte = HEAD_BYTE_REQUIRED;
1562
+ }
1563
+ readArraySize() {
1564
+ const headByte = this.readHeadByte();
1565
+ switch (headByte) {
1566
+ case 0xdc:
1567
+ return this.readU16();
1568
+ case 0xdd:
1569
+ return this.readU32();
1570
+ default: {
1571
+ if (headByte < 0xa0) {
1572
+ return headByte - 0x90;
1573
+ }
1574
+ else {
1575
+ throw new DecodeError(`Unrecognized array type byte: ${prettyByte(headByte)}`);
1576
+ }
1577
+ }
1578
+ }
1579
+ }
1580
+ pushMapState(size) {
1581
+ if (size > this.maxMapLength) {
1582
+ throw new DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`);
1583
+ }
1584
+ this.stack.pushMapState(size);
1585
+ }
1586
+ pushArrayState(size) {
1587
+ if (size > this.maxArrayLength) {
1588
+ throw new DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`);
1589
+ }
1590
+ this.stack.pushArrayState(size);
1591
+ }
1592
+ decodeString(byteLength, headerOffset) {
1593
+ if (!this.rawStrings || this.stateIsMapKey()) {
1594
+ return this.decodeUtf8String(byteLength, headerOffset);
1595
+ }
1596
+ return this.decodeBinary(byteLength, headerOffset);
1597
+ }
1598
+ /**
1599
+ * @throws {@link RangeError}
1600
+ */
1601
+ decodeUtf8String(byteLength, headerOffset) {
1602
+ if (byteLength > this.maxStrLength) {
1603
+ throw new DecodeError(`Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`);
1604
+ }
1605
+ if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {
1606
+ throw MORE_DATA;
1607
+ }
1608
+ const offset = this.pos + headerOffset;
1609
+ let object;
1610
+ if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {
1611
+ object = this.keyDecoder.decode(this.bytes, offset, byteLength);
1612
+ }
1613
+ else {
1614
+ object = utf8Decode(this.bytes, offset, byteLength);
1615
+ }
1616
+ this.pos += headerOffset + byteLength;
1617
+ return object;
1618
+ }
1619
+ stateIsMapKey() {
1620
+ if (this.stack.length > 0) {
1621
+ const state = this.stack.top();
1622
+ return state.type === STATE_MAP_KEY;
1623
+ }
1624
+ return false;
1625
+ }
1626
+ /**
1627
+ * @throws {@link RangeError}
1628
+ */
1629
+ decodeBinary(byteLength, headOffset) {
1630
+ if (byteLength > this.maxBinLength) {
1631
+ throw new DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);
1632
+ }
1633
+ if (!this.hasRemaining(byteLength + headOffset)) {
1634
+ throw MORE_DATA;
1635
+ }
1636
+ const offset = this.pos + headOffset;
1637
+ const object = this.bytes.subarray(offset, offset + byteLength);
1638
+ this.pos += headOffset + byteLength;
1639
+ return object;
1640
+ }
1641
+ decodeExtension(size, headOffset) {
1642
+ if (size > this.maxExtLength) {
1643
+ throw new DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`);
1644
+ }
1645
+ const extType = this.view.getInt8(this.pos + headOffset);
1646
+ const data = this.decodeBinary(size, headOffset + 1 /* extType */);
1647
+ return this.extensionCodec.decode(data, extType, this.context);
1648
+ }
1649
+ lookU8() {
1650
+ return this.view.getUint8(this.pos);
1651
+ }
1652
+ lookU16() {
1653
+ return this.view.getUint16(this.pos);
1654
+ }
1655
+ lookU32() {
1656
+ return this.view.getUint32(this.pos);
1657
+ }
1658
+ readU8() {
1659
+ const value = this.view.getUint8(this.pos);
1660
+ this.pos++;
1661
+ return value;
1662
+ }
1663
+ readI8() {
1664
+ const value = this.view.getInt8(this.pos);
1665
+ this.pos++;
1666
+ return value;
1667
+ }
1668
+ readU16() {
1669
+ const value = this.view.getUint16(this.pos);
1670
+ this.pos += 2;
1671
+ return value;
1672
+ }
1673
+ readI16() {
1674
+ const value = this.view.getInt16(this.pos);
1675
+ this.pos += 2;
1676
+ return value;
1677
+ }
1678
+ readU32() {
1679
+ const value = this.view.getUint32(this.pos);
1680
+ this.pos += 4;
1681
+ return value;
1682
+ }
1683
+ readI32() {
1684
+ const value = this.view.getInt32(this.pos);
1685
+ this.pos += 4;
1686
+ return value;
1687
+ }
1688
+ readU64() {
1689
+ const value = getUint64(this.view, this.pos);
1690
+ this.pos += 8;
1691
+ return value;
1692
+ }
1693
+ readI64() {
1694
+ const value = getInt64(this.view, this.pos);
1695
+ this.pos += 8;
1696
+ return value;
1697
+ }
1698
+ readU64AsBigInt() {
1699
+ const value = this.view.getBigUint64(this.pos);
1700
+ this.pos += 8;
1701
+ return value;
1702
+ }
1703
+ readI64AsBigInt() {
1704
+ const value = this.view.getBigInt64(this.pos);
1705
+ this.pos += 8;
1706
+ return value;
1707
+ }
1708
+ readF32() {
1709
+ const value = this.view.getFloat32(this.pos);
1710
+ this.pos += 4;
1711
+ return value;
1712
+ }
1713
+ readF64() {
1714
+ const value = this.view.getFloat64(this.pos);
1715
+ this.pos += 8;
1716
+ return value;
1717
+ }
1718
+ }
1719
+
1720
+ /**
1721
+ * It decodes a single MessagePack object in a buffer.
1722
+ *
1723
+ * This is a synchronous decoding function.
1724
+ * See other variants for asynchronous decoding: {@link decodeAsync}, {@link decodeMultiStream}, or {@link decodeArrayStream}.
1725
+ *
1726
+ * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.
1727
+ * @throws {@link DecodeError} if the buffer contains invalid data.
1728
+ */
1729
+ function decode(buffer, options) {
1730
+ const decoder = new Decoder(options);
1731
+ return decoder.decode(buffer);
1732
+ }
1733
+
1734
+ const OOXEvent = {
1735
+ CONNECT: 'open',
1736
+ DISCONNECT: 'close',
1737
+ ERROR: 'socket:error',
1738
+ CALL: 'call',
1739
+ READY: 'oox:ready',
1740
+ ENABLED: 'oox:enabled',
1741
+ DISABLED: 'oox:disabled',
1742
+ REGISTRY_SYNC_CONNECTIONS: 'oox:registry:sync_connections',
1743
+ REGISTRY_SUBSCRIBE: 'oox:registry:subscribe',
1744
+ REGISTRY_NOTIFY: 'oox:registry:notify',
1745
+ };
1746
+ function isWebSocketURL(url) {
1747
+ if ('string' === typeof url) {
1748
+ return /^wss?:\/\/.+$/.test(url);
1749
+ }
1750
+ else {
1751
+ return url.protocol === 'ws:' || url.protocol === 'wss:';
1752
+ }
1753
+ }
1754
+ function genWebSocketURL(url) {
1755
+ // :6000
1756
+ if (url.startsWith(':'))
1757
+ url = 'ws://localhost' + url;
1758
+ // 127.0.0.1:6000
1759
+ if (!/^\w+?:\/.+$/.test(url))
1760
+ url = 'ws://' + url;
1761
+ const urlObject = new URL(url);
1762
+ // :8000 => :8000/ws
1763
+ const notSetPath = !urlObject.pathname || (urlObject.pathname === '/'
1764
+ && !url.endsWith('/')
1765
+ && !urlObject.search
1766
+ && !urlObject.hash);
1767
+ if (notSetPath) {
1768
+ urlObject.pathname = '/ws';
1769
+ }
1770
+ if (urlObject.protocol !== 'wss:') {
1771
+ if (urlObject.port === '443')
1772
+ urlObject.protocol = 'wss:';
1773
+ else
1774
+ urlObject.protocol = 'ws:';
1775
+ }
1776
+ return urlObject;
1777
+ }
1778
+
1779
+ function getDefaultExportFromCjs (x) {
1780
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1781
+ }
1782
+
1783
+ var events = {exports: {}};
1784
+
1785
+ var hasRequiredEvents;
1786
+
1787
+ function requireEvents () {
1788
+ if (hasRequiredEvents) return events.exports;
1789
+ hasRequiredEvents = 1;
1790
+
1791
+ var R = typeof Reflect === 'object' ? Reflect : null;
1792
+ var ReflectApply = R && typeof R.apply === 'function'
1793
+ ? R.apply
1794
+ : function ReflectApply(target, receiver, args) {
1795
+ return Function.prototype.apply.call(target, receiver, args);
1796
+ };
1797
+
1798
+ var ReflectOwnKeys;
1799
+ if (R && typeof R.ownKeys === 'function') {
1800
+ ReflectOwnKeys = R.ownKeys;
1801
+ } else if (Object.getOwnPropertySymbols) {
1802
+ ReflectOwnKeys = function ReflectOwnKeys(target) {
1803
+ return Object.getOwnPropertyNames(target)
1804
+ .concat(Object.getOwnPropertySymbols(target));
1805
+ };
1806
+ } else {
1807
+ ReflectOwnKeys = function ReflectOwnKeys(target) {
1808
+ return Object.getOwnPropertyNames(target);
1809
+ };
1810
+ }
1811
+
1812
+ function ProcessEmitWarning(warning) {
1813
+ if (console && console.warn) console.warn(warning);
1814
+ }
1815
+
1816
+ var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
1817
+ return value !== value;
1818
+ };
1819
+
1820
+ function EventEmitter() {
1821
+ EventEmitter.init.call(this);
1822
+ }
1823
+ events.exports = EventEmitter;
1824
+ events.exports.once = once;
1825
+
1826
+ // Backwards-compat with node 0.10.x
1827
+ EventEmitter.EventEmitter = EventEmitter;
1828
+
1829
+ EventEmitter.prototype._events = undefined;
1830
+ EventEmitter.prototype._eventsCount = 0;
1831
+ EventEmitter.prototype._maxListeners = undefined;
1832
+
1833
+ // By default EventEmitters will print a warning if more than 10 listeners are
1834
+ // added to it. This is a useful default which helps finding memory leaks.
1835
+ var defaultMaxListeners = 10;
1836
+
1837
+ function checkListener(listener) {
1838
+ if (typeof listener !== 'function') {
1839
+ throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
1840
+ }
1841
+ }
1842
+
1843
+ Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
1844
+ enumerable: true,
1845
+ get: function() {
1846
+ return defaultMaxListeners;
1847
+ },
1848
+ set: function(arg) {
1849
+ if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
1850
+ throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
1851
+ }
1852
+ defaultMaxListeners = arg;
1853
+ }
1854
+ });
1855
+
1856
+ EventEmitter.init = function() {
1857
+
1858
+ if (this._events === undefined ||
1859
+ this._events === Object.getPrototypeOf(this)._events) {
1860
+ this._events = Object.create(null);
1861
+ this._eventsCount = 0;
1862
+ }
1863
+
1864
+ this._maxListeners = this._maxListeners || undefined;
1865
+ };
1866
+
1867
+ // Obviously not all Emitters should be limited to 10. This function allows
1868
+ // that to be increased. Set to zero for unlimited.
1869
+ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
1870
+ if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
1871
+ throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
1872
+ }
1873
+ this._maxListeners = n;
1874
+ return this;
1875
+ };
1876
+
1877
+ function _getMaxListeners(that) {
1878
+ if (that._maxListeners === undefined)
1879
+ return EventEmitter.defaultMaxListeners;
1880
+ return that._maxListeners;
1881
+ }
1882
+
1883
+ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
1884
+ return _getMaxListeners(this);
1885
+ };
1886
+
1887
+ EventEmitter.prototype.emit = function emit(type) {
1888
+ var args = [];
1889
+ for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
1890
+ var doError = (type === 'error');
1891
+
1892
+ var events = this._events;
1893
+ if (events !== undefined)
1894
+ doError = (doError && events.error === undefined);
1895
+ else if (!doError)
1896
+ return false;
1897
+
1898
+ // If there is no 'error' event listener then throw.
1899
+ if (doError) {
1900
+ var er;
1901
+ if (args.length > 0)
1902
+ er = args[0];
1903
+ if (er instanceof Error) {
1904
+ // Note: The comments on the `throw` lines are intentional, they show
1905
+ // up in Node's output if this results in an unhandled exception.
1906
+ throw er; // Unhandled 'error' event
1907
+ }
1908
+ // At least give some kind of context to the user
1909
+ var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
1910
+ err.context = er;
1911
+ throw err; // Unhandled 'error' event
1912
+ }
1913
+
1914
+ var handler = events[type];
1915
+
1916
+ if (handler === undefined)
1917
+ return false;
1918
+
1919
+ if (typeof handler === 'function') {
1920
+ ReflectApply(handler, this, args);
1921
+ } else {
1922
+ var len = handler.length;
1923
+ var listeners = arrayClone(handler, len);
1924
+ for (var i = 0; i < len; ++i)
1925
+ ReflectApply(listeners[i], this, args);
1926
+ }
1927
+
1928
+ return true;
1929
+ };
1930
+
1931
+ function _addListener(target, type, listener, prepend) {
1932
+ var m;
1933
+ var events;
1934
+ var existing;
1935
+
1936
+ checkListener(listener);
1937
+
1938
+ events = target._events;
1939
+ if (events === undefined) {
1940
+ events = target._events = Object.create(null);
1941
+ target._eventsCount = 0;
1942
+ } else {
1943
+ // To avoid recursion in the case that type === "newListener"! Before
1944
+ // adding it to the listeners, first emit "newListener".
1945
+ if (events.newListener !== undefined) {
1946
+ target.emit('newListener', type,
1947
+ listener.listener ? listener.listener : listener);
1948
+
1949
+ // Re-assign `events` because a newListener handler could have caused the
1950
+ // this._events to be assigned to a new object
1951
+ events = target._events;
1952
+ }
1953
+ existing = events[type];
1954
+ }
1955
+
1956
+ if (existing === undefined) {
1957
+ // Optimize the case of one listener. Don't need the extra array object.
1958
+ existing = events[type] = listener;
1959
+ ++target._eventsCount;
1960
+ } else {
1961
+ if (typeof existing === 'function') {
1962
+ // Adding the second element, need to change to array.
1963
+ existing = events[type] =
1964
+ prepend ? [listener, existing] : [existing, listener];
1965
+ // If we've already got an array, just append.
1966
+ } else if (prepend) {
1967
+ existing.unshift(listener);
1968
+ } else {
1969
+ existing.push(listener);
1970
+ }
1971
+
1972
+ // Check for listener leak
1973
+ m = _getMaxListeners(target);
1974
+ if (m > 0 && existing.length > m && !existing.warned) {
1975
+ existing.warned = true;
1976
+ // No error code for this since it is a Warning
1977
+ // eslint-disable-next-line no-restricted-syntax
1978
+ var w = new Error('Possible EventEmitter memory leak detected. ' +
1979
+ existing.length + ' ' + String(type) + ' listeners ' +
1980
+ 'added. Use emitter.setMaxListeners() to ' +
1981
+ 'increase limit');
1982
+ w.name = 'MaxListenersExceededWarning';
1983
+ w.emitter = target;
1984
+ w.type = type;
1985
+ w.count = existing.length;
1986
+ ProcessEmitWarning(w);
1987
+ }
1988
+ }
1989
+
1990
+ return target;
1991
+ }
1992
+
1993
+ EventEmitter.prototype.addListener = function addListener(type, listener) {
1994
+ return _addListener(this, type, listener, false);
1995
+ };
1996
+
1997
+ EventEmitter.prototype.on = EventEmitter.prototype.addListener;
1998
+
1999
+ EventEmitter.prototype.prependListener =
2000
+ function prependListener(type, listener) {
2001
+ return _addListener(this, type, listener, true);
2002
+ };
2003
+
2004
+ function onceWrapper() {
2005
+ if (!this.fired) {
2006
+ this.target.removeListener(this.type, this.wrapFn);
2007
+ this.fired = true;
2008
+ if (arguments.length === 0)
2009
+ return this.listener.call(this.target);
2010
+ return this.listener.apply(this.target, arguments);
2011
+ }
2012
+ }
2013
+
2014
+ function _onceWrap(target, type, listener) {
2015
+ var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
2016
+ var wrapped = onceWrapper.bind(state);
2017
+ wrapped.listener = listener;
2018
+ state.wrapFn = wrapped;
2019
+ return wrapped;
2020
+ }
2021
+
2022
+ EventEmitter.prototype.once = function once(type, listener) {
2023
+ checkListener(listener);
2024
+ this.on(type, _onceWrap(this, type, listener));
2025
+ return this;
2026
+ };
2027
+
2028
+ EventEmitter.prototype.prependOnceListener =
2029
+ function prependOnceListener(type, listener) {
2030
+ checkListener(listener);
2031
+ this.prependListener(type, _onceWrap(this, type, listener));
2032
+ return this;
2033
+ };
2034
+
2035
+ // Emits a 'removeListener' event if and only if the listener was removed.
2036
+ EventEmitter.prototype.removeListener =
2037
+ function removeListener(type, listener) {
2038
+ var list, events, position, i, originalListener;
2039
+
2040
+ checkListener(listener);
2041
+
2042
+ events = this._events;
2043
+ if (events === undefined)
2044
+ return this;
2045
+
2046
+ list = events[type];
2047
+ if (list === undefined)
2048
+ return this;
2049
+
2050
+ if (list === listener || list.listener === listener) {
2051
+ if (--this._eventsCount === 0)
2052
+ this._events = Object.create(null);
2053
+ else {
2054
+ delete events[type];
2055
+ if (events.removeListener)
2056
+ this.emit('removeListener', type, list.listener || listener);
2057
+ }
2058
+ } else if (typeof list !== 'function') {
2059
+ position = -1;
2060
+
2061
+ for (i = list.length - 1; i >= 0; i--) {
2062
+ if (list[i] === listener || list[i].listener === listener) {
2063
+ originalListener = list[i].listener;
2064
+ position = i;
2065
+ break;
2066
+ }
2067
+ }
2068
+
2069
+ if (position < 0)
2070
+ return this;
2071
+
2072
+ if (position === 0)
2073
+ list.shift();
2074
+ else {
2075
+ spliceOne(list, position);
2076
+ }
2077
+
2078
+ if (list.length === 1)
2079
+ events[type] = list[0];
2080
+
2081
+ if (events.removeListener !== undefined)
2082
+ this.emit('removeListener', type, originalListener || listener);
2083
+ }
2084
+
2085
+ return this;
2086
+ };
2087
+
2088
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
2089
+
2090
+ EventEmitter.prototype.removeAllListeners =
2091
+ function removeAllListeners(type) {
2092
+ var listeners, events, i;
2093
+
2094
+ events = this._events;
2095
+ if (events === undefined)
2096
+ return this;
2097
+
2098
+ // not listening for removeListener, no need to emit
2099
+ if (events.removeListener === undefined) {
2100
+ if (arguments.length === 0) {
2101
+ this._events = Object.create(null);
2102
+ this._eventsCount = 0;
2103
+ } else if (events[type] !== undefined) {
2104
+ if (--this._eventsCount === 0)
2105
+ this._events = Object.create(null);
2106
+ else
2107
+ delete events[type];
2108
+ }
2109
+ return this;
2110
+ }
2111
+
2112
+ // emit removeListener for all listeners on all events
2113
+ if (arguments.length === 0) {
2114
+ var keys = Object.keys(events);
2115
+ var key;
2116
+ for (i = 0; i < keys.length; ++i) {
2117
+ key = keys[i];
2118
+ if (key === 'removeListener') continue;
2119
+ this.removeAllListeners(key);
2120
+ }
2121
+ this.removeAllListeners('removeListener');
2122
+ this._events = Object.create(null);
2123
+ this._eventsCount = 0;
2124
+ return this;
2125
+ }
2126
+
2127
+ listeners = events[type];
2128
+
2129
+ if (typeof listeners === 'function') {
2130
+ this.removeListener(type, listeners);
2131
+ } else if (listeners !== undefined) {
2132
+ // LIFO order
2133
+ for (i = listeners.length - 1; i >= 0; i--) {
2134
+ this.removeListener(type, listeners[i]);
2135
+ }
2136
+ }
2137
+
2138
+ return this;
2139
+ };
2140
+
2141
+ function _listeners(target, type, unwrap) {
2142
+ var events = target._events;
2143
+
2144
+ if (events === undefined)
2145
+ return [];
2146
+
2147
+ var evlistener = events[type];
2148
+ if (evlistener === undefined)
2149
+ return [];
2150
+
2151
+ if (typeof evlistener === 'function')
2152
+ return unwrap ? [evlistener.listener || evlistener] : [evlistener];
2153
+
2154
+ return unwrap ?
2155
+ unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
2156
+ }
2157
+
2158
+ EventEmitter.prototype.listeners = function listeners(type) {
2159
+ return _listeners(this, type, true);
2160
+ };
2161
+
2162
+ EventEmitter.prototype.rawListeners = function rawListeners(type) {
2163
+ return _listeners(this, type, false);
2164
+ };
2165
+
2166
+ EventEmitter.listenerCount = function(emitter, type) {
2167
+ if (typeof emitter.listenerCount === 'function') {
2168
+ return emitter.listenerCount(type);
2169
+ } else {
2170
+ return listenerCount.call(emitter, type);
2171
+ }
2172
+ };
2173
+
2174
+ EventEmitter.prototype.listenerCount = listenerCount;
2175
+ function listenerCount(type) {
2176
+ var events = this._events;
2177
+
2178
+ if (events !== undefined) {
2179
+ var evlistener = events[type];
2180
+
2181
+ if (typeof evlistener === 'function') {
2182
+ return 1;
2183
+ } else if (evlistener !== undefined) {
2184
+ return evlistener.length;
2185
+ }
2186
+ }
2187
+
2188
+ return 0;
2189
+ }
2190
+
2191
+ EventEmitter.prototype.eventNames = function eventNames() {
2192
+ return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
2193
+ };
2194
+
2195
+ function arrayClone(arr, n) {
2196
+ var copy = new Array(n);
2197
+ for (var i = 0; i < n; ++i)
2198
+ copy[i] = arr[i];
2199
+ return copy;
2200
+ }
2201
+
2202
+ function spliceOne(list, index) {
2203
+ for (; index + 1 < list.length; index++)
2204
+ list[index] = list[index + 1];
2205
+ list.pop();
2206
+ }
2207
+
2208
+ function unwrapListeners(arr) {
2209
+ var ret = new Array(arr.length);
2210
+ for (var i = 0; i < ret.length; ++i) {
2211
+ ret[i] = arr[i].listener || arr[i];
2212
+ }
2213
+ return ret;
2214
+ }
2215
+
2216
+ function once(emitter, name) {
2217
+ return new Promise(function (resolve, reject) {
2218
+ function errorListener(err) {
2219
+ emitter.removeListener(name, resolver);
2220
+ reject(err);
2221
+ }
2222
+
2223
+ function resolver() {
2224
+ if (typeof emitter.removeListener === 'function') {
2225
+ emitter.removeListener('error', errorListener);
2226
+ }
2227
+ resolve([].slice.call(arguments));
2228
+ }
2229
+ eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
2230
+ if (name !== 'error') {
2231
+ addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
2232
+ }
2233
+ });
2234
+ }
2235
+
2236
+ function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
2237
+ if (typeof emitter.on === 'function') {
2238
+ eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
2239
+ }
2240
+ }
2241
+
2242
+ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
2243
+ if (typeof emitter.on === 'function') {
2244
+ if (flags.once) {
2245
+ emitter.once(name, listener);
2246
+ } else {
2247
+ emitter.on(name, listener);
2248
+ }
2249
+ } else if (typeof emitter.addEventListener === 'function') {
2250
+ // EventTarget does not have `error` event semantics like Node
2251
+ // EventEmitters, we do not listen for `error` events here.
2252
+ emitter.addEventListener(name, function wrapListener(arg) {
2253
+ // IE does not have builtin `{ once: true }` support so we
2254
+ // have to do it manually.
2255
+ if (flags.once) {
2256
+ emitter.removeEventListener(name, wrapListener);
2257
+ }
2258
+ listener(arg);
2259
+ });
2260
+ } else {
2261
+ throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
2262
+ }
2263
+ }
2264
+ return events.exports;
2265
+ }
2266
+
2267
+ var eventsExports = requireEvents();
2268
+ var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventsExports);
2269
+
2270
+ const WebsocketEvents = [
2271
+ 'open',
2272
+ 'close',
2273
+ 'error',
2274
+ 'message',
2275
+ ];
2276
+ // 消息Pack编码选项
2277
+ const MessagePackEncodeOptions = {
2278
+ ignoreUndefined: true
2279
+ };
2280
+ // RPC事件类型
2281
+ exports.RPCType = void 0;
2282
+ (function (RPCType) {
2283
+ RPCType[RPCType["Request"] = 1] = "Request";
2284
+ RPCType[RPCType["Response"] = 2] = "Response";
2285
+ })(exports.RPCType || (exports.RPCType = {}));
2286
+ // RPC事件
2287
+ class RPCEvent extends Event {
2288
+ data;
2289
+ constructor(type, data) {
2290
+ super(type);
2291
+ this.data = data;
2292
+ }
2293
+ }
2294
+ // 最大请求ID
2295
+ const MAX_REQUEST_ID = 0xFFFFFFFF;
2296
+ class Socket extends EventEmitter {
2297
+ callbacks = new Map();
2298
+ requestId = 0;
2299
+ eventHub = new EventEmitter();
2300
+ native = null;
2301
+ connected = false;
2302
+ url;
2303
+ protocols;
2304
+ constructor(address, protocols) {
2305
+ super();
2306
+ const mURL = 'string' === typeof address ? genWebSocketURL(address) : address;
2307
+ this.url = mURL;
2308
+ this.protocols = protocols;
2309
+ }
2310
+ isNativeEvent(event) {
2311
+ return WebsocketEvents.includes(event);
2312
+ }
2313
+ off(event, listener) {
2314
+ if (!event) {
2315
+ return super.removeAllListeners();
2316
+ }
2317
+ else if (!listener) {
2318
+ return super.removeAllListeners(event);
2319
+ }
2320
+ else {
2321
+ return super.off(event, listener);
2322
+ }
2323
+ }
2324
+ emit(event, ...args) {
2325
+ if (this.isNativeEvent(event)) {
2326
+ return super.emit(event, ...args);
2327
+ }
2328
+ else {
2329
+ this.rpc(event, ...args);
2330
+ return true;
2331
+ }
2332
+ }
2333
+ /**
2334
+ * 生成自增请求ID
2335
+ */
2336
+ generateRequestId() {
2337
+ // 处理上限翻转
2338
+ if (this.requestId >= MAX_REQUEST_ID) {
2339
+ this.requestId = 0;
2340
+ }
2341
+ return ++this.requestId;
2342
+ }
2343
+ disconnect() {
2344
+ if (!this.native)
2345
+ return;
2346
+ this.connected = false;
2347
+ this.native.close();
2348
+ }
2349
+ connect() {
2350
+ if (this.native)
2351
+ return;
2352
+ this.native = new WebSocket(this.url, this.protocols);
2353
+ this.native.addEventListener('open', () => {
2354
+ this.connected = true;
2355
+ super.emit(OOXEvent.CONNECT);
2356
+ });
2357
+ this.native.addEventListener('close', (event) => {
2358
+ this.connected = false;
2359
+ this.callbacks.clear();
2360
+ super.emit(OOXEvent.DISCONNECT);
2361
+ });
2362
+ this.native.addEventListener('error', (event) => {
2363
+ this.connected = false;
2364
+ this.callbacks.clear();
2365
+ super.emit(OOXEvent.ERROR, new Error('WebSocket error:'));
2366
+ });
2367
+ // 监听消息
2368
+ this.native.addEventListener('message', async (event) => {
2369
+ const isBinary = event.data instanceof Blob;
2370
+ if (isBinary) {
2371
+ const blob = event.data;
2372
+ const arrBuf = await blob.arrayBuffer();
2373
+ const uint8 = new Uint8Array(arrBuf);
2374
+ this.handleMessage(uint8, isBinary);
2375
+ return;
2376
+ }
2377
+ else {
2378
+ this.handleMessage(event.data, isBinary);
2379
+ }
2380
+ });
2381
+ }
2382
+ send(data) {
2383
+ if (!this.native || !this.connected)
2384
+ throw new Error('Socket not connected');
2385
+ this.native.send(data);
2386
+ }
2387
+ /**
2388
+ * 发送RPC消息
2389
+ */
2390
+ sendRPCMessage(message) {
2391
+ if (!this.native || !this.connected)
2392
+ return;
2393
+ const buffer = encode(message, MessagePackEncodeOptions);
2394
+ this.send(buffer);
2395
+ }
2396
+ handleMessage(message, isBinary) {
2397
+ super.emit('message', message, isBinary);
2398
+ if (isBinary) {
2399
+ const data = decode(message);
2400
+ this.handleRPC(data);
2401
+ }
2402
+ }
2403
+ /**
2404
+ * 处理RPC消息
2405
+ */
2406
+ handleRPC(message) {
2407
+ const { type, event, args, id } = message;
2408
+ if (type === exports.RPCType.Request) {
2409
+ if (typeof event !== 'string')
2410
+ return;
2411
+ if (this.isNativeEvent(event))
2412
+ return;
2413
+ const nArgs = Array.isArray(args) ? args : [args];
2414
+ // 触发事件,等待回调函数
2415
+ super.emit(event, ...nArgs, (...returns) => {
2416
+ if (id !== undefined) {
2417
+ // 发送响应消息
2418
+ this.sendRPCMessage({
2419
+ type: exports.RPCType.Response,
2420
+ id,
2421
+ args: returns
2422
+ });
2423
+ }
2424
+ });
2425
+ }
2426
+ else if (type === exports.RPCType.Response && id !== undefined) {
2427
+ const callback = this.callbacks.get(id);
2428
+ if (callback) {
2429
+ this.callbacks.delete(id);
2430
+ const nArgs = Array.isArray(args) ? args : [args];
2431
+ callback(...nArgs);
2432
+ }
2433
+ }
2434
+ }
2435
+ rpc(event, ...args) {
2436
+ let callback;
2437
+ let id;
2438
+ // 检查最后一个参数是否是回调函数
2439
+ if (args.length > 0 && typeof args[args.length - 1] === 'function') {
2440
+ callback = args.pop();
2441
+ id = this.generateRequestId();
2442
+ }
2443
+ // 发送消息
2444
+ this.sendRPCMessage({
2445
+ type: exports.RPCType.Request,
2446
+ event,
2447
+ args,
2448
+ id
2449
+ });
2450
+ // 如果提供了回调函数,使用回调模式
2451
+ if (callback && id !== undefined) {
2452
+ this.callbacks.set(id, callback);
2453
+ }
2454
+ }
2455
+ }
2456
+
2457
+ class WebSocketAdapter extends oox.SampleKeepAliveConnectionAdapter {
2458
+ name = 'ws';
2459
+ OOXEvent = OOXEvent;
2460
+ connectionId = 0;
2461
+ newConnection(identify) {
2462
+ const { id, name } = oox__namespace.config;
2463
+ const headers = {
2464
+ 'x-caller': name,
2465
+ 'x-caller-id': id,
2466
+ };
2467
+ let mURL;
2468
+ const connectionData = {
2469
+ name: 'anonymous',
2470
+ id: String(++this.connectionId),
2471
+ adapter: this.name,
2472
+ ip: '',
2473
+ token: ''
2474
+ };
2475
+ if ('string' === typeof identify) {
2476
+ mURL = genWebSocketURL(identify);
2477
+ }
2478
+ else if (identify instanceof URL) {
2479
+ mURL = identify;
2480
+ }
2481
+ else if (identify.url) {
2482
+ // KeepAliveConnectionData
2483
+ Object.assign(connectionData, identify);
2484
+ mURL = new URL(identify.url);
2485
+ if (identify.token) {
2486
+ headers['x-token'] = identify.token;
2487
+ }
2488
+ }
2489
+ else {
2490
+ throw new Error('identify must be string, URL, or KeepAliveConnectionData');
2491
+ }
2492
+ for (const key in headers) {
2493
+ const val = headers[key];
2494
+ if (val) {
2495
+ mURL.searchParams.append(key, String(val));
2496
+ }
2497
+ }
2498
+ const socket = new Socket(mURL);
2499
+ const connection = new oox.KeepAliveConnection(this, socket, connectionData);
2500
+ return connection;
2501
+ }
2502
+ }
2503
+
2504
+ exports.MAX_REQUEST_ID = MAX_REQUEST_ID;
2505
+ exports.MessagePackEncodeOptions = MessagePackEncodeOptions;
2506
+ exports.OOXEvent = OOXEvent;
2507
+ exports.RPCEvent = RPCEvent;
2508
+ exports.Socket = Socket;
2509
+ exports.WebSocketAdapter = WebSocketAdapter;
2510
+ exports.WebsocketEvents = WebsocketEvents;
2511
+ exports.genWebSocketURL = genWebSocketURL;
2512
+ exports.isWebSocketURL = isWebSocketURL;
2513
+
2514
+ return exports;
2515
+
2516
+ })({}, oox);
2517
+ //# sourceMappingURL=browser.js.map