@colyseus/schema 3.0.0-alpha.1 → 3.0.0-alpha.10

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.
Files changed (40) hide show
  1. package/build/cjs/index.js +85 -64
  2. package/build/cjs/index.js.map +1 -1
  3. package/build/esm/index.mjs +85 -64
  4. package/build/esm/index.mjs.map +1 -1
  5. package/build/umd/index.js +85 -64
  6. package/lib/Reflection.d.ts +1 -1
  7. package/lib/Reflection.js +1 -2
  8. package/lib/Reflection.js.map +1 -1
  9. package/lib/decoder/DecodeOperation.js +2 -2
  10. package/lib/decoder/DecodeOperation.js.map +1 -1
  11. package/lib/decoder/Decoder.d.ts +1 -1
  12. package/lib/decoder/Decoder.js +4 -4
  13. package/lib/decoder/Decoder.js.map +1 -1
  14. package/lib/decoder/strategy/StateCallbacks.js +1 -1
  15. package/lib/decoder/strategy/StateCallbacks.js.map +1 -1
  16. package/lib/encoder/ChangeTree.d.ts +0 -2
  17. package/lib/encoder/ChangeTree.js +2 -6
  18. package/lib/encoder/ChangeTree.js.map +1 -1
  19. package/lib/encoder/Encoder.d.ts +5 -4
  20. package/lib/encoder/Encoder.js +46 -43
  21. package/lib/encoder/Encoder.js.map +1 -1
  22. package/lib/encoder/StateView.d.ts +2 -0
  23. package/lib/encoder/StateView.js +4 -1
  24. package/lib/encoder/StateView.js.map +1 -1
  25. package/lib/encoding/decode.d.ts +21 -19
  26. package/lib/encoding/decode.js +6 -6
  27. package/lib/encoding/decode.js.map +1 -1
  28. package/lib/encoding/encode.d.ts +3 -2
  29. package/lib/encoding/encode.js +24 -22
  30. package/lib/encoding/encode.js.map +1 -1
  31. package/package.json +1 -1
  32. package/src/Reflection.ts +1 -2
  33. package/src/decoder/DecodeOperation.ts +3 -3
  34. package/src/decoder/Decoder.ts +5 -5
  35. package/src/decoder/strategy/StateCallbacks.ts +1 -1
  36. package/src/encoder/ChangeTree.ts +2 -6
  37. package/src/encoder/Encoder.ts +51 -47
  38. package/src/encoder/StateView.ts +4 -0
  39. package/src/encoding/decode.ts +24 -25
  40. package/src/encoding/encode.ts +26 -23
@@ -170,7 +170,6 @@
170
170
  // pending changes to be encoded
171
171
  this.changes = new Map();
172
172
  this.filteredChanges = new Map();
173
- this.views = [];
174
173
  }
175
174
  getNextUniqueId() {
176
175
  return this.nextUniqueId++;
@@ -265,14 +264,12 @@
265
264
  this.checkIsFiltered(parent, parentIndex);
266
265
  if (!this.isFiltered) {
267
266
  this.root.changes.set(this, this.changes);
267
+ this.root.allChanges.set(this, this.allChanges);
268
268
  }
269
269
  if (this.isFiltered || this.isPartiallyFiltered) {
270
270
  this.root.filteredChanges.set(this, this.filteredChanges);
271
271
  this.root.allFilteredChanges.set(this, this.filteredChanges);
272
272
  }
273
- else {
274
- this.root.allChanges.set(this, this.allChanges);
275
- }
276
273
  this.ensureRefId();
277
274
  this.forEachChild((changeTree, atIndex) => {
278
275
  changeTree.setParent(this.ref, root, atIndex);
@@ -364,7 +361,6 @@
364
361
  }
365
362
  _shiftAllChangeIndexes(shiftIndex, startIndex = 0, allChangeSet) {
366
363
  Array.from(allChangeSet.entries()).forEach(([index, op]) => {
367
- // console.log('shiftAllChangeIndexes', index >= startIndex, { index, op, shiftIndex, startIndex })
368
364
  if (index >= startIndex) {
369
365
  allChangeSet.delete(index);
370
366
  allChangeSet.set(index + shiftIndex, op);
@@ -505,7 +501,7 @@
505
501
  }
506
502
  checkIsFiltered(parent, parentIndex) {
507
503
  // Detect if current structure has "filters" declared
508
- this.isPartiallyFiltered = this.ref['constructor']?.[Symbol.metadata]?.[-2];
504
+ this.isPartiallyFiltered = (this.ref['constructor']?.[Symbol.metadata]?.[-2] !== undefined);
509
505
  // TODO: support "partially filtered", where the instance is visible, but only a field is not.
510
506
  // Detect if parent has "filters" declared
511
507
  while (parent && !this.isFiltered) {
@@ -566,6 +562,29 @@
566
562
  textEncoder = new TextEncoder();
567
563
  }
568
564
  catch (e) { }
565
+ const hasBufferByteLength = (typeof Buffer !== 'undefined' && Buffer.byteLength);
566
+ const utf8Length = (hasBufferByteLength)
567
+ ? Buffer.byteLength // node
568
+ : function (str, _) {
569
+ var c = 0, length = 0;
570
+ for (var i = 0, l = str.length; i < l; i++) {
571
+ c = str.charCodeAt(i);
572
+ if (c < 0x80) {
573
+ length += 1;
574
+ }
575
+ else if (c < 0x800) {
576
+ length += 2;
577
+ }
578
+ else if (c < 0xd800 || c >= 0xe000) {
579
+ length += 3;
580
+ }
581
+ else {
582
+ i++;
583
+ length += 4;
584
+ }
585
+ }
586
+ return length;
587
+ };
569
588
  function utf8Write(view, str, it) {
570
589
  var c = 0;
571
590
  for (var i = 0, l = str.length; i < l; i++) {
@@ -660,8 +679,7 @@
660
679
  if (!value) {
661
680
  value = "";
662
681
  }
663
- // let length = utf8Length(value);
664
- let length = Buffer.byteLength(value, "utf8");
682
+ let length = utf8Length(value, "utf8");
665
683
  let size = 0;
666
684
  // fixstr
667
685
  if (length < 0x20) {
@@ -772,6 +790,7 @@
772
790
 
773
791
  var encode = /*#__PURE__*/Object.freeze({
774
792
  __proto__: null,
793
+ utf8Length: utf8Length,
775
794
  utf8Write: utf8Write,
776
795
  int8: int8$1,
777
796
  uint8: uint8$1,
@@ -995,9 +1014,9 @@
995
1014
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
996
1015
  * SOFTWARE
997
1016
  */
998
- function utf8Read(bytes, offset, length) {
1017
+ function utf8Read(bytes, it, length) {
999
1018
  var string = '', chr = 0;
1000
- for (var i = offset, end = offset + length; i < end; i++) {
1019
+ for (var i = it.offset, end = it.offset + length; i < end; i++) {
1001
1020
  var byte = bytes[i];
1002
1021
  if ((byte & 0x80) === 0x00) {
1003
1022
  string += String.fromCharCode(byte);
@@ -1032,6 +1051,7 @@
1032
1051
  // (do not throw error to avoid server/client from crashing due to hack attemps)
1033
1052
  // throw new Error('Invalid byte ' + byte.toString(16));
1034
1053
  }
1054
+ it.offset += length;
1035
1055
  return string;
1036
1056
  }
1037
1057
  function int8(bytes, it) {
@@ -1099,9 +1119,7 @@
1099
1119
  else if (prefix === 0xdb) {
1100
1120
  length = uint32(bytes, it);
1101
1121
  }
1102
- const value = utf8Read(bytes, it.offset, length);
1103
- it.offset += length;
1104
- return value;
1122
+ return utf8Read(bytes, it, length);
1105
1123
  }
1106
1124
  function stringCheck(bytes, it) {
1107
1125
  const prefix = bytes[it.offset];
@@ -1205,6 +1223,7 @@
1205
1223
 
1206
1224
  var decode = /*#__PURE__*/Object.freeze({
1207
1225
  __proto__: null,
1226
+ utf8Read: utf8Read,
1208
1227
  int8: int8,
1209
1228
  uint8: uint8,
1210
1229
  int16: int16,
@@ -1228,7 +1247,7 @@
1228
1247
 
1229
1248
  const DEFINITION_MISMATCH = -1;
1230
1249
  function decodeValue(decoder, operation, ref, index, type, bytes, it, allChanges) {
1231
- const $root = decoder.$root;
1250
+ const $root = decoder.root;
1232
1251
  const previousValue = ref[$getByIndex](index);
1233
1252
  let value;
1234
1253
  if ((operation & exports.OPERATION.DELETE) === exports.OPERATION.DELETE) {
@@ -1428,7 +1447,7 @@
1428
1447
  else if (operation === exports.OPERATION.DELETE_BY_REFID) {
1429
1448
  // TODO: refactor here, try to follow same flow as below
1430
1449
  const refId = number(bytes, it);
1431
- const previousValue = decoder.$root.refs.get(refId);
1450
+ const previousValue = decoder.root.refs.get(refId);
1432
1451
  const index = ref.findIndex((value) => value === previousValue);
1433
1452
  ref[$deleteByIndex](index);
1434
1453
  allChanges.push({
@@ -3364,13 +3383,13 @@
3364
3383
  // });
3365
3384
  }
3366
3385
  setRoot(state) {
3367
- this.$root = new Root();
3386
+ this.root = new Root();
3368
3387
  this.state = state;
3369
- state[$changes].setRoot(this.$root);
3388
+ state[$changes].setRoot(this.root);
3370
3389
  }
3371
- encode(it = { offset: 0 }, view, bytes = this.sharedBuffer, changeTrees = this.$root.changes) {
3390
+ encode(it = { offset: 0 }, view, buffer = this.sharedBuffer, changeTrees = this.root.changes) {
3372
3391
  const initialOffset = it.offset; // cache current offset in case we need to resize the buffer
3373
- const isEncodeAll = this.$root.allChanges === changeTrees;
3392
+ const isEncodeAll = this.root.allChanges === changeTrees;
3374
3393
  const hasView = (view !== undefined);
3375
3394
  const rootChangeTree = this.state[$changes];
3376
3395
  const changeTreesIterator = changeTrees.entries();
@@ -3390,8 +3409,8 @@
3390
3409
  }
3391
3410
  // skip root `refId` if it's the first change tree
3392
3411
  if (it.offset !== initialOffset || changeTree !== rootChangeTree) {
3393
- bytes[it.offset++] = SWITCH_TO_STRUCTURE & 255;
3394
- number$1(bytes, changeTree.refId, it);
3412
+ buffer[it.offset++] = SWITCH_TO_STRUCTURE & 255;
3413
+ number$1(buffer, changeTree.refId, it);
3395
3414
  }
3396
3415
  const changesIterator = changes.entries();
3397
3416
  for (const [fieldIndex, operation] of changesIterator) {
@@ -3413,17 +3432,21 @@
3413
3432
  // fieldIndex,
3414
3433
  // operation: OPERATION[operation],
3415
3434
  // });
3416
- encoder(this, bytes, changeTree, fieldIndex, operation, it, isEncodeAll, hasView);
3435
+ encoder(this, buffer, changeTree, fieldIndex, operation, it, isEncodeAll, hasView);
3417
3436
  }
3418
3437
  }
3419
- if (it.offset > bytes.byteLength) {
3420
- const newSize = getNextPowerOf2(this.sharedBuffer.byteLength * 2);
3421
- console.warn("@colyseus/schema encode buffer overflow. Current buffer size: " + bytes.byteLength + ", encoding offset: " + it.offset + ", new size: " + newSize);
3438
+ if (it.offset > buffer.byteLength) {
3439
+ const newSize = getNextPowerOf2(buffer.byteLength * 2);
3440
+ console.warn("@colyseus/schema encode buffer overflow. Current buffer size: " + buffer.byteLength + ", encoding offset: " + it.offset + ", new size: " + newSize);
3422
3441
  //
3423
3442
  // resize buffer and re-encode (TODO: can we avoid re-encoding here?)
3424
3443
  //
3425
- this.sharedBuffer = Buffer.allocUnsafeSlow(newSize);
3426
- return this.encode({ offset: initialOffset }, view);
3444
+ buffer = Buffer.allocUnsafeSlow(newSize);
3445
+ // assign resized buffer to local sharedBuffer
3446
+ if (buffer === this.sharedBuffer) {
3447
+ this.sharedBuffer = buffer;
3448
+ }
3449
+ return this.encode({ offset: initialOffset }, view, buffer);
3427
3450
  }
3428
3451
  else {
3429
3452
  //
@@ -3435,42 +3458,41 @@
3435
3458
  //
3436
3459
  this.onEndEncode(changeTrees);
3437
3460
  }
3438
- // return bytes;
3439
- return bytes.slice(0, it.offset);
3461
+ return buffer.subarray(0, it.offset);
3440
3462
  }
3441
3463
  }
3442
- encodeAll(it = { offset: 0 }) {
3443
- // console.log(`encodeAll(), this.$root.allChanges (${this.$root.allChanges.size})`);
3444
- // Array.from(this.$root.allChanges.entries()).map((item) => {
3445
- // console.log("->", item[0].refId, item[0].ref.toJSON());
3464
+ encodeAll(it = { offset: 0 }, buffer = this.sharedBuffer) {
3465
+ // console.log(`encodeAll(), this.root.allChanges (${this.root.allChanges.size})`);
3466
+ // Array.from(this.root.allChanges.entries()).map((item) => {
3467
+ // console.log("->", { ref: item[0].ref.constructor.name, refId: item[0].refId, changes: item[1].size });
3446
3468
  // });
3447
- return this.encode(it, undefined, this.sharedBuffer, this.$root.allChanges);
3469
+ return this.encode(it, undefined, buffer, this.root.allChanges);
3448
3470
  }
3449
3471
  encodeAllView(view, sharedOffset, it, bytes = this.sharedBuffer) {
3450
3472
  const viewOffset = it.offset;
3451
- // console.log(`encodeAllView(), this.$root.allFilteredChanges (${this.$root.allFilteredChanges.size})`);
3473
+ // console.log(`encodeAllView(), this.root.allFilteredChanges (${this.root.allFilteredChanges.size})`);
3452
3474
  // this.debugAllFilteredChanges();
3453
3475
  // try to encode "filtered" changes
3454
- this.encode(it, view, bytes, this.$root.allFilteredChanges);
3476
+ this.encode(it, view, bytes, this.root.allFilteredChanges);
3455
3477
  return Buffer.concat([
3456
- bytes.slice(0, sharedOffset),
3457
- bytes.slice(viewOffset, it.offset)
3478
+ bytes.subarray(0, sharedOffset),
3479
+ bytes.subarray(viewOffset, it.offset)
3458
3480
  ]);
3459
3481
  }
3460
- // debugAllFilteredChanges() {
3461
- // Array.from(this.$root.allFilteredChanges.entries()).map((item) => {
3462
- // console.log("->", { refId: item[0].refId }, item[0].ref.toJSON());
3463
- // if (Array.isArray(item[0].ref.toJSON())) {
3464
- // item[1].forEach((op, key) => {
3465
- // console.log(" ->", { key, op: OPERATION[op] });
3466
- // })
3467
- // }
3468
- // });
3469
- // }
3482
+ debugAllFilteredChanges() {
3483
+ Array.from(this.root.allFilteredChanges.entries()).map((item) => {
3484
+ console.log("->", { refId: item[0].refId, changes: item[1].size }, item[0].ref.toJSON());
3485
+ if (Array.isArray(item[0].ref.toJSON())) {
3486
+ item[1].forEach((op, key) => {
3487
+ console.log(" ->", { key, op: exports.OPERATION[op] });
3488
+ });
3489
+ }
3490
+ });
3491
+ }
3470
3492
  encodeView(view, sharedOffset, it, bytes = this.sharedBuffer) {
3471
3493
  const viewOffset = it.offset;
3472
3494
  // try to encode "filtered" changes
3473
- this.encode(it, view, bytes, this.$root.filteredChanges);
3495
+ this.encode(it, view, bytes, this.root.filteredChanges);
3474
3496
  // encode visibility changes (add/remove for this view)
3475
3497
  const viewChangesIterator = view.changes.entries();
3476
3498
  for (const [changeTree, changes] of viewChangesIterator) {
@@ -3498,11 +3520,11 @@
3498
3520
  // clear "view" changes after encoding
3499
3521
  view.changes.clear();
3500
3522
  return Buffer.concat([
3501
- bytes.slice(0, sharedOffset),
3502
- bytes.slice(viewOffset, it.offset)
3523
+ bytes.subarray(0, sharedOffset),
3524
+ bytes.subarray(viewOffset, it.offset)
3503
3525
  ]);
3504
3526
  }
3505
- onEndEncode(changeTrees = this.$root.changes) {
3527
+ onEndEncode(changeTrees = this.root.changes) {
3506
3528
  const changeTreesIterator = changeTrees.entries();
3507
3529
  for (const [changeTree, _] of changeTreesIterator) {
3508
3530
  changeTree.endEncode();
@@ -3510,14 +3532,14 @@
3510
3532
  }
3511
3533
  discardChanges() {
3512
3534
  // discard shared changes
3513
- if (this.$root.changes.size > 0) {
3514
- this.onEndEncode(this.$root.changes);
3515
- this.$root.changes.clear();
3535
+ if (this.root.changes.size > 0) {
3536
+ this.onEndEncode(this.root.changes);
3537
+ this.root.changes.clear();
3516
3538
  }
3517
3539
  // discard filtered changes
3518
- if (this.$root.filteredChanges.size > 0) {
3519
- this.onEndEncode(this.$root.filteredChanges);
3520
- this.$root.filteredChanges.clear();
3540
+ if (this.root.filteredChanges.size > 0) {
3541
+ this.onEndEncode(this.root.filteredChanges);
3542
+ this.root.filteredChanges.clear();
3521
3543
  }
3522
3544
  }
3523
3545
  tryEncodeTypeId(bytes, baseType, targetType, it) {
@@ -3678,12 +3700,12 @@
3678
3700
  }
3679
3701
  setRoot(root) {
3680
3702
  this.state = root;
3681
- this.$root = new ReferenceTracker();
3682
- this.$root.addRef(0, root);
3703
+ this.root = new ReferenceTracker();
3704
+ this.root.addRef(0, root);
3683
3705
  }
3684
3706
  decode(bytes, it = { offset: 0 }, ref = this.state) {
3685
3707
  const allChanges = [];
3686
- const $root = this.$root;
3708
+ const $root = this.root;
3687
3709
  const totalBytes = bytes.byteLength;
3688
3710
  let decoder = ref['constructor'][$decoder];
3689
3711
  this.currentRefId = 0;
@@ -3764,7 +3786,7 @@
3764
3786
  previousValue: value
3765
3787
  });
3766
3788
  if (needRemoveRef) {
3767
- this.$root.removeRef(this.$root.refIds.get(value));
3789
+ this.root.removeRef(this.root.refIds.get(value));
3768
3790
  }
3769
3791
  });
3770
3792
  }
@@ -3804,7 +3826,7 @@
3804
3826
  super(...arguments);
3805
3827
  this.types = new ArraySchema();
3806
3828
  }
3807
- static encode(instance, context) {
3829
+ static encode(instance, context, it = { offset: 0 }) {
3808
3830
  if (!context) {
3809
3831
  context = new TypeContext(instance.constructor);
3810
3832
  }
@@ -3861,7 +3883,6 @@
3861
3883
  }
3862
3884
  buildType(type, klass[Symbol.metadata]);
3863
3885
  }
3864
- const it = { offset: 0 };
3865
3886
  const buf = encoder.encodeAll(it);
3866
3887
  return Buffer.from(buf, 0, it.offset);
3867
3888
  }
@@ -18,6 +18,6 @@ export declare class ReflectionType extends Schema {
18
18
  }
19
19
  export declare class Reflection extends Schema {
20
20
  types: ArraySchema<ReflectionType>;
21
- static encode(instance: Schema, context?: TypeContext): Buffer;
21
+ static encode(instance: Schema, context?: TypeContext, it?: Iterator): Buffer;
22
22
  static decode<T extends Schema = Schema>(bytes: Buffer, it?: Iterator): T;
23
23
  }
package/lib/Reflection.js CHANGED
@@ -49,7 +49,7 @@ class Reflection extends Schema_1.Schema {
49
49
  super(...arguments);
50
50
  this.types = new ArraySchema_1.ArraySchema();
51
51
  }
52
- static encode(instance, context) {
52
+ static encode(instance, context, it = { offset: 0 }) {
53
53
  if (!context) {
54
54
  context = new annotations_1.TypeContext(instance.constructor);
55
55
  }
@@ -106,7 +106,6 @@ class Reflection extends Schema_1.Schema {
106
106
  }
107
107
  buildType(type, klass[Symbol.metadata]);
108
108
  }
109
- const it = { offset: 0 };
110
109
  const buf = encoder.encodeAll(it);
111
110
  return Buffer.from(buf, 0, it.offset);
112
111
  }
@@ -1 +1 @@
1
- {"version":3,"file":"Reflection.js","sourceRoot":"","sources":["../src/Reflection.ts"],"names":[],"mappings":";;;;;;;;;AAAA,+CAAiF;AACjF,yCAAsC;AACtC,4DAAyD;AAEzD,+CAA4C;AAC5C,+CAA4C;AAC5C,qCAAkC;AAElC;;GAEG;AACH,MAAa,eAAgB,SAAQ,eAAM;CAI1C;AAJD,0CAIC;AAHmB;IAAf,IAAA,kBAAI,EAAC,QAAQ,CAAC;6CAAc;AACb;IAAf,IAAA,kBAAI,EAAC,QAAQ,CAAC;6CAAc;AACb;IAAf,IAAA,kBAAI,EAAC,QAAQ,CAAC;uDAAwB;AAG3C,MAAa,cAAe,SAAQ,eAAM;IAA1C;;QAG+B,WAAM,GAAG,IAAI,yBAAW,EAAmB,CAAC;IAC3E,CAAC;CAAA;AAJD,wCAIC;AAHmB;IAAf,IAAA,kBAAI,EAAC,QAAQ,CAAC;0CAAY;AACX;IAAf,IAAA,kBAAI,E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CAAC;yBAAM,CAAC;wBACJ,sFAAsF;wBACtF,mBAAQ,CAAC,QAAQ,CAAC,QAAQ,EAAE,UAAU,EAAE,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,EAAE,OAAO,EAAoB,CAAC,CAAC;oBACpG,CAAC;gBAEL,CAAC;qBAAM,CAAC;oBACJ,uEAAuE;oBACvE,mBAAQ,CAAC,QAAQ,CAAC,QAAQ,EAAE,UAAU,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,IAAqB,CAAC,CAAC;gBACrF,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAClC,CAAC;CACJ;AAhJD,gCAgJC;AA/I6B;IAAzB,IAAA,kBAAI,EAAC,CAAE,cAAc,CAAE,CAAC;yCAAwE","sourcesContent":["import { type, PrimitiveType, DefinitionType, TypeContext } from \"./annotations\";\nimport { Metadata } from \"./Metadata\";\nimport { ArraySchema } from \"./types/custom/ArraySchema\";\nimport { Iterator } from \"./encoding/decode\";\nimport { Encoder } from \"./encoder/Encoder\";\nimport { Decoder } from \"./decoder/Decoder\";\nimport { Schema } from \"./Schema\";\n\n/**\n * Reflection\n */\nexport class ReflectionField extends Schema {\n @type(\"string\") name: string;\n @type(\"string\") type: string;\n @type(\"number\") referencedType: number;\n}\n\nexport class ReflectionType extends Schema {\n @type(\"number\") id: number;\n @type(\"number\") extendsId: number;\n @type([ ReflectionField ]) fields = new ArraySchema<ReflectionField>();\n}\n\nexport class Reflection extends Schema {\n @type([ ReflectionType ]) types: ArraySchema<ReflectionType> = new ArraySchema<ReflectionType>();\n\n static encode (instance: Schema, context?: TypeContext) {\n if (!context) {\n context = new TypeContext(instance.constructor as typeof Schema);\n }\n\n const reflection = new Reflection();\n const encoder = new Encoder(reflection);\n\n const buildType = (currentType: ReflectionType, metadata: Metadata) => {\n for (const fieldName in metadata) {\n // skip fields from parent classes\n if (!Object.prototype.hasOwnProperty.call(metadata, fieldName)) {\n continue;\n }\n\n const field = new ReflectionField();\n field.name = fieldName;\n\n let fieldType: string;\n\n const type = metadata[fieldName].type;\n\n if (typeof (type) === \"string\") {\n fieldType = type;\n\n } else {\n let childTypeSchema: typeof Schema;\n\n //\n // TODO: refactor below.\n //\n if (Schema.is(type)) {\n fieldType = \"ref\";\n childTypeSchema = type as typeof Schema;\n\n } else {\n fieldType = Object.keys(type)[0];\n\n if (typeof(type[fieldType]) === \"string\") {\n fieldType += \":\" + type[fieldType]; // array:string\n\n } else {\n childTypeSchema = type[fieldType];\n }\n }\n\n field.referencedType = (childTypeSchema)\n ? context.getTypeId(childTypeSchema)\n : -1;\n }\n\n field.type = fieldType;\n currentType.fields.push(field);\n }\n\n reflection.types.push(currentType);\n }\n\n for (let typeid in context.types) {\n const klass = context.types[typeid];\n const type = new ReflectionType();\n type.id = Number(typeid);\n\n // support inheritance\n const inheritFrom = Object.getPrototypeOf(klass);\n if (inheritFrom !== Schema) {\n type.extendsId = context.schemas.get(inheritFrom);\n }\n\n buildType(type, klass[Symbol.metadata]);\n }\n\n const it = { offset: 0 };\n const buf = encoder.encodeAll(it);\n return Buffer.from(buf, 0, it.offset);\n }\n\n static decode<T extends Schema = Schema>(bytes: Buffer, it?: Iterator): T {\n const reflection = new Reflection();\n\n const reflectionDecoder = new Decoder(reflection);\n reflectionDecoder.decode(bytes, it);\n\n const context = new TypeContext();\n\n const schemaTypes = reflection.types.reduce((types, reflectionType) => {\n const parentKlass: typeof Schema = types[reflectionType.extendsId] || Schema;\n const schema: typeof Schema = class _ extends parentKlass {};\n\n // const _metadata = Object.create(_classSuper[Symbol.metadata] ?? null);\n const _metadata = parentKlass && parentKlass[Symbol.metadata] || Object.create(null);\n Object.defineProperty(schema, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata })\n\n // register for inheritance support\n TypeContext.register(schema);\n\n const typeid = reflectionType.id;\n types[typeid] = schema\n context.add(schema, typeid);\n return types;\n }, {});\n\n reflection.types.forEach((reflectionType) => {\n const schemaType = schemaTypes[reflectionType.id];\n const metadata = schemaType[Symbol.metadata];\n\n const parentKlass = reflection.types[reflectionType.extendsId];\n const parentFieldIndex = parentKlass && parentKlass.fields.length || 0;\n\n reflectionType.fields.forEach((field, i) => {\n const fieldIndex = parentFieldIndex + i;\n\n if (field.referencedType !== undefined) {\n let fieldType = field.type;\n let refType = schemaTypes[field.referencedType];\n\n // map or array of primitive type (-1)\n if (!refType) {\n const typeInfo = field.type.split(\":\");\n fieldType = typeInfo[0];\n refType = typeInfo[1];\n }\n\n if (fieldType === \"ref\") {\n // type(refType)(schemaType.prototype, field.name);\n Metadata.addField(metadata, fieldIndex, field.name, refType);\n\n } else {\n // type({ [fieldType]: refType } as DefinitionType)(schemaType.prototype, field.name);\n Metadata.addField(metadata, fieldIndex, field.name, { [fieldType]: refType } as DefinitionType);\n }\n\n } else {\n // type(field.type as PrimitiveType)(schemaType.prototype, field.name);\n Metadata.addField(metadata, fieldIndex, field.name, field.type as PrimitiveType);\n }\n });\n });\n\n return new (schemaTypes[0])();\n }\n}\n"]}
1
+ {"version":3,"file":"Reflection.js","sourceRoot":"","sources":["../src/Reflection.ts"],"names":[],"mappings":";;;;;;;;;AAAA,+CAAiF;AACjF,yCAAsC;AACtC,4DAAyD;AAEzD,+CAA4C;AAC5C,+CAA4C;AAC5C,qCAAkC;AAElC;;GAEG;AACH,MAAa,eAAgB,SAAQ,eAAM;CAI1C;AAJD,0CAIC;AAHmB;IAAf,IAAA,kBAAI,EAAC,QAAQ,CAAC;6CAAc;AACb;IAAf,IAAA,kBAAI,EAAC,QAAQ,CAAC;6CAAc;AACb;IAAf,IAAA,kBAAI,EAAC,QAAQ,CAAC;uDAAwB;AAG3C,MAAa,cAAe,SAAQ,eAAM;IAA1C;;QAG+B,WAAM,GAAG,IAAI,yBAAW,EAAmB,CAAC;IAC3E,CAAC;CAAA;AAJD,wCAIC;AAHmB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AAE,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;oBAEjE,CAAC;yBAAM,CAAC;wBACJ,sFAAsF;wBACtF,mBAAQ,CAAC,QAAQ,CAAC,QAAQ,EAAE,UAAU,EAAE,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,EAAE,OAAO,EAAoB,CAAC,CAAC;oBACpG,CAAC;gBAEL,CAAC;qBAAM,CAAC;oBACJ,uEAAuE;oBACvE,mBAAQ,CAAC,QAAQ,CAAC,QAAQ,EAAE,UAAU,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,IAAqB,CAAC,CAAC;gBACrF,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAClC,CAAC;CACJ;AA/ID,gCA+IC;AA9I6B;IAAzB,IAAA,kBAAI,EAAC,CAAE,cAAc,CAAE,CAAC;yCAAwE","sourcesContent":["import { type, PrimitiveType, DefinitionType, TypeContext } from \"./annotations\";\nimport { Metadata } from \"./Metadata\";\nimport { ArraySchema } from \"./types/custom/ArraySchema\";\nimport { Iterator } from \"./encoding/decode\";\nimport { Encoder } from \"./encoder/Encoder\";\nimport { Decoder } from \"./decoder/Decoder\";\nimport { Schema } from \"./Schema\";\n\n/**\n * Reflection\n */\nexport class ReflectionField extends Schema {\n @type(\"string\") name: string;\n @type(\"string\") type: string;\n @type(\"number\") referencedType: number;\n}\n\nexport class ReflectionType extends Schema {\n @type(\"number\") id: number;\n @type(\"number\") extendsId: number;\n @type([ ReflectionField ]) fields = new ArraySchema<ReflectionField>();\n}\n\nexport class Reflection extends Schema {\n @type([ ReflectionType ]) types: ArraySchema<ReflectionType> = new ArraySchema<ReflectionType>();\n\n static encode(instance: Schema, context?: TypeContext, it: Iterator = { offset: 0 }) {\n if (!context) {\n context = new TypeContext(instance.constructor as typeof Schema);\n }\n\n const reflection = new Reflection();\n const encoder = new Encoder(reflection);\n\n const buildType = (currentType: ReflectionType, metadata: Metadata) => {\n for (const fieldName in metadata) {\n // skip fields from parent classes\n if (!Object.prototype.hasOwnProperty.call(metadata, fieldName)) {\n continue;\n }\n\n const field = new ReflectionField();\n field.name = fieldName;\n\n let fieldType: string;\n\n const type = metadata[fieldName].type;\n\n if (typeof (type) === \"string\") {\n fieldType = type;\n\n } else {\n let childTypeSchema: typeof Schema;\n\n //\n // TODO: refactor below.\n //\n if (Schema.is(type)) {\n fieldType = \"ref\";\n childTypeSchema = type as typeof Schema;\n\n } else {\n fieldType = Object.keys(type)[0];\n\n if (typeof(type[fieldType]) === \"string\") {\n fieldType += \":\" + type[fieldType]; // array:string\n\n } else {\n childTypeSchema = type[fieldType];\n }\n }\n\n field.referencedType = (childTypeSchema)\n ? context.getTypeId(childTypeSchema)\n : -1;\n }\n\n field.type = fieldType;\n currentType.fields.push(field);\n }\n\n reflection.types.push(currentType);\n }\n\n for (let typeid in context.types) {\n const klass = context.types[typeid];\n const type = new ReflectionType();\n type.id = Number(typeid);\n\n // support inheritance\n const inheritFrom = Object.getPrototypeOf(klass);\n if (inheritFrom !== Schema) {\n type.extendsId = context.schemas.get(inheritFrom);\n }\n\n buildType(type, klass[Symbol.metadata]);\n }\n\n const buf = encoder.encodeAll(it);\n return Buffer.from(buf, 0, it.offset);\n }\n\n static decode<T extends Schema = Schema>(bytes: Buffer, it?: Iterator): T {\n const reflection = new Reflection();\n\n const reflectionDecoder = new Decoder(reflection);\n reflectionDecoder.decode(bytes, it);\n\n const context = new TypeContext();\n\n const schemaTypes = reflection.types.reduce((types, reflectionType) => {\n const parentKlass: typeof Schema = types[reflectionType.extendsId] || Schema;\n const schema: typeof Schema = class _ extends parentKlass {};\n\n // const _metadata = Object.create(_classSuper[Symbol.metadata] ?? null);\n const _metadata = parentKlass && parentKlass[Symbol.metadata] || Object.create(null);\n Object.defineProperty(schema, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata })\n\n // register for inheritance support\n TypeContext.register(schema);\n\n const typeid = reflectionType.id;\n types[typeid] = schema\n context.add(schema, typeid);\n return types;\n }, {});\n\n reflection.types.forEach((reflectionType) => {\n const schemaType = schemaTypes[reflectionType.id];\n const metadata = schemaType[Symbol.metadata];\n\n const parentKlass = reflection.types[reflectionType.extendsId];\n const parentFieldIndex = parentKlass && parentKlass.fields.length || 0;\n\n reflectionType.fields.forEach((field, i) => {\n const fieldIndex = parentFieldIndex + i;\n\n if (field.referencedType !== undefined) {\n let fieldType = field.type;\n let refType = schemaTypes[field.referencedType];\n\n // map or array of primitive type (-1)\n if (!refType) {\n const typeInfo = field.type.split(\":\");\n fieldType = typeInfo[0];\n refType = typeInfo[1];\n }\n\n if (fieldType === \"ref\") {\n // type(refType)(schemaType.prototype, field.name);\n Metadata.addField(metadata, fieldIndex, field.name, refType);\n\n } else {\n // type({ [fieldType]: refType } as DefinitionType)(schemaType.prototype, field.name);\n Metadata.addField(metadata, fieldIndex, field.name, { [fieldType]: refType } as DefinitionType);\n }\n\n } else {\n // type(field.type as PrimitiveType)(schemaType.prototype, field.name);\n Metadata.addField(metadata, fieldIndex, field.name, field.type as PrimitiveType);\n }\n });\n });\n\n return new (schemaTypes[0])();\n }\n}\n"]}
@@ -8,7 +8,7 @@ const symbols_1 = require("../types/symbols");
8
8
  const registry_1 = require("../types/registry");
9
9
  exports.DEFINITION_MISMATCH = -1;
10
10
  function decodeValue(decoder, operation, ref, index, type, bytes, it, allChanges) {
11
- const $root = decoder.$root;
11
+ const $root = decoder.root;
12
12
  const previousValue = ref[symbols_1.$getByIndex](index);
13
13
  let value;
14
14
  if ((operation & spec_1.OPERATION.DELETE) === spec_1.OPERATION.DELETE) {
@@ -215,7 +215,7 @@ const decodeArray = function (decoder, bytes, it, ref, allChanges) {
215
215
  else if (operation === spec_1.OPERATION.DELETE_BY_REFID) {
216
216
  // TODO: refactor here, try to follow same flow as below
217
217
  const refId = decode.number(bytes, it);
218
- const previousValue = decoder.$root.refs.get(refId);
218
+ const previousValue = decoder.root.refs.get(refId);
219
219
  const index = ref.findIndex((value) => value === previousValue);
220
220
  ref[symbols_1.$deleteByIndex](index);
221
221
  allChanges.push({
@@ -1 +1 @@
1
- {"version":3,"file":"DecodeOperation.js","sourceRoot":"","sources":["../../src/decoder/DecodeOperation.ts"],"names":[],"mappings":";;;AAAA,2CAA6C;AAE7C,sCAAmC;AAGnC,6CAA6C;AAC7C,8CAAqF;AAMrF,gDAA4C;AAa/B,QAAA,mBAAmB,GAAG,CAAC,CAAC,CAAC;AAUtC,SAAgB,WAAW,CACvB,OAAgB,EAChB,SAAoB,EACpB,GAAQ,EACR,KAAa,EACb,IAAS,EACT,KAAa,EACb,EAAmB,EACnB,UAAwB;IAExB,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;IAC5B,MAAM,aAAa,GAAG,GAAG,CAAC,qBAAW,CAAC,CAAC,KAAK,CAAC,CAAC;IAE9C,IAAI,KAAU,CAAC;IAEf,IAAI,CAAC,SAAS,GAAG,gBAAS,CAAC,MAAM,CAAC,KAAK,gBAAS,CAAC,MAAM,EACvD,CAAC;QACG,uCAAuC;QACvC,MAAM,aAAa,GAAG,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QACtD,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YAAC,KAAK,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;QAAC,CAAC;QAEpE,EAAE;QACF,oBAAoB;QACpB,EAAE;QACF,IAAI,SAAS,KAAK,gBAAS,CAAC,cAAc,EAAE,CAAC;YACzC,GAAG,CAAC,wBAAc,CAAC,CAAC,KAAK,CAAC,CAAC;YAE3B,KAAK;YACL,0CAA0C;YAC1C,wEAAwE;YACxE,iEAAiE;YACjE,KAAK;YACL,oBAAoB;YACpB,WAAW;YACX,mCAAmC;YACnC,4BAA4B;YAC5B,yCAAyC;YACzC,wBAAwB;YACxB,qBAAqB;YACrB,MAAM;QACV,CAAC;QA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,UAAU,CAAC,IAAI,CAAC;YACZ,GAAG;YACH,KAAK,EAAE,OAAO,CAAC,YAAY;YAC3B,EAAE,EAAE,gBAAS,CAAC,MAAM;YACpB,KAAK,EAAE,EAAE,EAAE,qBAAqB;YAChC,YAAY,EAAE,KAAK;YACnB,KAAK,EAAE,SAAS;YAChB,aAAa;SAChB,CAAC,CAAC;QACH,OAAO;IACX,CAAC;IAED,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACvC,MAAM,IAAI,GAAG,GAAG,CAAC,oBAAU,CAAC,CAAC;IAE7B,IAAI,YAAY,GAAoB,KAAK,CAAC;IAE1C,MAAM,EAAE,KAAK,EAAE,aAAa,EAAE,GAAG,WAAW,CACxC,OAAO,EACP,SAAS,EACT,GAAG,EACH,KAAK,EACL,IAAI,EACJ,KAAK,EACL,EAAE,EACF,UAAU,CACb,CAAC;IAEF,IACI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;QACrC,KAAK,KAAK,aAAa,CAAC,gGAAgG;MAC1H,CAAC;QACC,cAAc;QACb,GAAmB,CAAC,QAAQ,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;IAC5D,CAAC;IAED,aAAa;IACb,IAAI,aAAa,KAAK,KAAK,EAAE,CAAC;QAC1B,UAAU,CAAC,IAAI,CAAC;YACZ,GAAG;YACH,KAAK,EAAE,OAAO,CAAC,YAAY;YAC3B,EAAE,EAAE,SAAS;YACb,KAAK,EAAE,EAAE,EAAE,qBAAqB;YAChC,YAAY;YACZ,KAAK;YACL,aAAa;SAChB,CAAC,CAAC;IACP,CAAC;AACL,CAAC,CAAA;AA1EY,QAAA,WAAW,eA0EvB","sourcesContent":["import { OPERATION } from \"../encoding/spec\";\nimport { Metadata } from \"../Metadata\";\nimport { Schema } from \"../Schema\";\nimport type { Ref } from \"../encoder/ChangeTree\";\nimport type { Decoder } from \"./Decoder\";\nimport * as decode from \"../encoding/decode\";\nimport { $changes, $childType, $deleteByIndex, $getByIndex } from \"../types/symbols\";\n\nimport type { MapSchema } from \"../types/custom/MapSchema\";\nimport type { ArraySchema } from \"../types/custom/ArraySchema\";\nimport type { CollectionSchema } from \"../types/custom/CollectionSchema\";\n\nimport { getType } from \"../types/registry\";\nimport { Collection } from \"../types/HelperTypes\";\n\nexport interface DataChange<T = any, F = string> {\n ref: Ref,\n refId: number,\n op: OPERATION,\n field: F;\n dynamicIndex?: number | string;\n value: T;\n previousValue: T;\n}\n\nexport const DEFINITION_MISMATCH = -1;\n\nexport type DecodeOperation<T extends Schema = any> = (\n decoder: Decoder<T>,\n bytes: Buffer,\n it: decode.Iterator,\n ref: Ref,\n allChanges: DataChange[],\n) => number | void;\n\nexport function decodeValue(\n decoder: Decoder,\n operation: OPERATION,\n ref: Ref,\n index: number,\n type: any,\n bytes: Buffer,\n it: decode.Iterator,\n allChanges: DataChange[],\n) {\n const $root = decoder.$root;\n const previousValue = ref[$getByIndex](index);\n\n let value: any;\n\n if ((operation & OPERATION.DELETE) === OPERATION.DELETE)\n {\n // Flag `refId` for garbage collection.\n const previousRefId = $root.refIds.get(previousValue);\n if (previousRefId !== undefined) { $root.removeRef(previousRefId); }\n\n //\n // Delete operations\n //\n if (operation !== OPERATION.DELETE_AND_ADD) {\n ref[$deleteByIndex](index);\n\n // //\n // // FIXME: is this in the correct place?\n // // (This is sounding like a workaround just for ArraySchema, see\n // // \"should splice and move\" test on ArraySchema.test.ts)\n // //\n // allChanges.push({\n // ref,\n // refId: decoder.currentRefId,\n // op: OPERATION.DELETE,\n // field: index as unknown as string,\n // value: undefined,\n // previousValue,\n // });\n }\n\n value = null;\n }\n\n if (operation === OPERATION.DELETE) {\n //\n // Don't do anything\n //\n\n } else if (Schema.is(type)) {\n const refId = decode.number(bytes, it);\n value = $root.refs.get(refId);\n\n if (previousValue) {\n const previousRefId = $root.refIds.get(previousValue);\n if (\n previousRefId &&\n refId !== previousRefId &&\n // FIXME: we may need to check for REPLACE operation as well\n ((operation & OPERATION.DELETE) === OPERATION.DELETE)\n ) {\n $root.removeRef(previousRefId);\n }\n }\n\n if ((operation & OPERATION.ADD) === OPERATION.ADD) {\n const childType = decoder.getInstanceType(bytes, it, type);\n if (!value) {\n value = decoder.createInstanceOfType(childType);\n }\n\n $root.addRef(refId, value, (value !== previousValue));\n }\n\n\n } else if (typeof(type) === \"string\") {\n //\n // primitive value (number, string, boolean, etc)\n //\n value = decode[type as string](bytes, it);\n\n } else {\n const typeDef = getType(Object.keys(type)[0]);\n const refId = decode.number(bytes, it);\n\n const valueRef: Ref = ($root.refs.has(refId))\n ? previousValue || $root.refs.get(refId)\n : new typeDef.constructor();\n\n value = valueRef.clone(true);\n value[$childType] = Object.values(type)[0]; // cache childType for ArraySchema and MapSchema\n\n if (previousValue) {\n let previousRefId = $root.refIds.get(previousValue);\n\n if (previousRefId !== undefined && refId !== previousRefId) {\n $root.removeRef(previousRefId);\n\n //\n // enqueue onRemove if structure has been replaced.\n //\n const entries: IterableIterator<[any, any]> = previousValue.entries();\n let iter: IteratorResult<[any, any]>;\n while ((iter = entries.next()) && !iter.done) {\n const [key, value] = iter.value;\n\n // if value is a schema, remove its reference\n // FIXME: not sure if this is necessary, add more tests to confirm\n if (typeof(value) === \"object\") {\n previousRefId = $root.refIds.get(value);\n $root.removeRef(previousRefId);\n }\n\n allChanges.push({\n ref: previousValue,\n refId: previousRefId,\n op: OPERATION.DELETE,\n field: key,\n value: undefined,\n previousValue: value,\n });\n }\n\n }\n }\n\n $root.addRef(refId, value, (valueRef !== previousValue));\n }\n\n return { value, previousValue };\n}\n\nexport const decodeSchemaOperation: DecodeOperation = function (\n decoder: Decoder<any>,\n bytes: Buffer,\n it: decode.Iterator,\n ref: Ref,\n allChanges: DataChange[],\n) {\n const first_byte = bytes[it.offset++];\n const metadata: Metadata = ref['constructor'][Symbol.metadata];\n\n // \"compressed\" index + operation\n const operation = (first_byte >> 6) << 6\n const index = first_byte % (operation || 255);\n\n // skip early if field is not defined\n const field = metadata[index];\n if (field === undefined) { return DEFINITION_MISMATCH; }\n\n const { value, previousValue } = decodeValue(\n decoder,\n operation,\n ref,\n index,\n metadata[field].type,\n bytes,\n it,\n allChanges,\n );\n\n if (value !== null && value !== undefined) {\n ref[field] = value;\n }\n\n // add change\n if (previousValue !== value) {\n allChanges.push({\n ref,\n refId: decoder.currentRefId,\n op: operation,\n field: field,\n value,\n previousValue,\n });\n }\n}\n\nexport const decodeKeyValueOperation: DecodeOperation = function (\n decoder: Decoder<any>,\n bytes: Buffer,\n it: decode.Iterator,\n ref: Ref,\n allChanges: DataChange[]\n) {\n // \"uncompressed\" index + operation (array/map items)\n const operation = bytes[it.offset++];\n\n if (operation === OPERATION.CLEAR) {\n //\n // When decoding:\n // - enqueue items for DELETE callback.\n // - flag child items for garbage collection.\n //\n decoder.removeChildRefs(ref as unknown as Collection, allChanges);\n\n (ref as any).clear();\n return;\n }\n\n const index = decode.number(bytes, it);\n const type = ref[$childType];\n\n let dynamicIndex: number | string;\n\n if ((operation & OPERATION.ADD) === OPERATION.ADD) { // ADD or DELETE_AND_ADD\n if (typeof(ref['set']) === \"function\") {\n dynamicIndex = decode.string(bytes, it); // MapSchema\n ref['setIndex'](index, dynamicIndex);\n } else {\n dynamicIndex = index; // ArraySchema\n }\n } else {\n // get dynamic index from \"ref\"\n dynamicIndex = ref['getIndex'](index);\n }\n\n const { value, previousValue } = decodeValue(\n decoder,\n operation,\n ref,\n index,\n type,\n bytes,\n it,\n allChanges,\n );\n\n if (value !== null && value !== undefined) {\n if (typeof(ref['set']) === \"function\") {\n // MapSchema\n (ref as MapSchema)['$items'].set(dynamicIndex as string, value);\n\n } else if (typeof(ref['$setAt']) === \"function\") {\n // ArraySchema\n (ref as ArraySchema)['$setAt'](index, value, operation);\n\n } else if (typeof(ref['add']) === \"function\") {\n // CollectionSchema && SetSchema\n const index = (ref as CollectionSchema).add(value);\n\n if (typeof(index) === \"number\") {\n ref['setIndex'](index, index);\n }\n }\n }\n\n // add change\n if (previousValue !== value) {\n allChanges.push({\n ref,\n refId: decoder.currentRefId,\n op: operation,\n field: \"\", // FIXME: remove this\n dynamicIndex,\n value,\n previousValue,\n });\n }\n}\n\nexport const decodeArray: DecodeOperation = function (\n decoder: Decoder<any>,\n bytes: Buffer,\n it: decode.Iterator,\n ref: ArraySchema,\n allChanges: DataChange[]\n) {\n // \"uncompressed\" index + operation (array/map items)\n const operation = bytes[it.offset++];\n\n if (operation === OPERATION.CLEAR) {\n //\n // When decoding:\n // - enqueue items for DELETE callback.\n // - flag child items for garbage collection.\n //\n decoder.removeChildRefs(ref as unknown as Collection, allChanges);\n (ref as ArraySchema).clear();\n return;\n\n } else if (operation === OPERATION.DELETE_BY_REFID) {\n // TODO: refactor here, try to follow same flow as below\n const refId = decode.number(bytes, it);\n const previousValue = decoder.$root.refs.get(refId);\n const index = ref.findIndex((value) => value === previousValue);\n ref[$deleteByIndex](index);\n allChanges.push({\n ref,\n refId: decoder.currentRefId,\n op: OPERATION.DELETE,\n field: \"\", // FIXME: remove this\n dynamicIndex: index,\n value: undefined,\n previousValue,\n });\n return;\n }\n\n const index = decode.number(bytes, it);\n const type = ref[$childType];\n\n let dynamicIndex: number | string = index;\n\n const { value, previousValue } = decodeValue(\n decoder,\n operation,\n ref,\n index,\n type,\n bytes,\n it,\n allChanges,\n );\n\n if (\n value !== null && value !== undefined &&\n value !== previousValue // avoid setting same value twice (if index === 0 it will result in a \"unshift\" for ArraySchema)\n ) {\n // ArraySchema\n (ref as ArraySchema)['$setAt'](index, value, operation);\n }\n\n // add change\n if (previousValue !== value) {\n allChanges.push({\n ref,\n refId: decoder.currentRefId,\n op: operation,\n field: \"\", // FIXME: remove this\n dynamicIndex,\n value,\n previousValue,\n });\n }\n}"]}
1
+ {"version":3,"file":"DecodeOperation.js","sourceRoot":"","sources":["../../src/decoder/DecodeOperation.ts"],"names":[],"mappings":";;;AAAA,2CAA6C;AAE7C,sCAAmC;AAGnC,6CAA6C;AAC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AAG,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACvC,MAAM,IAAI,GAAG,GAAG,CAAC,oBAAU,CAAC,CAAC;IAE7B,IAAI,YAAY,GAAoB,KAAK,CAAC;IAE1C,MAAM,EAAE,KAAK,EAAE,aAAa,EAAE,GAAG,WAAW,CACxC,OAAO,EACP,SAAS,EACT,GAAG,EACH,KAAK,EACL,IAAI,EACJ,KAAK,EACL,EAAE,EACF,UAAU,CACb,CAAC;IAEF,IACI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;QACrC,KAAK,KAAK,aAAa,CAAC,gGAAgG;MAC1H,CAAC;QACC,cAAc;QACb,GAAmB,CAAC,QAAQ,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;IAC5D,CAAC;IAED,aAAa;IACb,IAAI,aAAa,KAAK,KAAK,EAAE,CAAC;QAC1B,UAAU,CAAC,IAAI,CAAC;YACZ,GAAG;YACH,KAAK,EAAE,OAAO,CAAC,YAAY;YAC3B,EAAE,EAAE,SAAS;YACb,KAAK,EAAE,EAAE,EAAE,qBAAqB;YAChC,YAAY;YACZ,KAAK;YACL,aAAa;SAChB,CAAC,CAAC;IACP,CAAC;AACL,CAAC,CAAA;AA1EY,QAAA,WAAW,eA0EvB","sourcesContent":["import { OPERATION } from \"../encoding/spec\";\nimport { Metadata } from \"../Metadata\";\nimport { Schema } from \"../Schema\";\nimport type { Ref } from \"../encoder/ChangeTree\";\nimport type { Decoder } from \"./Decoder\";\nimport * as decode from \"../encoding/decode\";\nimport { $childType, $deleteByIndex, $getByIndex } from \"../types/symbols\";\n\nimport type { MapSchema } from \"../types/custom/MapSchema\";\nimport type { ArraySchema } from \"../types/custom/ArraySchema\";\nimport type { CollectionSchema } from \"../types/custom/CollectionSchema\";\n\nimport { getType } from \"../types/registry\";\nimport { Collection } from \"../types/HelperTypes\";\n\nexport interface DataChange<T = any, F = string> {\n ref: Ref,\n refId: number,\n op: OPERATION,\n field: F;\n dynamicIndex?: number | string;\n value: T;\n previousValue: T;\n}\n\nexport const DEFINITION_MISMATCH = -1;\n\nexport type DecodeOperation<T extends Schema = any> = (\n decoder: Decoder<T>,\n bytes: Buffer,\n it: decode.Iterator,\n ref: Ref,\n allChanges: DataChange[],\n) => number | void;\n\nexport function decodeValue(\n decoder: Decoder,\n operation: OPERATION,\n ref: Ref,\n index: number,\n type: any,\n bytes: Buffer,\n it: decode.Iterator,\n allChanges: DataChange[],\n) {\n const $root = decoder.root;\n const previousValue = ref[$getByIndex](index);\n\n let value: any;\n\n if ((operation & OPERATION.DELETE) === OPERATION.DELETE)\n {\n // Flag `refId` for garbage collection.\n const previousRefId = $root.refIds.get(previousValue);\n if (previousRefId !== undefined) { $root.removeRef(previousRefId); }\n\n //\n // Delete operations\n //\n if (operation !== OPERATION.DELETE_AND_ADD) {\n ref[$deleteByIndex](index);\n\n // //\n // // FIXME: is this in the correct place?\n // // (This is sounding like a workaround just for ArraySchema, see\n // // \"should splice and move\" test on ArraySchema.test.ts)\n // //\n // allChanges.push({\n // ref,\n // refId: decoder.currentRefId,\n // op: OPERATION.DELETE,\n // field: index as unknown as string,\n // value: undefined,\n // previousValue,\n // });\n }\n\n value = null;\n }\n\n if (operation === OPERATION.DELETE) {\n //\n // Don't do anything\n //\n\n } else if (Schema.is(type)) {\n const refId = decode.number(bytes, it);\n value = $root.refs.get(refId);\n\n if (previousValue) {\n const previousRefId = $root.refIds.get(previousValue);\n if (\n previousRefId &&\n refId !== previousRefId &&\n // FIXME: we may need to check for REPLACE operation as well\n ((operation & OPERATION.DELETE) === OPERATION.DELETE)\n ) {\n $root.removeRef(previousRefId);\n }\n }\n\n if ((operation & OPERATION.ADD) === OPERATION.ADD) {\n const childType = decoder.getInstanceType(bytes, it, type);\n if (!value) {\n value = decoder.createInstanceOfType(childType);\n }\n\n $root.addRef(refId, value, (value !== previousValue));\n }\n\n\n } else if (typeof(type) === \"string\") {\n //\n // primitive value (number, string, boolean, etc)\n //\n value = decode[type as string](bytes, it);\n\n } else {\n const typeDef = getType(Object.keys(type)[0]);\n const refId = decode.number(bytes, it);\n\n const valueRef: Ref = ($root.refs.has(refId))\n ? previousValue || $root.refs.get(refId)\n : new typeDef.constructor();\n\n value = valueRef.clone(true);\n value[$childType] = Object.values(type)[0]; // cache childType for ArraySchema and MapSchema\n\n if (previousValue) {\n let previousRefId = $root.refIds.get(previousValue);\n\n if (previousRefId !== undefined && refId !== previousRefId) {\n $root.removeRef(previousRefId);\n\n //\n // enqueue onRemove if structure has been replaced.\n //\n const entries: IterableIterator<[any, any]> = previousValue.entries();\n let iter: IteratorResult<[any, any]>;\n while ((iter = entries.next()) && !iter.done) {\n const [key, value] = iter.value;\n\n // if value is a schema, remove its reference\n // FIXME: not sure if this is necessary, add more tests to confirm\n if (typeof(value) === \"object\") {\n previousRefId = $root.refIds.get(value);\n $root.removeRef(previousRefId);\n }\n\n allChanges.push({\n ref: previousValue,\n refId: previousRefId,\n op: OPERATION.DELETE,\n field: key,\n value: undefined,\n previousValue: value,\n });\n }\n\n }\n }\n\n $root.addRef(refId, value, (valueRef !== previousValue));\n }\n\n return { value, previousValue };\n}\n\nexport const decodeSchemaOperation: DecodeOperation = function (\n decoder: Decoder<any>,\n bytes: Buffer,\n it: decode.Iterator,\n ref: Ref,\n allChanges: DataChange[],\n) {\n const first_byte = bytes[it.offset++];\n const metadata: Metadata = ref['constructor'][Symbol.metadata];\n\n // \"compressed\" index + operation\n const operation = (first_byte >> 6) << 6\n const index = first_byte % (operation || 255);\n\n // skip early if field is not defined\n const field = metadata[index];\n if (field === undefined) { return DEFINITION_MISMATCH; }\n\n const { value, previousValue } = decodeValue(\n decoder,\n operation,\n ref,\n index,\n metadata[field].type,\n bytes,\n it,\n allChanges,\n );\n\n if (value !== null && value !== undefined) {\n ref[field] = value;\n }\n\n // add change\n if (previousValue !== value) {\n allChanges.push({\n ref,\n refId: decoder.currentRefId,\n op: operation,\n field: field,\n value,\n previousValue,\n });\n }\n}\n\nexport const decodeKeyValueOperation: DecodeOperation = function (\n decoder: Decoder<any>,\n bytes: Buffer,\n it: decode.Iterator,\n ref: Ref,\n allChanges: DataChange[]\n) {\n // \"uncompressed\" index + operation (array/map items)\n const operation = bytes[it.offset++];\n\n if (operation === OPERATION.CLEAR) {\n //\n // When decoding:\n // - enqueue items for DELETE callback.\n // - flag child items for garbage collection.\n //\n decoder.removeChildRefs(ref as unknown as Collection, allChanges);\n\n (ref as any).clear();\n return;\n }\n\n const index = decode.number(bytes, it);\n const type = ref[$childType];\n\n let dynamicIndex: number | string;\n\n if ((operation & OPERATION.ADD) === OPERATION.ADD) { // ADD or DELETE_AND_ADD\n if (typeof(ref['set']) === \"function\") {\n dynamicIndex = decode.string(bytes, it); // MapSchema\n ref['setIndex'](index, dynamicIndex);\n } else {\n dynamicIndex = index; // ArraySchema\n }\n } else {\n // get dynamic index from \"ref\"\n dynamicIndex = ref['getIndex'](index);\n }\n\n const { value, previousValue } = decodeValue(\n decoder,\n operation,\n ref,\n index,\n type,\n bytes,\n it,\n allChanges,\n );\n\n if (value !== null && value !== undefined) {\n if (typeof(ref['set']) === \"function\") {\n // MapSchema\n (ref as MapSchema)['$items'].set(dynamicIndex as string, value);\n\n } else if (typeof(ref['$setAt']) === \"function\") {\n // ArraySchema\n (ref as ArraySchema)['$setAt'](index, value, operation);\n\n } else if (typeof(ref['add']) === \"function\") {\n // CollectionSchema && SetSchema\n const index = (ref as CollectionSchema).add(value);\n\n if (typeof(index) === \"number\") {\n ref['setIndex'](index, index);\n }\n }\n }\n\n // add change\n if (previousValue !== value) {\n allChanges.push({\n ref,\n refId: decoder.currentRefId,\n op: operation,\n field: \"\", // FIXME: remove this\n dynamicIndex,\n value,\n previousValue,\n });\n }\n}\n\nexport const decodeArray: DecodeOperation = function (\n decoder: Decoder<any>,\n bytes: Buffer,\n it: decode.Iterator,\n ref: ArraySchema,\n allChanges: DataChange[]\n) {\n // \"uncompressed\" index + operation (array/map items)\n const operation = bytes[it.offset++];\n\n if (operation === OPERATION.CLEAR) {\n //\n // When decoding:\n // - enqueue items for DELETE callback.\n // - flag child items for garbage collection.\n //\n decoder.removeChildRefs(ref as unknown as Collection, allChanges);\n (ref as ArraySchema).clear();\n return;\n\n } else if (operation === OPERATION.DELETE_BY_REFID) {\n // TODO: refactor here, try to follow same flow as below\n const refId = decode.number(bytes, it);\n const previousValue = decoder.root.refs.get(refId);\n const index = ref.findIndex((value) => value === previousValue);\n ref[$deleteByIndex](index);\n allChanges.push({\n ref,\n refId: decoder.currentRefId,\n op: OPERATION.DELETE,\n field: \"\", // FIXME: remove this\n dynamicIndex: index,\n value: undefined,\n previousValue,\n });\n return;\n }\n\n const index = decode.number(bytes, it);\n const type = ref[$childType];\n\n let dynamicIndex: number | string = index;\n\n const { value, previousValue } = decodeValue(\n decoder,\n operation,\n ref,\n index,\n type,\n bytes,\n it,\n allChanges,\n );\n\n if (\n value !== null && value !== undefined &&\n value !== previousValue // avoid setting same value twice (if index === 0 it will result in a \"unshift\" for ArraySchema)\n ) {\n // ArraySchema\n (ref as ArraySchema)['$setAt'](index, value, operation);\n }\n\n // add change\n if (previousValue !== value) {\n allChanges.push({\n ref,\n refId: decoder.currentRefId,\n op: operation,\n field: \"\", // FIXME: remove this\n dynamicIndex,\n value,\n previousValue,\n });\n }\n}"]}
@@ -9,7 +9,7 @@ import { Collection } from "../types/HelperTypes";
9
9
  export declare class Decoder<T extends Schema = any> {
10
10
  context: TypeContext;
11
11
  state: T;
12
- $root: ReferenceTracker;
12
+ root: ReferenceTracker;
13
13
  currentRefId: number;
14
14
  triggerChanges?: (allChanges: DataChange[]) => void;
15
15
  constructor(root: T, context?: TypeContext);
@@ -19,12 +19,12 @@ class Decoder {
19
19
  }
20
20
  setRoot(root) {
21
21
  this.state = root;
22
- this.$root = new ReferenceTracker_1.ReferenceTracker();
23
- this.$root.addRef(0, root);
22
+ this.root = new ReferenceTracker_1.ReferenceTracker();
23
+ this.root.addRef(0, root);
24
24
  }
25
25
  decode(bytes, it = { offset: 0 }, ref = this.state) {
26
26
  const allChanges = [];
27
- const $root = this.$root;
27
+ const $root = this.root;
28
28
  const totalBytes = bytes.byteLength;
29
29
  let decoder = ref['constructor'][symbols_1.$decoder];
30
30
  this.currentRefId = 0;
@@ -105,7 +105,7 @@ class Decoder {
105
105
  previousValue: value
106
106
  });
107
107
  if (needRemoveRef) {
108
- this.$root.removeRef(this.$root.refIds.get(value));
108
+ this.root.removeRef(this.root.refIds.get(value));
109
109
  }
110
110
  });
111
111
  }
@@ -1 +1 @@
1
- {"version":3,"file":"Decoder.js","sourceRoot":"","sources":["../../src/decoder/Decoder.ts"],"names":[],"mappings":";;;AAAA,gDAA6C;AAC7C,8CAAgF;AAGhF,6CAA6C;AAC7C,2CAA2E;AAG3E,yDAAsD;AACtD,uDAAqF;AAGrF,MAAa,OAAO;IAUhB,YAAY,IAAO,EAAE,OAAqB;QAJ1C,iBAAY,GAAW,CAAC,CAAC;QAKrB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,IAAI,yBAAW,CAAC,IAAI,CAAC,WAA4B,CAAC,CAAC;QAE7E,iDAAiD;QACjD,iDAAiD;QACjD,mFAAmF;QACnF,MAAM;IACV,CAAC;IAES,OAAO,CAAC,IAAO;QACrB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,KAAK,GAAG,IAAI,mCAAgB,EAAE,CAAC;QACpC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC;IAED,MAAM,CACF,KAAa,EACb,KAAe,EAAE,MAAM,EAAE,CAAC,EAAE,EAC5B,MAAW,IAAI,CAAC,KAAK;QAErB,MAAM,UAAU,GAAiB,EAAE,CAAC;QAEpC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;QACzB,MAAM,UAAU,GAAG,KAAK,CAAC,U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AAC,CAAC;QAEjC,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,oBAAU,CAAC,CAAC,KAAK,QAAQ,CAAC;QAC5D,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;QAE/B,GAAG,CAAC,OAAO,CAAC,CAAC,KAAU,EAAE,GAAQ,EAAE,EAAE;YACjC,UAAU,CAAC,IAAI,CAAC;gBACZ,GAAG,EAAE,KAAK;gBACV,KAAK;gBACL,EAAE,EAAE,gBAAS,CAAC,MAAM;gBACpB,KAAK,EAAE,GAAG;gBACV,KAAK,EAAE,SAAS;gBAChB,aAAa,EAAE,KAAK;aACvB,CAAC,CAAC;YAEH,IAAI,aAAa,EAAE,CAAC;gBAChB,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;YACvD,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CAEJ;AA7ID,0BA6IC","sourcesContent":["import { TypeContext } from \"../annotations\";\nimport { $changes, $childType, $decoder, $onDecodeEnd } from \"../types/symbols\";\nimport { Schema } from \"../Schema\";\n\nimport * as decode from \"../encoding/decode\";\nimport { OPERATION, SWITCH_TO_STRUCTURE, TYPE_ID } from '../encoding/spec';\nimport { Ref } from \"../encoder/ChangeTree\";\nimport { Iterator } from \"../encoding/decode\";\nimport { ReferenceTracker } from \"./ReferenceTracker\";\nimport { DEFINITION_MISMATCH, DataChange, DecodeOperation } from \"./DecodeOperation\";\nimport { Collection } from \"../types/HelperTypes\";\n\nexport class Decoder<T extends Schema = any> {\n context: TypeContext;\n\n state: T;\n $root: ReferenceTracker;\n\n currentRefId: number = 0;\n\n triggerChanges?: (allChanges: DataChange[]) => void;\n\n constructor(root: T, context?: TypeContext) {\n this.setRoot(root);\n this.context = context || new TypeContext(root.constructor as typeof Schema);\n\n // console.log(\">>>>>>>>>>>>>>>> Decoder types\");\n // this.context.schemas.forEach((id, schema) => {\n // console.log(\"type:\", id, schema.name, Object.keys(schema[Symbol.metadata]));\n // });\n }\n\n protected setRoot(root: T) {\n this.state = root;\n this.$root = new ReferenceTracker();\n this.$root.addRef(0, root);\n }\n\n decode(\n bytes: Buffer,\n it: Iterator = { offset: 0 },\n ref: Ref = this.state,\n ) {\n const allChanges: DataChange[] = [];\n\n const $root = this.$root;\n const totalBytes = bytes.byteLength;\n\n let decoder: DecodeOperation = ref['constructor'][$decoder];\n\n this.currentRefId = 0;\n\n while (it.offset < totalBytes) {\n //\n // Peek ahead, check if it's a switch to a different structure\n //\n if (bytes[it.offset] == SWITCH_TO_STRUCTURE) {\n it.offset++;\n\n this.currentRefId = decode.number(bytes, it);\n const nextRef = $root.refs.get(this.currentRefId) as Schema;\n\n //\n // Trying to access a reference that haven't been decoded yet.\n //\n if (!nextRef) { throw new Error(`\"refId\" not found: ${this.currentRefId}`); }\n ref[$onDecodeEnd]?.()\n ref = nextRef;\n decoder = ref['constructor'][$decoder];\n\n continue;\n }\n\n const result = decoder(this, bytes, it, ref, allChanges);\n\n if (result === DEFINITION_MISMATCH) {\n console.warn(\"@colyseus/schema: definition mismatch\");\n\n //\n // keep skipping next bytes until reaches a known structure\n // by local decoder.\n //\n const nextIterator: decode.Iterator = { offset: it.offset };\n while (it.offset < totalBytes) {\n if (decode.switchStructureCheck(bytes, it)) {\n nextIterator.offset = it.offset + 1;\n if ($root.refs.has(decode.number(bytes, nextIterator))) {\n break;\n }\n }\n\n it.offset++;\n }\n continue;\n }\n }\n\n // FIXME: DRY with SWITCH_TO_STRUCTURE block.\n ref[$onDecodeEnd]?.()\n\n // trigger changes\n this.triggerChanges?.(allChanges);\n\n // drop references of unused schemas\n $root.garbageCollectDeletedRefs();\n\n return allChanges;\n }\n\n getInstanceType(bytes: Buffer, it: Iterator, defaultType: typeof Schema): typeof Schema {\n let type: typeof Schema;\n\n if (bytes[it.offset] === TYPE_ID) {\n it.offset++;\n const type_id = decode.number(bytes, it);\n type = this.context.get(type_id);\n }\n\n return type || defaultType;\n }\n\n createInstanceOfType (type: typeof Schema): Schema {\n // let instance: Schema = new (type as any)();\n\n // // assign root on $changes\n // instance[$changes].root = this.root[$changes].root;\n\n // return instance;\n return new (type as any)();\n }\n\n removeChildRefs(ref: Collection, allChanges: DataChange[]) {\n const changeTree = ref[$changes];\n\n const needRemoveRef = typeof (ref[$childType]) !== \"string\";\n const refId = changeTree.refId;\n\n ref.forEach((value: any, key: any) => {\n allChanges.push({\n ref: value,\n refId,\n op: OPERATION.DELETE,\n field: key,\n value: undefined,\n previousValue: value\n });\n\n if (needRemoveRef) {\n this.$root.removeRef(this.$root.refIds.get(value));\n }\n });\n }\n\n}\n\n"]}
1
+ {"version":3,"file":"Decoder.js","sourceRoot":"","sources":["../../src/decoder/Decoder.ts"],"names":[],"mappings":";;;AAAA,gDAA6C;AAC7C,8CAAgF;AAGhF,6CAA6C;AAC7C,2CAA2E;AAG3E,yDAAsD;AACtD,uDAAqF;AAGrF,MAAa,OAAO;IAUhB,YAAY,IAAO,EAAE,OAAqB;QAJ1C,iBAAY,GAAW,CAAC,CAAC;QAKrB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,IAAI,yBAAW,CAAC,IAAI,CAAC,WAA4B,CAAC,CAAC;QAE7E,iDAAiD;QACjD,iDAAiD;QACjD,mFAAmF;QACnF,MAAM;IACV,CAAC;IAES,OAAO,CAAC,IAAO;QACrB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,IAAI,GAAG,IAAI,mCAAgB,EAAE,CAAC;QACnC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAC9B,CAAC;IAED,MAAM,CACF,KAAa,EACb,KAAe,EAAE,MAAM,EAAE,CAAC,EAAE,EAC5B,MAAW,IAAI,CAAC,KAAK;QAErB,MAAM,UAAU,GAAiB,EAAE,CAA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,CAAC;IAED,eAAe,CAAC,GAAe,EAAE,UAAwB;QACrD,MAAM,UAAU,GAAG,GAAG,CAAC,kBAAQ,CAAC,CAAC;QAEjC,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,oBAAU,CAAC,CAAC,KAAK,QAAQ,CAAC;QAC5D,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;QAE/B,GAAG,CAAC,OAAO,CAAC,CAAC,KAAU,EAAE,GAAQ,EAAE,EAAE;YACjC,UAAU,CAAC,IAAI,CAAC;gBACZ,GAAG,EAAE,KAAK;gBACV,KAAK;gBACL,EAAE,EAAE,gBAAS,CAAC,MAAM;gBACpB,KAAK,EAAE,GAAG;gBACV,KAAK,EAAE,SAAS;gBAChB,aAAa,EAAE,KAAK;aACvB,CAAC,CAAC;YAEH,IAAI,aAAa,EAAE,CAAC;gBAChB,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;YACrD,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CAEJ;AA7ID,0BA6IC","sourcesContent":["import { TypeContext } from \"../annotations\";\nimport { $changes, $childType, $decoder, $onDecodeEnd } from \"../types/symbols\";\nimport { Schema } from \"../Schema\";\n\nimport * as decode from \"../encoding/decode\";\nimport { OPERATION, SWITCH_TO_STRUCTURE, TYPE_ID } from '../encoding/spec';\nimport { Ref } from \"../encoder/ChangeTree\";\nimport { Iterator } from \"../encoding/decode\";\nimport { ReferenceTracker } from \"./ReferenceTracker\";\nimport { DEFINITION_MISMATCH, DataChange, DecodeOperation } from \"./DecodeOperation\";\nimport { Collection } from \"../types/HelperTypes\";\n\nexport class Decoder<T extends Schema = any> {\n context: TypeContext;\n\n state: T;\n root: ReferenceTracker;\n\n currentRefId: number = 0;\n\n triggerChanges?: (allChanges: DataChange[]) => void;\n\n constructor(root: T, context?: TypeContext) {\n this.setRoot(root);\n this.context = context || new TypeContext(root.constructor as typeof Schema);\n\n // console.log(\">>>>>>>>>>>>>>>> Decoder types\");\n // this.context.schemas.forEach((id, schema) => {\n // console.log(\"type:\", id, schema.name, Object.keys(schema[Symbol.metadata]));\n // });\n }\n\n protected setRoot(root: T) {\n this.state = root;\n this.root = new ReferenceTracker();\n this.root.addRef(0, root);\n }\n\n decode(\n bytes: Buffer,\n it: Iterator = { offset: 0 },\n ref: Ref = this.state,\n ) {\n const allChanges: DataChange[] = [];\n\n const $root = this.root;\n const totalBytes = bytes.byteLength;\n\n let decoder: DecodeOperation = ref['constructor'][$decoder];\n\n this.currentRefId = 0;\n\n while (it.offset < totalBytes) {\n //\n // Peek ahead, check if it's a switch to a different structure\n //\n if (bytes[it.offset] == SWITCH_TO_STRUCTURE) {\n it.offset++;\n\n this.currentRefId = decode.number(bytes, it);\n const nextRef = $root.refs.get(this.currentRefId) as Schema;\n\n //\n // Trying to access a reference that haven't been decoded yet.\n //\n if (!nextRef) { throw new Error(`\"refId\" not found: ${this.currentRefId}`); }\n ref[$onDecodeEnd]?.()\n ref = nextRef;\n decoder = ref['constructor'][$decoder];\n\n continue;\n }\n\n const result = decoder(this, bytes, it, ref, allChanges);\n\n if (result === DEFINITION_MISMATCH) {\n console.warn(\"@colyseus/schema: definition mismatch\");\n\n //\n // keep skipping next bytes until reaches a known structure\n // by local decoder.\n //\n const nextIterator: decode.Iterator = { offset: it.offset };\n while (it.offset < totalBytes) {\n if (decode.switchStructureCheck(bytes, it)) {\n nextIterator.offset = it.offset + 1;\n if ($root.refs.has(decode.number(bytes, nextIterator))) {\n break;\n }\n }\n\n it.offset++;\n }\n continue;\n }\n }\n\n // FIXME: DRY with SWITCH_TO_STRUCTURE block.\n ref[$onDecodeEnd]?.()\n\n // trigger changes\n this.triggerChanges?.(allChanges);\n\n // drop references of unused schemas\n $root.garbageCollectDeletedRefs();\n\n return allChanges;\n }\n\n getInstanceType(bytes: Buffer, it: Iterator, defaultType: typeof Schema): typeof Schema {\n let type: typeof Schema;\n\n if (bytes[it.offset] === TYPE_ID) {\n it.offset++;\n const type_id = decode.number(bytes, it);\n type = this.context.get(type_id);\n }\n\n return type || defaultType;\n }\n\n createInstanceOfType (type: typeof Schema): Schema {\n // let instance: Schema = new (type as any)();\n\n // // assign root on $changes\n // instance[$changes].root = this.root[$changes].root;\n\n // return instance;\n return new (type as any)();\n }\n\n removeChildRefs(ref: Collection, allChanges: DataChange[]) {\n const changeTree = ref[$changes];\n\n const needRemoveRef = typeof (ref[$childType]) !== \"string\";\n const refId = changeTree.refId;\n\n ref.forEach((value: any, key: any) => {\n allChanges.push({\n ref: value,\n refId,\n op: OPERATION.DELETE,\n field: key,\n value: undefined,\n previousValue: value\n });\n\n if (needRemoveRef) {\n this.root.removeRef(this.root.refIds.get(value));\n }\n });\n }\n\n}\n\n"]}
@@ -4,7 +4,7 @@ exports.getStateCallbacks = void 0;
4
4
  const spec_1 = require("../../encoding/spec");
5
5
  const Schema_1 = require("../../Schema");
6
6
  function getStateCallbacks(decoder) {
7
- const $root = decoder.$root;
7
+ const $root = decoder.root;
8
8
  const callbacks = $root.callbacks;
9
9
  let isTriggeringOnAdd = false;
10
10
  decoder.triggerChanges = function (allChanges) {