@colyseus/schema 3.0.43 → 3.0.45

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.
@@ -1092,6 +1092,7 @@
1092
1092
  // re-assigning a child of the same root, move it to the end
1093
1093
  // of the changes queue so encoding order is preserved
1094
1094
  //
1095
+ root.add(child);
1095
1096
  root.moveToEndOfChanges(child);
1096
1097
  return;
1097
1098
  }
@@ -1429,7 +1430,7 @@
1429
1430
  */
1430
1431
  addParent(parent, index) {
1431
1432
  // Check if this parent already exists in the chain
1432
- if (this.hasParent((p, i) => p === parent && i === index)) {
1433
+ if (this.hasParent((p, i) => p[$changes] === parent[$changes] && i === index)) {
1433
1434
  return;
1434
1435
  }
1435
1436
  this.parentChain = {
@@ -1443,7 +1444,7 @@
1443
1444
  * @param parent - The parent to remove
1444
1445
  * @returns true if parent was removed
1445
1446
  */
1446
- removeParent(parent) {
1447
+ removeParent(parent = this.parent) {
1447
1448
  let current = this.parentChain;
1448
1449
  let previous = null;
1449
1450
  while (current) {
@@ -3402,9 +3403,9 @@
3402
3403
  });
3403
3404
  return output;
3404
3405
  }
3405
- static debugRefIdEncodeOrder(ref) {
3406
+ static debugRefIdEncodingOrder(ref, changeSet = 'allChanges') {
3406
3407
  let encodeOrder = [];
3407
- let current = ref[$changes].root.allChanges.next;
3408
+ let current = ref[$changes].root[changeSet].next;
3408
3409
  while (current) {
3409
3410
  if (current.changeTree) {
3410
3411
  encodeOrder.push(current.changeTree.refId);
@@ -3413,7 +3414,7 @@
3413
3414
  }
3414
3415
  return encodeOrder;
3415
3416
  }
3416
- static debugRefIdsDecoder(decoder) {
3417
+ static debugRefIdsFromDecoder(decoder) {
3417
3418
  return this.debugRefIds(decoder.state, false, 0, decoder);
3418
3419
  }
3419
3420
  /**
@@ -3922,10 +3923,12 @@
3922
3923
  }
3923
3924
  }
3924
3925
  this.refCount[changeTree.refId] = (previousRefCount || 0) + 1;
3926
+ // console.log("ADD", { refId: changeTree.refId, refCount: this.refCount[changeTree.refId] });
3925
3927
  return isNewChangeTree;
3926
3928
  }
3927
3929
  remove(changeTree) {
3928
3930
  const refCount = (this.refCount[changeTree.refId]) - 1;
3931
+ // console.log("REMOVE", { refId: changeTree.refId, refCount });
3929
3932
  if (refCount <= 0) {
3930
3933
  //
3931
3934
  // Only remove "root" reference if it's the last reference
@@ -4428,7 +4431,7 @@
4428
4431
  // throw new Error(`"refId" not found: ${nextRefId}`);
4429
4432
  console.error(`"refId" not found: ${nextRefId}`, { previousRef: ref, previousRefId: this.currentRefId });
4430
4433
  console.warn("Please report this to the developers. All refIds =>");
4431
- console.warn(Schema.debugRefIdsDecoder(this));
4434
+ console.warn(Schema.debugRefIdsFromDecoder(this));
4432
4435
  this.skipCurrentStructure(bytes, it, totalBytes);
4433
4436
  }
4434
4437
  else {
@@ -5005,11 +5008,12 @@
5005
5008
  // TODO: allow to set multiple tags at once
5006
5009
  add(obj, tag = DEFAULT_VIEW_TAG, checkIncludeParent = true) {
5007
5010
  const changeTree = obj?.[$changes];
5011
+ const parentChangeTree = changeTree.parent;
5008
5012
  if (!changeTree) {
5009
5013
  console.warn("StateView#add(), invalid object:", obj);
5010
- return this;
5014
+ return false;
5011
5015
  }
5012
- else if (!changeTree.parent &&
5016
+ else if (!parentChangeTree &&
5013
5017
  changeTree.refId !== 0 // allow root object
5014
5018
  ) {
5015
5019
  /**
@@ -5031,18 +5035,31 @@
5031
5035
  // add parent ChangeTree's
5032
5036
  // - if it was invisible to this view
5033
5037
  // - if it were previously filtered out
5034
- if (checkIncludeParent && changeTree.parent) {
5038
+ if (checkIncludeParent && parentChangeTree) {
5035
5039
  this.addParentOf(changeTree, tag);
5036
5040
  }
5037
- //
5038
- // TODO: when adding an item of a MapSchema, the changes may not
5039
- // be set (only the parent's changes are set)
5040
- //
5041
5041
  let changes = this.changes.get(changeTree.refId);
5042
5042
  if (changes === undefined) {
5043
5043
  changes = {};
5044
+ // FIXME / OPTIMIZE: do not add if no changes are needed
5044
5045
  this.changes.set(changeTree.refId, changes);
5045
5046
  }
5047
+ let isChildAdded = false;
5048
+ //
5049
+ // Add children of this ChangeTree first.
5050
+ // If successful, we must link the current ChangeTree to the child.
5051
+ //
5052
+ changeTree.forEachChild((change, index) => {
5053
+ // Do not ADD children that don't have the same tag
5054
+ if (metadata &&
5055
+ metadata[index].tag !== undefined &&
5056
+ metadata[index].tag !== tag) {
5057
+ return;
5058
+ }
5059
+ if (this.add(change.ref, tag, false)) {
5060
+ isChildAdded = true;
5061
+ }
5062
+ });
5046
5063
  // set tag
5047
5064
  if (tag !== DEFAULT_VIEW_TAG) {
5048
5065
  if (!this.tags) {
@@ -5064,11 +5081,12 @@
5064
5081
  }
5065
5082
  });
5066
5083
  }
5067
- else {
5068
- const isInvisible = this.invisible.has(changeTree);
5084
+ else if (!changeTree.isNew || isChildAdded) {
5085
+ // new structures will be added as part of .encode() call, no need to force it to .encodeView()
5069
5086
  const changeSet = (changeTree.filteredChanges !== undefined)
5070
5087
  ? changeTree.allFilteredChanges
5071
5088
  : changeTree.allChanges;
5089
+ const isInvisible = this.invisible.has(changeTree);
5072
5090
  for (let i = 0, len = changeSet.operations.length; i < len; i++) {
5073
5091
  const index = changeSet.operations[i];
5074
5092
  if (index === undefined) {
@@ -5076,27 +5094,17 @@
5076
5094
  } // skip "undefined" indexes
5077
5095
  const op = changeTree.indexedOperations[index] ?? exports.OPERATION.ADD;
5078
5096
  const tagAtIndex = metadata?.[index].tag;
5079
- if (!changeTree.isNew && // new structures will be added as part of .encode() call, no need to force it to .encodeView()
5097
+ if (op !== exports.OPERATION.DELETE &&
5080
5098
  (isInvisible || // if "invisible", include all
5081
5099
  tagAtIndex === undefined || // "all change" with no tag
5082
5100
  tagAtIndex === tag // tagged property
5083
- ) &&
5084
- op !== exports.OPERATION.DELETE) {
5101
+ )) {
5085
5102
  changes[index] = op;
5103
+ isChildAdded = true; // FIXME: assign only once
5086
5104
  }
5087
5105
  }
5088
5106
  }
5089
- // Add children of this ChangeTree to this view
5090
- changeTree.forEachChild((change, index) => {
5091
- // Do not ADD children that don't have the same tag
5092
- if (metadata &&
5093
- metadata[index].tag !== undefined &&
5094
- metadata[index].tag !== tag) {
5095
- return;
5096
- }
5097
- this.add(change.ref, tag, false);
5098
- });
5099
- return this;
5107
+ return isChildAdded;
5100
5108
  }
5101
5109
  addParentOf(childChangeTree, tag) {
5102
5110
  const changeTree = childChangeTree.parent[$changes];
package/lib/Schema.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { OPERATION } from './encoding/spec';
2
2
  import { type DefinitionType } from "./annotations";
3
3
  import { NonFunctionPropNames, ToJSON } from './types/HelperTypes';
4
- import { ChangeTree, Ref } from './encoder/ChangeTree';
4
+ import { ChangeSetName, ChangeTree, Ref } from './encoder/ChangeTree';
5
5
  import { $decoder, $deleteByIndex, $encoder, $filter, $getByIndex, $track } from './types/symbols';
6
6
  import { StateView } from './encoder/StateView';
7
7
  import type { Decoder } from './decoder/Decoder';
@@ -59,8 +59,8 @@ export declare class Schema {
59
59
  * @returns
60
60
  */
61
61
  static debugRefIds(ref: Ref, showContents?: boolean, level?: number, decoder?: Decoder, keyPrefix?: string): string;
62
- static debugRefIdEncodeOrder(ref: Ref): number[];
63
- static debugRefIdsDecoder(decoder: Decoder): string;
62
+ static debugRefIdEncodingOrder(ref: Ref, changeSet?: ChangeSetName): number[];
63
+ static debugRefIdsFromDecoder(decoder: Decoder): string;
64
64
  /**
65
65
  * Return a string representation of the changes on a Schema instance.
66
66
  * The list of changes is cleared after each encode.
package/lib/Schema.js CHANGED
@@ -170,9 +170,9 @@ class Schema {
170
170
  });
171
171
  return output;
172
172
  }
173
- static debugRefIdEncodeOrder(ref) {
173
+ static debugRefIdEncodingOrder(ref, changeSet = 'allChanges') {
174
174
  let encodeOrder = [];
175
- let current = ref[symbols_1.$changes].root.allChanges.next;
175
+ let current = ref[symbols_1.$changes].root[changeSet].next;
176
176
  while (current) {
177
177
  if (current.changeTree) {
178
178
  encodeOrder.push(current.changeTree.refId);
@@ -181,7 +181,7 @@ class Schema {
181
181
  }
182
182
  return encodeOrder;
183
183
  }
184
- static debugRefIdsDecoder(decoder) {
184
+ static debugRefIdsFromDecoder(decoder) {
185
185
  return this.debugRefIds(decoder.state, false, 0, decoder);
186
186
  }
187
187
  /**
package/lib/Schema.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Schema.js","sourceRoot":"","sources":["../src/Schema.ts"],"names":[],"mappings":";;;;AAAA,0CAA4C;AAC5C,+CAAsE;AAItE,qDAAkE;AAClE,6CAA2H;AAG3H,+DAAkE;AAClE,+DAAkE;AAIlE,mCAAoC;AAEpC;;GAEG;AACH,MAAa,MAAM;aACR,QAAU,GAAG,uCAAqB,CAAC;aACnC,QAAU,GAAG,uCAAqB,CAAC;IAE1C;;;OAGG;IACH,MAAM,CAAC,UAAU,CAAC,QAAa;QAC3B,MAAM,CAAC,cAAc,CAAC,QAAQ,EAAE,kBAAQ,EAAE;YACtC,KAAK,EAAE,IAAI,uBAAU,CAAC,QAAQ,CAAC;YAC/B,UAAU,EAAE,KAAK;YACjB,QAAQ,EAAE,IAAI;SACjB,CAAC,CAAC;QAEH,MAAM,CAAC,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,CAAC,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,sBAAY,CAAC,IAAI,EAAE,CAAC,CAAC;IACnG,CAAC;IAED,MAAM,CAAC,EAAE,CAAC,IAAoB;QAC1B,OAAO,OAAM,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,KAAK,QAAQ,CAAC;QAClD,0CAA0C;QAC1C,yEAAyE;IAC7E,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,OA1BC,kBAAQ,OACR,kBAAQ,EAyBR,gBAAM,EAAC,CAAE,UAAsB,EAAE,KAAa,EAAE,YAAuB,gBAAS,CAAC,GAAG;QACxF,UAAU,CAAC,MAAM,CAAC,KAAK,EAAE,SAAS,C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AAW,GAAG,UAAU,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,YAAY,UAAU,CAAC,KAAK,gBAAgB,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,IAAI,CAAC;YAE/I,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;gBAC1B,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;gBACjC,MAAM,IAAI,GAAG,IAAA,iBAAS,EAAC,KAAK,GAAG,CAAC,CAAC,GAAG,gBAAS,CAAC,SAAS,CAAC,KAAK,KAAK,IAAI,CAAC;YAC3E,CAAC;QACL,CAAC;QAED,OAAO,GAAG,MAAM,EAAE,CAAC;IACvB,CAAC;;AAvUL,wBA0UC","sourcesContent":["import { OPERATION } from './encoding/spec';\nimport { DEFAULT_VIEW_TAG, type DefinitionType } from \"./annotations\";\n\nimport { NonFunctionPropNames, ToJSON } from './types/HelperTypes';\n\nimport { ChangeSet, ChangeTree, Ref } from './encoder/ChangeTree';\nimport { $changes, $decoder, $deleteByIndex, $descriptors, $encoder, $filter, $getByIndex, $track } from './types/symbols';\nimport { StateView } from './encoder/StateView';\n\nimport { encodeSchemaOperation } from './encoder/EncodeOperation';\nimport { decodeSchemaOperation } from './decoder/DecodeOperation';\n\nimport type { Decoder } from './decoder/Decoder';\nimport type { Metadata } from './Metadata';\nimport { getIndent } from './utils';\n\n/**\n * Schema encoder / decoder\n */\nexport class Schema {\n static [$encoder] = encodeSchemaOperation;\n static [$decoder] = decodeSchemaOperation;\n\n /**\n * Assign the property descriptors required to track changes on this instance.\n * @param instance\n */\n static initialize(instance: any) {\n Object.defineProperty(instance, $changes, {\n value: new ChangeTree(instance),\n enumerable: false,\n writable: true\n });\n\n Object.defineProperties(instance, instance.constructor[Symbol.metadata]?.[$descriptors] || {});\n }\n\n static is(type: DefinitionType) {\n return typeof(type[Symbol.metadata]) === \"object\";\n // const metadata = type[Symbol.metadata];\n // return metadata && Object.prototype.hasOwnProperty.call(metadata, -1);\n }\n\n /**\n * Track property changes\n */\n static [$track] (changeTree: ChangeTree, index: number, operation: OPERATION = OPERATION.ADD) {\n changeTree.change(index, operation);\n }\n\n /**\n * Determine if a property must be filtered.\n * - If returns false, the property is NOT going to be encoded.\n * - If returns true, the property is going to be encoded.\n *\n * Encoding with \"filters\" happens in two steps:\n * - First, the encoder iterates over all \"not owned\" properties and encodes them.\n * - Then, the encoder iterates over all \"owned\" properties per instance and encodes them.\n */\n static [$filter] (ref: Schema, index: number, view: StateView) {\n const metadata: Metadata = ref.constructor[Symbol.metadata];\n const tag = metadata[index]?.tag;\n\n if (view === undefined) {\n // shared pass/encode: encode if doesn't have a tag\n return tag === undefined;\n\n } else if (tag === undefined) {\n // view pass: no tag\n return true;\n\n } else if (tag === DEFAULT_VIEW_TAG) {\n // view pass: default tag\n return view.isChangeTreeVisible(ref[$changes]);\n\n } else {\n // view pass: custom tag\n const tags = view.tags?.get(ref[$changes]);\n return tags && tags.has(tag);\n }\n }\n\n // allow inherited classes to have a constructor\n constructor(...args: any[]) {\n //\n // inline\n // Schema.initialize(this);\n //\n Schema.initialize(this);\n\n //\n // Assign initial values\n //\n if (args[0]) {\n Object.assign(this, args[0]);\n }\n }\n\n public assign(\n props: { [prop in NonFunctionPropNames<this>]?: this[prop] } | ToJSON<this>,\n ) {\n Object.assign(this, props);\n return this;\n }\n\n /**\n * (Server-side): Flag a property to be encoded for the next patch.\n * @param instance Schema instance\n * @param property string representing the property name, or number representing the index of the property.\n * @param operation OPERATION to perform (detected automatically)\n */\n public setDirty<K extends NonFunctionPropNames<this>>(property: K | number, operation?: OPERATION) {\n const metadata: Metadata = this.constructor[Symbol.metadata];\n this[$changes].change(\n metadata[metadata[property as string]].index,\n operation\n );\n }\n\n clone (): this {\n const cloned = new ((this as any).constructor);\n const metadata: Metadata = this.constructor[Symbol.metadata];\n\n //\n // TODO: clone all properties, not only annotated ones\n //\n // for (const field in this) {\n for (const fieldIndex in metadata) {\n // const field = metadata[metadata[fieldIndex]].name;\n const field = metadata[fieldIndex as any as number].name;\n\n if (\n typeof (this[field]) === \"object\" &&\n typeof (this[field]?.clone) === \"function\"\n ) {\n // deep clone\n cloned[field] = this[field].clone();\n\n } else {\n // primitive values\n cloned[field] = this[field];\n }\n }\n\n return cloned;\n }\n\n toJSON () {\n const obj: unknown = {};\n const metadata = this.constructor[Symbol.metadata];\n for (const index in metadata) {\n const field = metadata[index];\n const fieldName = field.name;\n if (!field.deprecated && this[fieldName] !== null && typeof (this[fieldName]) !== \"undefined\") {\n obj[fieldName] = (typeof (this[fieldName]['toJSON']) === \"function\")\n ? this[fieldName]['toJSON']()\n : this[fieldName];\n }\n }\n return obj as ToJSON<typeof this>;\n }\n\n /**\n * Used in tests only\n * @internal\n */\n discardAllChanges() {\n this[$changes].discardAll();\n }\n\n protected [$getByIndex](index: number) {\n const metadata: Metadata = this.constructor[Symbol.metadata];\n return this[metadata[index].name];\n }\n\n protected [$deleteByIndex](index: number) {\n const metadata: Metadata = this.constructor[Symbol.metadata];\n this[metadata[index].name] = undefined;\n }\n\n /**\n * Inspect the `refId` of all Schema instances in the tree. Optionally display the contents of the instance.\n *\n * @param ref Schema instance\n * @param showContents display JSON contents of the instance\n * @returns\n */\n static debugRefIds(ref: Ref, showContents: boolean = false, level: number = 0, decoder?: Decoder, keyPrefix: string = \"\") {\n const contents = (showContents) ? ` - ${JSON.stringify(ref.toJSON())}` : \"\";\n const changeTree: ChangeTree = ref[$changes];\n\n const refId = (decoder) ? decoder.root.refIds.get(ref) : changeTree.refId;\n const root = (decoder) ? decoder.root : changeTree.root;\n\n // log reference count if > 1\n const refCount = (root?.refCount?.[refId] > 1)\n ? ` [×${root.refCount[refId]}]`\n : '';\n\n let output = `${getIndent(level)}${keyPrefix}${ref.constructor.name} (refId: ${refId})${refCount}${contents}\\n`;\n\n changeTree.forEachChild((childChangeTree, key) => {\n const keyPrefix = (ref['forEach'] !== undefined && key !== undefined) ? `[\"${key}\"]: ` : \"\";\n output += this.debugRefIds(childChangeTree.ref, showContents, level + 1, decoder, keyPrefix);\n });\n\n return output;\n }\n\n static debugRefIdEncodeOrder(ref: Ref) {\n let encodeOrder: number[] = [];\n let current = ref[$changes].root.allChanges.next;\n while (current) {\n if (current.changeTree) {\n encodeOrder.push(current.changeTree.refId);\n }\n current = current.next;\n }\n return encodeOrder;\n }\n\n static debugRefIdsDecoder(decoder: Decoder) {\n return this.debugRefIds(decoder.state, false, 0, decoder);\n }\n\n /**\n * Return a string representation of the changes on a Schema instance.\n * The list of changes is cleared after each encode.\n *\n * @param instance Schema instance\n * @param isEncodeAll Return \"full encode\" instead of current change set.\n * @returns\n */\n static debugChanges(instance: Ref, isEncodeAll: boolean = false) {\n const changeTree: ChangeTree = instance[$changes];\n\n const changeSet = (isEncodeAll) ? changeTree.allChanges : changeTree.changes;\n const changeSetName = (isEncodeAll) ? \"allChanges\" : \"changes\";\n\n let output = `${instance.constructor.name} (${changeTree.refId}) -> .${changeSetName}:\\n`;\n\n function dumpChangeSet(changeSet: ChangeSet) {\n changeSet.operations\n .filter(op => op)\n .forEach((index) => {\n const operation = changeTree.indexedOperations[index];\n console.log({ index, operation })\n output += `- [${index}]: ${OPERATION[operation]} (${JSON.stringify(changeTree.getValue(Number(index), isEncodeAll))})\\n`\n });\n }\n\n dumpChangeSet(changeSet);\n\n // display filtered changes\n if (\n !isEncodeAll &&\n changeTree.filteredChanges &&\n (changeTree.filteredChanges.operations).filter(op => op).length > 0\n ) {\n output += `${instance.constructor.name} (${changeTree.refId}) -> .filteredChanges:\\n`;\n dumpChangeSet(changeTree.filteredChanges);\n }\n\n // display filtered changes\n if (\n isEncodeAll &&\n changeTree.allFilteredChanges &&\n (changeTree.allFilteredChanges.operations).filter(op => op).length > 0\n ) {\n output += `${instance.constructor.name} (${changeTree.refId}) -> .allFilteredChanges:\\n`;\n dumpChangeSet(changeTree.allFilteredChanges);\n }\n\n return output;\n }\n\n static debugChangesDeep(ref: Ref, changeSetName: \"changes\" | \"allChanges\" | \"allFilteredChanges\" | \"filteredChanges\" = \"changes\") {\n let output = \"\";\n\n const rootChangeTree: ChangeTree = ref[$changes];\n const root = rootChangeTree.root;\n const changeTrees: Map<ChangeTree, ChangeTree[]> = new Map();\n\n const instanceRefIds = [];\n let totalOperations = 0;\n\n // TODO: FIXME: this method is not working as expected\n for (const [refId, changes] of Object.entries(root[changeSetName])) {\n const changeTree = root.changeTrees[refId];\n if (!changeTree) { continue; }\n\n let includeChangeTree = false;\n let parentChangeTrees: ChangeTree[] = [];\n let parentChangeTree = changeTree.parent?.[$changes];\n\n if (changeTree === rootChangeTree) {\n includeChangeTree = true;\n\n } else {\n while (parentChangeTree !== undefined) {\n parentChangeTrees.push(parentChangeTree);\n if (parentChangeTree.ref === ref) {\n includeChangeTree = true;\n break;\n }\n parentChangeTree = parentChangeTree.parent?.[$changes];\n }\n }\n\n if (includeChangeTree) {\n instanceRefIds.push(changeTree.refId);\n totalOperations += Object.keys(changes).length;\n changeTrees.set(changeTree, parentChangeTrees.reverse());\n }\n }\n\n output += \"---\\n\"\n output += `root refId: ${rootChangeTree.refId}\\n`;\n output += `Total instances: ${instanceRefIds.length} (refIds: ${instanceRefIds.join(\", \")})\\n`;\n output += `Total changes: ${totalOperations}\\n`;\n output += \"---\\n\"\n\n // based on root.changes, display a tree of changes that has the \"ref\" instance as parent\n const visitedParents = new WeakSet<ChangeTree>();\n for (const [changeTree, parentChangeTrees] of changeTrees.entries()) {\n parentChangeTrees.forEach((parentChangeTree, level) => {\n if (!visitedParents.has(parentChangeTree)) {\n output += `${getIndent(level)}${parentChangeTree.ref.constructor.name} (refId: ${parentChangeTree.refId})\\n`;\n visitedParents.add(parentChangeTree);\n }\n });\n\n const changes = changeTree.indexedOperations;\n const level = parentChangeTrees.length;\n const indent = getIndent(level);\n\n const parentIndex = (level > 0) ? `(${changeTree.parentIndex}) ` : \"\";\n output += `${indent}${parentIndex}${changeTree.ref.constructor.name} (refId: ${changeTree.refId}) - changes: ${Object.keys(changes).length}\\n`;\n\n for (const index in changes) {\n const operation = changes[index];\n output += `${getIndent(level + 1)}${OPERATION[operation]}: ${index}\\n`;\n }\n }\n\n return `${output}`;\n }\n\n\n}\n\n"]}
1
+ {"version":3,"file":"Schema.js","sourceRoot":"","sources":["../src/Schema.ts"],"names":[],"mappings":";;;;AAAA,0CAA4C;AAC5C,+CAAsE;AAItE,qDAAiF;AACjF,6CAA2H;AAG3H,+DAAkE;AAClE,+DAAkE;AAIlE,mCAAoC;AAEpC;;GAEG;AACH,MAAa,MAAM;aACR,QAAU,GAAG,uCAAqB,CAAC;aACnC,QAAU,GAAG,uCAAqB,CAAC;IAE1C;;;OAGG;IACH,MAAM,CAAC,UAAU,CAAC,QAAa;QAC3B,MAAM,CAAC,cAAc,CAAC,QAAQ,EAAE,kBAAQ,EAAE;YACtC,KAAK,EAAE,IAAI,uBAAU,CAAC,QAAQ,CAAC;YAC/B,UAAU,EAAE,KAAK;YACjB,QAAQ,EAAE,IAAI;SACjB,CAAC,CAAC;QAEH,MAAM,CAAC,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,CAAC,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,sBAAY,CAAC,IAAI,EAAE,CAAC,CAAC;IACnG,CAAC;IAED,MAAM,CAAC,EAAE,CAAC,IAAoB;QAC1B,OAAO,OAAM,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,KAAK,QAAQ,CAAC;QAClD,0CAA0C;QAC1C,yEAAyE;IAC7E,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,OA1BC,kBAAQ,OACR,kBAAQ,EAyBR,gBAAM,EAAC,CAAE,UAAsB,EAAE,KAAa,EAAE,YAAuB,gBAAS,CAAC,GAAG;QACxF,UAAU,CAAC,MAAM,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;IACxC,CAAC;IAED;;;;;;;;OAQG;IACH,MAAM,CAAC,CAAC,iBAAO,CAAC,CAAE,GAAW,EAAE,KAAa,E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,gBAAgB,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,IAAI,CAAC;YAE/I,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;gBAC1B,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;gBACjC,MAAM,IAAI,GAAG,IAAA,iBAAS,EAAC,KAAK,GAAG,CAAC,CAAC,GAAG,gBAAS,CAAC,SAAS,CAAC,KAAK,KAAK,IAAI,CAAC;YAC3E,CAAC;QACL,CAAC;QAED,OAAO,GAAG,MAAM,EAAE,CAAC;IACvB,CAAC;;AAvUL,wBA0UC","sourcesContent":["import { OPERATION } from './encoding/spec';\nimport { DEFAULT_VIEW_TAG, type DefinitionType } from \"./annotations\";\n\nimport { NonFunctionPropNames, ToJSON } from './types/HelperTypes';\n\nimport { ChangeSet, ChangeSetName, ChangeTree, Ref } from './encoder/ChangeTree';\nimport { $changes, $decoder, $deleteByIndex, $descriptors, $encoder, $filter, $getByIndex, $track } from './types/symbols';\nimport { StateView } from './encoder/StateView';\n\nimport { encodeSchemaOperation } from './encoder/EncodeOperation';\nimport { decodeSchemaOperation } from './decoder/DecodeOperation';\n\nimport type { Decoder } from './decoder/Decoder';\nimport type { Metadata } from './Metadata';\nimport { getIndent } from './utils';\n\n/**\n * Schema encoder / decoder\n */\nexport class Schema {\n static [$encoder] = encodeSchemaOperation;\n static [$decoder] = decodeSchemaOperation;\n\n /**\n * Assign the property descriptors required to track changes on this instance.\n * @param instance\n */\n static initialize(instance: any) {\n Object.defineProperty(instance, $changes, {\n value: new ChangeTree(instance),\n enumerable: false,\n writable: true\n });\n\n Object.defineProperties(instance, instance.constructor[Symbol.metadata]?.[$descriptors] || {});\n }\n\n static is(type: DefinitionType) {\n return typeof(type[Symbol.metadata]) === \"object\";\n // const metadata = type[Symbol.metadata];\n // return metadata && Object.prototype.hasOwnProperty.call(metadata, -1);\n }\n\n /**\n * Track property changes\n */\n static [$track] (changeTree: ChangeTree, index: number, operation: OPERATION = OPERATION.ADD) {\n changeTree.change(index, operation);\n }\n\n /**\n * Determine if a property must be filtered.\n * - If returns false, the property is NOT going to be encoded.\n * - If returns true, the property is going to be encoded.\n *\n * Encoding with \"filters\" happens in two steps:\n * - First, the encoder iterates over all \"not owned\" properties and encodes them.\n * - Then, the encoder iterates over all \"owned\" properties per instance and encodes them.\n */\n static [$filter] (ref: Schema, index: number, view: StateView) {\n const metadata: Metadata = ref.constructor[Symbol.metadata];\n const tag = metadata[index]?.tag;\n\n if (view === undefined) {\n // shared pass/encode: encode if doesn't have a tag\n return tag === undefined;\n\n } else if (tag === undefined) {\n // view pass: no tag\n return true;\n\n } else if (tag === DEFAULT_VIEW_TAG) {\n // view pass: default tag\n return view.isChangeTreeVisible(ref[$changes]);\n\n } else {\n // view pass: custom tag\n const tags = view.tags?.get(ref[$changes]);\n return tags && tags.has(tag);\n }\n }\n\n // allow inherited classes to have a constructor\n constructor(...args: any[]) {\n //\n // inline\n // Schema.initialize(this);\n //\n Schema.initialize(this);\n\n //\n // Assign initial values\n //\n if (args[0]) {\n Object.assign(this, args[0]);\n }\n }\n\n public assign(\n props: { [prop in NonFunctionPropNames<this>]?: this[prop] } | ToJSON<this>,\n ) {\n Object.assign(this, props);\n return this;\n }\n\n /**\n * (Server-side): Flag a property to be encoded for the next patch.\n * @param instance Schema instance\n * @param property string representing the property name, or number representing the index of the property.\n * @param operation OPERATION to perform (detected automatically)\n */\n public setDirty<K extends NonFunctionPropNames<this>>(property: K | number, operation?: OPERATION) {\n const metadata: Metadata = this.constructor[Symbol.metadata];\n this[$changes].change(\n metadata[metadata[property as string]].index,\n operation\n );\n }\n\n clone (): this {\n const cloned = new ((this as any).constructor);\n const metadata: Metadata = this.constructor[Symbol.metadata];\n\n //\n // TODO: clone all properties, not only annotated ones\n //\n // for (const field in this) {\n for (const fieldIndex in metadata) {\n // const field = metadata[metadata[fieldIndex]].name;\n const field = metadata[fieldIndex as any as number].name;\n\n if (\n typeof (this[field]) === \"object\" &&\n typeof (this[field]?.clone) === \"function\"\n ) {\n // deep clone\n cloned[field] = this[field].clone();\n\n } else {\n // primitive values\n cloned[field] = this[field];\n }\n }\n\n return cloned;\n }\n\n toJSON () {\n const obj: unknown = {};\n const metadata = this.constructor[Symbol.metadata];\n for (const index in metadata) {\n const field = metadata[index];\n const fieldName = field.name;\n if (!field.deprecated && this[fieldName] !== null && typeof (this[fieldName]) !== \"undefined\") {\n obj[fieldName] = (typeof (this[fieldName]['toJSON']) === \"function\")\n ? this[fieldName]['toJSON']()\n : this[fieldName];\n }\n }\n return obj as ToJSON<typeof this>;\n }\n\n /**\n * Used in tests only\n * @internal\n */\n discardAllChanges() {\n this[$changes].discardAll();\n }\n\n protected [$getByIndex](index: number) {\n const metadata: Metadata = this.constructor[Symbol.metadata];\n return this[metadata[index].name];\n }\n\n protected [$deleteByIndex](index: number) {\n const metadata: Metadata = this.constructor[Symbol.metadata];\n this[metadata[index].name] = undefined;\n }\n\n /**\n * Inspect the `refId` of all Schema instances in the tree. Optionally display the contents of the instance.\n *\n * @param ref Schema instance\n * @param showContents display JSON contents of the instance\n * @returns\n */\n static debugRefIds(ref: Ref, showContents: boolean = false, level: number = 0, decoder?: Decoder, keyPrefix: string = \"\") {\n const contents = (showContents) ? ` - ${JSON.stringify(ref.toJSON())}` : \"\";\n const changeTree: ChangeTree = ref[$changes];\n\n const refId = (decoder) ? decoder.root.refIds.get(ref) : changeTree.refId;\n const root = (decoder) ? decoder.root : changeTree.root;\n\n // log reference count if > 1\n const refCount = (root?.refCount?.[refId] > 1)\n ? ` [×${root.refCount[refId]}]`\n : '';\n\n let output = `${getIndent(level)}${keyPrefix}${ref.constructor.name} (refId: ${refId})${refCount}${contents}\\n`;\n\n changeTree.forEachChild((childChangeTree, key) => {\n const keyPrefix = (ref['forEach'] !== undefined && key !== undefined) ? `[\"${key}\"]: ` : \"\";\n output += this.debugRefIds(childChangeTree.ref, showContents, level + 1, decoder, keyPrefix);\n });\n\n return output;\n }\n\n static debugRefIdEncodingOrder(ref: Ref, changeSet: ChangeSetName = 'allChanges') {\n let encodeOrder: number[] = [];\n let current = ref[$changes].root[changeSet].next;\n while (current) {\n if (current.changeTree) {\n encodeOrder.push(current.changeTree.refId);\n }\n current = current.next;\n }\n return encodeOrder;\n }\n\n static debugRefIdsFromDecoder(decoder: Decoder) {\n return this.debugRefIds(decoder.state, false, 0, decoder);\n }\n\n /**\n * Return a string representation of the changes on a Schema instance.\n * The list of changes is cleared after each encode.\n *\n * @param instance Schema instance\n * @param isEncodeAll Return \"full encode\" instead of current change set.\n * @returns\n */\n static debugChanges(instance: Ref, isEncodeAll: boolean = false) {\n const changeTree: ChangeTree = instance[$changes];\n\n const changeSet = (isEncodeAll) ? changeTree.allChanges : changeTree.changes;\n const changeSetName = (isEncodeAll) ? \"allChanges\" : \"changes\";\n\n let output = `${instance.constructor.name} (${changeTree.refId}) -> .${changeSetName}:\\n`;\n\n function dumpChangeSet(changeSet: ChangeSet) {\n changeSet.operations\n .filter(op => op)\n .forEach((index) => {\n const operation = changeTree.indexedOperations[index];\n console.log({ index, operation })\n output += `- [${index}]: ${OPERATION[operation]} (${JSON.stringify(changeTree.getValue(Number(index), isEncodeAll))})\\n`\n });\n }\n\n dumpChangeSet(changeSet);\n\n // display filtered changes\n if (\n !isEncodeAll &&\n changeTree.filteredChanges &&\n (changeTree.filteredChanges.operations).filter(op => op).length > 0\n ) {\n output += `${instance.constructor.name} (${changeTree.refId}) -> .filteredChanges:\\n`;\n dumpChangeSet(changeTree.filteredChanges);\n }\n\n // display filtered changes\n if (\n isEncodeAll &&\n changeTree.allFilteredChanges &&\n (changeTree.allFilteredChanges.operations).filter(op => op).length > 0\n ) {\n output += `${instance.constructor.name} (${changeTree.refId}) -> .allFilteredChanges:\\n`;\n dumpChangeSet(changeTree.allFilteredChanges);\n }\n\n return output;\n }\n\n static debugChangesDeep(ref: Ref, changeSetName: \"changes\" | \"allChanges\" | \"allFilteredChanges\" | \"filteredChanges\" = \"changes\") {\n let output = \"\";\n\n const rootChangeTree: ChangeTree = ref[$changes];\n const root = rootChangeTree.root;\n const changeTrees: Map<ChangeTree, ChangeTree[]> = new Map();\n\n const instanceRefIds = [];\n let totalOperations = 0;\n\n // TODO: FIXME: this method is not working as expected\n for (const [refId, changes] of Object.entries(root[changeSetName])) {\n const changeTree = root.changeTrees[refId];\n if (!changeTree) { continue; }\n\n let includeChangeTree = false;\n let parentChangeTrees: ChangeTree[] = [];\n let parentChangeTree = changeTree.parent?.[$changes];\n\n if (changeTree === rootChangeTree) {\n includeChangeTree = true;\n\n } else {\n while (parentChangeTree !== undefined) {\n parentChangeTrees.push(parentChangeTree);\n if (parentChangeTree.ref === ref) {\n includeChangeTree = true;\n break;\n }\n parentChangeTree = parentChangeTree.parent?.[$changes];\n }\n }\n\n if (includeChangeTree) {\n instanceRefIds.push(changeTree.refId);\n totalOperations += Object.keys(changes).length;\n changeTrees.set(changeTree, parentChangeTrees.reverse());\n }\n }\n\n output += \"---\\n\"\n output += `root refId: ${rootChangeTree.refId}\\n`;\n output += `Total instances: ${instanceRefIds.length} (refIds: ${instanceRefIds.join(\", \")})\\n`;\n output += `Total changes: ${totalOperations}\\n`;\n output += \"---\\n\"\n\n // based on root.changes, display a tree of changes that has the \"ref\" instance as parent\n const visitedParents = new WeakSet<ChangeTree>();\n for (const [changeTree, parentChangeTrees] of changeTrees.entries()) {\n parentChangeTrees.forEach((parentChangeTree, level) => {\n if (!visitedParents.has(parentChangeTree)) {\n output += `${getIndent(level)}${parentChangeTree.ref.constructor.name} (refId: ${parentChangeTree.refId})\\n`;\n visitedParents.add(parentChangeTree);\n }\n });\n\n const changes = changeTree.indexedOperations;\n const level = parentChangeTrees.length;\n const indent = getIndent(level);\n\n const parentIndex = (level > 0) ? `(${changeTree.parentIndex}) ` : \"\";\n output += `${indent}${parentIndex}${changeTree.ref.constructor.name} (refId: ${changeTree.refId}) - changes: ${Object.keys(changes).length}\\n`;\n\n for (const index in changes) {\n const operation = changes[index];\n output += `${getIndent(level + 1)}${OPERATION[operation]}: ${index}\\n`;\n }\n }\n\n return `${output}`;\n }\n\n\n}\n\n"]}
@@ -45,7 +45,7 @@ class Decoder {
45
45
  // throw new Error(`"refId" not found: ${nextRefId}`);
46
46
  console.error(`"refId" not found: ${nextRefId}`, { previousRef: ref, previousRefId: this.currentRefId });
47
47
  console.warn("Please report this to the developers. All refIds =>");
48
- console.warn(Schema_1.Schema.debugRefIdsDecoder(this));
48
+ console.warn(Schema_1.Schema.debugRefIdsFromDecoder(this));
49
49
  this.skipCurrentStructure(bytes, it, totalBytes);
50
50
  }
51
51
  else {
@@ -1 +1 @@
1
- {"version":3,"file":"Decoder.js","sourceRoot":"","sources":["../../src/decoder/Decoder.ts"],"names":[],"mappings":";;;AAAA,sDAAmD;AACnD,8CAAgF;AAChF,sCAAmC;AAEnC,+CAA4C;AAC5C,2CAA2E;AAG3E,yDAAsD;AACtD,uDAA+F;AAG/F,MAAa,OAAO;IAUhB,YAAY,IAAO,EAAE,OAAqB;QAJ1C,iBAAY,GAAW,CAAC,CAAC;QAKrB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAEpB,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,QAAQ,CAAC,IAAO;QACtB,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,CAAC;QAEpC,MAAM,KAAK,GAAG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AAK,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,cAAO,EAAE,CAAC;YAC/B,EAAE,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,OAAO,GAAG,eAAM,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YACzC,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QACrC,CAAC;QAED,OAAO,IAAI,IAAI,WAAW,CAAC;IAC/B,CAAC;IAED,oBAAoB,CAAE,IAAmB;QACrC,OAAO,IAAK,IAAY,EAAE,CAAC;IAC/B,CAAC;IAED,eAAe,CAAC,GAAe,EAAE,UAAwB;QACrD,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,oBAAU,CAAC,CAAC,KAAK,QAAQ,CAAC;QAC5D,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAU,CAAC,CAAC;QAE/C,GAAG,CAAC,OAAO,CAAC,CAAC,KAAU,EAAE,GAAQ,EAAE,EAAE;YACjC,UAAU,CAAC,IAAI,CAAC;gBACZ,GAAG,EAAE,GAAU;gBACf,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;AAlJD,0BAkJC","sourcesContent":["import { TypeContext } from \"../types/TypeContext\";\nimport { $changes, $childType, $decoder, $onDecodeEnd } from \"../types/symbols\";\nimport { Schema } from \"../Schema\";\n\nimport { decode } from \"../encoding/decode\";\nimport { OPERATION, SWITCH_TO_STRUCTURE, TYPE_ID } from '../encoding/spec';\nimport type { Ref } from \"../encoder/ChangeTree\";\nimport type { Iterator } from \"../encoding/decode\";\nimport { ReferenceTracker } from \"./ReferenceTracker\";\nimport { DEFINITION_MISMATCH, type DataChange, type 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.setState(root);\n\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 setState(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 ref[$onDecodeEnd]?.()\n\n const nextRefId = decode.number(bytes, it);\n const nextRef = $root.refs.get(nextRefId);\n\n //\n // Trying to access a reference that haven't been decoded yet.\n //\n if (!nextRef) {\n // throw new Error(`\"refId\" not found: ${nextRefId}`);\n console.error(`\"refId\" not found: ${nextRefId}`, { previousRef: ref, previousRefId: this.currentRefId });\n console.warn(\"Please report this to the developers. All refIds =>\");\n console.warn(Schema.debugRefIdsDecoder(this));\n this.skipCurrentStructure(bytes, it, totalBytes);\n\n } else {\n ref = nextRef;\n decoder = ref.constructor[$decoder];\n this.currentRefId = nextRefId;\n }\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 this.skipCurrentStructure(bytes, it, totalBytes);\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 skipCurrentStructure(bytes: Buffer, it: Iterator, totalBytes: number) {\n //\n // keep skipping next bytes until reaches a known structure\n // by local decoder.\n //\n const nextIterator: Iterator = { offset: it.offset };\n while (it.offset < totalBytes) {\n if (bytes[it.offset] === SWITCH_TO_STRUCTURE) {\n nextIterator.offset = it.offset + 1;\n if (this.root.refs.has(decode.number(bytes, nextIterator))) {\n break;\n }\n }\n it.offset++;\n }\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 return new (type as any)();\n }\n\n removeChildRefs(ref: Collection, allChanges: DataChange[]) {\n const needRemoveRef = typeof (ref[$childType]) !== \"string\";\n const refId = this.root.refIds.get(ref as Ref);\n\n ref.forEach((value: any, key: any) => {\n allChanges.push({\n ref: ref as Ref,\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,sDAAmD;AACnD,8CAAgF;AAChF,sCAAmC;AAEnC,+CAA4C;AAC5C,2CAA2E;AAG3E,yDAAsD;AAC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CAAC,GAAG,CAAC,GAAU,CAAC,CAAC;QAE/C,GAAG,CAAC,OAAO,CAAC,CAAC,KAAU,EAAE,GAAQ,EAAE,EAAE;YACjC,UAAU,CAAC,IAAI,CAAC;gBACZ,GAAG,EAAE,GAAU;gBACf,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;AAlJD,0BAkJC","sourcesContent":["import { TypeContext } from \"../types/TypeContext\";\nimport { $changes, $childType, $decoder, $onDecodeEnd } from \"../types/symbols\";\nimport { Schema } from \"../Schema\";\n\nimport { decode } from \"../encoding/decode\";\nimport { OPERATION, SWITCH_TO_STRUCTURE, TYPE_ID } from '../encoding/spec';\nimport type { Ref } from \"../encoder/ChangeTree\";\nimport type { Iterator } from \"../encoding/decode\";\nimport { ReferenceTracker } from \"./ReferenceTracker\";\nimport { DEFINITION_MISMATCH, type DataChange, type 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.setState(root);\n\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 setState(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 ref[$onDecodeEnd]?.()\n\n const nextRefId = decode.number(bytes, it);\n const nextRef = $root.refs.get(nextRefId);\n\n //\n // Trying to access a reference that haven't been decoded yet.\n //\n if (!nextRef) {\n // throw new Error(`\"refId\" not found: ${nextRefId}`);\n console.error(`\"refId\" not found: ${nextRefId}`, { previousRef: ref, previousRefId: this.currentRefId });\n console.warn(\"Please report this to the developers. All refIds =>\");\n console.warn(Schema.debugRefIdsFromDecoder(this));\n this.skipCurrentStructure(bytes, it, totalBytes);\n\n } else {\n ref = nextRef;\n decoder = ref.constructor[$decoder];\n this.currentRefId = nextRefId;\n }\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 this.skipCurrentStructure(bytes, it, totalBytes);\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 skipCurrentStructure(bytes: Buffer, it: Iterator, totalBytes: number) {\n //\n // keep skipping next bytes until reaches a known structure\n // by local decoder.\n //\n const nextIterator: Iterator = { offset: it.offset };\n while (it.offset < totalBytes) {\n if (bytes[it.offset] === SWITCH_TO_STRUCTURE) {\n nextIterator.offset = it.offset + 1;\n if (this.root.refs.has(decode.number(bytes, nextIterator))) {\n break;\n }\n }\n it.offset++;\n }\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 return new (type as any)();\n }\n\n removeChildRefs(ref: Collection, allChanges: DataChange[]) {\n const needRemoveRef = typeof (ref[$childType]) !== \"string\";\n const refId = this.root.refIds.get(ref as Ref);\n\n ref.forEach((value: any, key: any) => {\n allChanges.push({\n ref: ref as Ref,\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"]}
@@ -113,7 +113,7 @@ export declare class ChangeTree<T extends Ref = any> {
113
113
  * @param parent - The parent to remove
114
114
  * @returns true if parent was removed
115
115
  */
116
- removeParent(parent: Ref): boolean;
116
+ removeParent(parent?: Ref): boolean;
117
117
  /**
118
118
  * Find a specific parent in the chain
119
119
  */
@@ -153,6 +153,7 @@ class ChangeTree {
153
153
  // re-assigning a child of the same root, move it to the end
154
154
  // of the changes queue so encoding order is preserved
155
155
  //
156
+ root.add(child);
156
157
  root.moveToEndOfChanges(child);
157
158
  return;
158
159
  }
@@ -491,7 +492,7 @@ class ChangeTree {
491
492
  */
492
493
  addParent(parent, index) {
493
494
  // Check if this parent already exists in the chain
494
- if (this.hasParent((p, i) => p === parent && i === index)) {
495
+ if (this.hasParent((p, i) => p[symbols_1.$changes] === parent[symbols_1.$changes] && i === index)) {
495
496
  return;
496
497
  }
497
498
  this.parentChain = {
@@ -505,7 +506,7 @@ class ChangeTree {
505
506
  * @param parent - The parent to remove
506
507
  * @returns true if parent was removed
507
508
  */
508
- removeParent(parent) {
509
+ removeParent(parent = this.parent) {
509
510
  let current = this.parentChain;
510
511
  let previous = null;
511
512
  while (current) {
@@ -1 +1 @@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AAI,CAAC;QAC3B,CAAC;QACD,OAAO,OAAO,CAAC;IACnB,CAAC;CAEJ;AAljBD,gCAkjBC","sourcesContent":["import { OPERATION } from \"../encoding/spec\";\nimport { Schema } from \"../Schema\";\nimport { $changes, $childType, $decoder, $onEncodeEnd, $encoder, $getByIndex, $refTypeFieldIndexes, $viewFieldIndexes } 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\";\nimport type { SetSchema } from \"../types/custom/SetSchema\";\n\nimport { Root } from \"./Root\";\nimport { Metadata } from \"../Metadata\";\nimport type { EncodeOperation } from \"./EncodeOperation\";\nimport type { DecodeOperation } from \"../decoder/DecodeOperation\";\n\ndeclare global {\n interface Object {\n // FIXME: not a good practice to extend globals here\n [$changes]?: ChangeTree;\n [$encoder]?: EncodeOperation,\n [$decoder]?: DecodeOperation,\n }\n}\n\nexport type Ref = Schema\n | ArraySchema\n | MapSchema\n | CollectionSchema\n | SetSchema;\n\nexport type ChangeSetName = \"changes\"\n | \"allChanges\"\n | \"filteredChanges\"\n | \"allFilteredChanges\";\n\nexport interface IndexedOperations {\n [index: number]: OPERATION;\n}\n\n// Linked list node for change trees\nexport interface ChangeTreeNode {\n changeTree: ChangeTree;\n next?: ChangeTreeNode;\n prev?: ChangeTreeNode;\n}\n\n// Linked list for change trees\nexport interface ChangeTreeList {\n next?: ChangeTreeNode;\n tail?: ChangeTreeNode;\n length: number;\n}\n\nexport interface ChangeSet {\n // field index -> operation index\n indexes: { [index: number]: number };\n operations: number[];\n queueRootNode?: ChangeTreeNode; // direct reference to ChangeTreeNode in the linked list\n}\n\nfunction createChangeSet(): ChangeSet {\n return { indexes: {}, operations: [] };\n}\n\n// Linked list helper functions\nexport function createChangeTreeList(): ChangeTreeList {\n return { next: undefined, tail: undefined, length: 0 };\n}\n\nexport function addToChangeTreeList(list: ChangeTreeList, changeTree: ChangeTree): ChangeTreeNode {\n const node: ChangeTreeNode = { changeTree, next: undefined, prev: undefined };\n\n if (!list.next) {\n list.next = node;\n list.tail = node;\n } else {\n node.prev = list.tail;\n list.tail!.next = node;\n list.tail = node;\n }\n\n list.length++;\n\n return node;\n}\n\nexport function setOperationAtIndex(changeSet: ChangeSet, index: number) {\n const operationsIndex = changeSet.indexes[index];\n if (operationsIndex === undefined) {\n changeSet.indexes[index] = changeSet.operations.push(index) - 1;\n } else {\n changeSet.operations[operationsIndex] = index;\n }\n}\n\nexport function deleteOperationAtIndex(changeSet: ChangeSet, index: number | string) {\n let operationsIndex = changeSet.indexes[index];\n if (operationsIndex === undefined) {\n //\n // if index is not found, we need to find the last operation\n // FIXME: this is not very efficient\n //\n // > See \"should allow consecutive splices (same place)\" tests\n //\n operationsIndex = Object.values(changeSet.indexes).at(-1);\n index = Object.entries(changeSet.indexes).find(([_, value]) => value === operationsIndex)?.[0];\n }\n changeSet.operations[operationsIndex] = undefined;\n delete changeSet.indexes[index];\n}\n\nexport function debugChangeSet(label: string, changeSet: ChangeSet) {\n let indexes: string[] = [];\n let operations: string[] = [];\n\n for (const index in changeSet.indexes) {\n indexes.push(`\\t${index} => [${changeSet.indexes[index]}]`);\n }\n\n for (let i = 0; i < changeSet.operations.length; i++) {\n const index = changeSet.operations[i];\n if (index !== undefined) {\n operations.push(`\\t[${i}] => ${index}`);\n }\n }\n\n console.log(`${label} =>\\nindexes (${Object.keys(changeSet.indexes).length}) {`);\n console.log(indexes.join(\"\\n\"), \"\\n}\");\n console.log(`operations (${changeSet.operations.filter(op => op !== undefined).length}) {`);\n console.log(operations.join(\"\\n\"), \"\\n}\");\n}\n\nexport function enqueueChangeTree(\n root: Root,\n changeTree: ChangeTree,\n changeSet: 'changes' | 'filteredChanges' | 'allFilteredChanges' | 'allChanges',\n queueRootNode = changeTree[changeSet].queueRootNode\n) {\n // skip\n if (!root) { return; }\n\n if (queueRootNode) {\n } else {\n // Add to linked list if not already present\n changeTree[changeSet].queueRootNode = addToChangeTreeList(root[changeSet], changeTree);\n }\n}\n\nexport interface ParentChain {\n ref: Ref;\n index: number;\n next?: ParentChain;\n}\n\nexport class ChangeTree<T extends Ref=any> {\n ref: T;\n refId: number;\n metadata: Metadata;\n\n root?: Root;\n parentChain?: ParentChain; // Linked list for tracking parents\n\n /**\n * Whether this structure is parent of a filtered structure.\n */\n isFiltered: boolean = false;\n isVisibilitySharedWithParent?: boolean; // See test case: 'should not be required to manually call view.add() items to child arrays without @view() tag'\n\n indexedOperations: IndexedOperations = {};\n\n //\n // TODO:\n // try storing the index + operation per item.\n // example: 1024 & 1025 => ADD, 1026 => DELETE\n //\n // => https://chatgpt.com/share/67107d0c-bc20-8004-8583-83b17dd7c196\n //\n changes: ChangeSet = { indexes: {}, operations: [] };\n allChanges: ChangeSet = { indexes: {}, operations: [] };\n filteredChanges: ChangeSet;\n allFilteredChanges: ChangeSet;\n\n indexes: {[index: string]: any}; // TODO: remove this, only used by MapSchema/SetSchema/CollectionSchema (`encodeKeyValueOperation`)\n\n /**\n * Is this a new instance? Used on ArraySchema to determine OPERATION.MOVE_AND_ADD operation.\n */\n isNew = true;\n\n constructor(ref: T) {\n this.ref = ref;\n this.metadata = ref.constructor[Symbol.metadata];\n\n //\n // Does this structure have \"filters\" declared?\n //\n if (this.metadata?.[$viewFieldIndexes]) {\n this.allFilteredChanges = { indexes: {}, operations: [] };\n this.filteredChanges = { indexes: {}, operations: [] };\n }\n }\n\n setRoot(root: Root) {\n this.root = root;\n\n const isNewChangeTree = this.root.add(this);\n\n this.checkIsFiltered(this.parent, this.parentIndex, isNewChangeTree);\n\n // Recursively set root on child structures\n if (isNewChangeTree) {\n this.forEachChild((child, _) => {\n if (child.root !== root) {\n child.setRoot(root);\n } else {\n root.add(child); // increment refCount\n }\n });\n }\n }\n\n setParent(\n parent: Ref,\n root?: Root,\n parentIndex?: number,\n ) {\n this.addParent(parent, parentIndex);\n\n // avoid setting parents with empty `root`\n if (!root) { return; }\n\n const isNewChangeTree = root.add(this);\n\n // skip if parent is already set\n if (root !== this.root) {\n this.root = root;\n this.checkIsFiltered(parent, parentIndex, isNewChangeTree);\n }\n\n // assign same parent on child structures\n if (isNewChangeTree) {\n //\n // assign same parent on child structures\n //\n this.forEachChild((child, index) => {\n if (child.root === root) {\n //\n // re-assigning a child of the same root, move it to the end\n // of the changes queue so encoding order is preserved\n //\n root.moveToEndOfChanges(child);\n return;\n }\n child.setParent(this.ref, root, index);\n });\n }\n }\n\n forEachChild(callback: (change: ChangeTree, at: any) => void) {\n //\n // assign same parent on child structures\n //\n if (this.ref[$childType]) {\n if (typeof(this.ref[$childType]) !== \"string\") {\n // MapSchema / ArraySchema, etc.\n for (const [key, value] of (this.ref as MapSchema).entries()) {\n callback(value[$changes], key);\n };\n }\n\n } else {\n for (const index of this.metadata?.[$refTypeFieldIndexes] ?? []) {\n const field = this.metadata[index as any as number];\n const value = this.ref[field.name];\n if (!value) { continue; }\n callback(value[$changes], index);\n }\n }\n }\n\n operation(op: OPERATION) {\n // operations without index use negative values to represent them\n // this is checked during .encode() time.\n if (this.filteredChanges !== undefined) {\n this.filteredChanges.operations.push(-op);\n enqueueChangeTree(this.root, this, 'filteredChanges');\n\n } else {\n this.changes.operations.push(-op);\n enqueueChangeTree(this.root, this, 'changes');\n }\n }\n\n change(index: number, operation: OPERATION = OPERATION.ADD) {\n const isFiltered = this.isFiltered || (this.metadata?.[index]?.tag !== undefined);\n const changeSet = (isFiltered)\n ? this.filteredChanges\n : this.changes;\n\n const previousOperation = this.indexedOperations[index];\n if (!previousOperation || previousOperation === OPERATION.DELETE) {\n const op = (!previousOperation)\n ? operation\n : (previousOperation === OPERATION.DELETE)\n ? OPERATION.DELETE_AND_ADD\n : operation\n //\n // TODO: are DELETE operations being encoded as ADD here ??\n //\n this.indexedOperations[index] = op;\n }\n\n setOperationAtIndex(changeSet, index);\n\n if (isFiltered) {\n setOperationAtIndex(this.allFilteredChanges, index);\n\n if (this.root) {\n enqueueChangeTree(this.root, this, 'filteredChanges');\n enqueueChangeTree(this.root, this, 'allFilteredChanges');\n }\n\n } else {\n setOperationAtIndex(this.allChanges, index);\n enqueueChangeTree(this.root, this, 'changes');\n }\n }\n\n shiftChangeIndexes(shiftIndex: number) {\n //\n // Used only during:\n //\n // - ArraySchema#unshift()\n //\n const changeSet = (this.isFiltered)\n ? this.filteredChanges\n : this.changes;\n\n const newIndexedOperations = {};\n const newIndexes = {};\n for (const index in this.indexedOperations) {\n newIndexedOperations[Number(index) + shiftIndex] = this.indexedOperations[index];\n newIndexes[Number(index) + shiftIndex] = changeSet.indexes[index];\n }\n this.indexedOperations = newIndexedOperations;\n changeSet.indexes = newIndexes;\n\n changeSet.operations = changeSet.operations.map((index) => index + shiftIndex);\n }\n\n shiftAllChangeIndexes(shiftIndex: number, startIndex: number = 0) {\n //\n // Used only during:\n //\n // - ArraySchema#splice()\n //\n if (this.filteredChanges !== undefined) {\n this._shiftAllChangeIndexes(shiftIndex, startIndex, this.allFilteredChanges);\n this._shiftAllChangeIndexes(shiftIndex, startIndex, this.allChanges);\n\n } else {\n this._shiftAllChangeIndexes(shiftIndex, startIndex, this.allChanges);\n }\n }\n\n private _shiftAllChangeIndexes(shiftIndex: number, startIndex: number = 0, changeSet: ChangeSet) {\n const newIndexes = {};\n let newKey = 0;\n for (const key in changeSet.indexes) {\n newIndexes[newKey++] = changeSet.indexes[key];\n }\n changeSet.indexes = newIndexes;\n\n for (let i = 0; i < changeSet.operations.length; i++) {\n const index = changeSet.operations[i];\n if (index > startIndex) {\n changeSet.operations[i] = index + shiftIndex;\n }\n }\n }\n\n indexedOperation(index: number, operation: OPERATION, allChangesIndex: number = index) {\n this.indexedOperations[index] = operation;\n\n if (this.filteredChanges !== undefined) {\n setOperationAtIndex(this.allFilteredChanges, allChangesIndex);\n setOperationAtIndex(this.filteredChanges, index);\n enqueueChangeTree(this.root, this, 'filteredChanges');\n\n } else {\n setOperationAtIndex(this.allChanges, allChangesIndex);\n setOperationAtIndex(this.changes, index);\n enqueueChangeTree(this.root, this, 'changes');\n }\n }\n\n getType(index?: number) {\n return (\n //\n // Get the child type from parent structure.\n // - [\"string\"] => \"string\"\n // - { map: \"string\" } => \"string\"\n // - { set: \"string\" } => \"string\"\n //\n this.ref[$childType] || // ArraySchema | MapSchema | SetSchema | CollectionSchema\n this.metadata[index].type // Schema\n );\n }\n\n getChange(index: number) {\n return this.indexedOperations[index];\n }\n\n //\n // used during `.encode()`\n //\n getValue(index: number, isEncodeAll: boolean = false) {\n //\n // `isEncodeAll` param is only used by ArraySchema\n //\n return this.ref[$getByIndex](index, isEncodeAll);\n }\n\n delete(index: number, operation?: OPERATION, allChangesIndex = index) {\n if (index === undefined) {\n try {\n throw new Error(`@colyseus/schema ${this.ref.constructor.name}: trying to delete non-existing index '${index}'`);\n } catch (e) {\n console.warn(e);\n }\n return;\n }\n\n const changeSet = (this.filteredChanges !== undefined)\n ? this.filteredChanges\n : this.changes;\n\n this.indexedOperations[index] = operation ?? OPERATION.DELETE;\n setOperationAtIndex(changeSet, index);\n deleteOperationAtIndex(this.allChanges, allChangesIndex);\n\n const previousValue = this.getValue(index);\n\n // remove `root` reference\n if (previousValue && previousValue[$changes]) {\n //\n // FIXME: this.root is \"undefined\"\n //\n // This method is being called at decoding time when a DELETE operation is found.\n //\n // - This is due to using the concrete Schema class at decoding time.\n // - \"Reflected\" structures do not have this problem.\n //\n // (The property descriptors should NOT be used at decoding time. only at encoding time.)\n //\n this.root?.remove(previousValue[$changes]);\n }\n\n //\n // FIXME: this is looking a ugly and repeated\n //\n if (this.filteredChanges !== undefined) {\n deleteOperationAtIndex(this.allFilteredChanges, allChangesIndex);\n enqueueChangeTree(this.root, this, 'filteredChanges');\n\n } else {\n enqueueChangeTree(this.root, this, 'changes');\n }\n\n return previousValue;\n }\n\n endEncode(changeSetName: ChangeSetName) {\n this.indexedOperations = {};\n\n // clear changeset\n this[changeSetName] = createChangeSet();\n\n // ArraySchema and MapSchema have a custom \"encode end\" method\n this.ref[$onEncodeEnd]?.();\n\n // Not a new instance anymore\n this.isNew = false;\n }\n\n discard(discardAll: boolean = false) {\n //\n // > MapSchema:\n // Remove cached key to ensure ADD operations is unsed instead of\n // REPLACE in case same key is used on next patches.\n //\n this.ref[$onEncodeEnd]?.();\n\n this.indexedOperations = {};\n this.changes = createChangeSet();\n\n if (this.filteredChanges !== undefined) {\n this.filteredChanges = createChangeSet();\n }\n\n if (discardAll) {\n this.allChanges = createChangeSet();\n\n if (this.allFilteredChanges !== undefined) {\n this.allFilteredChanges = createChangeSet();\n }\n }\n }\n\n /**\n * Recursively discard all changes from this, and child structures.\n * (Used in tests only)\n */\n discardAll() {\n const keys = Object.keys(this.indexedOperations);\n for (let i = 0, len = keys.length; i < len; i++) {\n const value = this.getValue(Number(keys[i]));\n\n if (value && value[$changes]) {\n value[$changes].discardAll();\n }\n }\n\n this.discard();\n }\n\n get changed() {\n return (Object.entries(this.indexedOperations).length > 0);\n }\n\n protected checkIsFiltered(parent: Ref, parentIndex: number, isNewChangeTree: boolean) {\n if (this.root.types.hasFilters) {\n //\n // At Schema initialization, the \"root\" structure might not be available\n // yet, as it only does once the \"Encoder\" has been set up.\n //\n // So the \"parent\" may be already set without a \"root\".\n //\n this._checkFilteredByParent(parent, parentIndex);\n\n if (this.filteredChanges !== undefined) {\n enqueueChangeTree(this.root, this, 'filteredChanges');\n if (isNewChangeTree) {\n enqueueChangeTree(this.root, this, 'allFilteredChanges');\n }\n }\n }\n\n if (!this.isFiltered) {\n enqueueChangeTree(this.root, this, 'changes');\n if (isNewChangeTree) {\n enqueueChangeTree(this.root, this, 'allChanges');\n }\n }\n }\n\n protected _checkFilteredByParent(parent: Ref, parentIndex: number) {\n // skip if parent is not set\n if (!parent) { return; }\n\n //\n // ArraySchema | MapSchema - get the child type\n // (if refType is typeof string, the parentFiltered[key] below will always be invalid)\n //\n const refType = Metadata.isValidInstance(this.ref)\n ? this.ref.constructor\n : this.ref[$childType];\n\n let parentChangeTree: ChangeTree;\n\n let parentIsCollection = !Metadata.isValidInstance(parent);\n if (parentIsCollection) {\n parentChangeTree = parent[$changes];\n parent = parentChangeTree.parent;\n parentIndex = parentChangeTree.parentIndex;\n\n } else {\n parentChangeTree = parent[$changes]\n }\n\n const parentConstructor = parent.constructor as typeof Schema;\n\n let key = `${this.root.types.getTypeId(refType as typeof Schema)}`;\n if (parentConstructor) {\n key += `-${this.root.types.schemas.get(parentConstructor)}`;\n }\n key += `-${parentIndex}`;\n\n const fieldHasViewTag = Metadata.hasViewTagAtIndex(parentConstructor?.[Symbol.metadata], parentIndex);\n\n this.isFiltered = parent[$changes].isFiltered // in case parent is already filtered\n || this.root.types.parentFiltered[key]\n || fieldHasViewTag;\n\n //\n // \"isFiltered\" may not be imedialely available during `change()` due to the instance not being attached to the root yet.\n // when it's available, we need to enqueue the \"changes\" changeset into the \"filteredChanges\" changeset.\n //\n if (this.isFiltered) {\n\n this.isVisibilitySharedWithParent = (\n parentChangeTree.isFiltered &&\n typeof (refType) !== \"string\" &&\n !fieldHasViewTag &&\n parentIsCollection\n );\n\n if (!this.filteredChanges) {\n this.filteredChanges = createChangeSet();\n this.allFilteredChanges = createChangeSet();\n }\n\n if (this.changes.operations.length > 0) {\n this.changes.operations.forEach((index) =>\n setOperationAtIndex(this.filteredChanges, index));\n\n this.allChanges.operations.forEach((index) =>\n setOperationAtIndex(this.allFilteredChanges, index));\n\n this.changes = createChangeSet();\n this.allChanges = createChangeSet();\n }\n }\n }\n\n /**\n * Get the immediate parent\n */\n get parent(): Ref | undefined {\n return this.parentChain?.ref;\n }\n\n /**\n * Get the immediate parent index\n */\n get parentIndex(): number | undefined {\n return this.parentChain?.index;\n }\n\n /**\n * Add a parent to the chain\n */\n addParent(parent: Ref, index: number) {\n // Check if this parent already exists in the chain\n if (this.hasParent((p, i) => p === parent && i === index)) {\n return;\n }\n\n this.parentChain = {\n ref: parent,\n index,\n next: this.parentChain\n };\n }\n\n /**\n * Remove a parent from the chain\n * @param parent - The parent to remove\n * @returns true if parent was removed\n */\n removeParent(parent: Ref): boolean {\n let current = this.parentChain;\n let previous = null;\n while (current) {\n //\n // FIXME: it is required to check against `$changes` here because\n // ArraySchema is instance of Proxy\n //\n if (current.ref[$changes] === parent[$changes]) {\n if (previous) {\n previous.next = current.next;\n } else {\n this.parentChain = current.next;\n }\n return true;\n }\n previous = current;\n current = current.next;\n }\n return this.parentChain === undefined;\n }\n\n /**\n * Find a specific parent in the chain\n */\n findParent(predicate: (parent: Ref, index: number) => boolean): ParentChain | undefined {\n let current = this.parentChain;\n while (current) {\n if (predicate(current.ref, current.index)) {\n return current;\n }\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Check if this ChangeTree has a specific parent\n */\n hasParent(predicate: (parent: Ref, index: number) => boolean): boolean {\n return this.findParent(predicate) !== undefined;\n }\n\n /**\n * Get all parents as an array (for debugging/testing)\n */\n getAllParents(): Array<{ref: Ref, index: number}> {\n const parents: Array<{ref: Ref, index: number}> = [];\n let current = this.parentChain;\n while (current) {\n parents.push({ref: current.ref, index: current.index});\n current = current.next;\n }\n return parents;\n }\n\n}"]}
1
+ {"version":3,"file":"ChangeTree.js","sourceRoot":"","sources":["../../src/encoder/ChangeTree.ts"],"names":[],"mappings":";;;AAgEA,oDAEC;AAED,kDAeC;AAED,kDAOC;AAED,wDAcC;AAED,wCAmBC;AAED,8CAcC;AAjJD,2CAA6C;AAE7C,8CAAgJ;AAQhJ,0CAAuC;AAiDvC,SAAS,eAAe;IACpB,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;AAC3C,CAAC;AAED,+BAA+B;AAC/B,SAAgB,oBAAoB;IAChC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;AAC3D,CAAC;AAED,SAAgB,mBAAmB,CAAC,IAAoB,EAAE,UAAsB;IAC5E,MAAM,IAAI,GAAmB,EAAE,UAAU,EAAE,IAAI,EAAE,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O,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC;IAC1C,CAAC;IAED;;OAEG;IACH,UAAU,CAAC,SAAkD;QACzD,IAAI,OAAO,GAAG,IAAI,CAAC,WAAW,CAAC;QAC/B,OAAO,OAAO,EAAE,CAAC;YACb,IAAI,SAAS,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;gBACxC,OAAO,OAAO,CAAC;YACnB,CAAC;YACD,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;QAC3B,CAAC;QACD,OAAO,SAAS,CAAC;IACrB,CAAC;IAED;;OAEG;IACH,SAAS,CAAC,SAAkD;QACxD,OAAO,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,KAAK,SAAS,CAAC;IACpD,CAAC;IAED;;OAEG;IACH,aAAa;QACT,MAAM,OAAO,GAAuC,EAAE,CAAC;QACvD,IAAI,OAAO,GAAG,IAAI,CAAC,WAAW,CAAC;QAC/B,OAAO,OAAO,EAAE,CAAC;YACb,OAAO,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;YACzD,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;QAC3B,CAAC;QACD,OAAO,OAAO,CAAC;IACnB,CAAC;CAEJ;AAnjBD,gCAmjBC","sourcesContent":["import { OPERATION } from \"../encoding/spec\";\nimport { Schema } from \"../Schema\";\nimport { $changes, $childType, $decoder, $onEncodeEnd, $encoder, $getByIndex, $refTypeFieldIndexes, $viewFieldIndexes } 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\";\nimport type { SetSchema } from \"../types/custom/SetSchema\";\n\nimport { Root } from \"./Root\";\nimport { Metadata } from \"../Metadata\";\nimport type { EncodeOperation } from \"./EncodeOperation\";\nimport type { DecodeOperation } from \"../decoder/DecodeOperation\";\n\ndeclare global {\n interface Object {\n // FIXME: not a good practice to extend globals here\n [$changes]?: ChangeTree;\n [$encoder]?: EncodeOperation,\n [$decoder]?: DecodeOperation,\n }\n}\n\nexport type Ref = Schema\n | ArraySchema\n | MapSchema\n | CollectionSchema\n | SetSchema;\n\nexport type ChangeSetName = \"changes\"\n | \"allChanges\"\n | \"filteredChanges\"\n | \"allFilteredChanges\";\n\nexport interface IndexedOperations {\n [index: number]: OPERATION;\n}\n\n// Linked list node for change trees\nexport interface ChangeTreeNode {\n changeTree: ChangeTree;\n next?: ChangeTreeNode;\n prev?: ChangeTreeNode;\n}\n\n// Linked list for change trees\nexport interface ChangeTreeList {\n next?: ChangeTreeNode;\n tail?: ChangeTreeNode;\n length: number;\n}\n\nexport interface ChangeSet {\n // field index -> operation index\n indexes: { [index: number]: number };\n operations: number[];\n queueRootNode?: ChangeTreeNode; // direct reference to ChangeTreeNode in the linked list\n}\n\nfunction createChangeSet(): ChangeSet {\n return { indexes: {}, operations: [] };\n}\n\n// Linked list helper functions\nexport function createChangeTreeList(): ChangeTreeList {\n return { next: undefined, tail: undefined, length: 0 };\n}\n\nexport function addToChangeTreeList(list: ChangeTreeList, changeTree: ChangeTree): ChangeTreeNode {\n const node: ChangeTreeNode = { changeTree, next: undefined, prev: undefined };\n\n if (!list.next) {\n list.next = node;\n list.tail = node;\n } else {\n node.prev = list.tail;\n list.tail!.next = node;\n list.tail = node;\n }\n\n list.length++;\n\n return node;\n}\n\nexport function setOperationAtIndex(changeSet: ChangeSet, index: number) {\n const operationsIndex = changeSet.indexes[index];\n if (operationsIndex === undefined) {\n changeSet.indexes[index] = changeSet.operations.push(index) - 1;\n } else {\n changeSet.operations[operationsIndex] = index;\n }\n}\n\nexport function deleteOperationAtIndex(changeSet: ChangeSet, index: number | string) {\n let operationsIndex = changeSet.indexes[index];\n if (operationsIndex === undefined) {\n //\n // if index is not found, we need to find the last operation\n // FIXME: this is not very efficient\n //\n // > See \"should allow consecutive splices (same place)\" tests\n //\n operationsIndex = Object.values(changeSet.indexes).at(-1);\n index = Object.entries(changeSet.indexes).find(([_, value]) => value === operationsIndex)?.[0];\n }\n changeSet.operations[operationsIndex] = undefined;\n delete changeSet.indexes[index];\n}\n\nexport function debugChangeSet(label: string, changeSet: ChangeSet) {\n let indexes: string[] = [];\n let operations: string[] = [];\n\n for (const index in changeSet.indexes) {\n indexes.push(`\\t${index} => [${changeSet.indexes[index]}]`);\n }\n\n for (let i = 0; i < changeSet.operations.length; i++) {\n const index = changeSet.operations[i];\n if (index !== undefined) {\n operations.push(`\\t[${i}] => ${index}`);\n }\n }\n\n console.log(`${label} =>\\nindexes (${Object.keys(changeSet.indexes).length}) {`);\n console.log(indexes.join(\"\\n\"), \"\\n}\");\n console.log(`operations (${changeSet.operations.filter(op => op !== undefined).length}) {`);\n console.log(operations.join(\"\\n\"), \"\\n}\");\n}\n\nexport function enqueueChangeTree(\n root: Root,\n changeTree: ChangeTree,\n changeSet: 'changes' | 'filteredChanges' | 'allFilteredChanges' | 'allChanges',\n queueRootNode = changeTree[changeSet].queueRootNode\n) {\n // skip\n if (!root) { return; }\n\n if (queueRootNode) {\n } else {\n // Add to linked list if not already present\n changeTree[changeSet].queueRootNode = addToChangeTreeList(root[changeSet], changeTree);\n }\n}\n\nexport interface ParentChain {\n ref: Ref;\n index: number;\n next?: ParentChain;\n}\n\nexport class ChangeTree<T extends Ref = any> {\n ref: T;\n refId: number;\n metadata: Metadata;\n\n root?: Root;\n parentChain?: ParentChain; // Linked list for tracking parents\n\n /**\n * Whether this structure is parent of a filtered structure.\n */\n isFiltered: boolean = false;\n isVisibilitySharedWithParent?: boolean; // See test case: 'should not be required to manually call view.add() items to child arrays without @view() tag'\n\n indexedOperations: IndexedOperations = {};\n\n //\n // TODO:\n // try storing the index + operation per item.\n // example: 1024 & 1025 => ADD, 1026 => DELETE\n //\n // => https://chatgpt.com/share/67107d0c-bc20-8004-8583-83b17dd7c196\n //\n changes: ChangeSet = { indexes: {}, operations: [] };\n allChanges: ChangeSet = { indexes: {}, operations: [] };\n filteredChanges: ChangeSet;\n allFilteredChanges: ChangeSet;\n\n indexes: { [index: string]: any }; // TODO: remove this, only used by MapSchema/SetSchema/CollectionSchema (`encodeKeyValueOperation`)\n\n /**\n * Is this a new instance? Used on ArraySchema to determine OPERATION.MOVE_AND_ADD operation.\n */\n isNew = true;\n\n constructor(ref: T) {\n this.ref = ref;\n this.metadata = ref.constructor[Symbol.metadata];\n\n //\n // Does this structure have \"filters\" declared?\n //\n if (this.metadata?.[$viewFieldIndexes]) {\n this.allFilteredChanges = { indexes: {}, operations: [] };\n this.filteredChanges = { indexes: {}, operations: [] };\n }\n }\n\n setRoot(root: Root) {\n this.root = root;\n\n const isNewChangeTree = this.root.add(this);\n\n this.checkIsFiltered(this.parent, this.parentIndex, isNewChangeTree);\n\n // Recursively set root on child structures\n if (isNewChangeTree) {\n this.forEachChild((child, _) => {\n if (child.root !== root) {\n child.setRoot(root);\n } else {\n root.add(child); // increment refCount\n }\n });\n }\n }\n\n setParent(\n parent: Ref,\n root?: Root,\n parentIndex?: number,\n ) {\n this.addParent(parent, parentIndex);\n\n // avoid setting parents with empty `root`\n if (!root) { return; }\n\n const isNewChangeTree = root.add(this);\n\n // skip if parent is already set\n if (root !== this.root) {\n this.root = root;\n this.checkIsFiltered(parent, parentIndex, isNewChangeTree);\n }\n\n // assign same parent on child structures\n if (isNewChangeTree) {\n //\n // assign same parent on child structures\n //\n this.forEachChild((child, index) => {\n if (child.root === root) {\n //\n // re-assigning a child of the same root, move it to the end\n // of the changes queue so encoding order is preserved\n //\n root.add(child);\n root.moveToEndOfChanges(child);\n return;\n }\n child.setParent(this.ref, root, index);\n });\n }\n }\n\n forEachChild(callback: (change: ChangeTree, at: any) => void) {\n //\n // assign same parent on child structures\n //\n if (this.ref[$childType]) {\n if (typeof (this.ref[$childType]) !== \"string\") {\n // MapSchema / ArraySchema, etc.\n for (const [key, value] of (this.ref as MapSchema).entries()) {\n callback(value[$changes], key);\n };\n }\n\n } else {\n for (const index of this.metadata?.[$refTypeFieldIndexes] ?? []) {\n const field = this.metadata[index as any as number];\n const value = this.ref[field.name];\n if (!value) { continue; }\n callback(value[$changes], index);\n }\n }\n }\n\n operation(op: OPERATION) {\n // operations without index use negative values to represent them\n // this is checked during .encode() time.\n if (this.filteredChanges !== undefined) {\n this.filteredChanges.operations.push(-op);\n enqueueChangeTree(this.root, this, 'filteredChanges');\n\n } else {\n this.changes.operations.push(-op);\n enqueueChangeTree(this.root, this, 'changes');\n }\n }\n\n change(index: number, operation: OPERATION = OPERATION.ADD) {\n const isFiltered = this.isFiltered || (this.metadata?.[index]?.tag !== undefined);\n const changeSet = (isFiltered)\n ? this.filteredChanges\n : this.changes;\n\n const previousOperation = this.indexedOperations[index];\n if (!previousOperation || previousOperation === OPERATION.DELETE) {\n const op = (!previousOperation)\n ? operation\n : (previousOperation === OPERATION.DELETE)\n ? OPERATION.DELETE_AND_ADD\n : operation\n //\n // TODO: are DELETE operations being encoded as ADD here ??\n //\n this.indexedOperations[index] = op;\n }\n\n setOperationAtIndex(changeSet, index);\n\n if (isFiltered) {\n setOperationAtIndex(this.allFilteredChanges, index);\n\n if (this.root) {\n enqueueChangeTree(this.root, this, 'filteredChanges');\n enqueueChangeTree(this.root, this, 'allFilteredChanges');\n }\n\n } else {\n setOperationAtIndex(this.allChanges, index);\n enqueueChangeTree(this.root, this, 'changes');\n }\n }\n\n shiftChangeIndexes(shiftIndex: number) {\n //\n // Used only during:\n //\n // - ArraySchema#unshift()\n //\n const changeSet = (this.isFiltered)\n ? this.filteredChanges\n : this.changes;\n\n const newIndexedOperations = {};\n const newIndexes = {};\n for (const index in this.indexedOperations) {\n newIndexedOperations[Number(index) + shiftIndex] = this.indexedOperations[index];\n newIndexes[Number(index) + shiftIndex] = changeSet.indexes[index];\n }\n this.indexedOperations = newIndexedOperations;\n changeSet.indexes = newIndexes;\n\n changeSet.operations = changeSet.operations.map((index) => index + shiftIndex);\n }\n\n shiftAllChangeIndexes(shiftIndex: number, startIndex: number = 0) {\n //\n // Used only during:\n //\n // - ArraySchema#splice()\n //\n if (this.filteredChanges !== undefined) {\n this._shiftAllChangeIndexes(shiftIndex, startIndex, this.allFilteredChanges);\n this._shiftAllChangeIndexes(shiftIndex, startIndex, this.allChanges);\n\n } else {\n this._shiftAllChangeIndexes(shiftIndex, startIndex, this.allChanges);\n }\n }\n\n private _shiftAllChangeIndexes(shiftIndex: number, startIndex: number = 0, changeSet: ChangeSet) {\n const newIndexes = {};\n let newKey = 0;\n for (const key in changeSet.indexes) {\n newIndexes[newKey++] = changeSet.indexes[key];\n }\n changeSet.indexes = newIndexes;\n\n for (let i = 0; i < changeSet.operations.length; i++) {\n const index = changeSet.operations[i];\n if (index > startIndex) {\n changeSet.operations[i] = index + shiftIndex;\n }\n }\n }\n\n indexedOperation(index: number, operation: OPERATION, allChangesIndex: number = index) {\n this.indexedOperations[index] = operation;\n\n if (this.filteredChanges !== undefined) {\n setOperationAtIndex(this.allFilteredChanges, allChangesIndex);\n setOperationAtIndex(this.filteredChanges, index);\n enqueueChangeTree(this.root, this, 'filteredChanges');\n\n } else {\n setOperationAtIndex(this.allChanges, allChangesIndex);\n setOperationAtIndex(this.changes, index);\n enqueueChangeTree(this.root, this, 'changes');\n }\n }\n\n getType(index?: number) {\n return (\n //\n // Get the child type from parent structure.\n // - [\"string\"] => \"string\"\n // - { map: \"string\" } => \"string\"\n // - { set: \"string\" } => \"string\"\n //\n this.ref[$childType] || // ArraySchema | MapSchema | SetSchema | CollectionSchema\n this.metadata[index].type // Schema\n );\n }\n\n getChange(index: number) {\n return this.indexedOperations[index];\n }\n\n //\n // used during `.encode()`\n //\n getValue(index: number, isEncodeAll: boolean = false) {\n //\n // `isEncodeAll` param is only used by ArraySchema\n //\n return this.ref[$getByIndex](index, isEncodeAll);\n }\n\n delete(index: number, operation?: OPERATION, allChangesIndex = index) {\n if (index === undefined) {\n try {\n throw new Error(`@colyseus/schema ${this.ref.constructor.name}: trying to delete non-existing index '${index}'`);\n } catch (e) {\n console.warn(e);\n }\n return;\n }\n\n const changeSet = (this.filteredChanges !== undefined)\n ? this.filteredChanges\n : this.changes;\n\n this.indexedOperations[index] = operation ?? OPERATION.DELETE;\n setOperationAtIndex(changeSet, index);\n deleteOperationAtIndex(this.allChanges, allChangesIndex);\n\n const previousValue = this.getValue(index);\n\n // remove `root` reference\n if (previousValue && previousValue[$changes]) {\n //\n // FIXME: this.root is \"undefined\"\n //\n // This method is being called at decoding time when a DELETE operation is found.\n //\n // - This is due to using the concrete Schema class at decoding time.\n // - \"Reflected\" structures do not have this problem.\n //\n // (The property descriptors should NOT be used at decoding time. only at encoding time.)\n //\n this.root?.remove(previousValue[$changes]);\n }\n\n //\n // FIXME: this is looking a ugly and repeated\n //\n if (this.filteredChanges !== undefined) {\n deleteOperationAtIndex(this.allFilteredChanges, allChangesIndex);\n enqueueChangeTree(this.root, this, 'filteredChanges');\n\n } else {\n enqueueChangeTree(this.root, this, 'changes');\n }\n\n return previousValue;\n }\n\n endEncode(changeSetName: ChangeSetName) {\n this.indexedOperations = {};\n\n // clear changeset\n this[changeSetName] = createChangeSet();\n\n // ArraySchema and MapSchema have a custom \"encode end\" method\n this.ref[$onEncodeEnd]?.();\n\n // Not a new instance anymore\n this.isNew = false;\n }\n\n discard(discardAll: boolean = false) {\n //\n // > MapSchema:\n // Remove cached key to ensure ADD operations is unsed instead of\n // REPLACE in case same key is used on next patches.\n //\n this.ref[$onEncodeEnd]?.();\n\n this.indexedOperations = {};\n this.changes = createChangeSet();\n\n if (this.filteredChanges !== undefined) {\n this.filteredChanges = createChangeSet();\n }\n\n if (discardAll) {\n this.allChanges = createChangeSet();\n\n if (this.allFilteredChanges !== undefined) {\n this.allFilteredChanges = createChangeSet();\n }\n }\n }\n\n /**\n * Recursively discard all changes from this, and child structures.\n * (Used in tests only)\n */\n discardAll() {\n const keys = Object.keys(this.indexedOperations);\n for (let i = 0, len = keys.length; i < len; i++) {\n const value = this.getValue(Number(keys[i]));\n\n if (value && value[$changes]) {\n value[$changes].discardAll();\n }\n }\n\n this.discard();\n }\n\n get changed() {\n return (Object.entries(this.indexedOperations).length > 0);\n }\n\n protected checkIsFiltered(parent: Ref, parentIndex: number, isNewChangeTree: boolean) {\n if (this.root.types.hasFilters) {\n //\n // At Schema initialization, the \"root\" structure might not be available\n // yet, as it only does once the \"Encoder\" has been set up.\n //\n // So the \"parent\" may be already set without a \"root\".\n //\n this._checkFilteredByParent(parent, parentIndex);\n\n if (this.filteredChanges !== undefined) {\n enqueueChangeTree(this.root, this, 'filteredChanges');\n if (isNewChangeTree) {\n enqueueChangeTree(this.root, this, 'allFilteredChanges');\n }\n }\n }\n\n if (!this.isFiltered) {\n enqueueChangeTree(this.root, this, 'changes');\n if (isNewChangeTree) {\n enqueueChangeTree(this.root, this, 'allChanges');\n }\n }\n }\n\n protected _checkFilteredByParent(parent: Ref, parentIndex: number) {\n // skip if parent is not set\n if (!parent) { return; }\n\n //\n // ArraySchema | MapSchema - get the child type\n // (if refType is typeof string, the parentFiltered[key] below will always be invalid)\n //\n const refType = Metadata.isValidInstance(this.ref)\n ? this.ref.constructor\n : this.ref[$childType];\n\n let parentChangeTree: ChangeTree;\n\n let parentIsCollection = !Metadata.isValidInstance(parent);\n if (parentIsCollection) {\n parentChangeTree = parent[$changes];\n parent = parentChangeTree.parent;\n parentIndex = parentChangeTree.parentIndex;\n\n } else {\n parentChangeTree = parent[$changes]\n }\n\n const parentConstructor = parent.constructor as typeof Schema;\n\n let key = `${this.root.types.getTypeId(refType as typeof Schema)}`;\n if (parentConstructor) {\n key += `-${this.root.types.schemas.get(parentConstructor)}`;\n }\n key += `-${parentIndex}`;\n\n const fieldHasViewTag = Metadata.hasViewTagAtIndex(parentConstructor?.[Symbol.metadata], parentIndex);\n\n this.isFiltered = parent[$changes].isFiltered // in case parent is already filtered\n || this.root.types.parentFiltered[key]\n || fieldHasViewTag;\n\n //\n // \"isFiltered\" may not be imedialely available during `change()` due to the instance not being attached to the root yet.\n // when it's available, we need to enqueue the \"changes\" changeset into the \"filteredChanges\" changeset.\n //\n if (this.isFiltered) {\n\n this.isVisibilitySharedWithParent = (\n parentChangeTree.isFiltered &&\n typeof (refType) !== \"string\" &&\n !fieldHasViewTag &&\n parentIsCollection\n );\n\n if (!this.filteredChanges) {\n this.filteredChanges = createChangeSet();\n this.allFilteredChanges = createChangeSet();\n }\n\n if (this.changes.operations.length > 0) {\n this.changes.operations.forEach((index) =>\n setOperationAtIndex(this.filteredChanges, index));\n\n this.allChanges.operations.forEach((index) =>\n setOperationAtIndex(this.allFilteredChanges, index));\n\n this.changes = createChangeSet();\n this.allChanges = createChangeSet();\n }\n }\n }\n\n /**\n * Get the immediate parent\n */\n get parent(): Ref | undefined {\n return this.parentChain?.ref;\n }\n\n /**\n * Get the immediate parent index\n */\n get parentIndex(): number | undefined {\n return this.parentChain?.index;\n }\n\n /**\n * Add a parent to the chain\n */\n addParent(parent: Ref, index: number) {\n // Check if this parent already exists in the chain\n if (this.hasParent((p, i) => p[$changes] === parent[$changes] && i === index)) {\n return;\n }\n\n this.parentChain = {\n ref: parent,\n index,\n next: this.parentChain\n };\n }\n\n /**\n * Remove a parent from the chain\n * @param parent - The parent to remove\n * @returns true if parent was removed\n */\n removeParent(parent: Ref = this.parent): boolean {\n let current = this.parentChain;\n let previous = null;\n while (current) {\n //\n // FIXME: it is required to check against `$changes` here because\n // ArraySchema is instance of Proxy\n //\n if (current.ref[$changes] === parent[$changes]) {\n if (previous) {\n previous.next = current.next;\n } else {\n this.parentChain = current.next;\n }\n return true;\n }\n previous = current;\n current = current.next;\n }\n return this.parentChain === undefined;\n }\n\n /**\n * Find a specific parent in the chain\n */\n findParent(predicate: (parent: Ref, index: number) => boolean): ParentChain | undefined {\n let current = this.parentChain;\n while (current) {\n if (predicate(current.ref, current.index)) {\n return current;\n }\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Check if this ChangeTree has a specific parent\n */\n hasParent(predicate: (parent: Ref, index: number) => boolean): boolean {\n return this.findParent(predicate) !== undefined;\n }\n\n /**\n * Get all parents as an array (for debugging/testing)\n */\n getAllParents(): Array<{ ref: Ref, index: number }> {\n const parents: Array<{ ref: Ref, index: number }> = [];\n let current = this.parentChain;\n while (current) {\n parents.push({ ref: current.ref, index: current.index });\n current = current.next;\n }\n return parents;\n }\n\n}\n"]}