playsocketjs 2.4.2 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2646 @@
1
+ import { WebSocketServer } from 'ws';
2
+ import * as http from 'node:http';
3
+
4
+ function utf8Count(str) {
5
+ const strLength = str.length;
6
+ let byteLength = 0;
7
+ let pos = 0;
8
+ while (pos < strLength) {
9
+ let value = str.charCodeAt(pos++);
10
+ if ((value & 0xffffff80) === 0) {
11
+ // 1-byte
12
+ byteLength++;
13
+ continue;
14
+ }
15
+ else if ((value & 0xfffff800) === 0) {
16
+ // 2-bytes
17
+ byteLength += 2;
18
+ }
19
+ else {
20
+ // handle surrogate pair
21
+ if (value >= 0xd800 && value <= 0xdbff) {
22
+ // high surrogate
23
+ if (pos < strLength) {
24
+ const extra = str.charCodeAt(pos);
25
+ if ((extra & 0xfc00) === 0xdc00) {
26
+ ++pos;
27
+ value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
28
+ }
29
+ }
30
+ }
31
+ if ((value & 0xffff0000) === 0) {
32
+ // 3-byte
33
+ byteLength += 3;
34
+ }
35
+ else {
36
+ // 4-byte
37
+ byteLength += 4;
38
+ }
39
+ }
40
+ }
41
+ return byteLength;
42
+ }
43
+ function utf8EncodeJs(str, output, outputOffset) {
44
+ const strLength = str.length;
45
+ let offset = outputOffset;
46
+ let pos = 0;
47
+ while (pos < strLength) {
48
+ let value = str.charCodeAt(pos++);
49
+ if ((value & 0xffffff80) === 0) {
50
+ // 1-byte
51
+ output[offset++] = value;
52
+ continue;
53
+ }
54
+ else if ((value & 0xfffff800) === 0) {
55
+ // 2-bytes
56
+ output[offset++] = ((value >> 6) & 0x1f) | 0xc0;
57
+ }
58
+ else {
59
+ // handle surrogate pair
60
+ if (value >= 0xd800 && value <= 0xdbff) {
61
+ // high surrogate
62
+ if (pos < strLength) {
63
+ const extra = str.charCodeAt(pos);
64
+ if ((extra & 0xfc00) === 0xdc00) {
65
+ ++pos;
66
+ value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
67
+ }
68
+ }
69
+ }
70
+ if ((value & 0xffff0000) === 0) {
71
+ // 3-byte
72
+ output[offset++] = ((value >> 12) & 0x0f) | 0xe0;
73
+ output[offset++] = ((value >> 6) & 0x3f) | 0x80;
74
+ }
75
+ else {
76
+ // 4-byte
77
+ output[offset++] = ((value >> 18) & 0x07) | 0xf0;
78
+ output[offset++] = ((value >> 12) & 0x3f) | 0x80;
79
+ output[offset++] = ((value >> 6) & 0x3f) | 0x80;
80
+ }
81
+ }
82
+ output[offset++] = (value & 0x3f) | 0x80;
83
+ }
84
+ }
85
+ // TextEncoder and TextDecoder are standardized in whatwg encoding:
86
+ // https://encoding.spec.whatwg.org/
87
+ // and available in all the modern browsers:
88
+ // https://caniuse.com/textencoder
89
+ // They are available in Node.js since v12 LTS as well:
90
+ // https://nodejs.org/api/globals.html#textencoder
91
+ const sharedTextEncoder = new TextEncoder();
92
+ // This threshold should be determined by benchmarking, which might vary in engines and input data.
93
+ // Run `npx ts-node benchmark/encode-string.ts` for details.
94
+ const TEXT_ENCODER_THRESHOLD = 50;
95
+ function utf8EncodeTE(str, output, outputOffset) {
96
+ sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
97
+ }
98
+ function utf8Encode(str, output, outputOffset) {
99
+ if (str.length > TEXT_ENCODER_THRESHOLD) {
100
+ utf8EncodeTE(str, output, outputOffset);
101
+ }
102
+ else {
103
+ utf8EncodeJs(str, output, outputOffset);
104
+ }
105
+ }
106
+ const CHUNK_SIZE = 4096;
107
+ function utf8DecodeJs(bytes, inputOffset, byteLength) {
108
+ let offset = inputOffset;
109
+ const end = offset + byteLength;
110
+ const units = [];
111
+ let result = "";
112
+ while (offset < end) {
113
+ const byte1 = bytes[offset++];
114
+ if ((byte1 & 0x80) === 0) {
115
+ // 1 byte
116
+ units.push(byte1);
117
+ }
118
+ else if ((byte1 & 0xe0) === 0xc0) {
119
+ // 2 bytes
120
+ const byte2 = bytes[offset++] & 0x3f;
121
+ units.push(((byte1 & 0x1f) << 6) | byte2);
122
+ }
123
+ else if ((byte1 & 0xf0) === 0xe0) {
124
+ // 3 bytes
125
+ const byte2 = bytes[offset++] & 0x3f;
126
+ const byte3 = bytes[offset++] & 0x3f;
127
+ units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
128
+ }
129
+ else if ((byte1 & 0xf8) === 0xf0) {
130
+ // 4 bytes
131
+ const byte2 = bytes[offset++] & 0x3f;
132
+ const byte3 = bytes[offset++] & 0x3f;
133
+ const byte4 = bytes[offset++] & 0x3f;
134
+ let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
135
+ if (unit > 0xffff) {
136
+ unit -= 0x10000;
137
+ units.push(((unit >>> 10) & 0x3ff) | 0xd800);
138
+ unit = 0xdc00 | (unit & 0x3ff);
139
+ }
140
+ units.push(unit);
141
+ }
142
+ else {
143
+ units.push(byte1);
144
+ }
145
+ if (units.length >= CHUNK_SIZE) {
146
+ result += String.fromCharCode(...units);
147
+ units.length = 0;
148
+ }
149
+ }
150
+ if (units.length > 0) {
151
+ result += String.fromCharCode(...units);
152
+ }
153
+ return result;
154
+ }
155
+ const sharedTextDecoder = new TextDecoder();
156
+ // This threshold should be determined by benchmarking, which might vary in engines and input data.
157
+ // Run `npx ts-node benchmark/decode-string.ts` for details.
158
+ const TEXT_DECODER_THRESHOLD = 200;
159
+ function utf8DecodeTD(bytes, inputOffset, byteLength) {
160
+ const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
161
+ return sharedTextDecoder.decode(stringBytes);
162
+ }
163
+ function utf8Decode(bytes, inputOffset, byteLength) {
164
+ if (byteLength > TEXT_DECODER_THRESHOLD) {
165
+ return utf8DecodeTD(bytes, inputOffset, byteLength);
166
+ }
167
+ else {
168
+ return utf8DecodeJs(bytes, inputOffset, byteLength);
169
+ }
170
+ }
171
+
172
+ /**
173
+ * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.
174
+ */
175
+ class ExtData {
176
+ constructor(type, data) {
177
+ this.type = type;
178
+ this.data = data;
179
+ }
180
+ }
181
+
182
+ class DecodeError extends Error {
183
+ constructor(message) {
184
+ super(message);
185
+ // fix the prototype chain in a cross-platform way
186
+ const proto = Object.create(DecodeError.prototype);
187
+ Object.setPrototypeOf(this, proto);
188
+ Object.defineProperty(this, "name", {
189
+ configurable: true,
190
+ enumerable: false,
191
+ value: DecodeError.name,
192
+ });
193
+ }
194
+ }
195
+
196
+ // Integer Utility
197
+ const UINT32_MAX = 4294967295;
198
+ // DataView extension to handle int64 / uint64,
199
+ // where the actual range is 53-bits integer (a.k.a. safe integer)
200
+ function setUint64(view, offset, value) {
201
+ const high = value / 4294967296;
202
+ const low = value; // high bits are truncated by DataView
203
+ view.setUint32(offset, high);
204
+ view.setUint32(offset + 4, low);
205
+ }
206
+ function setInt64(view, offset, value) {
207
+ const high = Math.floor(value / 4294967296);
208
+ const low = value; // high bits are truncated by DataView
209
+ view.setUint32(offset, high);
210
+ view.setUint32(offset + 4, low);
211
+ }
212
+ function getInt64(view, offset) {
213
+ const high = view.getInt32(offset);
214
+ const low = view.getUint32(offset + 4);
215
+ return high * 4294967296 + low;
216
+ }
217
+ function getUint64(view, offset) {
218
+ const high = view.getUint32(offset);
219
+ const low = view.getUint32(offset + 4);
220
+ return high * 4294967296 + low;
221
+ }
222
+
223
+ // https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
224
+ const EXT_TIMESTAMP = -1;
225
+ const TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int
226
+ const TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int
227
+ function encodeTimeSpecToTimestamp({ sec, nsec }) {
228
+ if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
229
+ // Here sec >= 0 && nsec >= 0
230
+ if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
231
+ // timestamp 32 = { sec32 (unsigned) }
232
+ const rv = new Uint8Array(4);
233
+ const view = new DataView(rv.buffer);
234
+ view.setUint32(0, sec);
235
+ return rv;
236
+ }
237
+ else {
238
+ // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }
239
+ const secHigh = sec / 0x100000000;
240
+ const secLow = sec & 0xffffffff;
241
+ const rv = new Uint8Array(8);
242
+ const view = new DataView(rv.buffer);
243
+ // nsec30 | secHigh2
244
+ view.setUint32(0, (nsec << 2) | (secHigh & 0x3));
245
+ // secLow32
246
+ view.setUint32(4, secLow);
247
+ return rv;
248
+ }
249
+ }
250
+ else {
251
+ // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
252
+ const rv = new Uint8Array(12);
253
+ const view = new DataView(rv.buffer);
254
+ view.setUint32(0, nsec);
255
+ setInt64(view, 4, sec);
256
+ return rv;
257
+ }
258
+ }
259
+ function encodeDateToTimeSpec(date) {
260
+ const msec = date.getTime();
261
+ const sec = Math.floor(msec / 1e3);
262
+ const nsec = (msec - sec * 1e3) * 1e6;
263
+ // Normalizes { sec, nsec } to ensure nsec is unsigned.
264
+ const nsecInSec = Math.floor(nsec / 1e9);
265
+ return {
266
+ sec: sec + nsecInSec,
267
+ nsec: nsec - nsecInSec * 1e9,
268
+ };
269
+ }
270
+ function encodeTimestampExtension(object) {
271
+ if (object instanceof Date) {
272
+ const timeSpec = encodeDateToTimeSpec(object);
273
+ return encodeTimeSpecToTimestamp(timeSpec);
274
+ }
275
+ else {
276
+ return null;
277
+ }
278
+ }
279
+ function decodeTimestampToTimeSpec(data) {
280
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
281
+ // data may be 32, 64, or 96 bits
282
+ switch (data.byteLength) {
283
+ case 4: {
284
+ // timestamp 32 = { sec32 }
285
+ const sec = view.getUint32(0);
286
+ const nsec = 0;
287
+ return { sec, nsec };
288
+ }
289
+ case 8: {
290
+ // timestamp 64 = { nsec30, sec34 }
291
+ const nsec30AndSecHigh2 = view.getUint32(0);
292
+ const secLow32 = view.getUint32(4);
293
+ const sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;
294
+ const nsec = nsec30AndSecHigh2 >>> 2;
295
+ return { sec, nsec };
296
+ }
297
+ case 12: {
298
+ // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
299
+ const sec = getInt64(view, 4);
300
+ const nsec = view.getUint32(0);
301
+ return { sec, nsec };
302
+ }
303
+ default:
304
+ throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);
305
+ }
306
+ }
307
+ function decodeTimestampExtension(data) {
308
+ const timeSpec = decodeTimestampToTimeSpec(data);
309
+ return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
310
+ }
311
+ const timestampExtension = {
312
+ type: EXT_TIMESTAMP,
313
+ encode: encodeTimestampExtension,
314
+ decode: decodeTimestampExtension,
315
+ };
316
+
317
+ // ExtensionCodec to handle MessagePack extensions
318
+ class ExtensionCodec {
319
+ constructor() {
320
+ // built-in extensions
321
+ this.builtInEncoders = [];
322
+ this.builtInDecoders = [];
323
+ // custom extensions
324
+ this.encoders = [];
325
+ this.decoders = [];
326
+ this.register(timestampExtension);
327
+ }
328
+ register({ type, encode, decode, }) {
329
+ if (type >= 0) {
330
+ // custom extensions
331
+ this.encoders[type] = encode;
332
+ this.decoders[type] = decode;
333
+ }
334
+ else {
335
+ // built-in extensions
336
+ const index = -1 - type;
337
+ this.builtInEncoders[index] = encode;
338
+ this.builtInDecoders[index] = decode;
339
+ }
340
+ }
341
+ tryToEncode(object, context) {
342
+ // built-in extensions
343
+ for (let i = 0; i < this.builtInEncoders.length; i++) {
344
+ const encodeExt = this.builtInEncoders[i];
345
+ if (encodeExt != null) {
346
+ const data = encodeExt(object, context);
347
+ if (data != null) {
348
+ const type = -1 - i;
349
+ return new ExtData(type, data);
350
+ }
351
+ }
352
+ }
353
+ // custom extensions
354
+ for (let i = 0; i < this.encoders.length; i++) {
355
+ const encodeExt = this.encoders[i];
356
+ if (encodeExt != null) {
357
+ const data = encodeExt(object, context);
358
+ if (data != null) {
359
+ const type = i;
360
+ return new ExtData(type, data);
361
+ }
362
+ }
363
+ }
364
+ if (object instanceof ExtData) {
365
+ // to keep ExtData as is
366
+ return object;
367
+ }
368
+ return null;
369
+ }
370
+ decode(data, type, context) {
371
+ const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
372
+ if (decodeExt) {
373
+ return decodeExt(data, type, context);
374
+ }
375
+ else {
376
+ // decode() does not fail, returns ExtData instead.
377
+ return new ExtData(type, data);
378
+ }
379
+ }
380
+ }
381
+ ExtensionCodec.defaultCodec = new ExtensionCodec();
382
+
383
+ function isArrayBufferLike(buffer) {
384
+ return (buffer instanceof ArrayBuffer || (typeof SharedArrayBuffer !== "undefined" && buffer instanceof SharedArrayBuffer));
385
+ }
386
+ function ensureUint8Array(buffer) {
387
+ if (buffer instanceof Uint8Array) {
388
+ return buffer;
389
+ }
390
+ else if (ArrayBuffer.isView(buffer)) {
391
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
392
+ }
393
+ else if (isArrayBufferLike(buffer)) {
394
+ return new Uint8Array(buffer);
395
+ }
396
+ else {
397
+ // ArrayLike<number>
398
+ return Uint8Array.from(buffer);
399
+ }
400
+ }
401
+
402
+ const DEFAULT_MAX_DEPTH = 100;
403
+ const DEFAULT_INITIAL_BUFFER_SIZE = 2048;
404
+ class Encoder {
405
+ constructor(options) {
406
+ this.entered = false;
407
+ this.extensionCodec = options?.extensionCodec ?? ExtensionCodec.defaultCodec;
408
+ this.context = options?.context; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined
409
+ this.useBigInt64 = options?.useBigInt64 ?? false;
410
+ this.maxDepth = options?.maxDepth ?? DEFAULT_MAX_DEPTH;
411
+ this.initialBufferSize = options?.initialBufferSize ?? DEFAULT_INITIAL_BUFFER_SIZE;
412
+ this.sortKeys = options?.sortKeys ?? false;
413
+ this.forceFloat32 = options?.forceFloat32 ?? false;
414
+ this.ignoreUndefined = options?.ignoreUndefined ?? false;
415
+ this.forceIntegerToFloat = options?.forceIntegerToFloat ?? false;
416
+ this.pos = 0;
417
+ this.view = new DataView(new ArrayBuffer(this.initialBufferSize));
418
+ this.bytes = new Uint8Array(this.view.buffer);
419
+ }
420
+ clone() {
421
+ // Because of slightly special argument `context`,
422
+ // type assertion is needed.
423
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
424
+ return new Encoder({
425
+ extensionCodec: this.extensionCodec,
426
+ context: this.context,
427
+ useBigInt64: this.useBigInt64,
428
+ maxDepth: this.maxDepth,
429
+ initialBufferSize: this.initialBufferSize,
430
+ sortKeys: this.sortKeys,
431
+ forceFloat32: this.forceFloat32,
432
+ ignoreUndefined: this.ignoreUndefined,
433
+ forceIntegerToFloat: this.forceIntegerToFloat,
434
+ });
435
+ }
436
+ reinitializeState() {
437
+ this.pos = 0;
438
+ }
439
+ /**
440
+ * 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}.
441
+ *
442
+ * @returns Encodes the object and returns a shared reference the encoder's internal buffer.
443
+ */
444
+ encodeSharedRef(object) {
445
+ if (this.entered) {
446
+ const instance = this.clone();
447
+ return instance.encodeSharedRef(object);
448
+ }
449
+ try {
450
+ this.entered = true;
451
+ this.reinitializeState();
452
+ this.doEncode(object, 1);
453
+ return this.bytes.subarray(0, this.pos);
454
+ }
455
+ finally {
456
+ this.entered = false;
457
+ }
458
+ }
459
+ /**
460
+ * @returns Encodes the object and returns a copy of the encoder's internal buffer.
461
+ */
462
+ encode(object) {
463
+ if (this.entered) {
464
+ const instance = this.clone();
465
+ return instance.encode(object);
466
+ }
467
+ try {
468
+ this.entered = true;
469
+ this.reinitializeState();
470
+ this.doEncode(object, 1);
471
+ return this.bytes.slice(0, this.pos);
472
+ }
473
+ finally {
474
+ this.entered = false;
475
+ }
476
+ }
477
+ doEncode(object, depth) {
478
+ if (depth > this.maxDepth) {
479
+ throw new Error(`Too deep objects in depth ${depth}`);
480
+ }
481
+ if (object == null) {
482
+ this.encodeNil();
483
+ }
484
+ else if (typeof object === "boolean") {
485
+ this.encodeBoolean(object);
486
+ }
487
+ else if (typeof object === "number") {
488
+ if (!this.forceIntegerToFloat) {
489
+ this.encodeNumber(object);
490
+ }
491
+ else {
492
+ this.encodeNumberAsFloat(object);
493
+ }
494
+ }
495
+ else if (typeof object === "string") {
496
+ this.encodeString(object);
497
+ }
498
+ else if (this.useBigInt64 && typeof object === "bigint") {
499
+ this.encodeBigInt64(object);
500
+ }
501
+ else {
502
+ this.encodeObject(object, depth);
503
+ }
504
+ }
505
+ ensureBufferSizeToWrite(sizeToWrite) {
506
+ const requiredSize = this.pos + sizeToWrite;
507
+ if (this.view.byteLength < requiredSize) {
508
+ this.resizeBuffer(requiredSize * 2);
509
+ }
510
+ }
511
+ resizeBuffer(newSize) {
512
+ const newBuffer = new ArrayBuffer(newSize);
513
+ const newBytes = new Uint8Array(newBuffer);
514
+ const newView = new DataView(newBuffer);
515
+ newBytes.set(this.bytes);
516
+ this.view = newView;
517
+ this.bytes = newBytes;
518
+ }
519
+ encodeNil() {
520
+ this.writeU8(0xc0);
521
+ }
522
+ encodeBoolean(object) {
523
+ if (object === false) {
524
+ this.writeU8(0xc2);
525
+ }
526
+ else {
527
+ this.writeU8(0xc3);
528
+ }
529
+ }
530
+ encodeNumber(object) {
531
+ if (!this.forceIntegerToFloat && Number.isSafeInteger(object)) {
532
+ if (object >= 0) {
533
+ if (object < 0x80) {
534
+ // positive fixint
535
+ this.writeU8(object);
536
+ }
537
+ else if (object < 0x100) {
538
+ // uint 8
539
+ this.writeU8(0xcc);
540
+ this.writeU8(object);
541
+ }
542
+ else if (object < 0x10000) {
543
+ // uint 16
544
+ this.writeU8(0xcd);
545
+ this.writeU16(object);
546
+ }
547
+ else if (object < 0x100000000) {
548
+ // uint 32
549
+ this.writeU8(0xce);
550
+ this.writeU32(object);
551
+ }
552
+ else if (!this.useBigInt64) {
553
+ // uint 64
554
+ this.writeU8(0xcf);
555
+ this.writeU64(object);
556
+ }
557
+ else {
558
+ this.encodeNumberAsFloat(object);
559
+ }
560
+ }
561
+ else {
562
+ if (object >= -32) {
563
+ // negative fixint
564
+ this.writeU8(0xe0 | (object + 0x20));
565
+ }
566
+ else if (object >= -128) {
567
+ // int 8
568
+ this.writeU8(0xd0);
569
+ this.writeI8(object);
570
+ }
571
+ else if (object >= -32768) {
572
+ // int 16
573
+ this.writeU8(0xd1);
574
+ this.writeI16(object);
575
+ }
576
+ else if (object >= -2147483648) {
577
+ // int 32
578
+ this.writeU8(0xd2);
579
+ this.writeI32(object);
580
+ }
581
+ else if (!this.useBigInt64) {
582
+ // int 64
583
+ this.writeU8(0xd3);
584
+ this.writeI64(object);
585
+ }
586
+ else {
587
+ this.encodeNumberAsFloat(object);
588
+ }
589
+ }
590
+ }
591
+ else {
592
+ this.encodeNumberAsFloat(object);
593
+ }
594
+ }
595
+ encodeNumberAsFloat(object) {
596
+ if (this.forceFloat32) {
597
+ // float 32
598
+ this.writeU8(0xca);
599
+ this.writeF32(object);
600
+ }
601
+ else {
602
+ // float 64
603
+ this.writeU8(0xcb);
604
+ this.writeF64(object);
605
+ }
606
+ }
607
+ encodeBigInt64(object) {
608
+ if (object >= BigInt(0)) {
609
+ // uint 64
610
+ this.writeU8(0xcf);
611
+ this.writeBigUint64(object);
612
+ }
613
+ else {
614
+ // int 64
615
+ this.writeU8(0xd3);
616
+ this.writeBigInt64(object);
617
+ }
618
+ }
619
+ writeStringHeader(byteLength) {
620
+ if (byteLength < 32) {
621
+ // fixstr
622
+ this.writeU8(0xa0 + byteLength);
623
+ }
624
+ else if (byteLength < 0x100) {
625
+ // str 8
626
+ this.writeU8(0xd9);
627
+ this.writeU8(byteLength);
628
+ }
629
+ else if (byteLength < 0x10000) {
630
+ // str 16
631
+ this.writeU8(0xda);
632
+ this.writeU16(byteLength);
633
+ }
634
+ else if (byteLength < 0x100000000) {
635
+ // str 32
636
+ this.writeU8(0xdb);
637
+ this.writeU32(byteLength);
638
+ }
639
+ else {
640
+ throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);
641
+ }
642
+ }
643
+ encodeString(object) {
644
+ const maxHeaderSize = 1 + 4;
645
+ const byteLength = utf8Count(object);
646
+ this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
647
+ this.writeStringHeader(byteLength);
648
+ utf8Encode(object, this.bytes, this.pos);
649
+ this.pos += byteLength;
650
+ }
651
+ encodeObject(object, depth) {
652
+ // try to encode objects with custom codec first of non-primitives
653
+ const ext = this.extensionCodec.tryToEncode(object, this.context);
654
+ if (ext != null) {
655
+ this.encodeExtension(ext);
656
+ }
657
+ else if (Array.isArray(object)) {
658
+ this.encodeArray(object, depth);
659
+ }
660
+ else if (ArrayBuffer.isView(object)) {
661
+ this.encodeBinary(object);
662
+ }
663
+ else if (typeof object === "object") {
664
+ this.encodeMap(object, depth);
665
+ }
666
+ else {
667
+ // symbol, function and other special object come here unless extensionCodec handles them.
668
+ throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);
669
+ }
670
+ }
671
+ encodeBinary(object) {
672
+ const size = object.byteLength;
673
+ if (size < 0x100) {
674
+ // bin 8
675
+ this.writeU8(0xc4);
676
+ this.writeU8(size);
677
+ }
678
+ else if (size < 0x10000) {
679
+ // bin 16
680
+ this.writeU8(0xc5);
681
+ this.writeU16(size);
682
+ }
683
+ else if (size < 0x100000000) {
684
+ // bin 32
685
+ this.writeU8(0xc6);
686
+ this.writeU32(size);
687
+ }
688
+ else {
689
+ throw new Error(`Too large binary: ${size}`);
690
+ }
691
+ const bytes = ensureUint8Array(object);
692
+ this.writeU8a(bytes);
693
+ }
694
+ encodeArray(object, depth) {
695
+ const size = object.length;
696
+ if (size < 16) {
697
+ // fixarray
698
+ this.writeU8(0x90 + size);
699
+ }
700
+ else if (size < 0x10000) {
701
+ // array 16
702
+ this.writeU8(0xdc);
703
+ this.writeU16(size);
704
+ }
705
+ else if (size < 0x100000000) {
706
+ // array 32
707
+ this.writeU8(0xdd);
708
+ this.writeU32(size);
709
+ }
710
+ else {
711
+ throw new Error(`Too large array: ${size}`);
712
+ }
713
+ for (const item of object) {
714
+ this.doEncode(item, depth + 1);
715
+ }
716
+ }
717
+ countWithoutUndefined(object, keys) {
718
+ let count = 0;
719
+ for (const key of keys) {
720
+ if (object[key] !== undefined) {
721
+ count++;
722
+ }
723
+ }
724
+ return count;
725
+ }
726
+ encodeMap(object, depth) {
727
+ const keys = Object.keys(object);
728
+ if (this.sortKeys) {
729
+ keys.sort();
730
+ }
731
+ const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
732
+ if (size < 16) {
733
+ // fixmap
734
+ this.writeU8(0x80 + size);
735
+ }
736
+ else if (size < 0x10000) {
737
+ // map 16
738
+ this.writeU8(0xde);
739
+ this.writeU16(size);
740
+ }
741
+ else if (size < 0x100000000) {
742
+ // map 32
743
+ this.writeU8(0xdf);
744
+ this.writeU32(size);
745
+ }
746
+ else {
747
+ throw new Error(`Too large map object: ${size}`);
748
+ }
749
+ for (const key of keys) {
750
+ const value = object[key];
751
+ if (!(this.ignoreUndefined && value === undefined)) {
752
+ this.encodeString(key);
753
+ this.doEncode(value, depth + 1);
754
+ }
755
+ }
756
+ }
757
+ encodeExtension(ext) {
758
+ if (typeof ext.data === "function") {
759
+ const data = ext.data(this.pos + 6);
760
+ const size = data.length;
761
+ if (size >= 0x100000000) {
762
+ throw new Error(`Too large extension object: ${size}`);
763
+ }
764
+ this.writeU8(0xc9);
765
+ this.writeU32(size);
766
+ this.writeI8(ext.type);
767
+ this.writeU8a(data);
768
+ return;
769
+ }
770
+ const size = ext.data.length;
771
+ if (size === 1) {
772
+ // fixext 1
773
+ this.writeU8(0xd4);
774
+ }
775
+ else if (size === 2) {
776
+ // fixext 2
777
+ this.writeU8(0xd5);
778
+ }
779
+ else if (size === 4) {
780
+ // fixext 4
781
+ this.writeU8(0xd6);
782
+ }
783
+ else if (size === 8) {
784
+ // fixext 8
785
+ this.writeU8(0xd7);
786
+ }
787
+ else if (size === 16) {
788
+ // fixext 16
789
+ this.writeU8(0xd8);
790
+ }
791
+ else if (size < 0x100) {
792
+ // ext 8
793
+ this.writeU8(0xc7);
794
+ this.writeU8(size);
795
+ }
796
+ else if (size < 0x10000) {
797
+ // ext 16
798
+ this.writeU8(0xc8);
799
+ this.writeU16(size);
800
+ }
801
+ else if (size < 0x100000000) {
802
+ // ext 32
803
+ this.writeU8(0xc9);
804
+ this.writeU32(size);
805
+ }
806
+ else {
807
+ throw new Error(`Too large extension object: ${size}`);
808
+ }
809
+ this.writeI8(ext.type);
810
+ this.writeU8a(ext.data);
811
+ }
812
+ writeU8(value) {
813
+ this.ensureBufferSizeToWrite(1);
814
+ this.view.setUint8(this.pos, value);
815
+ this.pos++;
816
+ }
817
+ writeU8a(values) {
818
+ const size = values.length;
819
+ this.ensureBufferSizeToWrite(size);
820
+ this.bytes.set(values, this.pos);
821
+ this.pos += size;
822
+ }
823
+ writeI8(value) {
824
+ this.ensureBufferSizeToWrite(1);
825
+ this.view.setInt8(this.pos, value);
826
+ this.pos++;
827
+ }
828
+ writeU16(value) {
829
+ this.ensureBufferSizeToWrite(2);
830
+ this.view.setUint16(this.pos, value);
831
+ this.pos += 2;
832
+ }
833
+ writeI16(value) {
834
+ this.ensureBufferSizeToWrite(2);
835
+ this.view.setInt16(this.pos, value);
836
+ this.pos += 2;
837
+ }
838
+ writeU32(value) {
839
+ this.ensureBufferSizeToWrite(4);
840
+ this.view.setUint32(this.pos, value);
841
+ this.pos += 4;
842
+ }
843
+ writeI32(value) {
844
+ this.ensureBufferSizeToWrite(4);
845
+ this.view.setInt32(this.pos, value);
846
+ this.pos += 4;
847
+ }
848
+ writeF32(value) {
849
+ this.ensureBufferSizeToWrite(4);
850
+ this.view.setFloat32(this.pos, value);
851
+ this.pos += 4;
852
+ }
853
+ writeF64(value) {
854
+ this.ensureBufferSizeToWrite(8);
855
+ this.view.setFloat64(this.pos, value);
856
+ this.pos += 8;
857
+ }
858
+ writeU64(value) {
859
+ this.ensureBufferSizeToWrite(8);
860
+ setUint64(this.view, this.pos, value);
861
+ this.pos += 8;
862
+ }
863
+ writeI64(value) {
864
+ this.ensureBufferSizeToWrite(8);
865
+ setInt64(this.view, this.pos, value);
866
+ this.pos += 8;
867
+ }
868
+ writeBigUint64(value) {
869
+ this.ensureBufferSizeToWrite(8);
870
+ this.view.setBigUint64(this.pos, value);
871
+ this.pos += 8;
872
+ }
873
+ writeBigInt64(value) {
874
+ this.ensureBufferSizeToWrite(8);
875
+ this.view.setBigInt64(this.pos, value);
876
+ this.pos += 8;
877
+ }
878
+ }
879
+
880
+ /**
881
+ * It encodes `value` in the MessagePack format and
882
+ * returns a byte buffer.
883
+ *
884
+ * 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`.
885
+ */
886
+ function encode(value, options) {
887
+ const encoder = new Encoder(options);
888
+ return encoder.encodeSharedRef(value);
889
+ }
890
+
891
+ function prettyByte(byte) {
892
+ return `${byte < 0 ? "-" : ""}0x${Math.abs(byte).toString(16).padStart(2, "0")}`;
893
+ }
894
+
895
+ const DEFAULT_MAX_KEY_LENGTH = 16;
896
+ const DEFAULT_MAX_LENGTH_PER_KEY = 16;
897
+ class CachedKeyDecoder {
898
+ constructor(maxKeyLength = DEFAULT_MAX_KEY_LENGTH, maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {
899
+ this.hit = 0;
900
+ this.miss = 0;
901
+ this.maxKeyLength = maxKeyLength;
902
+ this.maxLengthPerKey = maxLengthPerKey;
903
+ // avoid `new Array(N)`, which makes a sparse array,
904
+ // because a sparse array is typically slower than a non-sparse array.
905
+ this.caches = [];
906
+ for (let i = 0; i < this.maxKeyLength; i++) {
907
+ this.caches.push([]);
908
+ }
909
+ }
910
+ canBeCached(byteLength) {
911
+ return byteLength > 0 && byteLength <= this.maxKeyLength;
912
+ }
913
+ find(bytes, inputOffset, byteLength) {
914
+ const records = this.caches[byteLength - 1];
915
+ FIND_CHUNK: for (const record of records) {
916
+ const recordBytes = record.bytes;
917
+ for (let j = 0; j < byteLength; j++) {
918
+ if (recordBytes[j] !== bytes[inputOffset + j]) {
919
+ continue FIND_CHUNK;
920
+ }
921
+ }
922
+ return record.str;
923
+ }
924
+ return null;
925
+ }
926
+ store(bytes, value) {
927
+ const records = this.caches[bytes.length - 1];
928
+ const record = { bytes, str: value };
929
+ if (records.length >= this.maxLengthPerKey) {
930
+ // `records` are full!
931
+ // Set `record` to an arbitrary position.
932
+ records[(Math.random() * records.length) | 0] = record;
933
+ }
934
+ else {
935
+ records.push(record);
936
+ }
937
+ }
938
+ decode(bytes, inputOffset, byteLength) {
939
+ const cachedValue = this.find(bytes, inputOffset, byteLength);
940
+ if (cachedValue != null) {
941
+ this.hit++;
942
+ return cachedValue;
943
+ }
944
+ this.miss++;
945
+ const str = utf8DecodeJs(bytes, inputOffset, byteLength);
946
+ // 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.
947
+ const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
948
+ this.store(slicedCopyOfBytes, str);
949
+ return str;
950
+ }
951
+ }
952
+
953
+ const STATE_ARRAY = "array";
954
+ const STATE_MAP_KEY = "map_key";
955
+ const STATE_MAP_VALUE = "map_value";
956
+ const mapKeyConverter = (key) => {
957
+ if (typeof key === "string" || typeof key === "number") {
958
+ return key;
959
+ }
960
+ throw new DecodeError("The type of key must be string or number but " + typeof key);
961
+ };
962
+ class StackPool {
963
+ constructor() {
964
+ this.stack = [];
965
+ this.stackHeadPosition = -1;
966
+ }
967
+ get length() {
968
+ return this.stackHeadPosition + 1;
969
+ }
970
+ top() {
971
+ return this.stack[this.stackHeadPosition];
972
+ }
973
+ pushArrayState(size) {
974
+ const state = this.getUninitializedStateFromPool();
975
+ state.type = STATE_ARRAY;
976
+ state.position = 0;
977
+ state.size = size;
978
+ state.array = new Array(size);
979
+ }
980
+ pushMapState(size) {
981
+ const state = this.getUninitializedStateFromPool();
982
+ state.type = STATE_MAP_KEY;
983
+ state.readCount = 0;
984
+ state.size = size;
985
+ state.map = {};
986
+ }
987
+ getUninitializedStateFromPool() {
988
+ this.stackHeadPosition++;
989
+ if (this.stackHeadPosition === this.stack.length) {
990
+ const partialState = {
991
+ type: undefined,
992
+ size: 0,
993
+ array: undefined,
994
+ position: 0,
995
+ readCount: 0,
996
+ map: undefined,
997
+ key: null,
998
+ };
999
+ this.stack.push(partialState);
1000
+ }
1001
+ return this.stack[this.stackHeadPosition];
1002
+ }
1003
+ release(state) {
1004
+ const topStackState = this.stack[this.stackHeadPosition];
1005
+ if (topStackState !== state) {
1006
+ throw new Error("Invalid stack state. Released state is not on top of the stack.");
1007
+ }
1008
+ if (state.type === STATE_ARRAY) {
1009
+ const partialState = state;
1010
+ partialState.size = 0;
1011
+ partialState.array = undefined;
1012
+ partialState.position = 0;
1013
+ partialState.type = undefined;
1014
+ }
1015
+ if (state.type === STATE_MAP_KEY || state.type === STATE_MAP_VALUE) {
1016
+ const partialState = state;
1017
+ partialState.size = 0;
1018
+ partialState.map = undefined;
1019
+ partialState.readCount = 0;
1020
+ partialState.type = undefined;
1021
+ }
1022
+ this.stackHeadPosition--;
1023
+ }
1024
+ reset() {
1025
+ this.stack.length = 0;
1026
+ this.stackHeadPosition = -1;
1027
+ }
1028
+ }
1029
+ const HEAD_BYTE_REQUIRED = -1;
1030
+ const EMPTY_VIEW = new DataView(new ArrayBuffer(0));
1031
+ const EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);
1032
+ try {
1033
+ // IE11: The spec says it should throw RangeError,
1034
+ // IE11: but in IE11 it throws TypeError.
1035
+ EMPTY_VIEW.getInt8(0);
1036
+ }
1037
+ catch (e) {
1038
+ if (!(e instanceof RangeError)) {
1039
+ throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access");
1040
+ }
1041
+ }
1042
+ const MORE_DATA = new RangeError("Insufficient data");
1043
+ const sharedCachedKeyDecoder = new CachedKeyDecoder();
1044
+ class Decoder {
1045
+ constructor(options) {
1046
+ this.totalPos = 0;
1047
+ this.pos = 0;
1048
+ this.view = EMPTY_VIEW;
1049
+ this.bytes = EMPTY_BYTES;
1050
+ this.headByte = HEAD_BYTE_REQUIRED;
1051
+ this.stack = new StackPool();
1052
+ this.entered = false;
1053
+ this.extensionCodec = options?.extensionCodec ?? ExtensionCodec.defaultCodec;
1054
+ this.context = options?.context; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined
1055
+ this.useBigInt64 = options?.useBigInt64 ?? false;
1056
+ this.rawStrings = options?.rawStrings ?? false;
1057
+ this.maxStrLength = options?.maxStrLength ?? UINT32_MAX;
1058
+ this.maxBinLength = options?.maxBinLength ?? UINT32_MAX;
1059
+ this.maxArrayLength = options?.maxArrayLength ?? UINT32_MAX;
1060
+ this.maxMapLength = options?.maxMapLength ?? UINT32_MAX;
1061
+ this.maxExtLength = options?.maxExtLength ?? UINT32_MAX;
1062
+ this.keyDecoder = options?.keyDecoder !== undefined ? options.keyDecoder : sharedCachedKeyDecoder;
1063
+ this.mapKeyConverter = options?.mapKeyConverter ?? mapKeyConverter;
1064
+ }
1065
+ clone() {
1066
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
1067
+ return new Decoder({
1068
+ extensionCodec: this.extensionCodec,
1069
+ context: this.context,
1070
+ useBigInt64: this.useBigInt64,
1071
+ rawStrings: this.rawStrings,
1072
+ maxStrLength: this.maxStrLength,
1073
+ maxBinLength: this.maxBinLength,
1074
+ maxArrayLength: this.maxArrayLength,
1075
+ maxMapLength: this.maxMapLength,
1076
+ maxExtLength: this.maxExtLength,
1077
+ keyDecoder: this.keyDecoder,
1078
+ });
1079
+ }
1080
+ reinitializeState() {
1081
+ this.totalPos = 0;
1082
+ this.headByte = HEAD_BYTE_REQUIRED;
1083
+ this.stack.reset();
1084
+ // view, bytes, and pos will be re-initialized in setBuffer()
1085
+ }
1086
+ setBuffer(buffer) {
1087
+ const bytes = ensureUint8Array(buffer);
1088
+ this.bytes = bytes;
1089
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1090
+ this.pos = 0;
1091
+ }
1092
+ appendBuffer(buffer) {
1093
+ if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {
1094
+ this.setBuffer(buffer);
1095
+ }
1096
+ else {
1097
+ const remainingData = this.bytes.subarray(this.pos);
1098
+ const newData = ensureUint8Array(buffer);
1099
+ // concat remainingData + newData
1100
+ const newBuffer = new Uint8Array(remainingData.length + newData.length);
1101
+ newBuffer.set(remainingData);
1102
+ newBuffer.set(newData, remainingData.length);
1103
+ this.setBuffer(newBuffer);
1104
+ }
1105
+ }
1106
+ hasRemaining(size) {
1107
+ return this.view.byteLength - this.pos >= size;
1108
+ }
1109
+ createExtraByteError(posToShow) {
1110
+ const { view, pos } = this;
1111
+ return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);
1112
+ }
1113
+ /**
1114
+ * @throws {@link DecodeError}
1115
+ * @throws {@link RangeError}
1116
+ */
1117
+ decode(buffer) {
1118
+ if (this.entered) {
1119
+ const instance = this.clone();
1120
+ return instance.decode(buffer);
1121
+ }
1122
+ try {
1123
+ this.entered = true;
1124
+ this.reinitializeState();
1125
+ this.setBuffer(buffer);
1126
+ const object = this.doDecodeSync();
1127
+ if (this.hasRemaining(1)) {
1128
+ throw this.createExtraByteError(this.pos);
1129
+ }
1130
+ return object;
1131
+ }
1132
+ finally {
1133
+ this.entered = false;
1134
+ }
1135
+ }
1136
+ *decodeMulti(buffer) {
1137
+ if (this.entered) {
1138
+ const instance = this.clone();
1139
+ yield* instance.decodeMulti(buffer);
1140
+ return;
1141
+ }
1142
+ try {
1143
+ this.entered = true;
1144
+ this.reinitializeState();
1145
+ this.setBuffer(buffer);
1146
+ while (this.hasRemaining(1)) {
1147
+ yield this.doDecodeSync();
1148
+ }
1149
+ }
1150
+ finally {
1151
+ this.entered = false;
1152
+ }
1153
+ }
1154
+ async decodeAsync(stream) {
1155
+ if (this.entered) {
1156
+ const instance = this.clone();
1157
+ return instance.decodeAsync(stream);
1158
+ }
1159
+ try {
1160
+ this.entered = true;
1161
+ let decoded = false;
1162
+ let object;
1163
+ for await (const buffer of stream) {
1164
+ if (decoded) {
1165
+ this.entered = false;
1166
+ throw this.createExtraByteError(this.totalPos);
1167
+ }
1168
+ this.appendBuffer(buffer);
1169
+ try {
1170
+ object = this.doDecodeSync();
1171
+ decoded = true;
1172
+ }
1173
+ catch (e) {
1174
+ if (!(e instanceof RangeError)) {
1175
+ throw e; // rethrow
1176
+ }
1177
+ // fallthrough
1178
+ }
1179
+ this.totalPos += this.pos;
1180
+ }
1181
+ if (decoded) {
1182
+ if (this.hasRemaining(1)) {
1183
+ throw this.createExtraByteError(this.totalPos);
1184
+ }
1185
+ return object;
1186
+ }
1187
+ const { headByte, pos, totalPos } = this;
1188
+ throw new RangeError(`Insufficient data in parsing ${prettyByte(headByte)} at ${totalPos} (${pos} in the current buffer)`);
1189
+ }
1190
+ finally {
1191
+ this.entered = false;
1192
+ }
1193
+ }
1194
+ decodeArrayStream(stream) {
1195
+ return this.decodeMultiAsync(stream, true);
1196
+ }
1197
+ decodeStream(stream) {
1198
+ return this.decodeMultiAsync(stream, false);
1199
+ }
1200
+ async *decodeMultiAsync(stream, isArray) {
1201
+ if (this.entered) {
1202
+ const instance = this.clone();
1203
+ yield* instance.decodeMultiAsync(stream, isArray);
1204
+ return;
1205
+ }
1206
+ try {
1207
+ this.entered = true;
1208
+ let isArrayHeaderRequired = isArray;
1209
+ let arrayItemsLeft = -1;
1210
+ for await (const buffer of stream) {
1211
+ if (isArray && arrayItemsLeft === 0) {
1212
+ throw this.createExtraByteError(this.totalPos);
1213
+ }
1214
+ this.appendBuffer(buffer);
1215
+ if (isArrayHeaderRequired) {
1216
+ arrayItemsLeft = this.readArraySize();
1217
+ isArrayHeaderRequired = false;
1218
+ this.complete();
1219
+ }
1220
+ try {
1221
+ while (true) {
1222
+ yield this.doDecodeSync();
1223
+ if (--arrayItemsLeft === 0) {
1224
+ break;
1225
+ }
1226
+ }
1227
+ }
1228
+ catch (e) {
1229
+ if (!(e instanceof RangeError)) {
1230
+ throw e; // rethrow
1231
+ }
1232
+ // fallthrough
1233
+ }
1234
+ this.totalPos += this.pos;
1235
+ }
1236
+ }
1237
+ finally {
1238
+ this.entered = false;
1239
+ }
1240
+ }
1241
+ doDecodeSync() {
1242
+ DECODE: while (true) {
1243
+ const headByte = this.readHeadByte();
1244
+ let object;
1245
+ if (headByte >= 0xe0) {
1246
+ // negative fixint (111x xxxx) 0xe0 - 0xff
1247
+ object = headByte - 0x100;
1248
+ }
1249
+ else if (headByte < 0xc0) {
1250
+ if (headByte < 0x80) {
1251
+ // positive fixint (0xxx xxxx) 0x00 - 0x7f
1252
+ object = headByte;
1253
+ }
1254
+ else if (headByte < 0x90) {
1255
+ // fixmap (1000 xxxx) 0x80 - 0x8f
1256
+ const size = headByte - 0x80;
1257
+ if (size !== 0) {
1258
+ this.pushMapState(size);
1259
+ this.complete();
1260
+ continue DECODE;
1261
+ }
1262
+ else {
1263
+ object = {};
1264
+ }
1265
+ }
1266
+ else if (headByte < 0xa0) {
1267
+ // fixarray (1001 xxxx) 0x90 - 0x9f
1268
+ const size = headByte - 0x90;
1269
+ if (size !== 0) {
1270
+ this.pushArrayState(size);
1271
+ this.complete();
1272
+ continue DECODE;
1273
+ }
1274
+ else {
1275
+ object = [];
1276
+ }
1277
+ }
1278
+ else {
1279
+ // fixstr (101x xxxx) 0xa0 - 0xbf
1280
+ const byteLength = headByte - 0xa0;
1281
+ object = this.decodeString(byteLength, 0);
1282
+ }
1283
+ }
1284
+ else if (headByte === 0xc0) {
1285
+ // nil
1286
+ object = null;
1287
+ }
1288
+ else if (headByte === 0xc2) {
1289
+ // false
1290
+ object = false;
1291
+ }
1292
+ else if (headByte === 0xc3) {
1293
+ // true
1294
+ object = true;
1295
+ }
1296
+ else if (headByte === 0xca) {
1297
+ // float 32
1298
+ object = this.readF32();
1299
+ }
1300
+ else if (headByte === 0xcb) {
1301
+ // float 64
1302
+ object = this.readF64();
1303
+ }
1304
+ else if (headByte === 0xcc) {
1305
+ // uint 8
1306
+ object = this.readU8();
1307
+ }
1308
+ else if (headByte === 0xcd) {
1309
+ // uint 16
1310
+ object = this.readU16();
1311
+ }
1312
+ else if (headByte === 0xce) {
1313
+ // uint 32
1314
+ object = this.readU32();
1315
+ }
1316
+ else if (headByte === 0xcf) {
1317
+ // uint 64
1318
+ if (this.useBigInt64) {
1319
+ object = this.readU64AsBigInt();
1320
+ }
1321
+ else {
1322
+ object = this.readU64();
1323
+ }
1324
+ }
1325
+ else if (headByte === 0xd0) {
1326
+ // int 8
1327
+ object = this.readI8();
1328
+ }
1329
+ else if (headByte === 0xd1) {
1330
+ // int 16
1331
+ object = this.readI16();
1332
+ }
1333
+ else if (headByte === 0xd2) {
1334
+ // int 32
1335
+ object = this.readI32();
1336
+ }
1337
+ else if (headByte === 0xd3) {
1338
+ // int 64
1339
+ if (this.useBigInt64) {
1340
+ object = this.readI64AsBigInt();
1341
+ }
1342
+ else {
1343
+ object = this.readI64();
1344
+ }
1345
+ }
1346
+ else if (headByte === 0xd9) {
1347
+ // str 8
1348
+ const byteLength = this.lookU8();
1349
+ object = this.decodeString(byteLength, 1);
1350
+ }
1351
+ else if (headByte === 0xda) {
1352
+ // str 16
1353
+ const byteLength = this.lookU16();
1354
+ object = this.decodeString(byteLength, 2);
1355
+ }
1356
+ else if (headByte === 0xdb) {
1357
+ // str 32
1358
+ const byteLength = this.lookU32();
1359
+ object = this.decodeString(byteLength, 4);
1360
+ }
1361
+ else if (headByte === 0xdc) {
1362
+ // array 16
1363
+ const size = this.readU16();
1364
+ if (size !== 0) {
1365
+ this.pushArrayState(size);
1366
+ this.complete();
1367
+ continue DECODE;
1368
+ }
1369
+ else {
1370
+ object = [];
1371
+ }
1372
+ }
1373
+ else if (headByte === 0xdd) {
1374
+ // array 32
1375
+ const size = this.readU32();
1376
+ if (size !== 0) {
1377
+ this.pushArrayState(size);
1378
+ this.complete();
1379
+ continue DECODE;
1380
+ }
1381
+ else {
1382
+ object = [];
1383
+ }
1384
+ }
1385
+ else if (headByte === 0xde) {
1386
+ // map 16
1387
+ const size = this.readU16();
1388
+ if (size !== 0) {
1389
+ this.pushMapState(size);
1390
+ this.complete();
1391
+ continue DECODE;
1392
+ }
1393
+ else {
1394
+ object = {};
1395
+ }
1396
+ }
1397
+ else if (headByte === 0xdf) {
1398
+ // map 32
1399
+ const size = this.readU32();
1400
+ if (size !== 0) {
1401
+ this.pushMapState(size);
1402
+ this.complete();
1403
+ continue DECODE;
1404
+ }
1405
+ else {
1406
+ object = {};
1407
+ }
1408
+ }
1409
+ else if (headByte === 0xc4) {
1410
+ // bin 8
1411
+ const size = this.lookU8();
1412
+ object = this.decodeBinary(size, 1);
1413
+ }
1414
+ else if (headByte === 0xc5) {
1415
+ // bin 16
1416
+ const size = this.lookU16();
1417
+ object = this.decodeBinary(size, 2);
1418
+ }
1419
+ else if (headByte === 0xc6) {
1420
+ // bin 32
1421
+ const size = this.lookU32();
1422
+ object = this.decodeBinary(size, 4);
1423
+ }
1424
+ else if (headByte === 0xd4) {
1425
+ // fixext 1
1426
+ object = this.decodeExtension(1, 0);
1427
+ }
1428
+ else if (headByte === 0xd5) {
1429
+ // fixext 2
1430
+ object = this.decodeExtension(2, 0);
1431
+ }
1432
+ else if (headByte === 0xd6) {
1433
+ // fixext 4
1434
+ object = this.decodeExtension(4, 0);
1435
+ }
1436
+ else if (headByte === 0xd7) {
1437
+ // fixext 8
1438
+ object = this.decodeExtension(8, 0);
1439
+ }
1440
+ else if (headByte === 0xd8) {
1441
+ // fixext 16
1442
+ object = this.decodeExtension(16, 0);
1443
+ }
1444
+ else if (headByte === 0xc7) {
1445
+ // ext 8
1446
+ const size = this.lookU8();
1447
+ object = this.decodeExtension(size, 1);
1448
+ }
1449
+ else if (headByte === 0xc8) {
1450
+ // ext 16
1451
+ const size = this.lookU16();
1452
+ object = this.decodeExtension(size, 2);
1453
+ }
1454
+ else if (headByte === 0xc9) {
1455
+ // ext 32
1456
+ const size = this.lookU32();
1457
+ object = this.decodeExtension(size, 4);
1458
+ }
1459
+ else {
1460
+ throw new DecodeError(`Unrecognized type byte: ${prettyByte(headByte)}`);
1461
+ }
1462
+ this.complete();
1463
+ const stack = this.stack;
1464
+ while (stack.length > 0) {
1465
+ // arrays and maps
1466
+ const state = stack.top();
1467
+ if (state.type === STATE_ARRAY) {
1468
+ state.array[state.position] = object;
1469
+ state.position++;
1470
+ if (state.position === state.size) {
1471
+ object = state.array;
1472
+ stack.release(state);
1473
+ }
1474
+ else {
1475
+ continue DECODE;
1476
+ }
1477
+ }
1478
+ else if (state.type === STATE_MAP_KEY) {
1479
+ if (object === "__proto__") {
1480
+ throw new DecodeError("The key __proto__ is not allowed");
1481
+ }
1482
+ state.key = this.mapKeyConverter(object);
1483
+ state.type = STATE_MAP_VALUE;
1484
+ continue DECODE;
1485
+ }
1486
+ else {
1487
+ // it must be `state.type === State.MAP_VALUE` here
1488
+ state.map[state.key] = object;
1489
+ state.readCount++;
1490
+ if (state.readCount === state.size) {
1491
+ object = state.map;
1492
+ stack.release(state);
1493
+ }
1494
+ else {
1495
+ state.key = null;
1496
+ state.type = STATE_MAP_KEY;
1497
+ continue DECODE;
1498
+ }
1499
+ }
1500
+ }
1501
+ return object;
1502
+ }
1503
+ }
1504
+ readHeadByte() {
1505
+ if (this.headByte === HEAD_BYTE_REQUIRED) {
1506
+ this.headByte = this.readU8();
1507
+ // console.log("headByte", prettyByte(this.headByte));
1508
+ }
1509
+ return this.headByte;
1510
+ }
1511
+ complete() {
1512
+ this.headByte = HEAD_BYTE_REQUIRED;
1513
+ }
1514
+ readArraySize() {
1515
+ const headByte = this.readHeadByte();
1516
+ switch (headByte) {
1517
+ case 0xdc:
1518
+ return this.readU16();
1519
+ case 0xdd:
1520
+ return this.readU32();
1521
+ default: {
1522
+ if (headByte < 0xa0) {
1523
+ return headByte - 0x90;
1524
+ }
1525
+ else {
1526
+ throw new DecodeError(`Unrecognized array type byte: ${prettyByte(headByte)}`);
1527
+ }
1528
+ }
1529
+ }
1530
+ }
1531
+ pushMapState(size) {
1532
+ if (size > this.maxMapLength) {
1533
+ throw new DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`);
1534
+ }
1535
+ this.stack.pushMapState(size);
1536
+ }
1537
+ pushArrayState(size) {
1538
+ if (size > this.maxArrayLength) {
1539
+ throw new DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`);
1540
+ }
1541
+ this.stack.pushArrayState(size);
1542
+ }
1543
+ decodeString(byteLength, headerOffset) {
1544
+ if (!this.rawStrings || this.stateIsMapKey()) {
1545
+ return this.decodeUtf8String(byteLength, headerOffset);
1546
+ }
1547
+ return this.decodeBinary(byteLength, headerOffset);
1548
+ }
1549
+ /**
1550
+ * @throws {@link RangeError}
1551
+ */
1552
+ decodeUtf8String(byteLength, headerOffset) {
1553
+ if (byteLength > this.maxStrLength) {
1554
+ throw new DecodeError(`Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`);
1555
+ }
1556
+ if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {
1557
+ throw MORE_DATA;
1558
+ }
1559
+ const offset = this.pos + headerOffset;
1560
+ let object;
1561
+ if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {
1562
+ object = this.keyDecoder.decode(this.bytes, offset, byteLength);
1563
+ }
1564
+ else {
1565
+ object = utf8Decode(this.bytes, offset, byteLength);
1566
+ }
1567
+ this.pos += headerOffset + byteLength;
1568
+ return object;
1569
+ }
1570
+ stateIsMapKey() {
1571
+ if (this.stack.length > 0) {
1572
+ const state = this.stack.top();
1573
+ return state.type === STATE_MAP_KEY;
1574
+ }
1575
+ return false;
1576
+ }
1577
+ /**
1578
+ * @throws {@link RangeError}
1579
+ */
1580
+ decodeBinary(byteLength, headOffset) {
1581
+ if (byteLength > this.maxBinLength) {
1582
+ throw new DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);
1583
+ }
1584
+ if (!this.hasRemaining(byteLength + headOffset)) {
1585
+ throw MORE_DATA;
1586
+ }
1587
+ const offset = this.pos + headOffset;
1588
+ const object = this.bytes.subarray(offset, offset + byteLength);
1589
+ this.pos += headOffset + byteLength;
1590
+ return object;
1591
+ }
1592
+ decodeExtension(size, headOffset) {
1593
+ if (size > this.maxExtLength) {
1594
+ throw new DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`);
1595
+ }
1596
+ const extType = this.view.getInt8(this.pos + headOffset);
1597
+ const data = this.decodeBinary(size, headOffset + 1 /* extType */);
1598
+ return this.extensionCodec.decode(data, extType, this.context);
1599
+ }
1600
+ lookU8() {
1601
+ return this.view.getUint8(this.pos);
1602
+ }
1603
+ lookU16() {
1604
+ return this.view.getUint16(this.pos);
1605
+ }
1606
+ lookU32() {
1607
+ return this.view.getUint32(this.pos);
1608
+ }
1609
+ readU8() {
1610
+ const value = this.view.getUint8(this.pos);
1611
+ this.pos++;
1612
+ return value;
1613
+ }
1614
+ readI8() {
1615
+ const value = this.view.getInt8(this.pos);
1616
+ this.pos++;
1617
+ return value;
1618
+ }
1619
+ readU16() {
1620
+ const value = this.view.getUint16(this.pos);
1621
+ this.pos += 2;
1622
+ return value;
1623
+ }
1624
+ readI16() {
1625
+ const value = this.view.getInt16(this.pos);
1626
+ this.pos += 2;
1627
+ return value;
1628
+ }
1629
+ readU32() {
1630
+ const value = this.view.getUint32(this.pos);
1631
+ this.pos += 4;
1632
+ return value;
1633
+ }
1634
+ readI32() {
1635
+ const value = this.view.getInt32(this.pos);
1636
+ this.pos += 4;
1637
+ return value;
1638
+ }
1639
+ readU64() {
1640
+ const value = getUint64(this.view, this.pos);
1641
+ this.pos += 8;
1642
+ return value;
1643
+ }
1644
+ readI64() {
1645
+ const value = getInt64(this.view, this.pos);
1646
+ this.pos += 8;
1647
+ return value;
1648
+ }
1649
+ readU64AsBigInt() {
1650
+ const value = this.view.getBigUint64(this.pos);
1651
+ this.pos += 8;
1652
+ return value;
1653
+ }
1654
+ readI64AsBigInt() {
1655
+ const value = this.view.getBigInt64(this.pos);
1656
+ this.pos += 8;
1657
+ return value;
1658
+ }
1659
+ readF32() {
1660
+ const value = this.view.getFloat32(this.pos);
1661
+ this.pos += 4;
1662
+ return value;
1663
+ }
1664
+ readF64() {
1665
+ const value = this.view.getFloat64(this.pos);
1666
+ this.pos += 8;
1667
+ return value;
1668
+ }
1669
+ }
1670
+
1671
+ /**
1672
+ * It decodes a single MessagePack object in a buffer.
1673
+ *
1674
+ * This is a synchronous decoding function.
1675
+ * See other variants for asynchronous decoding: {@link decodeAsync}, {@link decodeStream}, or {@link decodeArrayStream}.
1676
+ *
1677
+ * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.
1678
+ * @throws {@link DecodeError} if the buffer contains invalid data.
1679
+ */
1680
+ function decode(buffer, options) {
1681
+ const decoder = new Decoder(options);
1682
+ return decoder.decode(buffer);
1683
+ }
1684
+
1685
+ // Custom conflict-free replicated data type system with vector clocks
1686
+
1687
+ const CONSOLE_PREFIX = "PlaySocket CRDT manager: ";
1688
+
1689
+ class CRDTManager {
1690
+ // Storage
1691
+ #replicaId;
1692
+ #keyOperations = new Map();
1693
+ #vectorClock = new Map();
1694
+
1695
+ // Local only
1696
+ #propertyStore = {}; // Current local values per key, as object
1697
+ #lastPropertyStore = {}; // Last property store to compare against
1698
+
1699
+ // Local Garbage Collection
1700
+ #lastGCCheck = 0;
1701
+ #opUuidTimestamp = new Map(); // Map every operation to a timestamp for garbage collection
1702
+
1703
+ // Debug
1704
+ #debug = false;
1705
+
1706
+ /**
1707
+ * Create a new instance
1708
+ */
1709
+ constructor(debug) {
1710
+ if (debug) this.#debug = true;
1711
+ this.#replicaId = crypto.randomUUID();
1712
+ this.#vectorClock.set(this.#replicaId, 0);
1713
+ }
1714
+
1715
+ /**
1716
+ * Import the entire state of the CRDT manager (this overwrites the old state)
1717
+ * @param {Object} state
1718
+ */
1719
+ importState(state) {
1720
+ try {
1721
+ const { keyOperations, vectorClock } = state;
1722
+ if (this.#debug) console.log(CONSOLE_PREFIX + "Importing state:", state);
1723
+
1724
+ // Resets
1725
+ this.#opUuidTimestamp.clear();
1726
+ this.#propertyStore = {};
1727
+ this.#lastPropertyStore = {};
1728
+
1729
+ this.#keyOperations = new Map(keyOperations); // Rebuild the operations map
1730
+ this.#vectorClock = new Map(vectorClock); // Rebuild the vector clock map
1731
+ if (!this.#vectorClock.has(this.#replicaId)) this.#vectorClock.set(this.#replicaId, 0); // Add own vector clock if it wasn't present in the imported state
1732
+
1733
+ // Map all operation uuids to current timestamp
1734
+ this.#keyOperations.forEach((value, key) => {
1735
+ value?.forEach((operation) => {
1736
+ this.#opUuidTimestamp.set(operation?.uuid, Date.now());
1737
+ });
1738
+ });
1739
+
1740
+ // Process each key to update local values
1741
+ for (const key of this.#keyOperations.keys()) this.#processLocalProperty(key);
1742
+
1743
+ } catch (error) {
1744
+ console.error(CONSOLE_PREFIX + "Failed to import state:", error);
1745
+ }
1746
+ }
1747
+
1748
+ /**
1749
+ * Import property update
1750
+ * @param {Object} data - Data to import
1751
+ */
1752
+ importPropertyUpdate(data) {
1753
+ try {
1754
+ const { key, operation: rawOperation, vectorClock } = data;
1755
+ const operation = this.#sanitizeValue(rawOperation);
1756
+ if (this.#debug) console.log(CONSOLE_PREFIX + "Importing update:", data); // Debug
1757
+
1758
+ // Check key limit to afeguard against too many keys
1759
+ if (this.#keyOperations.size >= 100 && !this.#keyOperations.has(key)) throw new Error('Key limit exceeded!');
1760
+
1761
+ // Get COPY of current ops (or empty array if none yet)
1762
+ const currentOps = [...(this.#keyOperations.get(key) || [])];
1763
+ // Merge vector clocks (always take max value)
1764
+ for (const [id, counter] of vectorClock) {
1765
+ if (!this.#vectorClock.has(id) || this.#vectorClock.get(id) < counter) {
1766
+ this.#vectorClock.set(id, counter);
1767
+ }
1768
+ }
1769
+
1770
+ // Safeguard against massive vector clocks
1771
+ if (this.#vectorClock.size > 1000) this.#vectorClock = new Map([...this.#vectorClock].slice(-100));
1772
+
1773
+ // Add new operation if it's not already added
1774
+ const existingUuids = new Set(currentOps.map(op => op.uuid));
1775
+ if (operation.uuid && !existingUuids.has(operation.uuid)) {
1776
+ currentOps.push({ ...operation }); // Add operation
1777
+ this.#opUuidTimestamp.set(operation.uuid, Date.now()); // Add timestamp for gc
1778
+ }
1779
+
1780
+ // Sort, update operations & local value
1781
+ this.#keyOperations.set(key, this.#sortByVectorClock(currentOps));
1782
+ this.#processLocalProperty(key);
1783
+ this.#checkGarbageCollection();
1784
+
1785
+ } catch (error) {
1786
+ console.error(CONSOLE_PREFIX + "Failed to import property update:", error);
1787
+ }
1788
+ }
1789
+
1790
+ /**
1791
+ * Update a property
1792
+ * @param {string} key
1793
+ * @param {string} type
1794
+ * @param {*} value
1795
+ * @param {*} updateValue
1796
+ * @returns {Object} - Returns the property update
1797
+ */
1798
+ updateProperty(key, type, value, updateValue) {
1799
+ try {
1800
+ // Sanitize inputs
1801
+ value = this.#sanitizeValue(value);
1802
+ updateValue = this.#sanitizeValue(updateValue);
1803
+
1804
+ // Debug log
1805
+ if (this.#debug) console.log(CONSOLE_PREFIX + `Updating property with key ${key}, type ${type}, value ${value} and updateValue ${updateValue}.`);
1806
+
1807
+ // Increment vector clock
1808
+ const counter = this.#vectorClock.get(this.#replicaId) || 0;
1809
+ this.#vectorClock.set(this.#replicaId, counter + 1);
1810
+
1811
+ // Assign shallow COPY of currennt ops or fall back to empty array
1812
+ const currentOps = [...(this.#keyOperations.get(key) || [])];
1813
+
1814
+ // Add operation
1815
+ const newOp = this.#createOperation({ type, value, updateValue }, Array.from(this.#vectorClock.entries()));
1816
+ currentOps.push(newOp);
1817
+ this.#keyOperations.set(key, currentOps); // Update the operations (no need to sort via vector clock since local updates are always the latest)
1818
+ this.#processLocalProperty(key); // Process local value
1819
+ this.#checkGarbageCollection();
1820
+
1821
+ // Return the property update with the new operation (this can be imported using importPropertyUpdate)
1822
+ return {
1823
+ key,
1824
+ operation: { ...newOp },
1825
+ vectorClock: Array.from(this.#vectorClock.entries())
1826
+ };
1827
+
1828
+ } catch (error) {
1829
+ console.error(CONSOLE_PREFIX + `Failed to add operation for key "${key}":`, error);
1830
+ }
1831
+ }
1832
+
1833
+ #checkGarbageCollection() {
1834
+ const MIN_GC_DELAY = 1000; // Minimum 1s delay between garbage collection runs
1835
+ const MIN_AGE_FOR_GC = 5000; // Garbage collect ops that are older than 5s
1836
+
1837
+ try {
1838
+ if (Date.now() - this.#lastGCCheck < MIN_GC_DELAY) return;
1839
+ this.#lastGCCheck = Date.now();
1840
+
1841
+ for (const [key, operations] of this.#keyOperations.entries()) {
1842
+ if (operations?.length < 5) continue; // Min op amount per key for garbage collection to run (otherwise not worth it)
1843
+
1844
+ let retainCount = operations.length;
1845
+ operations.forEach((op, index) => {
1846
+ // Count how many ops, from last to latest, are older than the min-age in a row
1847
+ if (op.uuid && this.#opUuidTimestamp.has(op.uuid) && (Date.now() - this.#opUuidTimestamp.get(op.uuid)) > MIN_AGE_FOR_GC) {
1848
+ const removeCount = index + 1;
1849
+ retainCount = operations.length - removeCount;
1850
+ this.#opUuidTimestamp.delete(op.uuid); // Remove from timestamps if set to be deleted
1851
+ }
1852
+ });
1853
+
1854
+ if (retainCount < operations.length) {
1855
+ if (this.#debug) console.log(CONSOLE_PREFIX + `Running garbage collection for key ${key} with current operations:`, operations);
1856
+ const retainOps = operations.slice(-retainCount); // Newest ops
1857
+ const removeOps = operations.slice(0, -retainCount); // Oldest ops (start = idx 0, end = retainCount counted from right side)
1858
+ const baselineVectorClock = removeOps[removeOps.length - 1]?.vectorClock || []; // Use the vector clock from the last operation that we remove/overwrite
1859
+
1860
+ // Calculate the value at the point where retained operations start
1861
+ let baselineValue = null;
1862
+ for (const op of removeOps) {
1863
+ if (!op.data) continue;
1864
+ baselineValue = this.#handleOperation(
1865
+ baselineValue,
1866
+ op.data.type,
1867
+ op.data.value,
1868
+ op.data.updateValue
1869
+ );
1870
+ }
1871
+
1872
+ // Create a compact operation with baseline value and appropriate vector clock
1873
+ const compactOp = this.#createOperation({ type: "set", value: baselineValue }, baselineVectorClock);
1874
+
1875
+ // Debug log
1876
+ if (this.#debug) console.log(CONSOLE_PREFIX + "Operations after garbage collection for this key:", [compactOp, ...retainOps]);
1877
+
1878
+ // Combine compact op with retained operations
1879
+ this.#keyOperations.set(key, [compactOp, ...retainOps]);
1880
+ }
1881
+ }
1882
+ } catch (error) {
1883
+ console.error(CONSOLE_PREFIX + "Error running garbage collection:", error);
1884
+ }
1885
+ }
1886
+
1887
+ /**
1888
+ * Create an operation object
1889
+ * @param {Object} data
1890
+ * @param {Array} vectorClock
1891
+ * @returns {Object} - Operation object
1892
+ */
1893
+ #createOperation(data, vectorClock) {
1894
+ const newOperation = {
1895
+ data,
1896
+ vectorClock,
1897
+ source: this.#replicaId,
1898
+ uuid: crypto.randomUUID()
1899
+ };
1900
+ this.#opUuidTimestamp.set(newOperation.uuid, Date.now());
1901
+ return newOperation;
1902
+ }
1903
+
1904
+ /**
1905
+ * Process a property's value by applying all operations and set it in the property store
1906
+ * @param {string} key
1907
+ */
1908
+ #processLocalProperty(key) {
1909
+ try {
1910
+ const ops = this.#keyOperations.get(key);
1911
+ if (!ops?.length) return;
1912
+
1913
+ // Apply all operations in order
1914
+ let value = null;
1915
+
1916
+ for (const op of ops) {
1917
+ if (!op.data) continue;
1918
+ value = this.#handleOperation(
1919
+ value,
1920
+ op.data.type,
1921
+ op.data.value,
1922
+ op.data.updateValue
1923
+ );
1924
+ }
1925
+
1926
+ this.#propertyStore[key] = value; // Save locally
1927
+ } catch (error) {
1928
+ console.error(CONSOLE_PREFIX + `Failed to process property for key ${key}:`, error);
1929
+ }
1930
+ }
1931
+
1932
+ /**
1933
+ * Sort by vector clock (causal order)
1934
+ * @param {Array} operations
1935
+ * @returns {Array} - Sorted operations
1936
+ */
1937
+ #sortByVectorClock(operations) {
1938
+ return [...operations].sort((a, b) => {
1939
+ const clockA = new Map(a.vectorClock || []);
1940
+ const clockB = new Map(b.vectorClock || []);
1941
+
1942
+ // First sort by causal relationship
1943
+ let aGreater = false, bGreater = false;
1944
+
1945
+ const allIds = new Set([...clockA.keys(), ...clockB.keys()]);
1946
+ for (const id of allIds) {
1947
+ const countA = clockA.get(id) || 0;
1948
+ const countB = clockB.get(id) || 0;
1949
+
1950
+ if (countA > countB) aGreater = true;
1951
+ if (countA < countB) bGreater = true;
1952
+ }
1953
+
1954
+ // Determine causal relationship (if one is greater, and the other is smaller, it's clear)
1955
+ if (aGreater && !bGreater) return 1; // a happens after b
1956
+ if (!aGreater && bGreater) return -1; // a happens before b
1957
+
1958
+ // Concurrent (unclear): Compare highest counter in each (sort by which one is ahead)
1959
+ const maxA = Math.max(...Array.from(clockA.values()), 0);
1960
+ const maxB = Math.max(...Array.from(clockB.values()), 0);
1961
+ if (maxA !== maxB) return maxA - maxB;
1962
+
1963
+ // Final tiebreak: Sort by ID of Replica that actually generated the operation
1964
+ return a.source.localeCompare(b.source);
1965
+ });
1966
+ }
1967
+
1968
+ /**
1969
+ * Handle an operation
1970
+ * @param {*} curValue
1971
+ * @param {string} type
1972
+ * @param {*} value
1973
+ * @param {*} [updateValue]
1974
+ * @returns {*} - Value after the operation
1975
+ */
1976
+ #handleOperation(curValue, type, value, updateValue) {
1977
+ try {
1978
+ // Deep copy to avoid reference issues in case value is or contains object(s)
1979
+ curValue = structuredClone(curValue);
1980
+
1981
+ // Set operation
1982
+ if (type === "set") return value;
1983
+
1984
+ // Array operations
1985
+ if (type.startsWith('array')) {
1986
+ if (!Array.isArray(curValue)) curValue = []; // Auto-convert to array if current value isn't one
1987
+
1988
+ // Comparison function
1989
+ const isObject = typeof value === 'object' && value !== null;
1990
+ const compare = (item) => {
1991
+ if (isObject && typeof item === 'object' && item !== null) return JSON.stringify(item) === JSON.stringify(value); // Deep comparison
1992
+ return item === value; // Value comparison
1993
+ };
1994
+
1995
+ switch (type) {
1996
+ case 'array-add':
1997
+ curValue.push(value);
1998
+ break;
1999
+ case 'array-add-unique':
2000
+ if (!curValue.some(compare)) curValue.push(value);
2001
+ break;
2002
+ case 'array-remove-matching':
2003
+ curValue = curValue.filter(item => !compare(item));
2004
+ break;
2005
+ case 'array-update-matching':
2006
+ const index = curValue.findIndex(compare);
2007
+ if (index !== -1) curValue[index] = updateValue;
2008
+ break;
2009
+ }
2010
+ }
2011
+
2012
+ return curValue;
2013
+
2014
+ } catch (error) {
2015
+ console.error(CONSOLE_PREFIX + `Failed to handle operation with curValue ${curValue}:`, error);
2016
+ return curValue;
2017
+ }
2018
+ }
2019
+
2020
+ /**
2021
+ * Remove HTML to prevent XSS and enforce size limits
2022
+ * @param {Object} obj
2023
+ * @returns {Object} - Sanitized object
2024
+ */
2025
+ #sanitizeValue(obj) {
2026
+ // Check total serialized size
2027
+ const jsonString = JSON.stringify(obj);
2028
+ if (jsonString?.length > 50000) throw new Error('Value too large!'); // 50KB limit
2029
+
2030
+ if (typeof obj === 'string') return (obj.includes('<') || obj.includes('>')) ? obj.replace(/[<>]/g, '') : obj;
2031
+ if (Array.isArray(obj)) return obj.map(item => this.#sanitizeValue(item));
2032
+ if (obj && typeof obj === 'object') return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, this.#sanitizeValue(v)]));
2033
+ return obj;
2034
+ }
2035
+
2036
+ // Get property store
2037
+ get getPropertyStore() {
2038
+ try {
2039
+ return structuredClone(this.#propertyStore); // Return deep clone
2040
+ } catch {
2041
+ console.error(CONSOLE_PREFIX + "Failed to parse property store");
2042
+ return {};
2043
+ }
2044
+ }
2045
+
2046
+ // Check for changes in the local property store
2047
+ get didPropertiesChange() {
2048
+ try {
2049
+ if (JSON.stringify(this.#propertyStore) !== JSON.stringify(this.#lastPropertyStore)) {
2050
+ this.#lastPropertyStore = structuredClone(this.#propertyStore);
2051
+ return true;
2052
+ }
2053
+ } catch { }
2054
+ return false;
2055
+ }
2056
+
2057
+ // Get state (can be imported using importState, converts the maps to arrays for serialization)
2058
+ get getState() {
2059
+ return {
2060
+ keyOperations: [...this.#keyOperations.entries()],
2061
+ vectorClock: [...this.#vectorClock.entries()]
2062
+ };
2063
+ }
2064
+ }
2065
+
2066
+ /**
2067
+ * PlaySocketServer - WebSocket server for PlaySocket multiplayer library
2068
+ */
2069
+ class PlaySocketServer {
2070
+ #server;
2071
+ #ownsServer = false;
2072
+ #rateLimitMaxPoints;
2073
+ #wss;
2074
+ #clients = new Map(); // ClientId -> WebSocket instance
2075
+ #rooms = {};
2076
+ #clientRooms = new Map(); // ClientId -> RoomId
2077
+ #rateLimits = new Map(); // Rate limiting storage
2078
+ #callbacks = new Map(); // Event -> [callback functions]
2079
+ #heartbeatInterval;
2080
+ #pendingDisconnects = new Map(); // ClientId -> {timeout, roomId}
2081
+ #clientTokens = new Map(); // ClientId -> Token
2082
+ #roomVersions = new Map(); // RoomId -> Version
2083
+
2084
+ // Debug
2085
+ #debug = false;
2086
+
2087
+ /**
2088
+ * Create a new PlaySocketServer instance
2089
+ * @param {Object} options - Server configuration options
2090
+ * @param {HttpServer} [options.server] - Existing http server
2091
+ * @param {number} [options.port=3000] - Port to listen on (if no server provided)
2092
+ * @param {string} [options.path='/socket'] - WebSocket endpoint path
2093
+ */
2094
+ constructor(options = {}) {
2095
+ const { server, port = 3000, path = '/', debug = false, rateLimit = 20 } = options;
2096
+
2097
+ if (debug) this.#debug = true; // Enable extra logging
2098
+
2099
+ this.#rateLimitMaxPoints = rateLimit; // Set rate limit
2100
+
2101
+ // Handle server creation / usage
2102
+ if (server) {
2103
+ this.#server = server; // Use provided HTTP server
2104
+ } else {
2105
+ this.#ownsServer = true;
2106
+ this.#server = http.createServer(); // Create HTTP server and start it
2107
+ this.#server.listen(port, () => {
2108
+ console.log(`PlaySocket server running on port ${port}.`);
2109
+ });
2110
+ }
2111
+
2112
+ // Create WebSocket server
2113
+ this.#wss = new WebSocketServer({
2114
+ server: this.#server,
2115
+ path
2116
+ });
2117
+
2118
+ // Set up ws event handlers
2119
+ this.#wss.on('connection', ws => {
2120
+ ws.connectionId = crypto.randomUUID();
2121
+ ws.isAlive = true;
2122
+ ws.on('pong', () => { ws.isAlive = true; });
2123
+ ws.on('message', msg => this.#handleMessage(ws, msg));
2124
+ ws.on('close', () => this.#handleDisconnection(ws));
2125
+ ws.on('error', (error) => {
2126
+ console.error(`PlaySocket WebSocket connection error for client ${ws.clientId || 'unknown'}:`, error); // Catch conn errors
2127
+ });
2128
+ });
2129
+
2130
+ // Log & catch server-level errors
2131
+ this.#wss.on('error', (error) => {
2132
+ console.error('PlaySocket WebSocket server error:', error);
2133
+ });
2134
+
2135
+ // Start heartbeat
2136
+ this.#heartbeatInterval = setInterval(() => {
2137
+ this.#wss.clients.forEach(ws => {
2138
+ if (!ws.isAlive) return ws.terminate();
2139
+ ws.isAlive = false;
2140
+ ws.ping();
2141
+ });
2142
+ }, 15000);
2143
+ }
2144
+
2145
+ /**
2146
+ * Handle WebSocket message
2147
+ * @private
2148
+ */
2149
+ async #handleMessage(ws, message) {
2150
+ if (ws.isTerminating) return;
2151
+ try {
2152
+ const data = decode(message);
2153
+
2154
+ // Apply rate limiting to all connections (including unregistered)
2155
+ if (!this.#checkRateLimit(ws.connectionId, data.type)) {
2156
+ if (!ws.isTerminating) {
2157
+ ws.isTerminating = true; // Prevent multiple terminate calls (it is async)
2158
+ ws.terminate();
2159
+ return console.error(`Connection ${ws.connectionId} terminated due to rate limit violations.`);
2160
+ }
2161
+ }
2162
+
2163
+ switch (data.type) {
2164
+ case 'register':
2165
+ // Register client ID if provided & check for a duplicate
2166
+ if (data.id && this.#clients.get(data.id)) {
2167
+ ws.send(encode({ type: 'registration_failed', reason: 'ID is taken.' }), { binary: true });
2168
+ return;
2169
+ }
2170
+
2171
+ // Generate client ID if none provided
2172
+ if (!data.id) {
2173
+ for (let i = 0; i < 50; i++) {
2174
+ const id = this.#generateId();
2175
+ if (!this.#clients.get(id)) {
2176
+ data.id = id;
2177
+ break;
2178
+ }
2179
+ }
2180
+ if (!data.id) {
2181
+ ws.send(encode({ type: 'registration_failed', reason: 'No available ID found.' }), { binary: true });
2182
+ throw new Error('Failed to generate unique ID!');
2183
+ }
2184
+ }
2185
+
2186
+ // Event callback
2187
+ const registrationAllowed = await this.#triggerEvent("clientRegistrationRequested", data.id, data.customData);
2188
+ if (registrationAllowed === false || typeof registrationAllowed === 'string') {
2189
+ ws.send(encode({
2190
+ type: 'registration_failed',
2191
+ reason: typeof registrationAllowed === 'string' ? registrationAllowed : 'Denied.'
2192
+ }), { binary: true });
2193
+ return;
2194
+ }
2195
+
2196
+ ws.clientId = data.id; // Adds the provided id to the ws object as clientId
2197
+ this.#clients.set(data.id, ws);
2198
+ const sessionToken = this.#generateSessionToken();
2199
+ this.#clientTokens.set(data.id, sessionToken); // Token is used when reconnecting to prevent impersonation attacks
2200
+ ws.send(encode({ type: 'registered', id: data.id, sessionToken }), { binary: true });
2201
+ this.#triggerEvent("clientRegistered", data.id, data.customData);
2202
+ break;
2203
+
2204
+ case 'reconnect':
2205
+ // If user is pending disconnect, respond (otherwise it's too late)
2206
+ const pd = this.#pendingDisconnects.get(data.id);
2207
+ if (pd && data.sessionToken) {
2208
+ if (data.sessionToken !== this.#clientTokens.get(data.id)) {
2209
+ ws.send(encode({
2210
+ type: 'reconnection_failed',
2211
+ reason: "Session token does not match."
2212
+ }), { binary: true });
2213
+ return;
2214
+ }
2215
+ clearTimeout(pd.timeout);
2216
+ this.#pendingDisconnects.delete(data.id);
2217
+
2218
+ // Re-assign old client ID to the new ws connection
2219
+ ws.clientId = data.id;
2220
+ this.#clients.set(data.id, ws);
2221
+
2222
+ // If they were in a room, provide updated room data
2223
+ let roomData;
2224
+ const formerRoomId = this.#clientRooms.get(data.id);
2225
+ const formerRoom = this.#rooms[formerRoomId];
2226
+ if (formerRoom) {
2227
+ if (this.#debug) console.log(`State sent for reconnection for room ${formerRoomId}:`, formerRoom.crdtManager.getState);
2228
+ roomData = {
2229
+ state: formerRoom.crdtManager.getState,
2230
+ participantCount: formerRoom.participants.length,
2231
+ host: formerRoom.host,
2232
+ version: this.#roomVersions.get(formerRoomId)
2233
+ };
2234
+ }
2235
+
2236
+ ws.send(encode({ type: 'reconnected', roomData }), { binary: true });
2237
+ } else {
2238
+ ws.send(encode({ type: 'reconnection_failed', reason: "Client unknown to server." }), { binary: true });
2239
+ }
2240
+ break;
2241
+
2242
+ case 'create_room':
2243
+ if (!ws.clientId) return;
2244
+
2245
+ let newRoomId;
2246
+
2247
+ if (this.#clientRooms.get(ws.clientId)) {
2248
+ ws.send(encode({
2249
+ type: 'room_creation_failed',
2250
+ reason: 'Already in a room.'
2251
+ }), { binary: true });
2252
+ return;
2253
+ }
2254
+
2255
+ // Generate room ID
2256
+ for (let i = 0; i < 50; i++) {
2257
+ const id = this.#generateId();
2258
+ if (!this.#rooms[id]) {
2259
+ newRoomId = id;
2260
+ break;
2261
+ }
2262
+ }
2263
+
2264
+ if (!newRoomId) {
2265
+ ws.send(encode({ type: 'room_creation_failed', reason: 'No available ID found.' }), { binary: true });
2266
+ throw new Error('Failed to generate unique room ID!');
2267
+ }
2268
+
2269
+ const roomCrdtManager = new CRDTManager(this.#debug); // Create the room's crdt manager
2270
+
2271
+ // Event callback with potential initial storage modifications
2272
+ const reviewedStorage = await this.#triggerEvent("roomCreationRequested", { roomId: newRoomId, clientId: ws.clientId, initialStorage: structuredClone({ ...data.initialStorage }) });
2273
+ if (typeof reviewedStorage === 'object') data.initialStorage = reviewedStorage;
2274
+ if (reviewedStorage === false) {
2275
+ ws.send(encode({
2276
+ type: 'room_creation_failed',
2277
+ reason: 'Room creation denied.'
2278
+ }), { binary: true });
2279
+ return;
2280
+ }
2281
+
2282
+ // Check if client/creator is still connected
2283
+ if (!this.#clients.has(ws.clientId)) {
2284
+ if (this.#debug) console.log(`Room creation cancelled - client ${ws.clientId} disconnected during event callback.`);
2285
+ return; // Abort room creation if client is no longer connected
2286
+ }
2287
+
2288
+ // Load initial storage if provided
2289
+ if (data.initialStorage) {
2290
+ Object.entries(data.initialStorage)?.forEach(([key, value]) => {
2291
+ roomCrdtManager.updateProperty(key, "set", value);
2292
+ });
2293
+ }
2294
+
2295
+ // Create room
2296
+ const maxSize = Math.min(Number(data.size), 100) || 100; // Max. limit is 100 clients / room
2297
+ this.#roomVersions.set(newRoomId, 0); // Start with version 0
2298
+ this.#rooms[newRoomId] = {
2299
+ participants: [ws.clientId],
2300
+ host: ws.clientId,
2301
+ maxSize,
2302
+ crdtManager: roomCrdtManager
2303
+ };
2304
+ this.#clientRooms.set(ws.clientId, newRoomId); // Add client to the room
2305
+
2306
+ ws.send(encode({ type: 'room_created', state: roomCrdtManager.getState, roomId: newRoomId, size: maxSize }), { binary: true });
2307
+ this.#triggerEvent("roomCreated", newRoomId);
2308
+ if (this.#debug) console.log(`Room ${newRoomId} created with initial storage:`, data.initialStorage);
2309
+ break;
2310
+
2311
+ case 'join_room':
2312
+ if (!data.roomId || !ws.clientId) return;
2313
+ const roomId = data.roomId;
2314
+ const room = this.#rooms[roomId];
2315
+
2316
+ const rejectJoin = (reason) => {
2317
+ ws.send(encode({ type: 'join_rejected', reason }), { binary: true });
2318
+ };
2319
+
2320
+ // Event callback
2321
+ const joinAllowed = await this.#triggerEvent("clientJoinRequested", ws.clientId, roomId);
2322
+ if (joinAllowed === false || typeof joinAllowed === 'string') return rejectJoin(typeof joinAllowed === 'string' ? joinAllowed : 'Denied.');
2323
+
2324
+ if (!room) return rejectJoin("Room not found.");
2325
+ if (this.#clientRooms.get(ws.clientId)) return rejectJoin("Already in a room.");
2326
+ if (room.participants.length >= room.maxSize) return rejectJoin("Room full.");
2327
+
2328
+ room.participants.push(ws.clientId);
2329
+ this.#clientRooms.set(ws.clientId, roomId);
2330
+
2331
+ // Notify joiner with initial storage
2332
+ if (this.#debug) console.log("Room state sent for join:", room.crdtManager.getState);
2333
+ ws.send(encode({
2334
+ type: 'join_accepted',
2335
+ state: room.crdtManager.getState,
2336
+ participantCount: room.participants.length,
2337
+ host: room.host,
2338
+ version: this.#roomVersions.get(roomId)
2339
+ }), { binary: true });
2340
+
2341
+ // Notify existing participants
2342
+ room.participants.forEach(p => {
2343
+ if (p === ws.clientId) return;
2344
+ const client = this.#clients.get(p);
2345
+ if (client) {
2346
+ client.send(encode({
2347
+ type: 'client_connected',
2348
+ client: ws.clientId,
2349
+ participantCount: room.participants.length
2350
+ }), { binary: true });
2351
+ }
2352
+ });
2353
+ this.#triggerEvent("clientJoinedRoom", ws.clientId, roomId);
2354
+ break;
2355
+
2356
+ case 'update_property':
2357
+ const updateRoomId = this.#clientRooms.get(ws.clientId);
2358
+ const updateRoom = updateRoomId ? this.#rooms[updateRoomId] : null;
2359
+
2360
+ if (updateRoom && data.update) {
2361
+ // Check if update is allowed via event callback (provide clone to ensure update integrity)
2362
+ const updateAllowed = await this.#triggerEvent("storageUpdateRequested", { roomId: updateRoomId, clientId: ws.clientId, update: structuredClone(data.update) });
2363
+ if (updateAllowed === false) {
2364
+ ws.send(encode({
2365
+ type: 'property_update_rejected',
2366
+ state: updateRoom.crdtManager.getState
2367
+ }), { binary: true });
2368
+ return;
2369
+ }
2370
+
2371
+ updateRoom.crdtManager.importPropertyUpdate(data.update); // Import update into server state
2372
+
2373
+ // Increment version for this room
2374
+ const currentVersion = this.#roomVersions.get(updateRoomId) + 1;
2375
+ this.#roomVersions.set(updateRoomId, currentVersion);
2376
+
2377
+ updateRoom.participants?.forEach(p => {
2378
+ const client = this.#clients.get(p);
2379
+ if (client) {
2380
+ client.send(encode({
2381
+ type: 'property_updated',
2382
+ update: data.update,
2383
+ version: currentVersion
2384
+ }), { binary: true });
2385
+ }
2386
+ });
2387
+
2388
+ this.#triggerEvent("storageUpdated", { roomId: updateRoomId, clientId: ws.clientId, update: structuredClone(data.update), storage: this.getRoomStorage(updateRoomId) });
2389
+ if (this.#debug) console.log("Property update received and imported:", data.update);
2390
+ }
2391
+ break;
2392
+
2393
+ case 'request':
2394
+ if (!ws.clientId) return;
2395
+ const requestorRoomId = this.#clientRooms.get(ws.clientId) || null;
2396
+ this.#triggerEvent("requestReceived", { roomId: requestorRoomId, clientId: ws.clientId, name: data.request.name, data: data.request.data });
2397
+ break;
2398
+
2399
+ case 'disconnect':
2400
+ // Client signals to server that it will will willfully disconnect soon
2401
+ ws.willfulDisconnect = true;
2402
+ break;
2403
+ }
2404
+ } catch (error) {
2405
+ console.error('Error in message handler:', error);
2406
+ }
2407
+ }
2408
+
2409
+ /**
2410
+ * Generate a readable, 6 digit ID
2411
+ */
2412
+ #generateId() {
2413
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789';
2414
+ return Array.from({ length: 6 }, () => chars[Math.floor(Math.random() * chars.length)]).join('');
2415
+ }
2416
+
2417
+ /**
2418
+ * If the client that disconnected (and is now in the reconnection-phase) was the room host,
2419
+ * pick a new room host immediately to avoid host-less phase (in case important logic is attached to the host)
2420
+ * @param {string} roomId
2421
+ * @param {string} clientId
2422
+ */
2423
+ #changeHostIfDisconnected(roomId, clientId) {
2424
+ const room = this.#rooms[roomId];
2425
+ if (room && room.host === clientId && room.participants.length > 1) {
2426
+ const participantsWithoutClient = room.participants.filter((e) => e !== clientId);
2427
+ room.host = participantsWithoutClient[0]; // Set new host
2428
+
2429
+ // Inform all participants about the new host
2430
+ participantsWithoutClient.forEach(p => {
2431
+ const client = this.#clients.get(p);
2432
+ if (client) client.send(encode({
2433
+ type: 'host_migrated',
2434
+ newHost: room.host,
2435
+ }), { binary: true });
2436
+ });
2437
+ }
2438
+ }
2439
+
2440
+ /**
2441
+ * Generate a random token to prevent malicious reconnect attempts
2442
+ * @returns {string} - Token
2443
+ */
2444
+ #generateSessionToken() {
2445
+ let token = '';
2446
+ for (let i = 0; i < 16; i++) token += Math.floor(Math.random() * 16).toString(16);
2447
+ return token;
2448
+ }
2449
+
2450
+ /**
2451
+ * Check rate limit using token bucket algorithm
2452
+ * @private
2453
+ */
2454
+ #checkRateLimit(connectionId, operationType) {
2455
+ const now = Date.now();
2456
+
2457
+ if (!this.#rateLimits.has(connectionId)) {
2458
+ this.#rateLimits.set(connectionId, { points: this.#rateLimitMaxPoints, lastReset: now });
2459
+ return true;
2460
+ }
2461
+
2462
+ const limit = this.#rateLimits.get(connectionId);
2463
+
2464
+ // Reset points if interval has passed (1s)
2465
+ if (now - limit.lastReset > 1000) {
2466
+ limit.points = this.#rateLimitMaxPoints;
2467
+ limit.lastReset = now;
2468
+ }
2469
+
2470
+ const pointCost = operationType == "create_room" ? 5 : 1;
2471
+ if (limit.points < pointCost) return false;
2472
+
2473
+ limit.points -= pointCost;
2474
+ return true;
2475
+ }
2476
+
2477
+ /**
2478
+ * Handle client disconnection
2479
+ * @private
2480
+ */
2481
+ #handleDisconnection(ws) {
2482
+ this.#rateLimits.delete(ws.connectionId);
2483
+
2484
+ if (ws.clientId) {
2485
+ this.#clients.delete(ws.clientId); // Immediately remove from active clients (otherwise, server would try to message this client)
2486
+
2487
+ // If client was in a room, check if they were the host & migrate
2488
+ const roomId = this.#clientRooms.get(ws.clientId);
2489
+ if (roomId != null) this.#changeHostIfDisconnected(roomId, ws.clientId);
2490
+
2491
+ if (ws.willfulDisconnect) {
2492
+ this.#disconnectClient(ws); // Immediate disconnection
2493
+ } else {
2494
+ // Pending complete disconnection with 5s grace period to allow for reconnections
2495
+ this.#pendingDisconnects.set(ws.clientId, {
2496
+ timeout: setTimeout(() => {
2497
+ this.#disconnectClient(ws);
2498
+ }, 5000)
2499
+ });
2500
+ }
2501
+ }
2502
+ }
2503
+
2504
+ /**
2505
+ * Disconnect a client
2506
+ * @private
2507
+ * @param {Object} ws
2508
+ */
2509
+ #disconnectClient(ws) {
2510
+ this.#pendingDisconnects.delete(ws.clientId);
2511
+ this.#clientTokens.delete(ws.clientId);
2512
+ let roomId = this.#clientRooms.get(ws.clientId);
2513
+ const room = this.#rooms[roomId];
2514
+
2515
+ if (room) {
2516
+ room.participants = room.participants.filter(p => p !== ws.clientId); // Remove client from room
2517
+ this.#clientRooms.delete(ws.clientId);
2518
+
2519
+ if (room.participants?.length === 0) {
2520
+ delete this.#rooms[roomId]; // Delete room if now empty
2521
+ this.#roomVersions.delete(roomId); // Delete room version
2522
+ this.#triggerEvent("roomDestroyed", roomId);
2523
+ if (this.#debug) console.log("Deleted room with id " + roomId + ".");
2524
+ roomId = null; // If room was destroyed, set roomId to null
2525
+ } else {
2526
+ // Notify remaining participants
2527
+ room.participants.forEach(p => {
2528
+ const client = this.#clients.get(p);
2529
+ if (client) client.send(encode({
2530
+ type: 'client_disconnected',
2531
+ client: ws.clientId,
2532
+ participantCount: room.participants.length
2533
+ }), { binary: true });
2534
+ });
2535
+ }
2536
+ }
2537
+
2538
+ this.#triggerEvent("clientDisconnected", ws.clientId, roomId);
2539
+ }
2540
+
2541
+ /**
2542
+ * Register an event callback
2543
+ * @param {string} event - Event name
2544
+ * @param {Function} callback - Callback function
2545
+ */
2546
+ onEvent(event, callback) {
2547
+ const validEvents = ["clientRegistered", "clientRegistrationRequested", "clientDisconnected", "clientJoinedRoom", "clientJoinRequested", "roomCreated", "roomCreationRequested", "requestReceived", "storageUpdated", "storageUpdateRequested", "roomDestroyed"];
2548
+ if (!validEvents.includes(event)) return console.warn(`Invalid PlaySocket event type "${event}"`);
2549
+ if (!this.#callbacks.has(event)) this.#callbacks.set(event, []);
2550
+ this.#callbacks.get(event).push(callback);
2551
+ }
2552
+
2553
+ /**
2554
+ * Kick a player from the server
2555
+ * @param {string} clientId - Client ID
2556
+ * @param {string} [reason] - Optional reason
2557
+ */
2558
+ kick(clientId, reason) {
2559
+ const client = this.#clients.get(clientId);
2560
+ if (client) {
2561
+ client.willfulDisconnect = true;
2562
+ client.send(encode({ type: 'kicked', reason }), { binary: true });
2563
+ client.close();
2564
+ }
2565
+ }
2566
+
2567
+ /**
2568
+ * Trigger an event to registered callbacks
2569
+ * @private
2570
+ */
2571
+ async #triggerEvent(event, ...args) {
2572
+ const callbacks = this.#callbacks.get(event);
2573
+ if (!callbacks) return;
2574
+
2575
+ for (const callback of callbacks) {
2576
+ try {
2577
+ const result = await callback(...args);
2578
+ if (result != null) return result; // Return any non-null/undefined result
2579
+ } catch (error) {
2580
+ console.error(`PlaySocket ${event} callback error:`, error);
2581
+ }
2582
+ }
2583
+ return true;
2584
+ }
2585
+
2586
+ /**
2587
+ * Get snapshot of a room's storage
2588
+ * @returns {Object} - Storage object
2589
+ */
2590
+ getRoomStorage(roomId) {
2591
+ const room = this.#rooms[roomId];
2592
+ if (room) return room.crdtManager.getPropertyStore;
2593
+ }
2594
+
2595
+ /**
2596
+ * Update a value in a room's storage
2597
+ * @param {string} roomId - Room ID
2598
+ * @param {string} key - Storage key
2599
+ * @param {string} type - Operation type
2600
+ * @param {*} value - New value or value to operate on
2601
+ * @param {*} updateValue - New value for update-matching
2602
+ */
2603
+ updateRoomStorage(roomId, key, type, value, updateValue) {
2604
+ if (this.#debug) console.log(`Playsocket server property update for room ${roomId}, key ${key}, operation ${type}, value ${value} and updateValue ${updateValue}.`);
2605
+ const room = this.#rooms[roomId];
2606
+ if (room) {
2607
+ const propertyUpdate = room.crdtManager.updateProperty(key, type, value, updateValue);
2608
+ const currentVersion = this.#roomVersions.get(roomId) + 1;
2609
+ this.#roomVersions.set(roomId, currentVersion); // Increment version for this room
2610
+
2611
+ room.participants?.forEach(p => {
2612
+ const client = this.#clients.get(p);
2613
+ if (client) {
2614
+ client.send(encode({
2615
+ type: 'property_updated',
2616
+ update: propertyUpdate,
2617
+ version: currentVersion
2618
+ }), { binary: true });
2619
+ }
2620
+ });
2621
+ this.#triggerEvent("storageUpdated", { roomId, clientId: null, update: structuredClone(propertyUpdate), storage: this.getRoomStorage(roomId) });
2622
+ }
2623
+ }
2624
+
2625
+ /**
2626
+ * Close all client connections, then close the websocket and http server
2627
+ */
2628
+ stop() {
2629
+ clearInterval(this.#heartbeatInterval);
2630
+ if (this.#wss) {
2631
+ this.#clients.forEach(client => {
2632
+ client.send(encode({ type: 'server_stopped' }), { binary: true });
2633
+ client.close();
2634
+ });
2635
+ this.#wss.close();
2636
+ }
2637
+ if (this.#server && this.#ownsServer) this.#server.close(() => { console.log('PlaySocket server stopped.'); });
2638
+ this.#pendingDisconnects.forEach((data) => {
2639
+ clearTimeout(data.timeout);
2640
+ });
2641
+ }
2642
+
2643
+ get getRooms() { return { ...this.#rooms } }
2644
+ }
2645
+
2646
+ export { PlaySocketServer as default };