@colyseus/schema 3.0.0-alpha.2 → 3.0.0-alpha.22

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 (99) hide show
  1. package/README.md +131 -61
  2. package/build/cjs/index.js +472 -150
  3. package/build/cjs/index.js.map +1 -1
  4. package/build/esm/index.mjs +471 -149
  5. package/build/esm/index.mjs.map +1 -1
  6. package/build/umd/index.js +472 -150
  7. package/lib/Metadata.d.ts +2 -0
  8. package/lib/Metadata.js +39 -0
  9. package/lib/Metadata.js.map +1 -1
  10. package/lib/Reflection.d.ts +1 -2
  11. package/lib/Reflection.js +28 -22
  12. package/lib/Reflection.js.map +1 -1
  13. package/lib/Schema.d.ts +1 -1
  14. package/lib/annotations.js +12 -10
  15. package/lib/annotations.js.map +1 -1
  16. package/lib/bench_encode.d.ts +1 -0
  17. package/lib/bench_encode.js +93 -0
  18. package/lib/bench_encode.js.map +1 -0
  19. package/lib/codegen/api.js +1 -2
  20. package/lib/codegen/api.js.map +1 -1
  21. package/lib/codegen/languages/cpp.js +1 -2
  22. package/lib/codegen/languages/cpp.js.map +1 -1
  23. package/lib/codegen/languages/csharp.js +1 -2
  24. package/lib/codegen/languages/csharp.js.map +1 -1
  25. package/lib/codegen/languages/haxe.js +1 -2
  26. package/lib/codegen/languages/haxe.js.map +1 -1
  27. package/lib/codegen/languages/java.js +1 -2
  28. package/lib/codegen/languages/java.js.map +1 -1
  29. package/lib/codegen/languages/js.js +1 -2
  30. package/lib/codegen/languages/js.js.map +1 -1
  31. package/lib/codegen/languages/lua.js +1 -2
  32. package/lib/codegen/languages/lua.js.map +1 -1
  33. package/lib/codegen/languages/ts.js +1 -2
  34. package/lib/codegen/languages/ts.js.map +1 -1
  35. package/lib/codegen/parser.js +2 -3
  36. package/lib/codegen/parser.js.map +1 -1
  37. package/lib/codegen/types.js +3 -3
  38. package/lib/codegen/types.js.map +1 -1
  39. package/lib/decoder/DecodeOperation.d.ts +0 -1
  40. package/lib/decoder/DecodeOperation.js +22 -7
  41. package/lib/decoder/DecodeOperation.js.map +1 -1
  42. package/lib/decoder/Decoder.d.ts +1 -2
  43. package/lib/decoder/Decoder.js +4 -4
  44. package/lib/decoder/Decoder.js.map +1 -1
  45. package/lib/decoder/strategy/RawChanges.js +1 -2
  46. package/lib/decoder/strategy/RawChanges.js.map +1 -1
  47. package/lib/decoder/strategy/StateCallbacks.d.ts +36 -7
  48. package/lib/decoder/strategy/StateCallbacks.js +39 -46
  49. package/lib/decoder/strategy/StateCallbacks.js.map +1 -1
  50. package/lib/encoder/ChangeTree.js +2 -5
  51. package/lib/encoder/ChangeTree.js.map +1 -1
  52. package/lib/encoder/EncodeOperation.d.ts +0 -1
  53. package/lib/encoder/EncodeOperation.js +29 -13
  54. package/lib/encoder/EncodeOperation.js.map +1 -1
  55. package/lib/encoder/Encoder.d.ts +5 -4
  56. package/lib/encoder/Encoder.js +56 -38
  57. package/lib/encoder/Encoder.js.map +1 -1
  58. package/lib/encoder/StateView.js +11 -6
  59. package/lib/encoder/StateView.js.map +1 -1
  60. package/lib/encoding/assert.js +3 -3
  61. package/lib/encoding/assert.js.map +1 -1
  62. package/lib/encoding/decode.d.ts +21 -19
  63. package/lib/encoding/decode.js +24 -25
  64. package/lib/encoding/decode.js.map +1 -1
  65. package/lib/encoding/encode.d.ts +2 -2
  66. package/lib/encoding/encode.js +40 -39
  67. package/lib/encoding/encode.js.map +1 -1
  68. package/lib/encoding/spec.d.ts +2 -1
  69. package/lib/encoding/spec.js +1 -0
  70. package/lib/encoding/spec.js.map +1 -1
  71. package/lib/index.d.ts +3 -0
  72. package/lib/index.js +5 -1
  73. package/lib/index.js.map +1 -1
  74. package/lib/types/custom/ArraySchema.d.ts +2 -2
  75. package/lib/types/custom/ArraySchema.js +0 -8
  76. package/lib/types/custom/ArraySchema.js.map +1 -1
  77. package/lib/types/registry.js +3 -4
  78. package/lib/types/registry.js.map +1 -1
  79. package/lib/types/utils.js +1 -2
  80. package/lib/types/utils.js.map +1 -1
  81. package/lib/utils.js +3 -4
  82. package/lib/utils.js.map +1 -1
  83. package/package.json +5 -5
  84. package/src/Metadata.ts +47 -0
  85. package/src/Reflection.ts +31 -22
  86. package/src/annotations.ts +6 -2
  87. package/src/bench_encode.ts +66 -0
  88. package/src/decoder/DecodeOperation.ts +26 -6
  89. package/src/decoder/Decoder.ts +5 -5
  90. package/src/decoder/strategy/StateCallbacks.ts +93 -53
  91. package/src/encoder/ChangeTree.ts +2 -4
  92. package/src/encoder/EncodeOperation.ts +29 -12
  93. package/src/encoder/Encoder.ts +65 -41
  94. package/src/encoder/StateView.ts +10 -7
  95. package/src/encoding/decode.ts +24 -25
  96. package/src/encoding/encode.ts +25 -22
  97. package/src/encoding/spec.ts +1 -0
  98. package/src/index.ts +5 -0
  99. package/src/types/custom/ArraySchema.ts +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ts.js","sourceRoot":"","sources":["../../../src/codegen/languages/ts.ts"],"names":[],"mappings":";;;AAAA,oCAA2G;AAG3G,MAAM,QAAQ,GAAG;IACb,QAAQ,EAAE,QAAQ;IAClB,QAAQ,EAAE,QAAQ;IAClB,SAAS,EAAE,SAAS;IACpB,MAAM,EAAE,QAAQ;IAChB,OAAO,EAAE,QAAQ;IACjB,OAAO,EAAE,QAAQ;IACjB,QAAQ,EAAE,QAAQ;IAClB,OAAO,EAAE,QAAQ;IACjB,QAAQ,EAAE,QAAQ;IAClB,OAAO,EAAE,QAAQ;IACjB,QAAQ,EAAE,QAAQ;IAClB,SAAS,EAAE,QAAQ;IACnB,SAAS,EAAE,QAAQ;CACtB,CAAA;AAED,MAAM,QAAQ,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,KAAK,CAAC;AAEvE,SAAgB,QAAQ,CAAE,OAAgB,EAAE,OAAwB;IAChE,OAAO;QACH,GAAG,OAAO,CAAC,OAAO,CAAC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CAAC;IAED,2FAA2F;IAC3F,MAAM,iBAAiB,GAAG,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IAEjD,OAAO,SAAS,QAAQ,YAAY,IAAI,CAAC,IAAI,GAAG,iBAAiB,KAAK,QAAQ,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,MAAM,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,CAAA;AAChI,CAAC;AAGD,SAAS,iBAAiB,CAAC,SAAoB,EAAE,SAAiB,EAAE,UAAmB;IACnF,OAAO,GAAG,IAAA,wBAAgB,GAAE;;mBAEb,SAAS,CAAC,IAAI;EAC/B,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;;CAE/E,CAAC;AACF,CAAC","sourcesContent":["import { Class, Property, File, getCommentHeader, getInheritanceTree, Context, Interface } from \"../types\";\nimport { GenerateOptions } from \"../api\";\n\nconst typeMaps = {\n \"string\": \"string\",\n \"number\": \"number\",\n \"boolean\": \"boolean\",\n \"int8\": \"number\",\n \"uint8\": \"number\",\n \"int16\": \"number\",\n \"uint16\": \"number\",\n \"int32\": \"number\",\n \"uint32\": \"number\",\n \"int64\": \"number\",\n \"uint64\": \"number\",\n \"float32\": \"number\",\n \"float64\": \"number\",\n}\n\nconst distinct = (value, index, self) => self.indexOf(value) === index;\n\nexport function generate (context: Context, options: GenerateOptions): File[] {\n return [\n ...context.classes.map(structure => ({\n name: structure.name + \".ts\",\n content: generateClass(structure, options.namespace, context.classes)\n })),\n ...context.interfaces.map(structure => ({\n name: structure.name + \".ts\",\n content: generateInterface(structure, options.namespace, context.classes),\n }))\n ];\n}\n\nfunction generateClass(klass: Class, namespace: string, allClasses: Class[]) {\n const allRefs: Property[] = [];\n klass.properties.forEach(property => {\n let type = property.type;\n\n // keep all refs list\n if ((type === \"ref\" || type === \"array\" || type === \"map\" || type === \"set\")) {\n allRefs.push(property);\n }\n });\n\n return `${getCommentHeader()}\n\nimport { Schema, type, ArraySchema, MapSchema, SetSchema, DataChange } from '@colyseus/schema';\n${allRefs.\n filter(ref => ref.childType && typeMaps[ref.childType] === undefined).\n map(ref => ref.childType).\n concat(getInheritanceTree(klass, allClasses, false).map(klass => klass.name)).\n filter(distinct).\n map(childType => `import { ${childType} } from './${childType}'`).\n join(\"\\n\")}\n\nexport class ${klass.name} extends ${klass.extends} {\n${klass.properties.map(prop => ` ${generateProperty(prop)}`).join(\"\\n\")}\n}\n`;\n}\n\nfunction generateProperty(prop: Property) {\n let langType: string;\n let initializer = \"\";\n let typeArgs: string;\n\n if (prop.childType) {\n const isUpcaseFirst = prop.childType.match(/^[A-Z]/);\n\n if (isUpcaseFirst) {\n typeArgs += `, ${prop.childType}`;\n\n } else {\n typeArgs += `, \"${prop.childType}\"`;\n }\n\n if(prop.type === \"ref\") {\n langType = `${prop.childType}`;\n initializer = `new ${prop.childType}()`;\n typeArgs = `${prop.childType}`;\n\n } else if(prop.type === \"array\") {\n langType = (isUpcaseFirst)\n ? `ArraySchema<${prop.childType}>`\n : `ArraySchema<${typeMaps[prop.childType]}>`;\n initializer = `new ${langType}()`;\n typeArgs = (isUpcaseFirst)\n ? `[ ${prop.childType} ]`\n : `[ \"${prop.childType}\" ]`;\n\n } else if(prop.type === \"map\") {\n langType = (isUpcaseFirst)\n ? `MapSchema<${prop.childType}>`\n : `MapSchema<${typeMaps[prop.childType]}>`;\n initializer = `new ${langType}()`;\n typeArgs = (isUpcaseFirst)\n ? `{ map: ${prop.childType} }`\n : `{ map: \"${prop.childType}\" }`;\n } else if (prop.type === \"set\") {\n langType = (isUpcaseFirst)\n ? `SetSchema<${prop.childType}>`\n : `SetSchema<${typeMaps[prop.childType]}>`;\n initializer = `new ${langType}()`;\n typeArgs = (isUpcaseFirst)\n ? `{ set: ${prop.childType} }`\n : `{ set: \"${prop.childType}\" }`;\n }\n\n } else {\n langType = typeMaps[prop.type];\n typeArgs = `\"${prop.type}\"`;\n }\n\n // TS1263: \"Declarations with initializers cannot also have definite assignment assertions\"\n const definiteAssertion = initializer ? \"\" : \"!\";\n\n return `@type(${typeArgs}) public ${prop.name}${definiteAssertion}: ${langType}${(initializer) ? ` = ${initializer}` : \"\"};`\n}\n\n\nfunction generateInterface(structure: Interface, namespace: string, allClasses: Class[]) {\n return `${getCommentHeader()}\n\nexport interface ${structure.name} {\n${structure.properties.map(prop => ` ${prop.name}: ${prop.type};`).join(\"\\n\")}\n}\n`;\n}\n"]}
1
+ {"version":3,"file":"ts.js","sourceRoot":"","sources":["../../../src/codegen/languages/ts.ts"],"names":[],"mappings":";;AAqBA,4BAWC;AAhCD,oCAA2G;AAG3G,MAAM,QAAQ,GAAG;IACb,QAAQ,EAAE,QAAQ;IAClB,QAAQ,EAAE,QAAQ;IAClB,SAAS,EAAE,SAAS;IACpB,MAAM,EAAE,QAAQ;IAChB,OAAO,EAAE,QAAQ;IACjB,OAAO,EAAE,QAAQ;IACjB,QAAQ,EAAE,QAAQ;IAClB,OAAO,EAAE,QAAQ;IACjB,QAAQ,EAAE,QAAQ;IAClB,OAAO,EAAE,QAAQ;IACjB,QAAQ,EAAE,QAAQ;IAClB,SAAS,EAAE,QAAQ;IACnB,SAAS,EAAE,QAAQ;CACtB,CAAA;AAED,MAAM,QAAQ,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,KAAK,CAAC;AAEvE,SAAgB,QAAQ,CAAE,OAAgB,EAAE,OAAwB;IAChE,OAAO;QACH,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;YACjC,IAAI,EAAE,SAAS,CAAC,IAAI,GAAG,KAAK;YAC5B,OAAO,EAAE,aAAa,CAAC,SAAS,EAAE,OA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,IAAI,GAAG,iBAAiB,KAAK,QAAQ,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,MAAM,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,CAAA;AAChI,CAAC;AAGD,SAAS,iBAAiB,CAAC,SAAoB,EAAE,SAAiB,EAAE,UAAmB;IACnF,OAAO,GAAG,IAAA,wBAAgB,GAAE;;mBAEb,SAAS,CAAC,IAAI;EAC/B,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;;CAE/E,CAAC;AACF,CAAC","sourcesContent":["import { Class, Property, File, getCommentHeader, getInheritanceTree, Context, Interface } from \"../types\";\nimport { GenerateOptions } from \"../api\";\n\nconst typeMaps = {\n \"string\": \"string\",\n \"number\": \"number\",\n \"boolean\": \"boolean\",\n \"int8\": \"number\",\n \"uint8\": \"number\",\n \"int16\": \"number\",\n \"uint16\": \"number\",\n \"int32\": \"number\",\n \"uint32\": \"number\",\n \"int64\": \"number\",\n \"uint64\": \"number\",\n \"float32\": \"number\",\n \"float64\": \"number\",\n}\n\nconst distinct = (value, index, self) => self.indexOf(value) === index;\n\nexport function generate (context: Context, options: GenerateOptions): File[] {\n return [\n ...context.classes.map(structure => ({\n name: structure.name + \".ts\",\n content: generateClass(structure, options.namespace, context.classes)\n })),\n ...context.interfaces.map(structure => ({\n name: structure.name + \".ts\",\n content: generateInterface(structure, options.namespace, context.classes),\n }))\n ];\n}\n\nfunction generateClass(klass: Class, namespace: string, allClasses: Class[]) {\n const allRefs: Property[] = [];\n klass.properties.forEach(property => {\n let type = property.type;\n\n // keep all refs list\n if ((type === \"ref\" || type === \"array\" || type === \"map\" || type === \"set\")) {\n allRefs.push(property);\n }\n });\n\n return `${getCommentHeader()}\n\nimport { Schema, type, ArraySchema, MapSchema, SetSchema, DataChange } from '@colyseus/schema';\n${allRefs.\n filter(ref => ref.childType && typeMaps[ref.childType] === undefined).\n map(ref => ref.childType).\n concat(getInheritanceTree(klass, allClasses, false).map(klass => klass.name)).\n filter(distinct).\n map(childType => `import { ${childType} } from './${childType}'`).\n join(\"\\n\")}\n\nexport class ${klass.name} extends ${klass.extends} {\n${klass.properties.map(prop => ` ${generateProperty(prop)}`).join(\"\\n\")}\n}\n`;\n}\n\nfunction generateProperty(prop: Property) {\n let langType: string;\n let initializer = \"\";\n let typeArgs: string;\n\n if (prop.childType) {\n const isUpcaseFirst = prop.childType.match(/^[A-Z]/);\n\n if (isUpcaseFirst) {\n typeArgs += `, ${prop.childType}`;\n\n } else {\n typeArgs += `, \"${prop.childType}\"`;\n }\n\n if(prop.type === \"ref\") {\n langType = `${prop.childType}`;\n initializer = `new ${prop.childType}()`;\n typeArgs = `${prop.childType}`;\n\n } else if(prop.type === \"array\") {\n langType = (isUpcaseFirst)\n ? `ArraySchema<${prop.childType}>`\n : `ArraySchema<${typeMaps[prop.childType]}>`;\n initializer = `new ${langType}()`;\n typeArgs = (isUpcaseFirst)\n ? `[ ${prop.childType} ]`\n : `[ \"${prop.childType}\" ]`;\n\n } else if(prop.type === \"map\") {\n langType = (isUpcaseFirst)\n ? `MapSchema<${prop.childType}>`\n : `MapSchema<${typeMaps[prop.childType]}>`;\n initializer = `new ${langType}()`;\n typeArgs = (isUpcaseFirst)\n ? `{ map: ${prop.childType} }`\n : `{ map: \"${prop.childType}\" }`;\n } else if (prop.type === \"set\") {\n langType = (isUpcaseFirst)\n ? `SetSchema<${prop.childType}>`\n : `SetSchema<${typeMaps[prop.childType]}>`;\n initializer = `new ${langType}()`;\n typeArgs = (isUpcaseFirst)\n ? `{ set: ${prop.childType} }`\n : `{ set: \"${prop.childType}\" }`;\n }\n\n } else {\n langType = typeMaps[prop.type];\n typeArgs = `\"${prop.type}\"`;\n }\n\n // TS1263: \"Declarations with initializers cannot also have definite assignment assertions\"\n const definiteAssertion = initializer ? \"\" : \"!\";\n\n return `@type(${typeArgs}) public ${prop.name}${definiteAssertion}: ${langType}${(initializer) ? ` = ${initializer}` : \"\"};`\n}\n\n\nfunction generateInterface(structure: Interface, namespace: string, allClasses: Class[]) {\n return `${getCommentHeader()}\n\nexport interface ${structure.name} {\n${structure.properties.map(prop => ` ${prop.name}: ${prop.type};`).join(\"\\n\")}\n}\n`;\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getDecorators = exports.parseFiles = void 0;
3
+ exports.parseFiles = parseFiles;
4
+ exports.getDecorators = getDecorators;
4
5
  const ts = require("typescript");
5
6
  const path = require("path");
6
7
  const fs_1 = require("fs");
@@ -209,7 +210,6 @@ function parseFiles(fileNames, decoratorName = "type", context = new types_1.Con
209
210
  });
210
211
  return context.getStructures();
211
212
  }
212
- exports.parseFiles = parseFiles;
213
213
  /**
214
214
  * TypeScript 4.8+ has introduced a change on how to access decorators.
215
215
  * - https://github.com/microsoft/TypeScript/pull/49089
@@ -234,5 +234,4 @@ function getDecorators(node) {
234
234
  // @ts-ignore
235
235
  return node.modifiers?.filter(ts.isDecorator);
236
236
  }
237
- exports.getDecorators = getDecorators;
238
237
  //# sourceMappingURL=parser.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"parser.js","sourceRoot":"","sources":["../../src/codegen/parser.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AACjC,6BAA6B;AAC7B,2BAAgC;AAChC,mCAA8E;AAE9E,IAAI,gBAA4B,CAAC;AACjC,IAAI,eAAyB,CAAC;AAE9B,IAAI,aAAsB,CAAC;AAE3B,SAAS,cAAc,CAAC,QAAkB,EAAE,WAAgB;IACxD,IAAI,EAAE,CAAC,YAAY,CAAC,WAAW,CAAC,EAAE,CAAC;QAC/B,QAAQ,CAAC,IAAI,GAAG,KAAK,CAAC;QACtB,QAAQ,CAAC,SAAS,GAAG,WAAW,CAAC,IAAI,CAAC;IAE1C,CAAC;SAAM,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C,UAAU,EAAE,CAAC;QAAC,OAAO,IAAI,CAAC,UAAU,CAAC;IAAC,CAAC;IAEhD,2BAA2B;IAC3B,aAAa;IACb,IAAI,EAAE,CAAC,iBAAiB,IAAI,EAAE,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE,CAAC;QACrD,aAAa;QACb,MAAM,UAAU,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QAC1C,OAAO,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC3D,CAAC;IAED,aAAa;IACb,OAAO,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC;AAClD,CAAC;AAjBD,sCAiBC","sourcesContent":["import * as ts from \"typescript\";\nimport * as path from \"path\";\nimport {readFileSync} from \"fs\";\nimport {IStructure, Class, Interface, Property, Context, Enum} from \"./types\";\n\nlet currentStructure: IStructure;\nlet currentProperty: Property;\n\nlet globalContext: Context;\n\nfunction defineProperty(property: Property, initializer: any) {\n if (ts.isIdentifier(initializer)) {\n property.type = \"ref\";\n property.childType = initializer.text;\n\n } else if (initializer.kind == ts.SyntaxKind.ObjectLiteralExpression) {\n property.type = initializer.properties[0].name.text;\n property.childType = initializer.properties[0].initializer.text;\n\n } else if (initializer.kind == ts.SyntaxKind.ArrayLiteralExpression) {\n property.type = \"array\";\n property.childType = initializer.elements[0].text;\n\n } else {\n property.type = initializer.text;\n }\n}\n\nfunction inspectNode(node: ts.Node, context: Context, decoratorName: string) {\n switch (node.kind) {\n case ts.SyntaxKind.ImportClause:\n const specifier = (node.parent as any).moduleSpecifier;\n if (specifier && (specifier.text as string).startsWith('.')) {\n const currentDir = path.dirname(node.getSourceFile().fileName);\n const pathToImport = path.resolve(currentDir, specifier.text);\n parseFiles([pathToImport], decoratorName, globalContext);\n }\n break;\n\n case ts.SyntaxKind.ClassDeclaration:\n currentStructure = new Class();\n\n const heritageClauses = (node as ts.ClassLikeDeclarationBase).heritageClauses;\n if (heritageClauses && heritageClauses.length > 0) {\n (currentStructure as Class).extends = heritageClauses[0].types[0].expression.getText();\n }\n\n context.addStructure(currentStructure);\n break;\n\n case ts.SyntaxKind.InterfaceDeclaration:\n //\n // Only generate Interfaces if it has \"Message\" on its name.\n // Example: MyMessage\n //\n const interfaceName = (node as ts.TypeParameterDeclaration).name.escapedText.toString();\n if (interfaceName.indexOf(\"Message\") !== -1) {\n currentStructure = new Interface();\n currentStructure.name = interfaceName;\n\n context.addStructure(currentStructure);\n }\n break;\n\n case ts.SyntaxKind.EnumDeclaration:\n const enumName = (\n node as ts.EnumDeclaration\n ).name.escapedText.toString();\n currentStructure = new Enum();\n currentStructure.name = enumName;\n context.addStructure(currentStructure);\n break;\n\n case ts.SyntaxKind.ExtendsKeyword:\n // console.log(node.getText());\n break;\n\n case ts.SyntaxKind.PropertySignature:\n if (currentStructure instanceof Interface) {\n const interfaceDeclaration = node.parent;\n\n if (\n currentStructure.name !== (interfaceDeclaration as ts.TypeParameterDeclaration).name.escapedText.toString()\n ) {\n // skip if property if for a another interface than the one we're interested in.\n break;\n }\n\n // define a property of an interface\n const property = new Property();\n property.name = (node as any).name.escapedText.toString();\n property.type = (node as any).type.getText();\n currentStructure.addProperty(property);\n }\n break;\n\n case ts.SyntaxKind.Identifier:\n if (\n node.getText() === \"deprecated\" &&\n node.parent.kind !== ts.SyntaxKind.ImportSpecifier\n ) {\n currentProperty = new Property();\n currentProperty.deprecated = true;\n break;\n }\n\n if (node.getText() === decoratorName) {\n const prop: any = node.parent?.parent?.parent;\n const propDecorator = getDecorators(prop);\n const hasExpression = prop?.expression?.arguments;\n const hasDecorator = (propDecorator?.length > 0);\n\n /**\n * neither a `@type()` decorator or `type()` call. skip.\n */\n if (!hasDecorator && !hasExpression) {\n break;\n }\n\n // using as decorator\n if (propDecorator) {\n /**\n * Calling `@type()` as decorator\n */\n const typeDecorator: any = propDecorator.find((decorator => {\n return (decorator.expression as any).expression.escapedText === decoratorName;\n })).expression;\n\n const property = currentProperty || new Property();\n property.name = prop.name.escapedText;\n currentStructure.addProperty(property);\n\n const typeArgument = typeDecorator.arguments[0];\n defineProperty(property, typeArgument);\n\n } else if (\n prop.expression.arguments?.[1] &&\n prop.expression.expression.arguments?.[0]\n ) {\n /**\n * Calling `type()` as a regular method\n */\n const property = currentProperty || new Property();\n property.name = prop.expression.arguments[1].text;\n currentStructure.addProperty(property);\n\n const typeArgument = prop.expression.expression.arguments[0];\n defineProperty(property, typeArgument);\n }\n\n\n } else if (\n node.getText() === \"defineTypes\" &&\n (\n node.parent.kind === ts.SyntaxKind.CallExpression ||\n node.parent.kind === ts.SyntaxKind.PropertyAccessExpression\n )\n ) {\n /**\n * JavaScript source file (`.js`)\n * Using `defineTypes()`\n */\n const callExpression = (node.parent.kind === ts.SyntaxKind.PropertyAccessExpression)\n ? node.parent.parent as ts.CallExpression\n : node.parent as ts.CallExpression;\n\n if (callExpression.kind !== ts.SyntaxKind.CallExpression) {\n break;\n }\n\n const className = callExpression.arguments[0].getText()\n currentStructure.name = className;\n\n const types = callExpression.arguments[1] as any;\n for (let i = 0; i < types.properties.length; i++) {\n const prop = types.properties[i];\n\n const property = currentProperty || new Property();\n property.name = prop.name.escapedText;\n currentStructure.addProperty(property);\n\n defineProperty(property, prop.initializer);\n }\n\n }\n\n if (node.parent.kind === ts.SyntaxKind.ClassDeclaration) {\n currentStructure.name = node.getText();\n }\n\n currentProperty = undefined;\n\n break;\n\n case ts.SyntaxKind.EnumMember:\n if (currentStructure instanceof Enum) {\n const initializer = (node as any).initializer?.text;\n const name = node.getFirstToken().getText();\n const property = currentProperty || new Property();\n property.name = name;\n if (initializer !== undefined) {\n property.type = initializer;\n }\n currentStructure.addProperty(property);\n currentProperty = undefined;\n }\n break;\n }\n\n ts.forEachChild(node, (n) => inspectNode(n, context, decoratorName));\n}\n\nlet parsedFiles: { [filename: string]: boolean };\n\nexport function parseFiles(\n fileNames: string[],\n decoratorName: string = \"type\",\n context: Context = new Context()\n) {\n /**\n * Re-set globalContext for each test case\n */\n if (globalContext !== context) {\n parsedFiles = {};\n globalContext = context;\n }\n\n fileNames.forEach((fileName) => {\n let sourceFile: ts.Node;\n let sourceFileName: string;\n\n const fileNameAlternatives = [];\n\n if (\n !fileName.endsWith(\".ts\") &&\n !fileName.endsWith(\".js\") &&\n !fileName.endsWith(\".mjs\")\n ) {\n fileNameAlternatives.push(`${fileName}.ts`);\n fileNameAlternatives.push(`${fileName}/index.ts`);\n\n } else {\n fileNameAlternatives.push(fileName);\n }\n\n for (let i = 0; i < fileNameAlternatives.length; i++) {\n try {\n sourceFileName = path.resolve(fileNameAlternatives[i]);\n\n if (parsedFiles[sourceFileName]) {\n break;\n }\n\n sourceFile = ts.createSourceFile(\n sourceFileName,\n readFileSync(sourceFileName).toString(),\n ts.ScriptTarget.Latest,\n true\n );\n\n parsedFiles[sourceFileName] = true;\n\n break;\n } catch (e) {\n // console.log(`${fileNameAlternatives[i]} => ${e.message}`);\n }\n }\n\n if (sourceFile) {\n inspectNode(sourceFile, context, decoratorName);\n }\n });\n\n return context.getStructures();\n}\n\n/**\n * TypeScript 4.8+ has introduced a change on how to access decorators.\n * - https://github.com/microsoft/TypeScript/pull/49089\n * - https://devblogs.microsoft.com/typescript/announcing-typescript-4-8/#decorators-are-placed-on-modifiers-on-typescripts-syntax-trees\n */\nexport function getDecorators(node: ts.Node | null | undefined,): undefined | ts.Decorator[] {\n if (node == undefined) { return undefined; }\n\n // TypeScript 4.7 and below\n // @ts-ignore\n if (node.decorators) { return node.decorators; }\n\n // TypeScript 4.8 and above\n // @ts-ignore\n if (ts.canHaveDecorators && ts.canHaveDecorators(node)) {\n // @ts-ignore\n const decorators = ts.getDecorators(node);\n return decorators ? Array.from(decorators) : undefined;\n }\n\n // @ts-ignore\n return node.modifiers?.filter(ts.isDecorator);\n}\n"]}
1
+ {"version":3,"file":"parser.js","sourceRoot":"","sources":["../../src/codegen/parser.ts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,CAAC;gBACT,6DAA6D;YACjE,CAAC;QACL,CAAC;QAED,IAAI,UAAU,EAAE,CAAC;YACb,WAAW,CAAC,UAAU,EAAE,OAAO,EAAE,aAAa,CAAC,CAAC;QACpD,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC,aAAa,EAAE,CAAC;AACnC,CAAC;AAED;;;;GAIG;AACH,SAAgB,aAAa,CAAC,IAAgC;IAC1D,IAAI,IAAI,IAAI,SAAS,EAAE,CAAC;QAAC,OAAO,SAAS,CAAC;IAAC,CAAC;IAE5C,2BAA2B;IAC3B,aAAa;IACb,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;QAAC,OAAO,IAAI,CAAC,UAAU,CAAC;IAAC,CAAC;IAEhD,2BAA2B;IAC3B,aAAa;IACb,IAAI,EAAE,CAAC,iBAAiB,IAAI,EAAE,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE,CAAC;QACrD,aAAa;QACb,MAAM,UAAU,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QAC1C,OAAO,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC3D,CAAC;IAED,aAAa;IACb,OAAO,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import * as ts from \"typescript\";\nimport * as path from \"path\";\nimport {readFileSync} from \"fs\";\nimport {IStructure, Class, Interface, Property, Context, Enum} from \"./types\";\n\nlet currentStructure: IStructure;\nlet currentProperty: Property;\n\nlet globalContext: Context;\n\nfunction defineProperty(property: Property, initializer: any) {\n if (ts.isIdentifier(initializer)) {\n property.type = \"ref\";\n property.childType = initializer.text;\n\n } else if (initializer.kind == ts.SyntaxKind.ObjectLiteralExpression) {\n property.type = initializer.properties[0].name.text;\n property.childType = initializer.properties[0].initializer.text;\n\n } else if (initializer.kind == ts.SyntaxKind.ArrayLiteralExpression) {\n property.type = \"array\";\n property.childType = initializer.elements[0].text;\n\n } else {\n property.type = initializer.text;\n }\n}\n\nfunction inspectNode(node: ts.Node, context: Context, decoratorName: string) {\n switch (node.kind) {\n case ts.SyntaxKind.ImportClause:\n const specifier = (node.parent as any).moduleSpecifier;\n if (specifier && (specifier.text as string).startsWith('.')) {\n const currentDir = path.dirname(node.getSourceFile().fileName);\n const pathToImport = path.resolve(currentDir, specifier.text);\n parseFiles([pathToImport], decoratorName, globalContext);\n }\n break;\n\n case ts.SyntaxKind.ClassDeclaration:\n currentStructure = new Class();\n\n const heritageClauses = (node as ts.ClassLikeDeclarationBase).heritageClauses;\n if (heritageClauses && heritageClauses.length > 0) {\n (currentStructure as Class).extends = heritageClauses[0].types[0].expression.getText();\n }\n\n context.addStructure(currentStructure);\n break;\n\n case ts.SyntaxKind.InterfaceDeclaration:\n //\n // Only generate Interfaces if it has \"Message\" on its name.\n // Example: MyMessage\n //\n const interfaceName = (node as ts.TypeParameterDeclaration).name.escapedText.toString();\n if (interfaceName.indexOf(\"Message\") !== -1) {\n currentStructure = new Interface();\n currentStructure.name = interfaceName;\n\n context.addStructure(currentStructure);\n }\n break;\n\n case ts.SyntaxKind.EnumDeclaration:\n const enumName = (\n node as ts.EnumDeclaration\n ).name.escapedText.toString();\n currentStructure = new Enum();\n currentStructure.name = enumName;\n context.addStructure(currentStructure);\n break;\n\n case ts.SyntaxKind.ExtendsKeyword:\n // console.log(node.getText());\n break;\n\n case ts.SyntaxKind.PropertySignature:\n if (currentStructure instanceof Interface) {\n const interfaceDeclaration = node.parent;\n\n if (\n currentStructure.name !== (interfaceDeclaration as ts.TypeParameterDeclaration).name.escapedText.toString()\n ) {\n // skip if property if for a another interface than the one we're interested in.\n break;\n }\n\n // define a property of an interface\n const property = new Property();\n property.name = (node as any).name.escapedText.toString();\n property.type = (node as any).type.getText();\n currentStructure.addProperty(property);\n }\n break;\n\n case ts.SyntaxKind.Identifier:\n if (\n node.getText() === \"deprecated\" &&\n node.parent.kind !== ts.SyntaxKind.ImportSpecifier\n ) {\n currentProperty = new Property();\n currentProperty.deprecated = true;\n break;\n }\n\n if (node.getText() === decoratorName) {\n const prop: any = node.parent?.parent?.parent;\n const propDecorator = getDecorators(prop);\n const hasExpression = prop?.expression?.arguments;\n const hasDecorator = (propDecorator?.length > 0);\n\n /**\n * neither a `@type()` decorator or `type()` call. skip.\n */\n if (!hasDecorator && !hasExpression) {\n break;\n }\n\n // using as decorator\n if (propDecorator) {\n /**\n * Calling `@type()` as decorator\n */\n const typeDecorator: any = propDecorator.find((decorator => {\n return (decorator.expression as any).expression.escapedText === decoratorName;\n })).expression;\n\n const property = currentProperty || new Property();\n property.name = prop.name.escapedText;\n currentStructure.addProperty(property);\n\n const typeArgument = typeDecorator.arguments[0];\n defineProperty(property, typeArgument);\n\n } else if (\n prop.expression.arguments?.[1] &&\n prop.expression.expression.arguments?.[0]\n ) {\n /**\n * Calling `type()` as a regular method\n */\n const property = currentProperty || new Property();\n property.name = prop.expression.arguments[1].text;\n currentStructure.addProperty(property);\n\n const typeArgument = prop.expression.expression.arguments[0];\n defineProperty(property, typeArgument);\n }\n\n\n } else if (\n node.getText() === \"defineTypes\" &&\n (\n node.parent.kind === ts.SyntaxKind.CallExpression ||\n node.parent.kind === ts.SyntaxKind.PropertyAccessExpression\n )\n ) {\n /**\n * JavaScript source file (`.js`)\n * Using `defineTypes()`\n */\n const callExpression = (node.parent.kind === ts.SyntaxKind.PropertyAccessExpression)\n ? node.parent.parent as ts.CallExpression\n : node.parent as ts.CallExpression;\n\n if (callExpression.kind !== ts.SyntaxKind.CallExpression) {\n break;\n }\n\n const className = callExpression.arguments[0].getText()\n currentStructure.name = className;\n\n const types = callExpression.arguments[1] as any;\n for (let i = 0; i < types.properties.length; i++) {\n const prop = types.properties[i];\n\n const property = currentProperty || new Property();\n property.name = prop.name.escapedText;\n currentStructure.addProperty(property);\n\n defineProperty(property, prop.initializer);\n }\n\n }\n\n if (node.parent.kind === ts.SyntaxKind.ClassDeclaration) {\n currentStructure.name = node.getText();\n }\n\n currentProperty = undefined;\n\n break;\n\n case ts.SyntaxKind.EnumMember:\n if (currentStructure instanceof Enum) {\n const initializer = (node as any).initializer?.text;\n const name = node.getFirstToken().getText();\n const property = currentProperty || new Property();\n property.name = name;\n if (initializer !== undefined) {\n property.type = initializer;\n }\n currentStructure.addProperty(property);\n currentProperty = undefined;\n }\n break;\n }\n\n ts.forEachChild(node, (n) => inspectNode(n, context, decoratorName));\n}\n\nlet parsedFiles: { [filename: string]: boolean };\n\nexport function parseFiles(\n fileNames: string[],\n decoratorName: string = \"type\",\n context: Context = new Context()\n) {\n /**\n * Re-set globalContext for each test case\n */\n if (globalContext !== context) {\n parsedFiles = {};\n globalContext = context;\n }\n\n fileNames.forEach((fileName) => {\n let sourceFile: ts.Node;\n let sourceFileName: string;\n\n const fileNameAlternatives = [];\n\n if (\n !fileName.endsWith(\".ts\") &&\n !fileName.endsWith(\".js\") &&\n !fileName.endsWith(\".mjs\")\n ) {\n fileNameAlternatives.push(`${fileName}.ts`);\n fileNameAlternatives.push(`${fileName}/index.ts`);\n\n } else {\n fileNameAlternatives.push(fileName);\n }\n\n for (let i = 0; i < fileNameAlternatives.length; i++) {\n try {\n sourceFileName = path.resolve(fileNameAlternatives[i]);\n\n if (parsedFiles[sourceFileName]) {\n break;\n }\n\n sourceFile = ts.createSourceFile(\n sourceFileName,\n readFileSync(sourceFileName).toString(),\n ts.ScriptTarget.Latest,\n true\n );\n\n parsedFiles[sourceFileName] = true;\n\n break;\n } catch (e) {\n // console.log(`${fileNameAlternatives[i]} => ${e.message}`);\n }\n }\n\n if (sourceFile) {\n inspectNode(sourceFile, context, decoratorName);\n }\n });\n\n return context.getStructures();\n}\n\n/**\n * TypeScript 4.8+ has introduced a change on how to access decorators.\n * - https://github.com/microsoft/TypeScript/pull/49089\n * - https://devblogs.microsoft.com/typescript/announcing-typescript-4-8/#decorators-are-placed-on-modifiers-on-typescripts-syntax-trees\n */\nexport function getDecorators(node: ts.Node | null | undefined,): undefined | ts.Decorator[] {\n if (node == undefined) { return undefined; }\n\n // TypeScript 4.7 and below\n // @ts-ignore\n if (node.decorators) { return node.decorators; }\n\n // TypeScript 4.8 and above\n // @ts-ignore\n if (ts.canHaveDecorators && ts.canHaveDecorators(node)) {\n // @ts-ignore\n const decorators = ts.getDecorators(node);\n return decorators ? Array.from(decorators) : undefined;\n }\n\n // @ts-ignore\n return node.modifiers?.filter(ts.isDecorator);\n}\n"]}
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getInheritanceTree = exports.Property = exports.Enum = exports.Class = exports.Interface = exports.Context = exports.getCommentHeader = void 0;
3
+ exports.Property = exports.Enum = exports.Class = exports.Interface = exports.Context = void 0;
4
+ exports.getCommentHeader = getCommentHeader;
5
+ exports.getInheritanceTree = getInheritanceTree;
4
6
  const fs = require("fs");
5
7
  const VERSION = JSON.parse(fs.readFileSync(__dirname + "/../../package.json").toString()).version;
6
8
  const COMMENT_HEADER = `
@@ -12,7 +14,6 @@ GENERATED USING @colyseus/schema ${VERSION}
12
14
  function getCommentHeader(singleLineComment = "//") {
13
15
  return `${COMMENT_HEADER.split("\n").map(line => `${singleLineComment} ${line}`).join("\n")}`;
14
16
  }
15
- exports.getCommentHeader = getCommentHeader;
16
17
  class Context {
17
18
  constructor() {
18
19
  this.classes = [];
@@ -141,5 +142,4 @@ function getInheritanceTree(klass, allClasses, includeSelf = true) {
141
142
  }
142
143
  return inheritanceTree;
143
144
  }
144
- exports.getInheritanceTree = getInheritanceTree;
145
145
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/codegen/types.ts"],"names":[],"mappings":";;;AAAA,yBAAyB;AAEzB,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,SAAS,GAAG,qBAAqB,CA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,4BAMC;AAOD,SAAgB,kBAAkB,CAAC,KAAY,EAAE,UAAmB,EAAE,cAAuB,IAAI;IAC7F,IAAI,YAAY,GAAG,KAAK,CAAC;IACzB,IAAI,eAAe,GAAY,EAAE,CAAC;IAElC,IAAI,WAAW,EAAE,CAAC;QACd,eAAe,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,YAAY,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;QACvC,YAAY,GAAG,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,IAAI,YAAY,CAAC,OAAO,CAAC,CAAC;QAC5E,eAAe,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,eAAe,CAAC;AAC3B,CAAC;AAdD,gDAcC","sourcesContent":["import * as fs from \"fs\";\n\nconst VERSION = JSON.parse(fs.readFileSync(__dirname + \"/../../package.json\").toString()).version;\nconst COMMENT_HEADER = `\nTHIS FILE HAS BEEN GENERATED AUTOMATICALLY\nDO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING\n\nGENERATED USING @colyseus/schema ${VERSION}\n`;\n\nexport function getCommentHeader(singleLineComment: string = \"//\") {\n return `${COMMENT_HEADER.split(\"\\n\").map(line => `${singleLineComment} ${line}`).join(\"\\n\")}`;\n}\n\nexport class Context {\n classes: Class[] = [];\n interfaces: Interface[] = [];\n enums: Enum[] = [];\n\n getStructures() {\n return {\n classes: this.classes.filter(klass => {\n if (this.isSchemaClass(klass)) {\n return true;\n\n } else {\n let parentClass = klass;\n while (parentClass = this.getParentClass(parentClass)) {\n if (this.isSchemaClass(parentClass)) {\n return true;\n }\n }\n }\n return false;\n }),\n interfaces: this.interfaces,\n enums: this.enums,\n };\n }\n\n addStructure(structure: IStructure) {\n structure.context = this;\n\n if (structure instanceof Class) {\n this.classes.push(structure);\n } else if (structure instanceof Interface) {\n this.interfaces.push(structure);\n } else if (structure instanceof Enum) {\n this.enums.push(structure);\n }\n }\n\n private getParentClass(klass: Class) {\n return this.classes.find(c => c.name === klass.extends);\n }\n\n private isSchemaClass(klass: Class) {\n let isSchema: boolean = false;\n\n let currentClass = klass;\n while (!isSchema && currentClass) {\n //\n // TODO: ideally we should check for actual @colyseus/schema module\n // reference rather than arbitrary strings.\n //\n isSchema = (\n currentClass.extends === \"Schema\" ||\n currentClass.extends === \"schema.Schema\" ||\n currentClass.extends === \"Schema.Schema\"\n );\n\n //\n // When extending from `schema.Schema`, it is required to\n // normalize as \"Schema\" for code generation.\n //\n if (currentClass === klass && isSchema) {\n klass.extends = \"Schema\";\n }\n\n currentClass = this.getParentClass(currentClass);\n }\n\n return isSchema;\n }\n}\n\nexport interface IStructure {\n context: Context;\n name: string;\n properties: Property[];\n addProperty(property: Property);\n}\n\nexport class Interface implements IStructure {\n context: Context;\n name: string;\n properties: Property[] = [];\n\n addProperty(property: Property) {\n if (property.type.indexOf(\"[]\") >= 0) {\n // is array!\n property.childType = property.type.match(/([^\\[]+)/i)[1];\n property.type = \"array\";\n this.properties.push(property);\n\n } else {\n this.properties.push(property);\n }\n }\n}\n\nexport class Class implements IStructure {\n context: Context;\n name: string;\n properties: Property[] = [];\n extends: string;\n\n addProperty(property: Property) {\n property.index = this.properties.length;\n this.properties.push(property);\n }\n\n postProcessing() {\n /**\n * Ensure the proprierties `index` are correct using inheritance\n */\n let parentKlass: Class = this;\n\n while (\n parentKlass &&\n (parentKlass = this.context.classes.find(k => k.name === parentKlass.extends))\n ) {\n this.properties.forEach(prop => {\n prop.index += parentKlass.properties.length;\n });\n }\n }\n}\n\nexport class Enum implements IStructure {\n context: Context;\n name: string;\n properties: Property[] = [];\n\n addProperty(property: Property) {\n this.properties.push(property);\n }\n}\n\nexport class Property {\n index: number;\n name: string;\n type: string;\n childType: string;\n deprecated?: boolean;\n}\n\nexport interface File {\n name: string\n content: string;\n}\n\nexport function getInheritanceTree(klass: Class, allClasses: Class[], includeSelf: boolean = true) {\n let currentClass = klass;\n let inheritanceTree: Class[] = [];\n\n if (includeSelf) {\n inheritanceTree.push(currentClass);\n }\n\n while (currentClass.extends !== \"Schema\") {\n currentClass = allClasses.find(klass => klass.name == currentClass.extends);\n inheritanceTree.push(currentClass);\n }\n\n return inheritanceTree;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/codegen/types.ts"],"names":[],"mappings":";;;AAUA,4CAEC;AAsJD,gDAcC;AAhLD,yBAAyB;AAEzB,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,SAAS,GAAG,qBAAqB,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,OAAO,CAAC;AAClG,MAAM,cAAc,GAAG;;;;mCAIY,OAAO;CACzC,CAAC;AAEF,SAAgB,gBAAgB,CAAC,oBAA4B,IAAI;IAC7D,OAAO,GAAG,cAAc,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,iBAAiB,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAClG,CAAC;AAED,MAAa,OAAO;IAApB;QACI,YAAO,GAAY,EAAE,CAAC;QACtB,eAAU,GAAgB,EAAE,CAAC;QAC7B,UAAK,GAAW,EAAE,CAAC;IAmEvB,CAAC;IAjEG,aAAa;QACT,OAAO;YACH,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;gBACjC,IAAI,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;oBAC5B,OAAO,IAAI,CAAC;gBAEhB,CAAC;qBAAM,CAAC;oBACJ,IAAI,WAAW,GAAG,KAAK,CAAC;oBACxB,OAAO,WAAW,GAAG,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC,EAAE,CAAC;wBACpD,IAAI,IAAI,CAAC,aAAa,CAAC,WAAW,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,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;gBAC3B,IAAI,CAAC,KAAK,IAAI,WAAW,CAAC,UAAU,CAAC,MAAM,CAAC;YAChD,CAAC,CAAC,CAAC;QACP,CAAC;IACL,CAAC;CACJ;AA1BD,sBA0BC;AAED,MAAa,IAAI;IAAjB;QAGI,eAAU,GAAe,EAAE,CAAC;IAKhC,CAAC;IAHG,WAAW,CAAC,QAAkB;QAC1B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACnC,CAAC;CACJ;AARD,oBAQC;AAED,MAAa,QAAQ;CAMpB;AAND,4BAMC;AAOD,SAAgB,kBAAkB,CAAC,KAAY,EAAE,UAAmB,EAAE,cAAuB,IAAI;IAC7F,IAAI,YAAY,GAAG,KAAK,CAAC;IACzB,IAAI,eAAe,GAAY,EAAE,CAAC;IAElC,IAAI,WAAW,EAAE,CAAC;QACd,eAAe,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,YAAY,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;QACvC,YAAY,GAAG,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,IAAI,YAAY,CAAC,OAAO,CAAC,CAAC;QAC5E,eAAe,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,eAAe,CAAC;AAC3B,CAAC","sourcesContent":["import * as fs from \"fs\";\n\nconst VERSION = JSON.parse(fs.readFileSync(__dirname + \"/../../package.json\").toString()).version;\nconst COMMENT_HEADER = `\nTHIS FILE HAS BEEN GENERATED AUTOMATICALLY\nDO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING\n\nGENERATED USING @colyseus/schema ${VERSION}\n`;\n\nexport function getCommentHeader(singleLineComment: string = \"//\") {\n return `${COMMENT_HEADER.split(\"\\n\").map(line => `${singleLineComment} ${line}`).join(\"\\n\")}`;\n}\n\nexport class Context {\n classes: Class[] = [];\n interfaces: Interface[] = [];\n enums: Enum[] = [];\n\n getStructures() {\n return {\n classes: this.classes.filter(klass => {\n if (this.isSchemaClass(klass)) {\n return true;\n\n } else {\n let parentClass = klass;\n while (parentClass = this.getParentClass(parentClass)) {\n if (this.isSchemaClass(parentClass)) {\n return true;\n }\n }\n }\n return false;\n }),\n interfaces: this.interfaces,\n enums: this.enums,\n };\n }\n\n addStructure(structure: IStructure) {\n structure.context = this;\n\n if (structure instanceof Class) {\n this.classes.push(structure);\n } else if (structure instanceof Interface) {\n this.interfaces.push(structure);\n } else if (structure instanceof Enum) {\n this.enums.push(structure);\n }\n }\n\n private getParentClass(klass: Class) {\n return this.classes.find(c => c.name === klass.extends);\n }\n\n private isSchemaClass(klass: Class) {\n let isSchema: boolean = false;\n\n let currentClass = klass;\n while (!isSchema && currentClass) {\n //\n // TODO: ideally we should check for actual @colyseus/schema module\n // reference rather than arbitrary strings.\n //\n isSchema = (\n currentClass.extends === \"Schema\" ||\n currentClass.extends === \"schema.Schema\" ||\n currentClass.extends === \"Schema.Schema\"\n );\n\n //\n // When extending from `schema.Schema`, it is required to\n // normalize as \"Schema\" for code generation.\n //\n if (currentClass === klass && isSchema) {\n klass.extends = \"Schema\";\n }\n\n currentClass = this.getParentClass(currentClass);\n }\n\n return isSchema;\n }\n}\n\nexport interface IStructure {\n context: Context;\n name: string;\n properties: Property[];\n addProperty(property: Property);\n}\n\nexport class Interface implements IStructure {\n context: Context;\n name: string;\n properties: Property[] = [];\n\n addProperty(property: Property) {\n if (property.type.indexOf(\"[]\") >= 0) {\n // is array!\n property.childType = property.type.match(/([^\\[]+)/i)[1];\n property.type = \"array\";\n this.properties.push(property);\n\n } else {\n this.properties.push(property);\n }\n }\n}\n\nexport class Class implements IStructure {\n context: Context;\n name: string;\n properties: Property[] = [];\n extends: string;\n\n addProperty(property: Property) {\n property.index = this.properties.length;\n this.properties.push(property);\n }\n\n postProcessing() {\n /**\n * Ensure the proprierties `index` are correct using inheritance\n */\n let parentKlass: Class = this;\n\n while (\n parentKlass &&\n (parentKlass = this.context.classes.find(k => k.name === parentKlass.extends))\n ) {\n this.properties.forEach(prop => {\n prop.index += parentKlass.properties.length;\n });\n }\n }\n}\n\nexport class Enum implements IStructure {\n context: Context;\n name: string;\n properties: Property[] = [];\n\n addProperty(property: Property) {\n this.properties.push(property);\n }\n}\n\nexport class Property {\n index: number;\n name: string;\n type: string;\n childType: string;\n deprecated?: boolean;\n}\n\nexport interface File {\n name: string\n content: string;\n}\n\nexport function getInheritanceTree(klass: Class, allClasses: Class[], includeSelf: boolean = true) {\n let currentClass = klass;\n let inheritanceTree: Class[] = [];\n\n if (includeSelf) {\n inheritanceTree.push(currentClass);\n }\n\n while (currentClass.extends !== \"Schema\") {\n currentClass = allClasses.find(klass => klass.name == currentClass.extends);\n inheritanceTree.push(currentClass);\n }\n\n return inheritanceTree;\n}\n"]}
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { OPERATION } from "../encoding/spec";
3
2
  import { Schema } from "../Schema";
4
3
  import type { Ref } from "../encoder/ChangeTree";
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decodeArray = exports.decodeKeyValueOperation = exports.decodeSchemaOperation = exports.decodeValue = exports.DEFINITION_MISMATCH = void 0;
3
+ exports.decodeArray = exports.decodeKeyValueOperation = exports.decodeSchemaOperation = exports.DEFINITION_MISMATCH = void 0;
4
+ exports.decodeValue = decodeValue;
4
5
  const spec_1 = require("../encoding/spec");
5
6
  const Schema_1 = require("../Schema");
6
7
  const decode = require("../encoding/decode");
@@ -8,7 +9,7 @@ const symbols_1 = require("../types/symbols");
8
9
  const registry_1 = require("../types/registry");
9
10
  exports.DEFINITION_MISMATCH = -1;
10
11
  function decodeValue(decoder, operation, ref, index, type, bytes, it, allChanges) {
11
- const $root = decoder.$root;
12
+ const $root = decoder.root;
12
13
  const previousValue = ref[symbols_1.$getByIndex](index);
13
14
  let value;
14
15
  if ((operation & spec_1.OPERATION.DELETE) === spec_1.OPERATION.DELETE) {
@@ -109,7 +110,6 @@ function decodeValue(decoder, operation, ref, index, type, bytes, it, allChanges
109
110
  }
110
111
  return { value, previousValue };
111
112
  }
112
- exports.decodeValue = decodeValue;
113
113
  const decodeSchemaOperation = function (decoder, bytes, it, ref, allChanges) {
114
114
  const first_byte = bytes[it.offset++];
115
115
  const metadata = ref['constructor'][Symbol.metadata];
@@ -201,7 +201,9 @@ const decodeKeyValueOperation = function (decoder, bytes, it, ref, allChanges) {
201
201
  exports.decodeKeyValueOperation = decodeKeyValueOperation;
202
202
  const decodeArray = function (decoder, bytes, it, ref, allChanges) {
203
203
  // "uncompressed" index + operation (array/map items)
204
- const operation = bytes[it.offset++];
204
+ let operation = bytes[it.offset++];
205
+ let isSchemaChild;
206
+ let index;
205
207
  if (operation === spec_1.OPERATION.CLEAR) {
206
208
  //
207
209
  // When decoding:
@@ -215,8 +217,8 @@ const decodeArray = function (decoder, bytes, it, ref, allChanges) {
215
217
  else if (operation === spec_1.OPERATION.DELETE_BY_REFID) {
216
218
  // TODO: refactor here, try to follow same flow as below
217
219
  const refId = decode.number(bytes, it);
218
- const previousValue = decoder.$root.refs.get(refId);
219
- const index = ref.findIndex((value) => value === previousValue);
220
+ const previousValue = decoder.root.refs.get(refId);
221
+ index = ref.findIndex((value) => value === previousValue);
220
222
  ref[symbols_1.$deleteByIndex](index);
221
223
  allChanges.push({
222
224
  ref,
@@ -229,7 +231,20 @@ const decodeArray = function (decoder, bytes, it, ref, allChanges) {
229
231
  });
230
232
  return;
231
233
  }
232
- const index = decode.number(bytes, it);
234
+ else if (operation === spec_1.OPERATION.ADD_BY_REFID) {
235
+ isSchemaChild = true;
236
+ // operation = OPERATION.ADD;
237
+ const refId = decode.number(bytes, it);
238
+ const itemByRefId = decoder.root.refs.get(refId);
239
+ // use existing index, or push new value
240
+ index = (itemByRefId)
241
+ ? ref.findIndex((value) => value === itemByRefId)
242
+ : ref.length;
243
+ }
244
+ else {
245
+ isSchemaChild = false;
246
+ index = decode.number(bytes, it);
247
+ }
233
248
  const type = ref[symbols_1.$childType];
234
249
  let dynamicIndex = index;
235
250
  const { value, previousValue } = decodeValue(decoder, operation, ref, index, type, bytes, it, allChanges);
@@ -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;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C,CAAC;QAChE,GAAG,CAAC,wBAAc,CAAC,CAAC,KAAK,CAAC,CAAC;QAC3B,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.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AAI,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;AA7FY,QAAA,WAAW,eA6FvB","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\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 let operation = bytes[it.offset++];\n\n let isSchemaChild: boolean;\n let index: number;\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 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\n return;\n\n } else if (operation === OPERATION.ADD_BY_REFID) {\n isSchemaChild = true;\n // operation = OPERATION.ADD;\n\n const refId = decode.number(bytes, it);\n const itemByRefId = decoder.root.refs.get(refId);\n\n // use existing index, or push new value\n index = (itemByRefId)\n ? ref.findIndex((value) => value === itemByRefId)\n : ref.length;\n\n } else {\n isSchemaChild = false;\n index = decode.number(bytes, it);\n }\n\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,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { TypeContext } from "../annotations";
3
2
  import { Schema } from "../Schema";
4
3
  import { Ref } from "../encoder/ChangeTree";
@@ -9,7 +8,7 @@ import { Collection } from "../types/HelperTypes";
9
8
  export declare class Decoder<T extends Schema = any> {
10
9
  context: TypeContext;
11
10
  state: T;
12
- $root: ReferenceTracker;
11
+ root: ReferenceTracker;
13
12
  currentRefId: number;
14
13
  triggerChanges?: (allChanges: DataChange[]) => void;
15
14
  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,UAAU,CAAC;QAEpC,IAAI,OAAO,GAAoB,GAAG,CAAC,aAAa,CAAC,CAAC,kBAAQ,CAAC,CAAC;QAE5D,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC;QAEtB,OAAO,EAAE,CAAC,MAAM,GAAG,UAAU,EAAE,CAAC;YAC5B,EAAE;YACF,8DAA8D;YAC9D,EAAE;YAC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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,CAAC;QAEpC,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC;QACxB,MAAM,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;QAEpC,IAAI,OAAO,GAAoB,GAAG,CAAC,aAAa,CAAC,CAAC,kBAAQ,CAAC,CAAC;QAE5D,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC;QAEtB,O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K,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"]}
@@ -1,8 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getRawChangesCallback = void 0;
3
+ exports.getRawChangesCallback = getRawChangesCallback;
4
4
  function getRawChangesCallback(decoder, callback) {
5
5
  decoder.triggerChanges = callback;
6
6
  }
7
- exports.getRawChangesCallback = getRawChangesCallback;
8
7
  //# sourceMappingURL=RawChanges.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"RawChanges.js","sourceRoot":"","sources":["../../../src/decoder/strategy/RawChanges.ts"],"names":[],"mappings":";;;AAGA,SAAgB,qBAAqB,CACjC,OAAgB,EAChB,QAAyC;IAEzC,OAAO,CAAC,cAAc,GAAG,QAAQ,CAAC;AACtC,CAAC;AALD,sDAKC","sourcesContent":["import { DataChange } from \"../DecodeOperation\";\nimport { Decoder } from \"../Decoder\";\n\nexport function getRawChangesCallback(\n decoder: Decoder,\n callback: (changes: DataChange[]) => void\n) {\n decoder.triggerChanges = callback;\n}"]}
1
+ {"version":3,"file":"RawChanges.js","sourceRoot":"","sources":["../../../src/decoder/strategy/RawChanges.ts"],"names":[],"mappings":";;AAGA,sDAKC;AALD,SAAgB,qBAAqB,CACjC,OAAgB,EAChB,QAAyC;IAEzC,OAAO,CAAC,cAAc,GAAG,QAAQ,CAAC;AACtC,CAAC","sourcesContent":["import { DataChange } from \"../DecodeOperation\";\nimport { Decoder } from \"../Decoder\";\n\nexport function getRawChangesCallback(\n decoder: Decoder,\n callback: (changes: DataChange[]) => void\n) {\n decoder.triggerChanges = callback;\n}"]}
@@ -1,20 +1,49 @@
1
1
  import { Collection, NonFunctionNonPrimitivePropNames, NonFunctionPropNames } from "../../types/HelperTypes";
2
2
  import { Decoder } from "../Decoder";
3
- import { DataChange } from "../DecodeOperation";
4
- type GetProxyType<T> = unknown extends T ? InstanceCallback<T> & CollectionCallback<any, any> : T extends Collection<infer K, infer V, infer _> ? CollectionCallback<K, V> : InstanceCallback<T>;
3
+ import { Schema } from "../../Schema";
4
+ export type GetCallbackProxy = (<T extends Schema>(instance: T) => CallbackProxy<T>);
5
+ export type CallbackProxy<T> = unknown extends T ? InstanceCallback<T> & CollectionCallback<any, any> : T extends Collection<infer K, infer V, infer _> ? CollectionCallback<K, V> : InstanceCallback<T>;
5
6
  type InstanceCallback<T> = {
7
+ /**
8
+ * Trigger callback when value of a property changes.
9
+ *
10
+ * @param prop name of the property
11
+ * @param callback callback to be triggered on property change
12
+ * @param immediate trigger immediatelly if property has been already set.
13
+ */
6
14
  listen<K extends NonFunctionPropNames<T>>(prop: K, callback: (value: T[K], previousValue: T[K]) => void, immediate?: boolean): any;
15
+ /**
16
+ * Trigger callback whenever any property changed within this instance.
17
+ *
18
+ * @param prop name of the property
19
+ * @param callback callback to be triggered on property change
20
+ * @param immediate trigger immediatelly if property has been already set.
21
+ */
7
22
  onChange(callback: () => void): void;
23
+ /**
24
+ * Bind properties to another object. Changes on the properties will be reflected on the target object.
25
+ *
26
+ * @param targetObject object to bind properties to
27
+ * @param properties list of properties to bind. If not provided, all properties will be bound.
28
+ */
8
29
  bindTo(targetObject: any, properties?: Array<NonFunctionPropNames<T>>): void;
9
30
  } & {
10
- [K in NonFunctionNonPrimitivePropNames<T>]: GetProxyType<T[K]>;
31
+ [K in NonFunctionNonPrimitivePropNames<T>]: CallbackProxy<T[K]>;
11
32
  };
12
33
  type CollectionCallback<K, V> = {
34
+ /**
35
+ * Trigger callback when an item has been added to the collection.
36
+ *
37
+ * @param callback
38
+ * @param immediate
39
+ */
13
40
  onAdd(callback: (item: V, index: K) => void, immediate?: boolean): void;
41
+ /**
42
+ * Trigger callback when an item has been removed to the collection.
43
+ *
44
+ * @param callback
45
+ */
14
46
  onRemove(callback: (item: V, index: K) => void): void;
15
47
  };
16
- export declare function getStateCallbacks(decoder: Decoder): {
17
- $: <T>(instance: T) => GetProxyType<T>;
18
- trigger: (changes: DataChange[]) => void;
19
- };
48
+ export declare function getDecoderStateCallbacks<T extends Schema>(decoder: Decoder<T>): GetCallbackProxy;
20
49
  export {};