@getguru/slate-yjs-core 1.0.3

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 (126) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +3 -0
  3. package/dist/applyToSlate/index.d.ts +23 -0
  4. package/dist/applyToSlate/textEvent.d.ts +4 -0
  5. package/dist/applyToYjs/index.d.ts +4 -0
  6. package/dist/applyToYjs/node/index.d.ts +4 -0
  7. package/dist/applyToYjs/node/insertNode.d.ts +4 -0
  8. package/dist/applyToYjs/node/mergeNode.d.ts +4 -0
  9. package/dist/applyToYjs/node/moveNode.d.ts +4 -0
  10. package/dist/applyToYjs/node/removeNode.d.ts +4 -0
  11. package/dist/applyToYjs/node/setNode.d.ts +4 -0
  12. package/dist/applyToYjs/node/splitNode.d.ts +4 -0
  13. package/dist/applyToYjs/text/index.d.ts +4 -0
  14. package/dist/applyToYjs/text/insertText.d.ts +4 -0
  15. package/dist/applyToYjs/text/removeText.d.ts +4 -0
  16. package/dist/applyToYjs/types.d.ts +9 -0
  17. package/dist/index.cjs +1360 -0
  18. package/dist/index.cjs.map +1 -0
  19. package/dist/index.d.ts +6 -0
  20. package/dist/index.global.js +10365 -0
  21. package/dist/index.global.js.map +1 -0
  22. package/dist/index.js +1338 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/model/types.d.ts +38 -0
  25. package/dist/plugins/index.d.ts +4 -0
  26. package/dist/plugins/withCursors.d.ts +39 -0
  27. package/dist/plugins/withYHistory.d.ts +20 -0
  28. package/dist/plugins/withYjs.d.ts +43 -0
  29. package/dist/utils/clone.d.ts +5 -0
  30. package/dist/utils/convert.d.ts +8 -0
  31. package/dist/utils/delta.d.ts +8 -0
  32. package/dist/utils/errors.d.ts +2 -0
  33. package/dist/utils/location.d.ts +12 -0
  34. package/dist/utils/object.d.ts +10 -0
  35. package/dist/utils/position.d.ts +20 -0
  36. package/dist/utils/slate.d.ts +3 -0
  37. package/dist/utils/yjs.d.ts +5 -0
  38. package/package.json +47 -0
  39. package/src/applyToSlate/index.ts +118 -0
  40. package/src/applyToSlate/textEvent.ts +280 -0
  41. package/src/applyToYjs/index.ts +28 -0
  42. package/src/applyToYjs/node/index.ts +17 -0
  43. package/src/applyToYjs/node/insertNode.ts +23 -0
  44. package/src/applyToYjs/node/mergeNode.ts +82 -0
  45. package/src/applyToYjs/node/moveNode.ts +57 -0
  46. package/src/applyToYjs/node/removeNode.ts +16 -0
  47. package/src/applyToYjs/node/setNode.ts +42 -0
  48. package/src/applyToYjs/node/splitNode.ts +98 -0
  49. package/src/applyToYjs/text/index.ts +9 -0
  50. package/src/applyToYjs/text/insertText.ts +27 -0
  51. package/src/applyToYjs/text/removeText.ts +16 -0
  52. package/src/applyToYjs/types.ts +12 -0
  53. package/src/index.ts +47 -0
  54. package/src/model/types.ts +50 -0
  55. package/src/plugins/index.ts +3 -0
  56. package/src/plugins/withCursors.ts +269 -0
  57. package/src/plugins/withYHistory.ts +183 -0
  58. package/src/plugins/withYjs.ts +284 -0
  59. package/src/utils/clone.ts +29 -0
  60. package/src/utils/convert.ts +48 -0
  61. package/src/utils/delta.ts +97 -0
  62. package/src/utils/errors.ts +20 -0
  63. package/src/utils/location.ts +157 -0
  64. package/src/utils/object.ts +93 -0
  65. package/src/utils/position.ts +300 -0
  66. package/src/utils/slate.ts +11 -0
  67. package/src/utils/yjs.ts +10 -0
  68. package/test/collaboration/addMark/acrossMarks.tsx +40 -0
  69. package/test/collaboration/addMark/acrossMarksSame.tsx +36 -0
  70. package/test/collaboration/addMark/atBeginningOfDocument.tsx +27 -0
  71. package/test/collaboration/addMark/atEndOfDocument.tsx +30 -0
  72. package/test/collaboration/addMark/withOtherMarks.tsx +31 -0
  73. package/test/collaboration/insertNode/atBeginningOfDocument.tsx +28 -0
  74. package/test/collaboration/insertNode/atEndOfDocument.tsx +28 -0
  75. package/test/collaboration/insertNode/inTheMiddle.tsx +30 -0
  76. package/test/collaboration/insertText/atBeginningOfBlock.tsx +26 -0
  77. package/test/collaboration/insertText/atBeginningOfDocument.tsx +26 -0
  78. package/test/collaboration/insertText/atEndOfBlock.tsx +26 -0
  79. package/test/collaboration/insertText/atEndOfDocument.tsx +26 -0
  80. package/test/collaboration/insertText/inTheMiddle.tsx +32 -0
  81. package/test/collaboration/insertText/inTheMiddleOfNestedBlock.tsx +30 -0
  82. package/test/collaboration/insertText/insideMarks.tsx +28 -0
  83. package/test/collaboration/insertText/withEmptyString.tsx +25 -0
  84. package/test/collaboration/insertText/withEntities.tsx +28 -0
  85. package/test/collaboration/insertText/withMarks.tsx +25 -0
  86. package/test/collaboration/insertText/withUnicode.tsx +28 -0
  87. package/test/collaboration/mergeNode/afterADeleteBackward.tsx +27 -0
  88. package/test/collaboration/mergeNode/inSameParent.tsx +34 -0
  89. package/test/collaboration/mergeNode/onMixedNestedNodes.tsx +29 -0
  90. package/test/collaboration/mergeNode/onMixedTypeNodes.tsx +27 -0
  91. package/test/collaboration/mergeNode/withUnicode.tsx +25 -0
  92. package/test/collaboration/moveNode/downward/whenBlockBecomesNested.tsx +43 -0
  93. package/test/collaboration/moveNode/downward/whenBlockBecomesNonNested.tsx +41 -0
  94. package/test/collaboration/moveNode/downward/whenBlockStaysNested.tsx +38 -0
  95. package/test/collaboration/moveNode/downward/whenBlockStaysNonNested.tsx +30 -0
  96. package/test/collaboration/moveNode/upward/whenBlockBecomesNested.tsx +43 -0
  97. package/test/collaboration/moveNode/upward/whenBlockBecomesNonNested.tsx +41 -0
  98. package/test/collaboration/moveNode/upward/whenBlockStaysNested.tsx +38 -0
  99. package/test/collaboration/moveNode/upward/whenBlockStaysNonNested.tsx +30 -0
  100. package/test/collaboration/removeMark/inTheMiddleOfText.tsx +43 -0
  101. package/test/collaboration/removeMark/withAddMark.tsx +31 -0
  102. package/test/collaboration/removeMark/withOtherMarks.tsx +47 -0
  103. package/test/collaboration/removeNode/atBeginningOfDocument.tsx +26 -0
  104. package/test/collaboration/removeNode/atEndOfDocument.tsx +26 -0
  105. package/test/collaboration/removeNode/nestedBlock.tsx +28 -0
  106. package/test/collaboration/removeNode/wrapperBlock.tsx +28 -0
  107. package/test/collaboration/removeText/atBeginningOfDocument.tsx +34 -0
  108. package/test/collaboration/removeText/atEndOfDocument.tsx +37 -0
  109. package/test/collaboration/removeText/withUnicode.tsx +29 -0
  110. package/test/collaboration/setNode/atBeginningOfDocument.tsx +27 -0
  111. package/test/collaboration/setNode/atEndOfDocument.tsx +27 -0
  112. package/test/collaboration/setNode/onDataChange.tsx +35 -0
  113. package/test/collaboration/setNode/onDataChangeOnInline.tsx +35 -0
  114. package/test/collaboration/setNode/onResetBlock.tsx +27 -0
  115. package/test/collaboration/setNode/withAChangeOfType.tsx +26 -0
  116. package/test/collaboration/splitNode/atBeginningOfDocument.tsx +28 -0
  117. package/test/collaboration/splitNode/atEndOfBlock.tsx +27 -0
  118. package/test/collaboration/splitNode/atEndOfDocument.tsx +27 -0
  119. package/test/collaboration/splitNode/onNonDefaultBlock.tsx +27 -0
  120. package/test/collaboration/splitNode/withMultipleSubNodes.tsx +32 -0
  121. package/test/collaboration/splitNode/withUnicode.tsx +29 -0
  122. package/test/index.test.ts +65 -0
  123. package/test/slate.d.ts +8 -0
  124. package/test/withTestingElements.ts +46 -0
  125. package/tsconfig.json +11 -0
  126. package/tsup.config.ts +32 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../../../node_modules/is-plain-object/dist/is-plain-object.mjs","../../../node_modules/immer/src/utils/errors.ts","../../../node_modules/immer/src/utils/common.ts","../../../node_modules/immer/src/utils/plugins.ts","../../../node_modules/immer/src/core/scope.ts","../../../node_modules/immer/src/core/finalize.ts","../../../node_modules/immer/src/core/proxy.ts","../../../node_modules/immer/src/core/immerClass.ts","../../../node_modules/immer/src/core/current.ts","../../../node_modules/immer/src/plugins/es5.ts","../../../node_modules/immer/src/plugins/patches.ts","../../../node_modules/immer/src/plugins/mapset.ts","../../../node_modules/immer/src/plugins/all.ts","../../../node_modules/immer/src/immer.ts","../../../node_modules/immer/src/utils/env.ts","../../../.yarn/cache/@babel-runtime-npm-7.15.3-6333c71362-2f0b8d2d4e.zip/node_modules/@babel/runtime/helpers/esm/defineProperty.js","../../../node_modules/slate/src/utils/weak-maps.ts","../../../node_modules/slate/src/create-editor.ts","../../../.yarn/cache/@babel-runtime-npm-7.15.3-6333c71362-2f0b8d2d4e.zip/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","../../../.yarn/cache/@babel-runtime-npm-7.15.3-6333c71362-2f0b8d2d4e.zip/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js","../../../node_modules/slate/src/utils/string.ts","../../../node_modules/slate/src/interfaces/element.ts","../../../node_modules/slate/src/interfaces/editor.ts","../../../node_modules/slate/src/interfaces/location.ts","../../../node_modules/slate/src/interfaces/node.ts","../../../node_modules/slate/src/interfaces/operation.ts","../../../node_modules/slate/src/interfaces/path.ts","../../../node_modules/slate/src/interfaces/path-ref.ts","../../../node_modules/slate/src/interfaces/point.ts","../../../node_modules/slate/src/interfaces/point-ref.ts","../../../node_modules/slate/src/interfaces/range.ts","../../../node_modules/slate/src/interfaces/range-ref.ts","../../../node_modules/slate/src/interfaces/scrubber.ts","../../../node_modules/slate/src/utils/deep-equal.ts","../../../node_modules/slate/src/interfaces/text.ts","../../../node_modules/slate/src/transforms/general.ts","../../../node_modules/slate/src/transforms/node.ts","../../../node_modules/slate/src/transforms/selection.ts","../../../node_modules/slate/src/transforms/text.ts","../../../node_modules/slate/src/transforms/index.ts","../../../node_modules/lib0/map.js","../../../node_modules/lib0/set.js","../../../node_modules/lib0/array.js","../../../node_modules/lib0/observable.js","../../../node_modules/lib0/math.js","../../../node_modules/lib0/string.js","../../../node_modules/lib0/conditions.js","../../../node_modules/lib0/storage.js","../../../node_modules/lib0/environment.js","../../../node_modules/lib0/binary.js","../../../node_modules/lib0/decoding.js","../../../node_modules/lib0/buffer.js","../../../node_modules/lib0/number.js","../../../node_modules/lib0/encoding.js","../../../node_modules/isomorphic.js/browser.mjs","../../../node_modules/lib0/random.js","../../../node_modules/lib0/time.js","../../../node_modules/lib0/promise.js","../../../node_modules/lib0/error.js","../../../node_modules/lib0/object.js","../../../node_modules/lib0/function.js","../../../node_modules/lib0/symbol.js","../../../node_modules/lib0/pair.js","../../../node_modules/lib0/dom.js","../../../node_modules/lib0/logging.js","../../../node_modules/lib0/iterator.js","../../../node_modules/yjs/src/utils/AbstractConnector.js","../../../node_modules/yjs/src/utils/DeleteSet.js","../../../node_modules/yjs/src/utils/Doc.js","../../../node_modules/yjs/src/utils/UpdateDecoder.js","../../../node_modules/yjs/src/utils/UpdateEncoder.js","../../../node_modules/yjs/src/utils/encoding.js","../../../node_modules/yjs/src/utils/EventHandler.js","../../../node_modules/yjs/src/utils/ID.js","../../../node_modules/yjs/src/utils/isParentOf.js","../../../node_modules/yjs/src/utils/logging.js","../../../node_modules/yjs/src/utils/PermanentUserData.js","../../../node_modules/yjs/src/utils/RelativePosition.js","../../../node_modules/yjs/src/utils/Snapshot.js","../../../node_modules/yjs/src/utils/StructStore.js","../../../node_modules/yjs/src/utils/Transaction.js","../../../node_modules/yjs/src/utils/UndoManager.js","../../../node_modules/yjs/src/utils/updates.js","../../../node_modules/yjs/src/utils/YEvent.js","../../../node_modules/yjs/src/types/AbstractType.js","../../../node_modules/yjs/src/types/YArray.js","../../../node_modules/yjs/src/types/YMap.js","../../../node_modules/yjs/src/types/YText.js","../../../node_modules/yjs/src/types/YXmlFragment.js","../../../node_modules/yjs/src/types/YXmlElement.js","../../../node_modules/yjs/src/types/YXmlEvent.js","../../../node_modules/yjs/src/types/YXmlHook.js","../../../node_modules/yjs/src/types/YXmlText.js","../../../node_modules/yjs/src/structs/AbstractStruct.js","../../../node_modules/yjs/src/structs/GC.js","../../../node_modules/yjs/src/structs/ContentBinary.js","../../../node_modules/yjs/src/structs/ContentDeleted.js","../../../node_modules/yjs/src/structs/ContentDoc.js","../../../node_modules/yjs/src/structs/ContentEmbed.js","../../../node_modules/yjs/src/structs/ContentFormat.js","../../../node_modules/yjs/src/structs/ContentJSON.js","../../../node_modules/yjs/src/structs/ContentAny.js","../../../node_modules/yjs/src/structs/ContentString.js","../../../node_modules/yjs/src/structs/ContentType.js","../../../node_modules/yjs/src/structs/Item.js","../../../node_modules/yjs/src/structs/Skip.js","../../../node_modules/yjs/src/index.js","../src/utils/object.ts","../src/utils/delta.ts","../src/utils/slate.ts","../src/utils/convert.ts","../src/utils/errors.ts","../src/utils/location.ts","../src/utils/yjs.ts","../src/utils/position.ts","../src/applyToSlate/textEvent.ts","../src/applyToSlate/index.ts","../src/applyToYjs/node/insertNode.ts","../src/utils/clone.ts","../src/applyToYjs/node/mergeNode.ts","../src/applyToYjs/node/moveNode.ts","../src/applyToYjs/node/removeNode.ts","../src/applyToYjs/node/setNode.ts","../src/applyToYjs/node/splitNode.ts","../src/applyToYjs/node/index.ts","../src/applyToYjs/text/insertText.ts","../src/applyToYjs/text/removeText.ts","../src/applyToYjs/text/index.ts","../src/applyToYjs/index.ts","../src/plugins/withYjs.ts","../src/plugins/withYHistory.ts","../src/plugins/withCursors.ts"],"sourcesContent":["import { RelativeRange } from './model/types';\nimport {\n CursorEditor,\n CursorState,\n CursorStateChangeEvent,\n RemoteCursorChangeEventListener,\n withCursors,\n WithCursorsOptions,\n withYHistory,\n WithYHistoryOptions,\n withYjs,\n WithYjsOptions,\n YHistoryEditor,\n YjsEditor,\n} from './plugins';\nimport { slateNodesToInsertDelta, yTextToSlateElement } from './utils/convert';\nimport {\n relativePositionToSlatePoint,\n relativeRangeToSlateRange,\n slatePointToRelativePosition,\n slateRangeToRelativeRange,\n} from './utils/position';\n\nexport {\n withYjs,\n WithYjsOptions,\n YjsEditor,\n // History plugin\n withYHistory,\n WithYHistoryOptions,\n YHistoryEditor,\n // Base cursor plugin\n CursorEditor,\n WithCursorsOptions,\n withCursors,\n CursorState,\n RemoteCursorChangeEventListener,\n CursorStateChangeEvent,\n // Utils\n RelativeRange,\n yTextToSlateElement,\n slateNodesToInsertDelta,\n slateRangeToRelativeRange,\n relativeRangeToSlateRange,\n slatePointToRelativePosition,\n relativePositionToSlatePoint,\n};\n","/*!\n * is-plain-object <https://github.com/jonschlinkert/is-plain-object>\n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nfunction isObject(o) {\n return Object.prototype.toString.call(o) === '[object Object]';\n}\n\nfunction isPlainObject(o) {\n var ctor,prot;\n\n if (isObject(o) === false) return false;\n\n // If has modified constructor\n ctor = o.constructor;\n if (ctor === undefined) return true;\n\n // If has modified prototype\n prot = ctor.prototype;\n if (isObject(prot) === false) return false;\n\n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n\n // Most likely a plain Object\n return true;\n}\n\nexport { isPlainObject };\n","const errors = {\n\t0: \"Illegal state\",\n\t1: \"Immer drafts cannot have computed properties\",\n\t2: \"This object has been frozen and should not be mutated\",\n\t3(data: any) {\n\t\treturn (\n\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\tdata\n\t\t)\n\t},\n\t4: \"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t5: \"Immer forbids circular references\",\n\t6: \"The first or second argument to `produce` must be a function\",\n\t7: \"The third argument to `produce` must be a function or undefined\",\n\t8: \"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t9: \"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t10: \"The given draft is already finalized\",\n\t11: \"Object.defineProperty() cannot be used on an Immer draft\",\n\t12: \"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t13: \"Immer only supports deleting array indices\",\n\t14: \"Immer only supports setting array indices and the 'length' property\",\n\t15(path: string) {\n\t\treturn \"Cannot apply patch, path doesn't resolve: \" + path\n\t},\n\t16: 'Sets cannot have \"replace\" patches.',\n\t17(op: string) {\n\t\treturn \"Unsupported patch operation: \" + op\n\t},\n\t18(plugin: string) {\n\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t},\n\t20: \"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available\",\n\t21(thing: string) {\n\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t},\n\t22(thing: string) {\n\t\treturn `'current' expects a draft, got: ${thing}`\n\t},\n\t23(thing: string) {\n\t\treturn `'original' expects a draft, got: ${thing}`\n\t},\n\t24: \"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n} as const\n\nexport function die(error: keyof typeof errors, ...args: any[]): never {\n\tif (__DEV__) {\n\t\tconst e = errors[error]\n\t\tconst msg = !e\n\t\t\t? \"unknown error nr: \" + error\n\t\t\t: typeof e === \"function\"\n\t\t\t? e.apply(null, args as any)\n\t\t\t: e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}${\n\t\t\targs.length ? \" \" + args.map(s => `'${s}'`).join(\",\") : \"\"\n\t\t}. Find the full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n","import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\thasSet,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\thasMap,\n\tArchtype,\n\tdie\n} from \"../internal\"\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport function isDraft(value: any): boolean {\n\treturn !!value && !!value[DRAFT_STATE]\n}\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tArray.isArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value.constructor[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = Object.prototype.constructor.toString()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || typeof value !== \"object\") return false\n\tconst proto = Object.getPrototypeOf(value)\n\tif (proto === null) {\n\t\treturn true\n\t}\n\tconst Ctor =\n\t\tObject.hasOwnProperty.call(proto, \"constructor\") && proto.constructor\n\n\tif (Ctor === Object) return true\n\n\treturn (\n\t\ttypeof Ctor == \"function\" &&\n\t\tFunction.toString.call(Ctor) === objectCtorString\n\t)\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original<T>(value: T): T | undefined\nexport function original(value: Drafted<any>): any {\n\tif (!isDraft(value)) die(23, value)\n\treturn value[DRAFT_STATE].base_\n}\n\n/*#__PURE__*/\nexport const ownKeys: (target: AnyObject) => PropertyKey[] =\n\ttypeof Reflect !== \"undefined\" && Reflect.ownKeys\n\t\t? Reflect.ownKeys\n\t\t: typeof Object.getOwnPropertySymbols !== \"undefined\"\n\t\t? obj =>\n\t\t\t\tObject.getOwnPropertyNames(obj).concat(\n\t\t\t\t\tObject.getOwnPropertySymbols(obj) as any\n\t\t\t\t)\n\t\t: /* istanbul ignore next */ Object.getOwnPropertyNames\n\nexport const getOwnPropertyDescriptors =\n\tObject.getOwnPropertyDescriptors ||\n\tfunction getOwnPropertyDescriptors(target: any) {\n\t\t// Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n\t\tconst res: any = {}\n\t\townKeys(target).forEach(key => {\n\t\t\tres[key] = Object.getOwnPropertyDescriptor(target, key)\n\t\t})\n\t\treturn res\n\t}\n\nexport function each<T extends Objectish>(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void,\n\tenumerableOnly?: boolean\n): void\nexport function each(obj: any, iter: any, enumerableOnly = false) {\n\tif (getArchtype(obj) === Archtype.Object) {\n\t\t;(enumerableOnly ? Object.keys : ownKeys)(obj).forEach(key => {\n\t\t\tif (!enumerableOnly || typeof key !== \"symbol\") iter(key, obj[key], obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): Archtype {\n\t/* istanbul ignore next */\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_ > 3\n\t\t\t? state.type_ - 4 // cause Object and Array map back from 4 and 5\n\t\t\t: (state.type_ as any) // others are the same\n\t\t: Array.isArray(thing)\n\t\t? Archtype.Array\n\t\t: isMap(thing)\n\t\t? Archtype.Map\n\t\t: isSet(thing)\n\t\t? Archtype.Set\n\t\t: Archtype.Object\n}\n\n/*#__PURE__*/\nexport function has(thing: any, prop: PropertyKey): boolean {\n\treturn getArchtype(thing) === Archtype.Map\n\t\t? thing.has(prop)\n\t\t: Object.prototype.hasOwnProperty.call(thing, prop)\n}\n\n/*#__PURE__*/\nexport function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {\n\t// @ts-ignore\n\treturn getArchtype(thing) === Archtype.Map ? thing.get(prop) : thing[prop]\n}\n\n/*#__PURE__*/\nexport function set(thing: any, propOrOldValue: PropertyKey, value: any) {\n\tconst t = getArchtype(thing)\n\tif (t === Archtype.Map) thing.set(propOrOldValue, value)\n\telse if (t === Archtype.Set) {\n\t\tthing.delete(propOrOldValue)\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\n/*#__PURE__*/\nexport function isMap(target: any): target is AnyMap {\n\treturn hasMap && target instanceof Map\n}\n\n/*#__PURE__*/\nexport function isSet(target: any): target is AnySet {\n\treturn hasSet && target instanceof Set\n}\n/*#__PURE__*/\nexport function latest(state: ImmerState): any {\n\treturn state.copy_ || state.base_\n}\n\n/*#__PURE__*/\nexport function shallowCopy(base: any) {\n\tif (Array.isArray(base)) return Array.prototype.slice.call(base)\n\tconst descriptors = getOwnPropertyDescriptors(base)\n\tdelete descriptors[DRAFT_STATE as any]\n\tlet keys = ownKeys(descriptors)\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tconst key: any = keys[i]\n\t\tconst desc = descriptors[key]\n\t\tif (desc.writable === false) {\n\t\t\tdesc.writable = true\n\t\t\tdesc.configurable = true\n\t\t}\n\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t// with libraries that trap values, like mobx or vue\n\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\tif (desc.get || desc.set)\n\t\t\tdescriptors[key] = {\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true, // could live with !!desc.set as well here...\n\t\t\t\tenumerable: desc.enumerable,\n\t\t\t\tvalue: base[key]\n\t\t\t}\n\t}\n\treturn Object.create(Object.getPrototypeOf(base), descriptors)\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze<T>(obj: T, deep?: boolean): T\nexport function freeze<T>(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tobj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any\n\t}\n\tObject.freeze(obj)\n\tif (deep) each(obj, (key, value) => freeze(value, true), true)\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nexport function isFrozen(obj: any): boolean {\n\tif (obj == null || typeof obj !== \"object\") return true\n\t// See #600, IE dies on non-objects in Object.isFrozen\n\treturn Object.isFrozen(obj)\n}\n","import {\n\tImmerState,\n\tPatch,\n\tImmerScope,\n\tDrafted,\n\tAnyObject,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tProxyType,\n\tdie\n} from \"../internal\"\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: {\n\t\tgeneratePatches_(\n\t\t\tstate: ImmerState,\n\t\t\tbasePath: PatchPath,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tgenerateReplacementPatches_(\n\t\t\trootState: ImmerState,\n\t\t\treplacement: any,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tapplyPatches_<T>(draft: T, patches: Patch[]): T\n\t}\n\tES5?: {\n\t\twillFinalizeES5_(scope: ImmerScope, result: any, isReplaced: boolean): void\n\t\tcreateES5Proxy_<T>(\n\t\t\tbase: T,\n\t\t\tparent?: ImmerState\n\t\t): Drafted<T, ES5ObjectState | ES5ArrayState>\n\t\thasChanges_(state: ES5ArrayState | ES5ObjectState): boolean\n\t}\n\tMapSet?: {\n\t\tproxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T\n\t\tproxySet_<T extends AnySet>(target: T, parent?: ImmerState): T\n\t}\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin<K extends keyof Plugins>(\n\tpluginKey: K\n): Exclude<Plugins[K], undefined> {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(18, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport function loadPlugin<K extends keyof Plugins>(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n\n/** ES5 Plugin */\n\ninterface ES5BaseState extends ImmerBaseState {\n\tassigned_: {[key: string]: any}\n\tparent_?: ImmerState\n\trevoked_: boolean\n}\n\nexport interface ES5ObjectState extends ES5BaseState {\n\ttype_: ProxyType.ES5Object\n\tdraft_: Drafted<AnyObject, ES5ObjectState>\n\tbase_: AnyObject\n\tcopy_: AnyObject | null\n}\n\nexport interface ES5ArrayState extends ES5BaseState {\n\ttype_: ProxyType.ES5Array\n\tdraft_: Drafted<AnyObject, ES5ArrayState>\n\tbase_: any\n\tcopy_: any\n}\n\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ProxyType.Map\n\tcopy_: AnyMap | undefined\n\tassigned_: Map<any, boolean> | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted<AnyMap, MapState>\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ProxyType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map<any, Drafted> // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted<AnySet, SetState>\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n","import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tProxyType,\n\tgetPlugin\n} from \"../internal\"\nimport {die} from \"../utils/errors\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport function getCurrentScope() {\n\tif (__DEV__ && !currentScope) die(0)\n\treturn currentScope!\n}\n\nfunction createScope(\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope {\n\treturn {\n\t\tdrafts_: [],\n\t\tparent_,\n\t\timmer_,\n\t\t// Whenever the modified draft contains a draft from another scope, we\n\t\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\t\tcanAutoFreeze_: true,\n\t\tunfinalizedDrafts_: 0\n\t}\n}\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tgetPlugin(\"Patches\") // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport function enterScope(immer: Immer) {\n\treturn (currentScope = createScope(currentScope, immer))\n}\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (\n\t\tstate.type_ === ProxyType.ProxyObject ||\n\t\tstate.type_ === ProxyType.ProxyArray\n\t)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n","import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\thas,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tProxyType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen,\n\tshallowCopy\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\tif (!scope.immer_.useProxies_)\n\t\tgetPlugin(\"ES5\").willFinalizeES5_(scope, result, isReplaced)\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t\tif (!scope.parent_) maybeFreeze(scope, result)\n\t\t}\n\t\tif (scope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE],\n\t\t\t\tresult,\n\t\t\t\tscope.patches_,\n\t\t\t\tscope.inversePatches_!\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft, [])\n\t}\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\t// A plain object, might need freezing, might contain drafts\n\tif (!state) {\n\t\teach(\n\t\t\tvalue,\n\t\t\t(key, childValue) =>\n\t\t\t\tfinalizeProperty(rootScope, state, value, key, childValue, path),\n\t\t\ttrue // See #590, don't recurse into non-enumarable of non drafted objects\n\t\t)\n\t\treturn value\n\t}\n\t// Never finalize drafts owned by another scope.\n\tif (state.scope_ !== rootScope) return value\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\tmaybeFreeze(rootScope, state.base_, true)\n\t\treturn state.base_\n\t}\n\t// Not finalized yet, let's do that now\n\tif (!state.finalized_) {\n\t\tstate.finalized_ = true\n\t\tstate.scope_.unfinalizedDrafts_--\n\t\tconst result =\n\t\t\t// For ES5, create a good copy from the draft first, with added keys and without deleted keys.\n\t\t\tstate.type_ === ProxyType.ES5Object || state.type_ === ProxyType.ES5Array\n\t\t\t\t? (state.copy_ = shallowCopy(state.draft_))\n\t\t\t\t: state.copy_\n\t\t// Finalize all children of the copy\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// Although the original test case doesn't seem valid anyway, so if this in the way we can turn the next line\n\t\t// back to each(result, ....)\n\t\teach(\n\t\t\tstate.type_ === ProxyType.Set ? new Set(result) : result,\n\t\t\t(key, childValue) =>\n\t\t\t\tfinalizeProperty(rootScope, state, result, key, childValue, path)\n\t\t)\n\t\t// everything inside is frozen, we can freeze here\n\t\tmaybeFreeze(rootScope, result, false)\n\t\t// first time finalizing, let's create those patches\n\t\tif (path && rootScope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generatePatches_(\n\t\t\t\tstate,\n\t\t\t\tpath,\n\t\t\t\trootScope.patches_,\n\t\t\t\trootScope.inversePatches_!\n\t\t\t)\n\t\t}\n\t}\n\treturn state.copy_\n}\n\nfunction finalizeProperty(\n\trootScope: ImmerScope,\n\tparentState: undefined | ImmerState,\n\ttargetObject: any,\n\tprop: string | number,\n\tchildValue: any,\n\trootPath?: PatchPath\n) {\n\tif (__DEV__ && childValue === targetObject) die(5)\n\tif (isDraft(childValue)) {\n\t\tconst path =\n\t\t\trootPath &&\n\t\t\tparentState &&\n\t\t\tparentState!.type_ !== ProxyType.Set && // Set objects are atomic since they have no keys.\n\t\t\t!has((parentState as Exclude<ImmerState, SetState>).assigned_!, prop) // Skip deep patches for assigned keys.\n\t\t\t\t? rootPath!.concat(prop)\n\t\t\t\t: undefined\n\t\t// Drafts owned by `scope` are finalized here.\n\t\tconst res = finalize(rootScope, childValue, path)\n\t\tset(targetObject, prop, res)\n\t\t// Drafts from another scope must prevented to be frozen\n\t\t// if we got a draft back from finalize, we're in a nested produce and shouldn't freeze\n\t\tif (isDraft(res)) {\n\t\t\trootScope.canAutoFreeze_ = false\n\t\t} else return\n\t}\n\t// Search new objects for unfinalized drafts. Frozen objects should never contain drafts.\n\tif (isDraftable(childValue) && !isFrozen(childValue)) {\n\t\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t\t// This benefits especially adding large data tree's without further processing.\n\t\t\t// See add-data.js perf test\n\t\t\treturn\n\t\t}\n\t\tfinalize(rootScope, childValue)\n\t\t// immer deep freezes plain objects, so if there is no parent state, we freeze as well\n\t\tif (!parentState || !parentState.scope_.parent_)\n\t\t\tmaybeFreeze(rootScope, childValue)\n\t}\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\tif (scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n","import {\n\teach,\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tProxyType\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tassigned_: {\n\t\t[property: string]: boolean\n\t}\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ProxyType.ProxyObject\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted<AnyObject, ProxyObjectState>\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ProxyType.ProxyArray\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted<AnyArray, ProxyArrayState>\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy<T extends Objectish>(\n\tbase: T,\n\tparent?: ImmerState\n): Drafted<T, ProxyState> {\n\tconst isArray = Array.isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: isArray ? ProxyType.ProxyArray : (ProxyType.ProxyObject as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\tassigned_: {},\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler<object | Array<any>> = objectTraps\n\tif (isArray) {\n\t\ttarget = [state] as any\n\t\ttraps = arrayTraps\n\t}\n\n\tconst {revoke, proxy} = Proxy.revocable(target, traps)\n\tstate.draft_ = proxy as any\n\tstate.revoke_ = revoke\n\treturn proxy as any\n}\n\n/**\n * Object drafts\n */\nexport const objectTraps: ProxyHandler<ProxyState> = {\n\tget(state, prop) {\n\t\tif (prop === DRAFT_STATE) return state\n\n\t\tconst source = latest(state)\n\t\tif (!has(source, prop)) {\n\t\t\t// non-existing or non-own property...\n\t\t\treturn readPropFromProto(state, source, prop)\n\t\t}\n\t\tconst value = source[prop]\n\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\treturn value\n\t\t}\n\t\t// Check for existing draft in modified state.\n\t\t// Assigned values are never drafted. This catches any drafts we created, too.\n\t\tif (value === peek(state.base_, prop)) {\n\t\t\tprepareCopy(state)\n\t\t\treturn (state.copy_![prop as any] = createProxy(\n\t\t\t\tstate.scope_.immer_,\n\t\t\t\tvalue,\n\t\t\t\tstate\n\t\t\t))\n\t\t}\n\t\treturn value\n\t},\n\thas(state, prop) {\n\t\treturn prop in latest(state)\n\t},\n\townKeys(state) {\n\t\treturn Reflect.ownKeys(latest(state))\n\t},\n\tset(\n\t\tstate: ProxyObjectState,\n\t\tprop: string /* strictly not, but helps TS */,\n\t\tvalue\n\t) {\n\t\tconst desc = getDescriptorFromProto(latest(state), prop)\n\t\tif (desc?.set) {\n\t\t\t// special case: if this write is captured by a setter, we have\n\t\t\t// to trigger it with the correct context\n\t\t\tdesc.set.call(state.draft_, value)\n\t\t\treturn true\n\t\t}\n\t\tif (!state.modified_) {\n\t\t\t// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)\n\t\t\t// from setting an existing property with value undefined to undefined (which is not a change)\n\t\t\tconst current = peek(latest(state), prop)\n\t\t\t// special case, if we assigning the original value to a draft, we can ignore the assignment\n\t\t\tconst currentState: ProxyObjectState = current?.[DRAFT_STATE]\n\t\t\tif (currentState && currentState.base_ === value) {\n\t\t\t\tstate.copy_![prop] = value\n\t\t\t\tstate.assigned_[prop] = false\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (is(value, current) && (value !== undefined || has(state.base_, prop)))\n\t\t\t\treturn true\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t}\n\n\t\tif (\n\t\t\tstate.copy_![prop] === value &&\n\t\t\t// special case: NaN\n\t\t\ttypeof value !== \"number\" &&\n\t\t\t// special case: handle new props with value 'undefined'\n\t\t\t(value !== undefined || prop in state.copy_)\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tstate.copy_![prop] = value\n\t\tstate.assigned_[prop] = true\n\t\treturn true\n\t},\n\tdeleteProperty(state, prop: string) {\n\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\tif (peek(state.base_, prop) !== undefined || prop in state.base_) {\n\t\t\tstate.assigned_[prop] = false\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t} else {\n\t\t\t// if an originally not assigned property was deleted\n\t\t\tdelete state.assigned_[prop]\n\t\t}\n\t\t// @ts-ignore\n\t\tif (state.copy_) delete state.copy_[prop]\n\t\treturn true\n\t},\n\t// Note: We never coerce `desc.value` into an Immer draft, because we can't make\n\t// the same guarantee in ES5 mode.\n\tgetOwnPropertyDescriptor(state, prop) {\n\t\tconst owner = latest(state)\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(owner, prop)\n\t\tif (!desc) return desc\n\t\treturn {\n\t\t\twritable: true,\n\t\t\tconfigurable: state.type_ !== ProxyType.ProxyArray || prop !== \"length\",\n\t\t\tenumerable: desc.enumerable,\n\t\t\tvalue: owner[prop]\n\t\t}\n\t},\n\tdefineProperty() {\n\t\tdie(11)\n\t},\n\tgetPrototypeOf(state) {\n\t\treturn Object.getPrototypeOf(state.base_)\n\t},\n\tsetPrototypeOf() {\n\t\tdie(12)\n\t}\n}\n\n/**\n * Array drafts\n */\n\nconst arrayTraps: ProxyHandler<[ProxyArrayState]> = {}\neach(objectTraps, (key, fn) => {\n\t// @ts-ignore\n\tarrayTraps[key] = function() {\n\t\targuments[0] = arguments[0][0]\n\t\treturn fn.apply(this, arguments)\n\t}\n})\narrayTraps.deleteProperty = function(state, prop) {\n\tif (__DEV__ && isNaN(parseInt(prop as any))) die(13)\n\treturn objectTraps.deleteProperty!.call(this, state[0], prop)\n}\narrayTraps.set = function(state, prop, value) {\n\tif (__DEV__ && prop !== \"length\" && isNaN(parseInt(prop as any))) die(14)\n\treturn objectTraps.set!.call(this, state[0], prop, value, state[0])\n}\n\n// Access a property without creating an Immer draft.\nfunction peek(draft: Drafted, prop: PropertyKey) {\n\tconst state = draft[DRAFT_STATE]\n\tconst source = state ? latest(state) : draft\n\treturn source[prop]\n}\n\nfunction readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {\n\tconst desc = getDescriptorFromProto(source, prop)\n\treturn desc\n\t\t? `value` in desc\n\t\t\t? desc.value\n\t\t\t: // This is a very special case, if the prop is a getter defined by the\n\t\t\t // prototype, we should invoke it with the draft as context!\n\t\t\t desc.get?.call(state.draft_)\n\t\t: undefined\n}\n\nfunction getDescriptorFromProto(\n\tsource: any,\n\tprop: PropertyKey\n): PropertyDescriptor | undefined {\n\t// 'in' checks proto!\n\tif (!(prop in source)) return undefined\n\tlet proto = Object.getPrototypeOf(source)\n\twhile (proto) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(proto, prop)\n\t\tif (desc) return desc\n\t\tproto = Object.getPrototypeOf(proto)\n\t}\n\treturn undefined\n}\n\nexport function markChanged(state: ImmerState) {\n\tif (!state.modified_) {\n\t\tstate.modified_ = true\n\t\tif (state.parent_) {\n\t\t\tmarkChanged(state.parent_)\n\t\t}\n\t}\n}\n\nexport function prepareCopy(state: {base_: any; copy_: any}) {\n\tif (!state.copy_) {\n\t\tstate.copy_ = shallowCopy(state.base_)\n\t}\n}\n","import {\n\tIProduceWithPatches,\n\tIProduce,\n\tImmerState,\n\tDrafted,\n\tisDraftable,\n\tprocessResult,\n\tPatch,\n\tObjectish,\n\tDRAFT_STATE,\n\tDraft,\n\tPatchListener,\n\tisDraft,\n\tisMap,\n\tisSet,\n\tcreateProxyProxy,\n\tgetPlugin,\n\tdie,\n\thasProxies,\n\tenterScope,\n\trevokeScope,\n\tleaveScope,\n\tusePatchesInScope,\n\tgetCurrentScope,\n\tNOTHING,\n\tfreeze,\n\tcurrent\n} from \"../internal\"\n\ninterface ProducersFns {\n\tproduce: IProduce\n\tproduceWithPatches: IProduceWithPatches\n}\n\nexport class Immer implements ProducersFns {\n\tuseProxies_: boolean = hasProxies\n\n\tautoFreeze_: boolean = true\n\n\tconstructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {\n\t\tif (typeof config?.useProxies === \"boolean\")\n\t\t\tthis.setUseProxies(config!.useProxies)\n\t\tif (typeof config?.autoFreeze === \"boolean\")\n\t\t\tthis.setAutoFreeze(config!.autoFreeze)\n\t}\n\n\t/**\n\t * The `produce` function takes a value and a \"recipe function\" (whose\n\t * return value often depends on the base state). The recipe function is\n\t * free to mutate its first argument however it wants. All mutations are\n\t * only ever applied to a __copy__ of the base state.\n\t *\n\t * Pass only a function to create a \"curried producer\" which relieves you\n\t * from passing the recipe function every time.\n\t *\n\t * Only plain objects and arrays are made mutable. All other objects are\n\t * considered uncopyable.\n\t *\n\t * Note: This function is __bound__ to its `Immer` instance.\n\t *\n\t * @param {any} base - the initial state\n\t * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n\t * @param {Function} patchListener - optional function that will be called with all the patches produced here\n\t * @returns {any} a new state, or the initial state if nothing was modified\n\t */\n\tproduce: IProduce = (base: any, recipe?: any, patchListener?: any) => {\n\t\t// curried invocation\n\t\tif (typeof base === \"function\" && typeof recipe !== \"function\") {\n\t\t\tconst defaultBase = recipe\n\t\t\trecipe = base\n\n\t\t\tconst self = this\n\t\t\treturn function curriedProduce(\n\t\t\t\tthis: any,\n\t\t\t\tbase = defaultBase,\n\t\t\t\t...args: any[]\n\t\t\t) {\n\t\t\t\treturn self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore\n\t\t\t}\n\t\t}\n\n\t\tif (typeof recipe !== \"function\") die(6)\n\t\tif (patchListener !== undefined && typeof patchListener !== \"function\")\n\t\t\tdie(7)\n\n\t\tlet result\n\n\t\t// Only plain objects, arrays, and \"immerable classes\" are drafted.\n\t\tif (isDraftable(base)) {\n\t\t\tconst scope = enterScope(this)\n\t\t\tconst proxy = createProxy(this, base, undefined)\n\t\t\tlet hasError = true\n\t\t\ttry {\n\t\t\t\tresult = recipe(proxy)\n\t\t\t\thasError = false\n\t\t\t} finally {\n\t\t\t\t// finally instead of catch + rethrow better preserves original stack\n\t\t\t\tif (hasError) revokeScope(scope)\n\t\t\t\telse leaveScope(scope)\n\t\t\t}\n\t\t\tif (typeof Promise !== \"undefined\" && result instanceof Promise) {\n\t\t\t\treturn result.then(\n\t\t\t\t\tresult => {\n\t\t\t\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\t\t\t\treturn processResult(result, scope)\n\t\t\t\t\t},\n\t\t\t\t\terror => {\n\t\t\t\t\t\trevokeScope(scope)\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\treturn processResult(result, scope)\n\t\t} else if (!base || typeof base !== \"object\") {\n\t\t\tresult = recipe(base)\n\t\t\tif (result === NOTHING) return undefined\n\t\t\tif (result === undefined) result = base\n\t\t\tif (this.autoFreeze_) freeze(result, true)\n\t\t\treturn result\n\t\t} else die(21, base)\n\t}\n\n\tproduceWithPatches: IProduceWithPatches = (\n\t\targ1: any,\n\t\targ2?: any,\n\t\targ3?: any\n\t): any => {\n\t\tif (typeof arg1 === \"function\") {\n\t\t\treturn (state: any, ...args: any[]) =>\n\t\t\t\tthis.produceWithPatches(state, (draft: any) => arg1(draft, ...args))\n\t\t}\n\n\t\tlet patches: Patch[], inversePatches: Patch[]\n\t\tconst nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {\n\t\t\tpatches = p\n\t\t\tinversePatches = ip\n\t\t})\n\t\treturn [nextState, patches!, inversePatches!]\n\t}\n\n\tcreateDraft<T extends Objectish>(base: T): Draft<T> {\n\t\tif (!isDraftable(base)) die(8)\n\t\tif (isDraft(base)) base = current(base)\n\t\tconst scope = enterScope(this)\n\t\tconst proxy = createProxy(this, base, undefined)\n\t\tproxy[DRAFT_STATE].isManual_ = true\n\t\tleaveScope(scope)\n\t\treturn proxy as any\n\t}\n\n\tfinishDraft<D extends Draft<any>>(\n\t\tdraft: D,\n\t\tpatchListener?: PatchListener\n\t): D extends Draft<infer T> ? T : never {\n\t\tconst state: ImmerState = draft && (draft as any)[DRAFT_STATE]\n\t\tif (__DEV__) {\n\t\t\tif (!state || !state.isManual_) die(9)\n\t\t\tif (state.finalized_) die(10)\n\t\t}\n\t\tconst {scope_: scope} = state\n\t\tusePatchesInScope(scope, patchListener)\n\t\treturn processResult(undefined, scope)\n\t}\n\n\t/**\n\t * Pass true to automatically freeze all copies created by Immer.\n\t *\n\t * By default, auto-freezing is enabled.\n\t */\n\tsetAutoFreeze(value: boolean) {\n\t\tthis.autoFreeze_ = value\n\t}\n\n\t/**\n\t * Pass true to use the ES2015 `Proxy` class when creating drafts, which is\n\t * always faster than using ES5 proxies.\n\t *\n\t * By default, feature detection is used, so calling this is rarely necessary.\n\t */\n\tsetUseProxies(value: boolean) {\n\t\tif (value && !hasProxies) {\n\t\t\tdie(20)\n\t\t}\n\t\tthis.useProxies_ = value\n\t}\n\n\tapplyPatches<T extends Objectish>(base: T, patches: Patch[]): T {\n\t\t// If a patch replaces the entire state, take that replacement as base\n\t\t// before applying patches\n\t\tlet i: number\n\t\tfor (i = patches.length - 1; i >= 0; i--) {\n\t\t\tconst patch = patches[i]\n\t\t\tif (patch.path.length === 0 && patch.op === \"replace\") {\n\t\t\t\tbase = patch.value\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tconst applyPatchesImpl = getPlugin(\"Patches\").applyPatches_\n\t\tif (isDraft(base)) {\n\t\t\t// N.B: never hits if some patch a replacement, patches are never drafts\n\t\t\treturn applyPatchesImpl(base, patches) as any\n\t\t}\n\t\t// Otherwise, produce a copy of the base state.\n\t\treturn this.produce(base, (draft: Drafted) =>\n\t\t\tapplyPatchesImpl(draft, patches.slice(i + 1))\n\t\t) as any\n\t}\n}\n\nexport function createProxy<T extends Objectish>(\n\timmer: Immer,\n\tvalue: T,\n\tparent?: ImmerState\n): Drafted<T, ImmerState> {\n\t// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n\tconst draft: Drafted = isMap(value)\n\t\t? getPlugin(\"MapSet\").proxyMap_(value, parent)\n\t\t: isSet(value)\n\t\t? getPlugin(\"MapSet\").proxySet_(value, parent)\n\t\t: immer.useProxies_\n\t\t? createProxyProxy(value, parent)\n\t\t: getPlugin(\"ES5\").createES5Proxy_(value, parent)\n\n\tconst scope = parent ? parent.scope_ : getCurrentScope()\n\tscope.drafts_.push(draft)\n\treturn draft\n}\n","import {\n\tdie,\n\tisDraft,\n\tshallowCopy,\n\teach,\n\tDRAFT_STATE,\n\tget,\n\tset,\n\tImmerState,\n\tisDraftable,\n\tArchtype,\n\tgetArchtype,\n\tgetPlugin\n} from \"../internal\"\n\n/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */\nexport function current<T>(value: T): T\nexport function current(value: any): any {\n\tif (!isDraft(value)) die(22, value)\n\treturn currentImpl(value)\n}\n\nfunction currentImpl(value: any): any {\n\tif (!isDraftable(value)) return value\n\tconst state: ImmerState | undefined = value[DRAFT_STATE]\n\tlet copy: any\n\tconst archType = getArchtype(value)\n\tif (state) {\n\t\tif (\n\t\t\t!state.modified_ &&\n\t\t\t(state.type_ < 4 || !getPlugin(\"ES5\").hasChanges_(state as any))\n\t\t)\n\t\t\treturn state.base_\n\t\t// Optimization: avoid generating new drafts during copying\n\t\tstate.finalized_ = true\n\t\tcopy = copyHelper(value, archType)\n\t\tstate.finalized_ = false\n\t} else {\n\t\tcopy = copyHelper(value, archType)\n\t}\n\n\teach(copy, (key, childValue) => {\n\t\tif (state && get(state.base_, key) === childValue) return // no need to copy or search in something that didn't change\n\t\tset(copy, key, currentImpl(childValue))\n\t})\n\t// In the future, we might consider freezing here, based on the current settings\n\treturn archType === Archtype.Set ? new Set(copy) : copy\n}\n\nfunction copyHelper(value: any, archType: number): any {\n\t// creates a shallow copy, even if it is a map or set\n\tswitch (archType) {\n\t\tcase Archtype.Map:\n\t\t\treturn new Map(value)\n\t\tcase Archtype.Set:\n\t\t\t// Set will be cloned as array temporarily, so that we can replace individual items\n\t\t\treturn Array.from(value)\n\t}\n\treturn shallowCopy(value)\n}\n","import {\n\tImmerState,\n\tDrafted,\n\tES5ArrayState,\n\tES5ObjectState,\n\teach,\n\thas,\n\tisDraft,\n\tlatest,\n\tDRAFT_STATE,\n\tis,\n\tloadPlugin,\n\tImmerScope,\n\tProxyType,\n\tgetCurrentScope,\n\tdie,\n\tmarkChanged,\n\tobjectTraps,\n\townKeys,\n\tgetOwnPropertyDescriptors\n} from \"../internal\"\n\ntype ES5State = ES5ArrayState | ES5ObjectState\n\nexport function enableES5() {\n\tfunction willFinalizeES5_(\n\t\tscope: ImmerScope,\n\t\tresult: any,\n\t\tisReplaced: boolean\n\t) {\n\t\tif (!isReplaced) {\n\t\t\tif (scope.patches_) {\n\t\t\t\tmarkChangesRecursively(scope.drafts_![0])\n\t\t\t}\n\t\t\t// This is faster when we don't care about which attributes changed.\n\t\t\tmarkChangesSweep(scope.drafts_)\n\t\t}\n\t\t// When a child draft is returned, look for changes.\n\t\telse if (\n\t\t\tisDraft(result) &&\n\t\t\t(result[DRAFT_STATE] as ES5State).scope_ === scope\n\t\t) {\n\t\t\tmarkChangesSweep(scope.drafts_)\n\t\t}\n\t}\n\n\tfunction createES5Draft(isArray: boolean, base: any) {\n\t\tif (isArray) {\n\t\t\tconst draft = new Array(base.length)\n\t\t\tfor (let i = 0; i < base.length; i++)\n\t\t\t\tObject.defineProperty(draft, \"\" + i, proxyProperty(i, true))\n\t\t\treturn draft\n\t\t} else {\n\t\t\tconst descriptors = getOwnPropertyDescriptors(base)\n\t\t\tdelete descriptors[DRAFT_STATE as any]\n\t\t\tconst keys = ownKeys(descriptors)\n\t\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\t\tconst key: any = keys[i]\n\t\t\t\tdescriptors[key] = proxyProperty(\n\t\t\t\t\tkey,\n\t\t\t\t\tisArray || !!descriptors[key].enumerable\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn Object.create(Object.getPrototypeOf(base), descriptors)\n\t\t}\n\t}\n\n\tfunction createES5Proxy_<T>(\n\t\tbase: T,\n\t\tparent?: ImmerState\n\t): Drafted<T, ES5ObjectState | ES5ArrayState> {\n\t\tconst isArray = Array.isArray(base)\n\t\tconst draft = createES5Draft(isArray, base)\n\n\t\tconst state: ES5ObjectState | ES5ArrayState = {\n\t\t\ttype_: isArray ? ProxyType.ES5Array : (ProxyType.ES5Object as any),\n\t\t\tscope_: parent ? parent.scope_ : getCurrentScope(),\n\t\t\tmodified_: false,\n\t\t\tfinalized_: false,\n\t\t\tassigned_: {},\n\t\t\tparent_: parent,\n\t\t\t// base is the object we are drafting\n\t\t\tbase_: base,\n\t\t\t// draft is the draft object itself, that traps all reads and reads from either the base (if unmodified) or copy (if modified)\n\t\t\tdraft_: draft,\n\t\t\tcopy_: null,\n\t\t\trevoked_: false,\n\t\t\tisManual_: false\n\t\t}\n\n\t\tObject.defineProperty(draft, DRAFT_STATE, {\n\t\t\tvalue: state,\n\t\t\t// enumerable: false <- the default\n\t\t\twritable: true\n\t\t})\n\t\treturn draft\n\t}\n\n\t// property descriptors are recycled to make sure we don't create a get and set closure per property,\n\t// but share them all instead\n\tconst descriptors: {[prop: string]: PropertyDescriptor} = {}\n\n\tfunction proxyProperty(\n\t\tprop: string | number,\n\t\tenumerable: boolean\n\t): PropertyDescriptor {\n\t\tlet desc = descriptors[prop]\n\t\tif (desc) {\n\t\t\tdesc.enumerable = enumerable\n\t\t} else {\n\t\t\tdescriptors[prop] = desc = {\n\t\t\t\tconfigurable: true,\n\t\t\t\tenumerable,\n\t\t\t\tget(this: any) {\n\t\t\t\t\tconst state = this[DRAFT_STATE]\n\t\t\t\t\tif (__DEV__) assertUnrevoked(state)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\treturn objectTraps.get(state, prop)\n\t\t\t\t},\n\t\t\t\tset(this: any, value) {\n\t\t\t\t\tconst state = this[DRAFT_STATE]\n\t\t\t\t\tif (__DEV__) assertUnrevoked(state)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tobjectTraps.set(state, prop, value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn desc\n\t}\n\n\t// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.\n\tfunction markChangesSweep(drafts: Drafted<any, ImmerState>[]) {\n\t\t// The natural order of drafts in the `scope` array is based on when they\n\t\t// were accessed. By processing drafts in reverse natural order, we have a\n\t\t// better chance of processing leaf nodes first. When a leaf node is known to\n\t\t// have changed, we can avoid any traversal of its ancestor nodes.\n\t\tfor (let i = drafts.length - 1; i >= 0; i--) {\n\t\t\tconst state: ES5State = drafts[i][DRAFT_STATE]\n\t\t\tif (!state.modified_) {\n\t\t\t\tswitch (state.type_) {\n\t\t\t\t\tcase ProxyType.ES5Array:\n\t\t\t\t\t\tif (hasArrayChanges(state)) markChanged(state)\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase ProxyType.ES5Object:\n\t\t\t\t\t\tif (hasObjectChanges(state)) markChanged(state)\n\t\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction markChangesRecursively(object: any) {\n\t\tif (!object || typeof object !== \"object\") return\n\t\tconst state: ES5State | undefined = object[DRAFT_STATE]\n\t\tif (!state) return\n\t\tconst {base_, draft_, assigned_, type_} = state\n\t\tif (type_ === ProxyType.ES5Object) {\n\t\t\t// Look for added keys.\n\t\t\t// probably there is a faster way to detect changes, as sweep + recurse seems to do some\n\t\t\t// unnecessary work.\n\t\t\t// also: probably we can store the information we detect here, to speed up tree finalization!\n\t\t\teach(draft_, key => {\n\t\t\t\tif ((key as any) === DRAFT_STATE) return\n\t\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\t\tif ((base_ as any)[key] === undefined && !has(base_, key)) {\n\t\t\t\t\tassigned_[key] = true\n\t\t\t\t\tmarkChanged(state)\n\t\t\t\t} else if (!assigned_[key]) {\n\t\t\t\t\t// Only untouched properties trigger recursion.\n\t\t\t\t\tmarkChangesRecursively(draft_[key])\n\t\t\t\t}\n\t\t\t})\n\t\t\t// Look for removed keys.\n\t\t\teach(base_, key => {\n\t\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\t\tif (draft_[key] === undefined && !has(draft_, key)) {\n\t\t\t\t\tassigned_[key] = false\n\t\t\t\t\tmarkChanged(state)\n\t\t\t\t}\n\t\t\t})\n\t\t} else if (type_ === ProxyType.ES5Array) {\n\t\t\tif (hasArrayChanges(state as ES5ArrayState)) {\n\t\t\t\tmarkChanged(state)\n\t\t\t\tassigned_.length = true\n\t\t\t}\n\n\t\t\tif (draft_.length < base_.length) {\n\t\t\t\tfor (let i = draft_.length; i < base_.length; i++) assigned_[i] = false\n\t\t\t} else {\n\t\t\t\tfor (let i = base_.length; i < draft_.length; i++) assigned_[i] = true\n\t\t\t}\n\n\t\t\t// Minimum count is enough, the other parts has been processed.\n\t\t\tconst min = Math.min(draft_.length, base_.length)\n\n\t\t\tfor (let i = 0; i < min; i++) {\n\t\t\t\t// Only untouched indices trigger recursion.\n\t\t\t\tif (assigned_[i] === undefined) markChangesRecursively(draft_[i])\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction hasObjectChanges(state: ES5ObjectState) {\n\t\tconst {base_, draft_} = state\n\n\t\t// Search for added keys and changed keys. Start at the back, because\n\t\t// non-numeric keys are ordered by time of definition on the object.\n\t\tconst keys = ownKeys(draft_)\n\t\tfor (let i = keys.length - 1; i >= 0; i--) {\n\t\t\tconst key: any = keys[i]\n\t\t\tif (key === DRAFT_STATE) continue\n\t\t\tconst baseValue = base_[key]\n\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\tif (baseValue === undefined && !has(base_, key)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t// Once a base key is deleted, future changes go undetected, because its\n\t\t\t// descriptor is erased. This branch detects any missed changes.\n\t\t\telse {\n\t\t\t\tconst value = draft_[key]\n\t\t\t\tconst state: ImmerState = value && value[DRAFT_STATE]\n\t\t\t\tif (state ? state.base_ !== baseValue : !is(value, baseValue)) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// At this point, no keys were added or changed.\n\t\t// Compare key count to determine if keys were deleted.\n\t\tconst baseIsDraft = !!base_[DRAFT_STATE as any]\n\t\treturn keys.length !== ownKeys(base_).length + (baseIsDraft ? 0 : 1) // + 1 to correct for DRAFT_STATE\n\t}\n\n\tfunction hasArrayChanges(state: ES5ArrayState) {\n\t\tconst {draft_} = state\n\t\tif (draft_.length !== state.base_.length) return true\n\t\t// See #116\n\t\t// If we first shorten the length, our array interceptors will be removed.\n\t\t// If after that new items are added, result in the same original length,\n\t\t// those last items will have no intercepting property.\n\t\t// So if there is no own descriptor on the last position, we know that items were removed and added\n\t\t// N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check\n\t\t// the last one\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(\n\t\t\tdraft_,\n\t\t\tdraft_.length - 1\n\t\t)\n\t\t// descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)\n\t\tif (descriptor && !descriptor.get) return true\n\t\t// For all other cases, we don't have to compare, as they would have been picked up by the index setters\n\t\treturn false\n\t}\n\n\tfunction hasChanges_(state: ES5State) {\n\t\treturn state.type_ === ProxyType.ES5Object\n\t\t\t? hasObjectChanges(state)\n\t\t\t: hasArrayChanges(state)\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tloadPlugin(\"ES5\", {\n\t\tcreateES5Proxy_,\n\t\twillFinalizeES5_,\n\t\thasChanges_\n\t})\n}\n","import {immerable} from \"../immer\"\nimport {\n\tImmerState,\n\tPatch,\n\tSetState,\n\tES5ArrayState,\n\tProxyArrayState,\n\tMapState,\n\tES5ObjectState,\n\tProxyObjectState,\n\tPatchPath,\n\tget,\n\teach,\n\thas,\n\tgetArchtype,\n\tisSet,\n\tisMap,\n\tloadPlugin,\n\tProxyType,\n\tArchtype,\n\tdie,\n\tisDraft,\n\tisDraftable,\n\tNOTHING\n} from \"../internal\"\n\nexport function enablePatches() {\n\tconst REPLACE = \"replace\"\n\tconst ADD = \"add\"\n\tconst REMOVE = \"remove\"\n\n\tfunction generatePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t): void {\n\t\tswitch (state.type_) {\n\t\t\tcase ProxyType.ProxyObject:\n\t\t\tcase ProxyType.ES5Object:\n\t\t\tcase ProxyType.Map:\n\t\t\t\treturn generatePatchesFromAssigned(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches,\n\t\t\t\t\tinversePatches\n\t\t\t\t)\n\t\t\tcase ProxyType.ES5Array:\n\t\t\tcase ProxyType.ProxyArray:\n\t\t\t\treturn generateArrayPatches(state, basePath, patches, inversePatches)\n\t\t\tcase ProxyType.Set:\n\t\t\t\treturn generateSetPatches(\n\t\t\t\t\t(state as any) as SetState,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches,\n\t\t\t\t\tinversePatches\n\t\t\t\t)\n\t\t}\n\t}\n\n\tfunction generateArrayPatches(\n\t\tstate: ES5ArrayState | ProxyArrayState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, assigned_} = state\n\t\tlet copy_ = state.copy_!\n\n\t\t// Reduce complexity by ensuring `base` is never longer.\n\t\tif (copy_.length < base_.length) {\n\t\t\t// @ts-ignore\n\t\t\t;[base_, copy_] = [copy_, base_]\n\t\t\t;[patches, inversePatches] = [inversePatches, patches]\n\t\t}\n\n\t\t// Process replaced indices.\n\t\tfor (let i = 0; i < base_.length; i++) {\n\t\t\tif (assigned_[i] && copy_[i] !== base_[i]) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t\t})\n\t\t\t\tinversePatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(base_[i])\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Process added indices.\n\t\tfor (let i = base_.length; i < copy_.length; i++) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tpatches.push({\n\t\t\t\top: ADD,\n\t\t\t\tpath,\n\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t})\n\t\t}\n\t\tif (base_.length < copy_.length) {\n\t\t\tinversePatches.push({\n\t\t\t\top: REPLACE,\n\t\t\t\tpath: basePath.concat([\"length\"]),\n\t\t\t\tvalue: base_.length\n\t\t\t})\n\t\t}\n\t}\n\n\t// This is used for both Map objects and normal objects.\n\tfunction generatePatchesFromAssigned(\n\t\tstate: MapState | ES5ObjectState | ProxyObjectState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tconst {base_, copy_} = state\n\t\teach(state.assigned_!, (key, assignedValue) => {\n\t\t\tconst origValue = get(base_, key)\n\t\t\tconst value = get(copy_!, key)\n\t\t\tconst op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD\n\t\t\tif (origValue === value && op === REPLACE) return\n\t\t\tconst path = basePath.concat(key as any)\n\t\t\tpatches.push(op === REMOVE ? {op, path} : {op, path, value})\n\t\t\tinversePatches.push(\n\t\t\t\top === ADD\n\t\t\t\t\t? {op: REMOVE, path}\n\t\t\t\t\t: op === REMOVE\n\t\t\t\t\t? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t\t\t: {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t)\n\t\t})\n\t}\n\n\tfunction generateSetPatches(\n\t\tstate: SetState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, copy_} = state\n\n\t\tlet i = 0\n\t\tbase_.forEach((value: any) => {\n\t\t\tif (!copy_!.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t\ti = 0\n\t\tcopy_!.forEach((value: any) => {\n\t\t\tif (!base_.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t}\n\n\tfunction generateReplacementPatches_(\n\t\trootState: ImmerState,\n\t\treplacement: any,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t): void {\n\t\tpatches.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: replacement === NOTHING ? undefined : replacement\n\t\t})\n\t\tinversePatches.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: rootState.base_\n\t\t})\n\t}\n\n\tfunction applyPatches_<T>(draft: T, patches: Patch[]): T {\n\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tconst p = \"\" + path[i]\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === Archtype.Object || parentType === Archtype.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === \"constructor\")\n\t\t\t\t)\n\t\t\t\t\tdie(24)\n\t\t\t\tif (typeof base === \"function\" && p === \"prototype\") die(24)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (typeof base !== \"object\") die(15, path.join(\"/\"))\n\t\t\t}\n\n\t\t\tconst type = getArchtype(base)\n\t\t\tconst value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411\n\t\t\tconst key = path[path.length - 1]\n\t\t\tswitch (op) {\n\t\t\t\tcase REPLACE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase Archtype.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\t\tcase Archtype.Set:\n\t\t\t\t\t\t\tdie(16)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// if value is an object, then it's assigned by reference\n\t\t\t\t\t\t\t// in the following add or remove ops, the value field inside the patch will also be modifyed\n\t\t\t\t\t\t\t// so we use value from the cloned patch\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase ADD:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase Archtype.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 0, value)\n\t\t\t\t\t\tcase Archtype.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\tcase Archtype.Set:\n\t\t\t\t\t\t\treturn base.add(value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase Archtype.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 1)\n\t\t\t\t\t\tcase Archtype.Map:\n\t\t\t\t\t\t\treturn base.delete(key)\n\t\t\t\t\t\tcase Archtype.Set:\n\t\t\t\t\t\t\treturn base.delete(patch.value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn delete base[key]\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tdie(17, op)\n\t\t\t}\n\t\t})\n\n\t\treturn draft\n\t}\n\n\t// optimize: this is quite a performance hit, can we detect intelligently when it is needed?\n\t// E.g. auto-draft when new objects from outside are assigned and modified?\n\t// (See failing test when deepClone just returns obj)\n\tfunction deepClonePatchValue<T>(obj: T): T\n\tfunction deepClonePatchValue(obj: any) {\n\t\tif (!isDraftable(obj)) return obj\n\t\tif (Array.isArray(obj)) return obj.map(deepClonePatchValue)\n\t\tif (isMap(obj))\n\t\t\treturn new Map(\n\t\t\t\tArray.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n\t\t\t)\n\t\tif (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))\n\t\tconst cloned = Object.create(Object.getPrototypeOf(obj))\n\t\tfor (const key in obj) cloned[key] = deepClonePatchValue(obj[key])\n\t\tif (has(obj, immerable)) cloned[immerable] = obj[immerable]\n\t\treturn cloned\n\t}\n\n\tfunction clonePatchValueIfNeeded<T>(obj: T): T {\n\t\tif (isDraft(obj)) {\n\t\t\treturn deepClonePatchValue(obj)\n\t\t} else return obj\n\t}\n\n\tloadPlugin(\"Patches\", {\n\t\tapplyPatches_,\n\t\tgeneratePatches_,\n\t\tgenerateReplacementPatches_\n\t})\n}\n","// types only!\nimport {\n\tImmerState,\n\tAnyMap,\n\tAnySet,\n\tMapState,\n\tSetState,\n\tDRAFT_STATE,\n\tgetCurrentScope,\n\tlatest,\n\titeratorSymbol,\n\tisDraftable,\n\tcreateProxy,\n\tloadPlugin,\n\tmarkChanged,\n\tProxyType,\n\tdie,\n\teach\n} from \"../internal\"\n\nexport function enableMapSet() {\n\t/* istanbul ignore next */\n\tvar extendStatics = function(d: any, b: any): any {\n\t\textendStatics =\n\t\t\tObject.setPrototypeOf ||\n\t\t\t({__proto__: []} instanceof Array &&\n\t\t\t\tfunction(d, b) {\n\t\t\t\t\td.__proto__ = b\n\t\t\t\t}) ||\n\t\t\tfunction(d, b) {\n\t\t\t\tfor (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]\n\t\t\t}\n\t\treturn extendStatics(d, b)\n\t}\n\n\t// Ugly hack to resolve #502 and inherit built in Map / Set\n\tfunction __extends(d: any, b: any): any {\n\t\textendStatics(d, b)\n\t\tfunction __(this: any): any {\n\t\t\tthis.constructor = d\n\t\t}\n\t\td.prototype =\n\t\t\t// @ts-ignore\n\t\t\t((__.prototype = b.prototype), new __())\n\t}\n\n\tconst DraftMap = (function(_super) {\n\t\t__extends(DraftMap, _super)\n\t\t// Create class manually, cause #502\n\t\tfunction DraftMap(this: any, target: AnyMap, parent?: ImmerState): any {\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ProxyType.Map,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this as any,\n\t\t\t\tisManual_: false,\n\t\t\t\trevoked_: false\n\t\t\t} as MapState\n\t\t\treturn this\n\t\t}\n\t\tconst p = DraftMap.prototype\n\n\t\tObject.defineProperty(p, \"size\", {\n\t\t\tget: function() {\n\t\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t\t}\n\t\t\t// enumerable: false,\n\t\t\t// configurable: true\n\t\t})\n\n\t\tp.has = function(key: any): boolean {\n\t\t\treturn latest(this[DRAFT_STATE]).has(key)\n\t\t}\n\n\t\tp.set = function(key: any, value: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!latest(state).has(key) || latest(state).get(key) !== value) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\tstate.copy_!.set(key, value)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tp.delete = function(key: any): boolean {\n\t\t\tif (!this.has(key)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareMapCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\tstate.assigned_!.set(key, false)\n\t\t\tstate.copy_!.delete(key)\n\t\t\treturn true\n\t\t}\n\n\t\tp.clear = function() {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_ = new Map()\n\t\t\t\teach(state.base_, key => {\n\t\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t\t})\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tp.forEach = function(\n\t\t\tcb: (value: any, key: any, self: any) => void,\n\t\t\tthisArg?: any\n\t\t) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tlatest(state).forEach((_value: any, key: any, _map: any) => {\n\t\t\t\tcb.call(thisArg, this.get(key), key, this)\n\t\t\t})\n\t\t}\n\n\t\tp.get = function(key: any): any {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tconst value = latest(state).get(key)\n\t\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\tif (value !== state.base_.get(key)) {\n\t\t\t\treturn value // either already drafted or reassigned\n\t\t\t}\n\t\t\t// despite what it looks, this creates a draft only once, see above condition\n\t\t\tconst draft = createProxy(state.scope_.immer_, value, state)\n\t\t\tprepareMapCopy(state)\n\t\t\tstate.copy_!.set(key, draft)\n\t\t\treturn draft\n\t\t}\n\n\t\tp.keys = function(): IterableIterator<any> {\n\t\t\treturn latest(this[DRAFT_STATE]).keys()\n\t\t}\n\n\t\tp.values = function(): IterableIterator<any> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[iteratorSymbol]: () => this.values(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tp.entries = function(): IterableIterator<[any, any]> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[iteratorSymbol]: () => this.entries(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: [r.value, value]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tp[iteratorSymbol] = function() {\n\t\t\treturn this.entries()\n\t\t}\n\n\t\treturn DraftMap\n\t})(Map)\n\n\tfunction proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T {\n\t\t// @ts-ignore\n\t\treturn new DraftMap(target, parent)\n\t}\n\n\tfunction prepareMapCopy(state: MapState) {\n\t\tif (!state.copy_) {\n\t\t\tstate.assigned_ = new Map()\n\t\t\tstate.copy_ = new Map(state.base_)\n\t\t}\n\t}\n\n\tconst DraftSet = (function(_super) {\n\t\t__extends(DraftSet, _super)\n\t\t// Create class manually, cause #502\n\t\tfunction DraftSet(this: any, target: AnySet, parent?: ImmerState) {\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ProxyType.Set,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this,\n\t\t\t\tdrafts_: new Map(),\n\t\t\t\trevoked_: false,\n\t\t\t\tisManual_: false\n\t\t\t} as SetState\n\t\t\treturn this\n\t\t}\n\t\tconst p = DraftSet.prototype\n\n\t\tObject.defineProperty(p, \"size\", {\n\t\t\tget: function() {\n\t\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t\t}\n\t\t\t// enumerable: true,\n\t\t})\n\n\t\tp.has = function(value: any): boolean {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\t// bit of trickery here, to be able to recognize both the value, and the draft of its value\n\t\t\tif (!state.copy_) {\n\t\t\t\treturn state.base_.has(value)\n\t\t\t}\n\t\t\tif (state.copy_.has(value)) return true\n\t\t\tif (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n\t\t\t\treturn true\n\t\t\treturn false\n\t\t}\n\n\t\tp.add = function(value: any): any {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!this.has(value)) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.add(value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tp.delete = function(value: any): any {\n\t\t\tif (!this.has(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\treturn (\n\t\t\t\tstate.copy_!.delete(value) ||\n\t\t\t\t(state.drafts_.has(value)\n\t\t\t\t\t? state.copy_!.delete(state.drafts_.get(value))\n\t\t\t\t\t: /* istanbul ignore next */ false)\n\t\t\t)\n\t\t}\n\n\t\tp.clear = function() {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tp.values = function(): IterableIterator<any> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.values()\n\t\t}\n\n\t\tp.entries = function entries(): IterableIterator<[any, any]> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.entries()\n\t\t}\n\n\t\tp.keys = function(): IterableIterator<any> {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tp[iteratorSymbol] = function() {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tp.forEach = function forEach(cb: any, thisArg?: any) {\n\t\t\tconst iterator = this.values()\n\t\t\tlet result = iterator.next()\n\t\t\twhile (!result.done) {\n\t\t\t\tcb.call(thisArg, result.value, result.value, this)\n\t\t\t\tresult = iterator.next()\n\t\t\t}\n\t\t}\n\n\t\treturn DraftSet\n\t})(Set)\n\n\tfunction proxySet_<T extends AnySet>(target: T, parent?: ImmerState): T {\n\t\t// @ts-ignore\n\t\treturn new DraftSet(target, parent)\n\t}\n\n\tfunction prepareSetCopy(state: SetState) {\n\t\tif (!state.copy_) {\n\t\t\t// create drafts for all entries to preserve insertion order\n\t\t\tstate.copy_ = new Set()\n\t\t\tstate.base_.forEach(value => {\n\t\t\t\tif (isDraftable(value)) {\n\t\t\t\t\tconst draft = createProxy(state.scope_.immer_, value, state)\n\t\t\t\t\tstate.drafts_.set(value, draft)\n\t\t\t\t\tstate.copy_!.add(draft)\n\t\t\t\t} else {\n\t\t\t\t\tstate.copy_!.add(value)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tloadPlugin(\"MapSet\", {proxyMap_, proxySet_})\n}\n","import {enableES5} from \"./es5\"\nimport {enableMapSet} from \"./mapset\"\nimport {enablePatches} from \"./patches\"\n\nexport function enableAllPlugins() {\n\tenableES5()\n\tenableMapSet()\n\tenablePatches()\n}\n","import {\n\tIProduce,\n\tIProduceWithPatches,\n\tImmer,\n\tDraft,\n\tImmutable\n} from \"./internal\"\n\nexport {\n\tDraft,\n\tImmutable,\n\tPatch,\n\tPatchListener,\n\toriginal,\n\tcurrent,\n\tisDraft,\n\tisDraftable,\n\tNOTHING as nothing,\n\tDRAFTABLE as immerable,\n\tfreeze\n} from \"./internal\"\n\nconst immer = new Immer()\n\n/**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\nexport const produce: IProduce = immer.produce\nexport default produce\n\n/**\n * Like `produce`, but `produceWithPatches` always returns a tuple\n * [nextState, patches, inversePatches] (instead of just the next state)\n */\nexport const produceWithPatches: IProduceWithPatches = immer.produceWithPatches.bind(\n\timmer\n)\n\n/**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * Always freeze by default, even in production mode\n */\nexport const setAutoFreeze = immer.setAutoFreeze.bind(immer)\n\n/**\n * Pass true to use the ES2015 `Proxy` class when creating drafts, which is\n * always faster than using ES5 proxies.\n *\n * By default, feature detection is used, so calling this is rarely necessary.\n */\nexport const setUseProxies = immer.setUseProxies.bind(immer)\n\n/**\n * Apply an array of Immer patches to the first argument.\n *\n * This function is a producer, which means copy-on-write is in effect.\n */\nexport const applyPatches = immer.applyPatches.bind(immer)\n\n/**\n * Create an Immer draft from the given base state, which may be a draft itself.\n * The draft can be modified until you finalize it with the `finishDraft` function.\n */\nexport const createDraft = immer.createDraft.bind(immer)\n\n/**\n * Finalize an Immer draft from a `createDraft` call, returning the base state\n * (if no changes were made) or a modified copy. The draft must *not* be\n * mutated afterwards.\n *\n * Pass a function as the 2nd argument to generate Immer patches based on the\n * changes that were made.\n */\nexport const finishDraft = immer.finishDraft.bind(immer)\n\n/**\n * This function is actually a no-op, but can be used to cast an immutable type\n * to an draft type and make TypeScript happy\n *\n * @param value\n */\nexport function castDraft<T>(value: T): Draft<T> {\n\treturn value as any\n}\n\n/**\n * This function is actually a no-op, but can be used to cast a mutable type\n * to an immutable type and make TypeScript happy\n * @param value\n */\nexport function castImmutable<T>(value: T): Immutable<T> {\n\treturn value as any\n}\n\nexport {Immer}\n\nexport {enableES5} from \"./plugins/es5\"\nexport {enablePatches} from \"./plugins/patches\"\nexport {enableMapSet} from \"./plugins/mapset\"\nexport {enableAllPlugins} from \"./plugins/all\"\n","// Should be no imports here!\n\n// Some things that should be evaluated before all else...\n\n// We only want to know if non-polyfilled symbols are available\nconst hasSymbol =\n\ttypeof Symbol !== \"undefined\" && typeof Symbol(\"x\") === \"symbol\"\nexport const hasMap = typeof Map !== \"undefined\"\nexport const hasSet = typeof Set !== \"undefined\"\nexport const hasProxies =\n\ttypeof Proxy !== \"undefined\" &&\n\ttypeof Proxy.revocable !== \"undefined\" &&\n\ttypeof Reflect !== \"undefined\"\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: Nothing = hasSymbol\n\t? Symbol.for(\"immer-nothing\")\n\t: ({[\"immer-nothing\"]: true} as any)\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = hasSymbol\n\t? Symbol.for(\"immer-draftable\")\n\t: (\"__$immer_draftable\" as any)\n\nexport const DRAFT_STATE: unique symbol = hasSymbol\n\t? Symbol.for(\"immer-state\")\n\t: (\"__$immer_state\" as any)\n\n// Even a polyfilled Symbol might provide Symbol.iterator\nexport const iteratorSymbol: typeof Symbol.iterator =\n\t(typeof Symbol != \"undefined\" && Symbol.iterator) || (\"@@iterator\" as any)\n\n/** Use a class type for `nothing` so its type is unique */\nexport class Nothing {\n\t// This lets us do `Exclude<T, Nothing>`\n\t// @ts-ignore\n\tprivate _!: unique symbol\n}\n","export default function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}","import { Editor, Path, PathRef, PointRef, RangeRef } from '..'\n\nexport const DIRTY_PATHS: WeakMap<Editor, Path[]> = new WeakMap()\nexport const DIRTY_PATH_KEYS: WeakMap<Editor, Set<string>> = new WeakMap()\nexport const FLUSHING: WeakMap<Editor, boolean> = new WeakMap()\nexport const NORMALIZING: WeakMap<Editor, boolean> = new WeakMap()\nexport const PATH_REFS: WeakMap<Editor, Set<PathRef>> = new WeakMap()\nexport const POINT_REFS: WeakMap<Editor, Set<PointRef>> = new WeakMap()\nexport const RANGE_REFS: WeakMap<Editor, Set<RangeRef>> = new WeakMap()\n","import {\n Descendant,\n Editor,\n Element,\n Node,\n NodeEntry,\n Operation,\n Path,\n PathRef,\n PointRef,\n Range,\n RangeRef,\n Text,\n Transforms,\n} from './'\nimport { DIRTY_PATHS, DIRTY_PATH_KEYS, FLUSHING } from './utils/weak-maps'\nimport { TextUnit } from './interfaces/types'\n\n/**\n * Create a new Slate `Editor` object.\n */\n\nexport const createEditor = (): Editor => {\n const editor: Editor = {\n children: [],\n operations: [],\n selection: null,\n marks: null,\n isInline: () => false,\n isVoid: () => false,\n onChange: () => {},\n\n apply: (op: Operation) => {\n for (const ref of Editor.pathRefs(editor)) {\n PathRef.transform(ref, op)\n }\n\n for (const ref of Editor.pointRefs(editor)) {\n PointRef.transform(ref, op)\n }\n\n for (const ref of Editor.rangeRefs(editor)) {\n RangeRef.transform(ref, op)\n }\n\n const oldDirtyPaths = DIRTY_PATHS.get(editor) || []\n const oldDirtyPathKeys = DIRTY_PATH_KEYS.get(editor) || new Set()\n let dirtyPaths: Path[]\n let dirtyPathKeys: Set<string>\n\n const add = (path: Path | null) => {\n if (path) {\n const key = path.join(',')\n\n if (!dirtyPathKeys.has(key)) {\n dirtyPathKeys.add(key)\n dirtyPaths.push(path)\n }\n }\n }\n\n if (Path.operationCanTransformPath(op)) {\n dirtyPaths = []\n dirtyPathKeys = new Set()\n for (const path of oldDirtyPaths) {\n const newPath = Path.transform(path, op)\n add(newPath)\n }\n } else {\n dirtyPaths = oldDirtyPaths\n dirtyPathKeys = oldDirtyPathKeys\n }\n\n const newDirtyPaths = editor.getDirtyPaths(op)\n for (const path of newDirtyPaths) {\n add(path)\n }\n\n DIRTY_PATHS.set(editor, dirtyPaths)\n DIRTY_PATH_KEYS.set(editor, dirtyPathKeys)\n Transforms.transform(editor, op)\n editor.operations.push(op)\n Editor.normalize(editor)\n\n // Clear any formats applied to the cursor if the selection changes.\n if (op.type === 'set_selection') {\n editor.marks = null\n }\n\n if (!FLUSHING.get(editor)) {\n FLUSHING.set(editor, true)\n\n Promise.resolve().then(() => {\n FLUSHING.set(editor, false)\n editor.onChange()\n editor.operations = []\n })\n }\n },\n\n addMark: (key: string, value: any) => {\n const { selection } = editor\n\n if (selection) {\n if (Range.isExpanded(selection)) {\n Transforms.setNodes(\n editor,\n { [key]: value },\n { match: Text.isText, split: true }\n )\n } else {\n const marks = {\n ...(Editor.marks(editor) || {}),\n [key]: value,\n }\n\n editor.marks = marks\n if (!FLUSHING.get(editor)) {\n editor.onChange()\n }\n }\n }\n },\n\n deleteBackward: (unit: TextUnit) => {\n const { selection } = editor\n\n if (selection && Range.isCollapsed(selection)) {\n Transforms.delete(editor, { unit, reverse: true })\n }\n },\n\n deleteForward: (unit: TextUnit) => {\n const { selection } = editor\n\n if (selection && Range.isCollapsed(selection)) {\n Transforms.delete(editor, { unit })\n }\n },\n\n deleteFragment: (direction?: 'forward' | 'backward') => {\n const { selection } = editor\n\n if (selection && Range.isExpanded(selection)) {\n Transforms.delete(editor, { reverse: direction === 'backward' })\n }\n },\n\n getFragment: () => {\n const { selection } = editor\n\n if (selection) {\n return Node.fragment(editor, selection)\n }\n return []\n },\n\n insertBreak: () => {\n Transforms.splitNodes(editor, { always: true })\n },\n\n insertSoftBreak: () => {\n Transforms.splitNodes(editor, { always: true })\n },\n\n insertFragment: (fragment: Node[]) => {\n Transforms.insertFragment(editor, fragment)\n },\n\n insertNode: (node: Node) => {\n Transforms.insertNodes(editor, node)\n },\n\n insertText: (text: string) => {\n const { selection, marks } = editor\n\n if (selection) {\n if (marks) {\n const node = { text, ...marks }\n Transforms.insertNodes(editor, node)\n } else {\n Transforms.insertText(editor, text)\n }\n\n editor.marks = null\n }\n },\n\n normalizeNode: (entry: NodeEntry) => {\n const [node, path] = entry\n\n // There are no core normalizations for text nodes.\n if (Text.isText(node)) {\n return\n }\n\n // Ensure that block and inline nodes have at least one text child.\n if (Element.isElement(node) && node.children.length === 0) {\n const child = { text: '' }\n Transforms.insertNodes(editor, child, {\n at: path.concat(0),\n voids: true,\n })\n return\n }\n\n // Determine whether the node should have block or inline children.\n const shouldHaveInlines = Editor.isEditor(node)\n ? false\n : Element.isElement(node) &&\n (editor.isInline(node) ||\n node.children.length === 0 ||\n Text.isText(node.children[0]) ||\n editor.isInline(node.children[0]))\n\n // Since we'll be applying operations while iterating, keep track of an\n // index that accounts for any added/removed nodes.\n let n = 0\n\n for (let i = 0; i < node.children.length; i++, n++) {\n const currentNode = Node.get(editor, path)\n if (Text.isText(currentNode)) continue\n const child = node.children[i] as Descendant\n const prev = currentNode.children[n - 1] as Descendant\n const isLast = i === node.children.length - 1\n const isInlineOrText =\n Text.isText(child) ||\n (Element.isElement(child) && editor.isInline(child))\n\n // Only allow block nodes in the top-level children and parent blocks\n // that only contain block nodes. Similarly, only allow inline nodes in\n // other inline nodes, or parent blocks that only contain inlines and\n // text.\n if (isInlineOrText !== shouldHaveInlines) {\n Transforms.removeNodes(editor, { at: path.concat(n), voids: true })\n n--\n } else if (Element.isElement(child)) {\n // Ensure that inline nodes are surrounded by text nodes.\n if (editor.isInline(child)) {\n if (prev == null || !Text.isText(prev)) {\n const newChild = { text: '' }\n Transforms.insertNodes(editor, newChild, {\n at: path.concat(n),\n voids: true,\n })\n n++\n } else if (isLast) {\n const newChild = { text: '' }\n Transforms.insertNodes(editor, newChild, {\n at: path.concat(n + 1),\n voids: true,\n })\n n++\n }\n }\n } else {\n // Merge adjacent text nodes that are empty or match.\n if (prev != null && Text.isText(prev)) {\n if (Text.equals(child, prev, { loose: true })) {\n Transforms.mergeNodes(editor, { at: path.concat(n), voids: true })\n n--\n } else if (prev.text === '') {\n Transforms.removeNodes(editor, {\n at: path.concat(n - 1),\n voids: true,\n })\n n--\n } else if (child.text === '') {\n Transforms.removeNodes(editor, {\n at: path.concat(n),\n voids: true,\n })\n n--\n }\n }\n }\n }\n },\n\n removeMark: (key: string) => {\n const { selection } = editor\n\n if (selection) {\n if (Range.isExpanded(selection)) {\n Transforms.unsetNodes(editor, key, {\n match: Text.isText,\n split: true,\n })\n } else {\n const marks = { ...(Editor.marks(editor) || {}) }\n delete marks[key]\n editor.marks = marks\n if (!FLUSHING.get(editor)) {\n editor.onChange()\n }\n }\n }\n },\n\n /**\n * Get the \"dirty\" paths generated from an operation.\n */\n\n getDirtyPaths: (op: Operation): Path[] => {\n switch (op.type) {\n case 'insert_text':\n case 'remove_text':\n case 'set_node': {\n const { path } = op\n return Path.levels(path)\n }\n\n case 'insert_node': {\n const { node, path } = op\n const levels = Path.levels(path)\n const descendants = Text.isText(node)\n ? []\n : Array.from(Node.nodes(node), ([, p]) => path.concat(p))\n\n return [...levels, ...descendants]\n }\n\n case 'merge_node': {\n const { path } = op\n const ancestors = Path.ancestors(path)\n const previousPath = Path.previous(path)\n return [...ancestors, previousPath]\n }\n\n case 'move_node': {\n const { path, newPath } = op\n\n if (Path.equals(path, newPath)) {\n return []\n }\n\n const oldAncestors: Path[] = []\n const newAncestors: Path[] = []\n\n for (const ancestor of Path.ancestors(path)) {\n const p = Path.transform(ancestor, op)\n oldAncestors.push(p!)\n }\n\n for (const ancestor of Path.ancestors(newPath)) {\n const p = Path.transform(ancestor, op)\n newAncestors.push(p!)\n }\n\n const newParent = newAncestors[newAncestors.length - 1]\n const newIndex = newPath[newPath.length - 1]\n const resultPath = newParent.concat(newIndex)\n\n return [...oldAncestors, ...newAncestors, resultPath]\n }\n\n case 'remove_node': {\n const { path } = op\n const ancestors = Path.ancestors(path)\n return [...ancestors]\n }\n\n case 'split_node': {\n const { path } = op\n const levels = Path.levels(path)\n const nextPath = Path.next(path)\n return [...levels, nextPath]\n }\n\n default: {\n return []\n }\n }\n },\n }\n\n return editor\n}\n","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}","import objectWithoutPropertiesLoose from \"./objectWithoutPropertiesLoose.js\";\nexport default function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n var target = objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n}","// Character (grapheme cluster) boundaries are determined according to\n// the default grapheme cluster boundary specification, extended grapheme clusters variant[1].\n//\n// References:\n//\n// [1] https://www.unicode.org/reports/tr29/#Default_Grapheme_Cluster_Table\n// [2] https://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakProperty.txt\n// [3] https://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakTest.html\n// [4] https://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakTest.txt\n\n/**\n * Get the distance to the end of the first character in a string of text.\n */\n\nexport const getCharacterDistance = (str: string, isRTL = false): number => {\n const isLTR = !isRTL\n const codepoints = isRTL ? codepointsIteratorRTL(str) : str\n\n let left: CodepointType = CodepointType.None\n let right: CodepointType = CodepointType.None\n let distance = 0\n // Evaluation of these conditions are deferred.\n let gb11: boolean | null = null // Is GB11 applicable?\n let gb12Or13: boolean | null = null // Is GB12 or GB13 applicable?\n\n for (const char of codepoints) {\n const code = char.codePointAt(0)\n if (!code) break\n\n const type = getCodepointType(char, code)\n ;[left, right] = isLTR ? [right, type] : [type, left]\n\n if (\n intersects(left, CodepointType.ZWJ) &&\n intersects(right, CodepointType.ExtPict)\n ) {\n if (isLTR) {\n gb11 = endsWithEmojiZWJ(str.substring(0, distance))\n } else {\n gb11 = endsWithEmojiZWJ(str.substring(0, str.length - distance))\n }\n if (!gb11) break\n }\n\n if (\n intersects(left, CodepointType.RI) &&\n intersects(right, CodepointType.RI)\n ) {\n if (gb12Or13 !== null) {\n gb12Or13 = !gb12Or13\n } else {\n if (isLTR) {\n gb12Or13 = true\n } else {\n gb12Or13 = endsWithOddNumberOfRIs(\n str.substring(0, str.length - distance)\n )\n }\n }\n if (!gb12Or13) break\n }\n\n if (\n left !== CodepointType.None &&\n right !== CodepointType.None &&\n isBoundaryPair(left, right)\n ) {\n break\n }\n\n distance += char.length\n }\n\n return distance || 1\n}\n\nconst SPACE = /\\s/\nconst PUNCTUATION = /[\\u0021-\\u0023\\u0025-\\u002A\\u002C-\\u002F\\u003A\\u003B\\u003F\\u0040\\u005B-\\u005D\\u005F\\u007B\\u007D\\u00A1\\u00A7\\u00AB\\u00B6\\u00B7\\u00BB\\u00BF\\u037E\\u0387\\u055A-\\u055F\\u0589\\u058A\\u05BE\\u05C0\\u05C3\\u05C6\\u05F3\\u05F4\\u0609\\u060A\\u060C\\u060D\\u061B\\u061E\\u061F\\u066A-\\u066D\\u06D4\\u0700-\\u070D\\u07F7-\\u07F9\\u0830-\\u083E\\u085E\\u0964\\u0965\\u0970\\u0AF0\\u0DF4\\u0E4F\\u0E5A\\u0E5B\\u0F04-\\u0F12\\u0F14\\u0F3A-\\u0F3D\\u0F85\\u0FD0-\\u0FD4\\u0FD9\\u0FDA\\u104A-\\u104F\\u10FB\\u1360-\\u1368\\u1400\\u166D\\u166E\\u169B\\u169C\\u16EB-\\u16ED\\u1735\\u1736\\u17D4-\\u17D6\\u17D8-\\u17DA\\u1800-\\u180A\\u1944\\u1945\\u1A1E\\u1A1F\\u1AA0-\\u1AA6\\u1AA8-\\u1AAD\\u1B5A-\\u1B60\\u1BFC-\\u1BFF\\u1C3B-\\u1C3F\\u1C7E\\u1C7F\\u1CC0-\\u1CC7\\u1CD3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205E\\u207D\\u207E\\u208D\\u208E\\u2329\\u232A\\u2768-\\u2775\\u27C5\\u27C6\\u27E6-\\u27EF\\u2983-\\u2998\\u29D8-\\u29DB\\u29FC\\u29FD\\u2CF9-\\u2CFC\\u2CFE\\u2CFF\\u2D70\\u2E00-\\u2E2E\\u2E30-\\u2E3B\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\u3030\\u303D\\u30A0\\u30FB\\uA4FE\\uA4FF\\uA60D-\\uA60F\\uA673\\uA67E\\uA6F2-\\uA6F7\\uA874-\\uA877\\uA8CE\\uA8CF\\uA8F8-\\uA8FA\\uA92E\\uA92F\\uA95F\\uA9C1-\\uA9CD\\uA9DE\\uA9DF\\uAA5C-\\uAA5F\\uAADE\\uAADF\\uAAF0\\uAAF1\\uABEB\\uFD3E\\uFD3F\\uFE10-\\uFE19\\uFE30-\\uFE52\\uFE54-\\uFE61\\uFE63\\uFE68\\uFE6A\\uFE6B\\uFF01-\\uFF03\\uFF05-\\uFF0A\\uFF0C-\\uFF0F\\uFF1A\\uFF1B\\uFF1F\\uFF20\\uFF3B-\\uFF3D\\uFF3F\\uFF5B\\uFF5D\\uFF5F-\\uFF65]/\nconst CHAMELEON = /['\\u2018\\u2019]/\n\n/**\n * Get the distance to the end of the first word in a string of text.\n */\n\nexport const getWordDistance = (text: string, isRTL = false): number => {\n let dist = 0\n let started = false\n\n while (text.length > 0) {\n const charDist = getCharacterDistance(text, isRTL)\n const [char, remaining] = splitByCharacterDistance(text, charDist, isRTL)\n\n if (isWordCharacter(char, remaining, isRTL)) {\n started = true\n dist += charDist\n } else if (!started) {\n dist += charDist\n } else {\n break\n }\n\n text = remaining\n }\n\n return dist\n}\n\n/**\n * Split a string in two parts at a given distance starting from the end when\n * `isRTL` is set to `true`.\n */\n\nexport const splitByCharacterDistance = (\n str: string,\n dist: number,\n isRTL?: boolean\n): [string, string] => {\n if (isRTL) {\n const at = str.length - dist\n return [str.slice(at, str.length), str.slice(0, at)]\n }\n\n return [str.slice(0, dist), str.slice(dist)]\n}\n\n/**\n * Check if a character is a word character. The `remaining` argument is used\n * because sometimes you must read subsequent characters to truly determine it.\n */\n\nconst isWordCharacter = (\n char: string,\n remaining: string,\n isRTL = false\n): boolean => {\n if (SPACE.test(char)) {\n return false\n }\n\n // Chameleons count as word characters as long as they're in a word, so\n // recurse to see if the next one is a word character or not.\n if (CHAMELEON.test(char)) {\n const charDist = getCharacterDistance(remaining, isRTL)\n const [nextChar, nextRemaining] = splitByCharacterDistance(\n remaining,\n charDist,\n isRTL\n )\n\n if (isWordCharacter(nextChar, nextRemaining, isRTL)) {\n return true\n }\n }\n\n if (PUNCTUATION.test(char)) {\n return false\n }\n\n return true\n}\n\n/**\n * Iterate on codepoints from right to left.\n */\n\nexport const codepointsIteratorRTL = function*(str: string) {\n const end = str.length - 1\n\n for (let i = 0; i < str.length; i++) {\n const char1 = str.charAt(end - i)\n\n if (isLowSurrogate(char1.charCodeAt(0))) {\n const char2 = str.charAt(end - i - 1)\n if (isHighSurrogate(char2.charCodeAt(0))) {\n yield char2 + char1\n\n i++\n continue\n }\n }\n\n yield char1\n }\n}\n\n/**\n * Is `charCode` a high surrogate.\n *\n * https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates\n */\n\nconst isHighSurrogate = (charCode: number) => {\n return charCode >= 0xd800 && charCode <= 0xdbff\n}\n\n/**\n * Is `charCode` a low surrogate.\n *\n * https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates\n */\n\nconst isLowSurrogate = (charCode: number) => {\n return charCode >= 0xdc00 && charCode <= 0xdfff\n}\n\nenum CodepointType {\n None = 0,\n Extend = 1 << 0,\n ZWJ = 1 << 1,\n RI = 1 << 2,\n Prepend = 1 << 3,\n SpacingMark = 1 << 4,\n L = 1 << 5,\n V = 1 << 6,\n T = 1 << 7,\n LV = 1 << 8,\n LVT = 1 << 9,\n ExtPict = 1 << 10,\n Any = 1 << 11,\n}\n\nconst reExtend = /^[\\p{Gr_Ext}\\p{EMod}]$/u\nconst rePrepend = /^[\\u0600-\\u0605\\u06DD\\u070F\\u0890-\\u0891\\u08E2\\u0D4E\\u{110BD}\\u{110CD}\\u{111C2}-\\u{111C3}\\u{1193F}\\u{11941}\\u{11A3A}\\u{11A84}-\\u{11A89}\\u{11D46}]$/u\nconst reSpacingMark = /^[\\u0903\\u093B\\u093E-\\u0940\\u0949-\\u094C\\u094E-\\u094F\\u0982-\\u0983\\u09BF-\\u09C0\\u09C7-\\u09C8\\u09CB-\\u09CC\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB-\\u0ACC\\u0B02-\\u0B03\\u0B40\\u0B47-\\u0B48\\u0B4B-\\u0B4C\\u0BBF\\u0BC1-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82-\\u0C83\\u0CBE\\u0CC0-\\u0CC1\\u0CC3-\\u0CC4\\u0CC7-\\u0CC8\\u0CCA-\\u0CCB\\u0D02-\\u0D03\\u0D3F-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D82-\\u0D83\\u0DD0-\\u0DD1\\u0DD8-\\u0DDE\\u0DF2-\\u0DF3\\u0E33\\u0EB3\\u0F3E-\\u0F3F\\u0F7F\\u1031\\u103B-\\u103C\\u1056-\\u1057\\u1084\\u1715\\u1734\\u17B6\\u17BE-\\u17C5\\u17C7-\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930-\\u1931\\u1933-\\u1938\\u1A19-\\u1A1A\\u1A55\\u1A57\\u1A6D-\\u1A72\\u1B04\\u1B3B\\u1B3D-\\u1B41\\u1B43-\\u1B44\\u1B82\\u1BA1\\u1BA6-\\u1BA7\\u1BAA\\u1BE7\\u1BEA-\\u1BEC\\u1BEE\\u1BF2-\\u1BF3\\u1C24-\\u1C2B\\u1C34-\\u1C35\\u1CE1\\u1CF7\\uA823-\\uA824\\uA827\\uA880-\\uA881\\uA8B4-\\uA8C3\\uA952-\\uA953\\uA983\\uA9B4-\\uA9B5\\uA9BA-\\uA9BB\\uA9BE-\\uA9C0\\uAA2F-\\uAA30\\uAA33-\\uAA34\\uAA4D\\uAAEB\\uAAEE-\\uAAEF\\uAAF5\\uABE3-\\uABE4\\uABE6-\\uABE7\\uABE9-\\uABEA\\uABEC\\u{11000}\\u{11002}\\u{11082}\\u{110B0}-\\u{110B2}\\u{110B7}-\\u{110B8}\\u{1112C}\\u{11145}-\\u{11146}\\u{11182}\\u{111B3}-\\u{111B5}\\u{111BF}-\\u{111C0}\\u{111CE}\\u{1122C}-\\u{1122E}\\u{11232}-\\u{11233}\\u{11235}\\u{112E0}-\\u{112E2}\\u{11302}-\\u{11303}\\u{1133F}\\u{11341}-\\u{11344}\\u{11347}-\\u{11348}\\u{1134B}-\\u{1134D}\\u{11362}-\\u{11363}\\u{11435}-\\u{11437}\\u{11440}-\\u{11441}\\u{11445}\\u{114B1}-\\u{114B2}\\u{114B9}\\u{114BB}-\\u{114BC}\\u{114BE}\\u{114C1}\\u{115B0}-\\u{115B1}\\u{115B8}-\\u{115BB}\\u{115BE}\\u{11630}-\\u{11632}\\u{1163B}-\\u{1163C}\\u{1163E}\\u{116AC}\\u{116AE}-\\u{116AF}\\u{116B6}\\u{11726}\\u{1182C}-\\u{1182E}\\u{11838}\\u{11931}-\\u{11935}\\u{11937}-\\u{11938}\\u{1193D}\\u{11940}\\u{11942}\\u{119D1}-\\u{119D3}\\u{119DC}-\\u{119DF}\\u{119E4}\\u{11A39}\\u{11A57}-\\u{11A58}\\u{11A97}\\u{11C2F}\\u{11C3E}\\u{11CA9}\\u{11CB1}\\u{11CB4}\\u{11D8A}-\\u{11D8E}\\u{11D93}-\\u{11D94}\\u{11D96}\\u{11EF5}-\\u{11EF6}\\u{16F51}-\\u{16F87}\\u{16FF0}-\\u{16FF1}\\u{1D166}\\u{1D16D}]$/u\nconst reL = /^[\\u1100-\\u115F\\uA960-\\uA97C]$/u\nconst reV = /^[\\u1160-\\u11A7\\uD7B0-\\uD7C6]$/u\nconst reT = /^[\\u11A8-\\u11FF\\uD7CB-\\uD7FB]$/u\nconst reLV = /^[\\uAC00\\uAC1C\\uAC38\\uAC54\\uAC70\\uAC8C\\uACA8\\uACC4\\uACE0\\uACFC\\uAD18\\uAD34\\uAD50\\uAD6C\\uAD88\\uADA4\\uADC0\\uADDC\\uADF8\\uAE14\\uAE30\\uAE4C\\uAE68\\uAE84\\uAEA0\\uAEBC\\uAED8\\uAEF4\\uAF10\\uAF2C\\uAF48\\uAF64\\uAF80\\uAF9C\\uAFB8\\uAFD4\\uAFF0\\uB00C\\uB028\\uB044\\uB060\\uB07C\\uB098\\uB0B4\\uB0D0\\uB0EC\\uB108\\uB124\\uB140\\uB15C\\uB178\\uB194\\uB1B0\\uB1CC\\uB1E8\\uB204\\uB220\\uB23C\\uB258\\uB274\\uB290\\uB2AC\\uB2C8\\uB2E4\\uB300\\uB31C\\uB338\\uB354\\uB370\\uB38C\\uB3A8\\uB3C4\\uB3E0\\uB3FC\\uB418\\uB434\\uB450\\uB46C\\uB488\\uB4A4\\uB4C0\\uB4DC\\uB4F8\\uB514\\uB530\\uB54C\\uB568\\uB584\\uB5A0\\uB5BC\\uB5D8\\uB5F4\\uB610\\uB62C\\uB648\\uB664\\uB680\\uB69C\\uB6B8\\uB6D4\\uB6F0\\uB70C\\uB728\\uB744\\uB760\\uB77C\\uB798\\uB7B4\\uB7D0\\uB7EC\\uB808\\uB824\\uB840\\uB85C\\uB878\\uB894\\uB8B0\\uB8CC\\uB8E8\\uB904\\uB920\\uB93C\\uB958\\uB974\\uB990\\uB9AC\\uB9C8\\uB9E4\\uBA00\\uBA1C\\uBA38\\uBA54\\uBA70\\uBA8C\\uBAA8\\uBAC4\\uBAE0\\uBAFC\\uBB18\\uBB34\\uBB50\\uBB6C\\uBB88\\uBBA4\\uBBC0\\uBBDC\\uBBF8\\uBC14\\uBC30\\uBC4C\\uBC68\\uBC84\\uBCA0\\uBCBC\\uBCD8\\uBCF4\\uBD10\\uBD2C\\uBD48\\uBD64\\uBD80\\uBD9C\\uBDB8\\uBDD4\\uBDF0\\uBE0C\\uBE28\\uBE44\\uBE60\\uBE7C\\uBE98\\uBEB4\\uBED0\\uBEEC\\uBF08\\uBF24\\uBF40\\uBF5C\\uBF78\\uBF94\\uBFB0\\uBFCC\\uBFE8\\uC004\\uC020\\uC03C\\uC058\\uC074\\uC090\\uC0AC\\uC0C8\\uC0E4\\uC100\\uC11C\\uC138\\uC154\\uC170\\uC18C\\uC1A8\\uC1C4\\uC1E0\\uC1FC\\uC218\\uC234\\uC250\\uC26C\\uC288\\uC2A4\\uC2C0\\uC2DC\\uC2F8\\uC314\\uC330\\uC34C\\uC368\\uC384\\uC3A0\\uC3BC\\uC3D8\\uC3F4\\uC410\\uC42C\\uC448\\uC464\\uC480\\uC49C\\uC4B8\\uC4D4\\uC4F0\\uC50C\\uC528\\uC544\\uC560\\uC57C\\uC598\\uC5B4\\uC5D0\\uC5EC\\uC608\\uC624\\uC640\\uC65C\\uC678\\uC694\\uC6B0\\uC6CC\\uC6E8\\uC704\\uC720\\uC73C\\uC758\\uC774\\uC790\\uC7AC\\uC7C8\\uC7E4\\uC800\\uC81C\\uC838\\uC854\\uC870\\uC88C\\uC8A8\\uC8C4\\uC8E0\\uC8FC\\uC918\\uC934\\uC950\\uC96C\\uC988\\uC9A4\\uC9C0\\uC9DC\\uC9F8\\uCA14\\uCA30\\uCA4C\\uCA68\\uCA84\\uCAA0\\uCABC\\uCAD8\\uCAF4\\uCB10\\uCB2C\\uCB48\\uCB64\\uCB80\\uCB9C\\uCBB8\\uCBD4\\uCBF0\\uCC0C\\uCC28\\uCC44\\uCC60\\uCC7C\\uCC98\\uCCB4\\uCCD0\\uCCEC\\uCD08\\uCD24\\uCD40\\uCD5C\\uCD78\\uCD94\\uCDB0\\uCDCC\\uCDE8\\uCE04\\uCE20\\uCE3C\\uCE58\\uCE74\\uCE90\\uCEAC\\uCEC8\\uCEE4\\uCF00\\uCF1C\\uCF38\\uCF54\\uCF70\\uCF8C\\uCFA8\\uCFC4\\uCFE0\\uCFFC\\uD018\\uD034\\uD050\\uD06C\\uD088\\uD0A4\\uD0C0\\uD0DC\\uD0F8\\uD114\\uD130\\uD14C\\uD168\\uD184\\uD1A0\\uD1BC\\uD1D8\\uD1F4\\uD210\\uD22C\\uD248\\uD264\\uD280\\uD29C\\uD2B8\\uD2D4\\uD2F0\\uD30C\\uD328\\uD344\\uD360\\uD37C\\uD398\\uD3B4\\uD3D0\\uD3EC\\uD408\\uD424\\uD440\\uD45C\\uD478\\uD494\\uD4B0\\uD4CC\\uD4E8\\uD504\\uD520\\uD53C\\uD558\\uD574\\uD590\\uD5AC\\uD5C8\\uD5E4\\uD600\\uD61C\\uD638\\uD654\\uD670\\uD68C\\uD6A8\\uD6C4\\uD6E0\\uD6FC\\uD718\\uD734\\uD750\\uD76C\\uD788]$/u\nconst reLVT = /^[\\uAC01-\\uAC1B\\uAC1D-\\uAC37\\uAC39-\\uAC53\\uAC55-\\uAC6F\\uAC71-\\uAC8B\\uAC8D-\\uACA7\\uACA9-\\uACC3\\uACC5-\\uACDF\\uACE1-\\uACFB\\uACFD-\\uAD17\\uAD19-\\uAD33\\uAD35-\\uAD4F\\uAD51-\\uAD6B\\uAD6D-\\uAD87\\uAD89-\\uADA3\\uADA5-\\uADBF\\uADC1-\\uADDB\\uADDD-\\uADF7\\uADF9-\\uAE13\\uAE15-\\uAE2F\\uAE31-\\uAE4B\\uAE4D-\\uAE67\\uAE69-\\uAE83\\uAE85-\\uAE9F\\uAEA1-\\uAEBB\\uAEBD-\\uAED7\\uAED9-\\uAEF3\\uAEF5-\\uAF0F\\uAF11-\\uAF2B\\uAF2D-\\uAF47\\uAF49-\\uAF63\\uAF65-\\uAF7F\\uAF81-\\uAF9B\\uAF9D-\\uAFB7\\uAFB9-\\uAFD3\\uAFD5-\\uAFEF\\uAFF1-\\uB00B\\uB00D-\\uB027\\uB029-\\uB043\\uB045-\\uB05F\\uB061-\\uB07B\\uB07D-\\uB097\\uB099-\\uB0B3\\uB0B5-\\uB0CF\\uB0D1-\\uB0EB\\uB0ED-\\uB107\\uB109-\\uB123\\uB125-\\uB13F\\uB141-\\uB15B\\uB15D-\\uB177\\uB179-\\uB193\\uB195-\\uB1AF\\uB1B1-\\uB1CB\\uB1CD-\\uB1E7\\uB1E9-\\uB203\\uB205-\\uB21F\\uB221-\\uB23B\\uB23D-\\uB257\\uB259-\\uB273\\uB275-\\uB28F\\uB291-\\uB2AB\\uB2AD-\\uB2C7\\uB2C9-\\uB2E3\\uB2E5-\\uB2FF\\uB301-\\uB31B\\uB31D-\\uB337\\uB339-\\uB353\\uB355-\\uB36F\\uB371-\\uB38B\\uB38D-\\uB3A7\\uB3A9-\\uB3C3\\uB3C5-\\uB3DF\\uB3E1-\\uB3FB\\uB3FD-\\uB417\\uB419-\\uB433\\uB435-\\uB44F\\uB451-\\uB46B\\uB46D-\\uB487\\uB489-\\uB4A3\\uB4A5-\\uB4BF\\uB4C1-\\uB4DB\\uB4DD-\\uB4F7\\uB4F9-\\uB513\\uB515-\\uB52F\\uB531-\\uB54B\\uB54D-\\uB567\\uB569-\\uB583\\uB585-\\uB59F\\uB5A1-\\uB5BB\\uB5BD-\\uB5D7\\uB5D9-\\uB5F3\\uB5F5-\\uB60F\\uB611-\\uB62B\\uB62D-\\uB647\\uB649-\\uB663\\uB665-\\uB67F\\uB681-\\uB69B\\uB69D-\\uB6B7\\uB6B9-\\uB6D3\\uB6D5-\\uB6EF\\uB6F1-\\uB70B\\uB70D-\\uB727\\uB729-\\uB743\\uB745-\\uB75F\\uB761-\\uB77B\\uB77D-\\uB797\\uB799-\\uB7B3\\uB7B5-\\uB7CF\\uB7D1-\\uB7EB\\uB7ED-\\uB807\\uB809-\\uB823\\uB825-\\uB83F\\uB841-\\uB85B\\uB85D-\\uB877\\uB879-\\uB893\\uB895-\\uB8AF\\uB8B1-\\uB8CB\\uB8CD-\\uB8E7\\uB8E9-\\uB903\\uB905-\\uB91F\\uB921-\\uB93B\\uB93D-\\uB957\\uB959-\\uB973\\uB975-\\uB98F\\uB991-\\uB9AB\\uB9AD-\\uB9C7\\uB9C9-\\uB9E3\\uB9E5-\\uB9FF\\uBA01-\\uBA1B\\uBA1D-\\uBA37\\uBA39-\\uBA53\\uBA55-\\uBA6F\\uBA71-\\uBA8B\\uBA8D-\\uBAA7\\uBAA9-\\uBAC3\\uBAC5-\\uBADF\\uBAE1-\\uBAFB\\uBAFD-\\uBB17\\uBB19-\\uBB33\\uBB35-\\uBB4F\\uBB51-\\uBB6B\\uBB6D-\\uBB87\\uBB89-\\uBBA3\\uBBA5-\\uBBBF\\uBBC1-\\uBBDB\\uBBDD-\\uBBF7\\uBBF9-\\uBC13\\uBC15-\\uBC2F\\uBC31-\\uBC4B\\uBC4D-\\uBC67\\uBC69-\\uBC83\\uBC85-\\uBC9F\\uBCA1-\\uBCBB\\uBCBD-\\uBCD7\\uBCD9-\\uBCF3\\uBCF5-\\uBD0F\\uBD11-\\uBD2B\\uBD2D-\\uBD47\\uBD49-\\uBD63\\uBD65-\\uBD7F\\uBD81-\\uBD9B\\uBD9D-\\uBDB7\\uBDB9-\\uBDD3\\uBDD5-\\uBDEF\\uBDF1-\\uBE0B\\uBE0D-\\uBE27\\uBE29-\\uBE43\\uBE45-\\uBE5F\\uBE61-\\uBE7B\\uBE7D-\\uBE97\\uBE99-\\uBEB3\\uBEB5-\\uBECF\\uBED1-\\uBEEB\\uBEED-\\uBF07\\uBF09-\\uBF23\\uBF25-\\uBF3F\\uBF41-\\uBF5B\\uBF5D-\\uBF77\\uBF79-\\uBF93\\uBF95-\\uBFAF\\uBFB1-\\uBFCB\\uBFCD-\\uBFE7\\uBFE9-\\uC003\\uC005-\\uC01F\\uC021-\\uC03B\\uC03D-\\uC057\\uC059-\\uC073\\uC075-\\uC08F\\uC091-\\uC0AB\\uC0AD-\\uC0C7\\uC0C9-\\uC0E3\\uC0E5-\\uC0FF\\uC101-\\uC11B\\uC11D-\\uC137\\uC139-\\uC153\\uC155-\\uC16F\\uC171-\\uC18B\\uC18D-\\uC1A7\\uC1A9-\\uC1C3\\uC1C5-\\uC1DF\\uC1E1-\\uC1FB\\uC1FD-\\uC217\\uC219-\\uC233\\uC235-\\uC24F\\uC251-\\uC26B\\uC26D-\\uC287\\uC289-\\uC2A3\\uC2A5-\\uC2BF\\uC2C1-\\uC2DB\\uC2DD-\\uC2F7\\uC2F9-\\uC313\\uC315-\\uC32F\\uC331-\\uC34B\\uC34D-\\uC367\\uC369-\\uC383\\uC385-\\uC39F\\uC3A1-\\uC3BB\\uC3BD-\\uC3D7\\uC3D9-\\uC3F3\\uC3F5-\\uC40F\\uC411-\\uC42B\\uC42D-\\uC447\\uC449-\\uC463\\uC465-\\uC47F\\uC481-\\uC49B\\uC49D-\\uC4B7\\uC4B9-\\uC4D3\\uC4D5-\\uC4EF\\uC4F1-\\uC50B\\uC50D-\\uC527\\uC529-\\uC543\\uC545-\\uC55F\\uC561-\\uC57B\\uC57D-\\uC597\\uC599-\\uC5B3\\uC5B5-\\uC5CF\\uC5D1-\\uC5EB\\uC5ED-\\uC607\\uC609-\\uC623\\uC625-\\uC63F\\uC641-\\uC65B\\uC65D-\\uC677\\uC679-\\uC693\\uC695-\\uC6AF\\uC6B1-\\uC6CB\\uC6CD-\\uC6E7\\uC6E9-\\uC703\\uC705-\\uC71F\\uC721-\\uC73B\\uC73D-\\uC757\\uC759-\\uC773\\uC775-\\uC78F\\uC791-\\uC7AB\\uC7AD-\\uC7C7\\uC7C9-\\uC7E3\\uC7E5-\\uC7FF\\uC801-\\uC81B\\uC81D-\\uC837\\uC839-\\uC853\\uC855-\\uC86F\\uC871-\\uC88B\\uC88D-\\uC8A7\\uC8A9-\\uC8C3\\uC8C5-\\uC8DF\\uC8E1-\\uC8FB\\uC8FD-\\uC917\\uC919-\\uC933\\uC935-\\uC94F\\uC951-\\uC96B\\uC96D-\\uC987\\uC989-\\uC9A3\\uC9A5-\\uC9BF\\uC9C1-\\uC9DB\\uC9DD-\\uC9F7\\uC9F9-\\uCA13\\uCA15-\\uCA2F\\uCA31-\\uCA4B\\uCA4D-\\uCA67\\uCA69-\\uCA83\\uCA85-\\uCA9F\\uCAA1-\\uCABB\\uCABD-\\uCAD7\\uCAD9-\\uCAF3\\uCAF5-\\uCB0F\\uCB11-\\uCB2B\\uCB2D-\\uCB47\\uCB49-\\uCB63\\uCB65-\\uCB7F\\uCB81-\\uCB9B\\uCB9D-\\uCBB7\\uCBB9-\\uCBD3\\uCBD5-\\uCBEF\\uCBF1-\\uCC0B\\uCC0D-\\uCC27\\uCC29-\\uCC43\\uCC45-\\uCC5F\\uCC61-\\uCC7B\\uCC7D-\\uCC97\\uCC99-\\uCCB3\\uCCB5-\\uCCCF\\uCCD1-\\uCCEB\\uCCED-\\uCD07\\uCD09-\\uCD23\\uCD25-\\uCD3F\\uCD41-\\uCD5B\\uCD5D-\\uCD77\\uCD79-\\uCD93\\uCD95-\\uCDAF\\uCDB1-\\uCDCB\\uCDCD-\\uCDE7\\uCDE9-\\uCE03\\uCE05-\\uCE1F\\uCE21-\\uCE3B\\uCE3D-\\uCE57\\uCE59-\\uCE73\\uCE75-\\uCE8F\\uCE91-\\uCEAB\\uCEAD-\\uCEC7\\uCEC9-\\uCEE3\\uCEE5-\\uCEFF\\uCF01-\\uCF1B\\uCF1D-\\uCF37\\uCF39-\\uCF53\\uCF55-\\uCF6F\\uCF71-\\uCF8B\\uCF8D-\\uCFA7\\uCFA9-\\uCFC3\\uCFC5-\\uCFDF\\uCFE1-\\uCFFB\\uCFFD-\\uD017\\uD019-\\uD033\\uD035-\\uD04F\\uD051-\\uD06B\\uD06D-\\uD087\\uD089-\\uD0A3\\uD0A5-\\uD0BF\\uD0C1-\\uD0DB\\uD0DD-\\uD0F7\\uD0F9-\\uD113\\uD115-\\uD12F\\uD131-\\uD14B\\uD14D-\\uD167\\uD169-\\uD183\\uD185-\\uD19F\\uD1A1-\\uD1BB\\uD1BD-\\uD1D7\\uD1D9-\\uD1F3\\uD1F5-\\uD20F\\uD211-\\uD22B\\uD22D-\\uD247\\uD249-\\uD263\\uD265-\\uD27F\\uD281-\\uD29B\\uD29D-\\uD2B7\\uD2B9-\\uD2D3\\uD2D5-\\uD2EF\\uD2F1-\\uD30B\\uD30D-\\uD327\\uD329-\\uD343\\uD345-\\uD35F\\uD361-\\uD37B\\uD37D-\\uD397\\uD399-\\uD3B3\\uD3B5-\\uD3CF\\uD3D1-\\uD3EB\\uD3ED-\\uD407\\uD409-\\uD423\\uD425-\\uD43F\\uD441-\\uD45B\\uD45D-\\uD477\\uD479-\\uD493\\uD495-\\uD4AF\\uD4B1-\\uD4CB\\uD4CD-\\uD4E7\\uD4E9-\\uD503\\uD505-\\uD51F\\uD521-\\uD53B\\uD53D-\\uD557\\uD559-\\uD573\\uD575-\\uD58F\\uD591-\\uD5AB\\uD5AD-\\uD5C7\\uD5C9-\\uD5E3\\uD5E5-\\uD5FF\\uD601-\\uD61B\\uD61D-\\uD637\\uD639-\\uD653\\uD655-\\uD66F\\uD671-\\uD68B\\uD68D-\\uD6A7\\uD6A9-\\uD6C3\\uD6C5-\\uD6DF\\uD6E1-\\uD6FB\\uD6FD-\\uD717\\uD719-\\uD733\\uD735-\\uD74F\\uD751-\\uD76B\\uD76D-\\uD787\\uD789-\\uD7A3]$/u\nconst reExtPict = /^\\p{ExtPict}$/u\n\nconst getCodepointType = (char: string, code: number): CodepointType => {\n let type = CodepointType.Any\n if (char.search(reExtend) !== -1) {\n type |= CodepointType.Extend\n }\n if (code === 0x200d) {\n type |= CodepointType.ZWJ\n }\n if (code >= 0x1f1e6 && code <= 0x1f1ff) {\n type |= CodepointType.RI\n }\n if (char.search(rePrepend) !== -1) {\n type |= CodepointType.Prepend\n }\n if (char.search(reSpacingMark) !== -1) {\n type |= CodepointType.SpacingMark\n }\n if (char.search(reL) !== -1) {\n type |= CodepointType.L\n }\n if (char.search(reV) !== -1) {\n type |= CodepointType.V\n }\n if (char.search(reT) !== -1) {\n type |= CodepointType.T\n }\n if (char.search(reLV) !== -1) {\n type |= CodepointType.LV\n }\n if (char.search(reLVT) !== -1) {\n type |= CodepointType.LVT\n }\n if (char.search(reExtPict) !== -1) {\n type |= CodepointType.ExtPict\n }\n\n return type\n}\n\nfunction intersects(x: CodepointType, y: CodepointType) {\n return (x & y) !== 0\n}\n\nconst NonBoundaryPairs: [CodepointType, CodepointType][] = [\n // GB6\n [\n CodepointType.L,\n CodepointType.L | CodepointType.V | CodepointType.LV | CodepointType.LVT,\n ],\n // GB7\n [CodepointType.LV | CodepointType.V, CodepointType.V | CodepointType.T],\n // GB8\n [CodepointType.LVT | CodepointType.T, CodepointType.T],\n // GB9\n [CodepointType.Any, CodepointType.Extend | CodepointType.ZWJ],\n // GB9a\n [CodepointType.Any, CodepointType.SpacingMark],\n // GB9b\n [CodepointType.Prepend, CodepointType.Any],\n // GB11\n [CodepointType.ZWJ, CodepointType.ExtPict],\n // GB12 and GB13\n [CodepointType.RI, CodepointType.RI],\n]\n\nfunction isBoundaryPair(left: CodepointType, right: CodepointType) {\n return (\n NonBoundaryPairs.findIndex(\n r => intersects(left, r[0]) && intersects(right, r[1])\n ) === -1\n )\n}\n\nconst endingEmojiZWJ = /\\p{ExtPict}[\\p{Gr_Ext}\\p{EMod}]*\\u200D$/u\nconst endsWithEmojiZWJ = (str: string): boolean => {\n return str.search(endingEmojiZWJ) !== -1\n}\n\nconst endingRIs = /\\p{RI}+$/gu\nconst endsWithOddNumberOfRIs = (str: string): boolean => {\n const match = str.match(endingRIs)\n if (match === null) {\n return false\n } else {\n // A RI is represented by a surrogate pair.\n const numRIs = match[0].length / 2\n return numRIs % 2 === 1\n }\n}\n","import { isPlainObject } from 'is-plain-object'\nimport { Editor, Node, Path, Descendant, ExtendedType, Ancestor } from '..'\n\n/**\n * `Element` objects are a type of node in a Slate document that contain other\n * element nodes or text nodes. They can be either \"blocks\" or \"inlines\"\n * depending on the Slate editor's configuration.\n */\n\nexport interface BaseElement {\n children: Descendant[]\n}\n\nexport type Element = ExtendedType<'Element', BaseElement>\n\nexport interface ElementInterface {\n isAncestor: (value: any) => value is Ancestor\n isElement: (value: any) => value is Element\n isElementList: (value: any) => value is Element[]\n isElementProps: (props: any) => props is Partial<Element>\n isElementType: <T extends Element>(\n value: any,\n elementVal: string,\n elementKey?: string\n ) => value is T\n matches: (element: Element, props: Partial<Element>) => boolean\n}\n\n/**\n * Shared the function with isElementType utility\n */\nconst isElement = (value: any): value is Element => {\n return (\n isPlainObject(value) &&\n Node.isNodeList(value.children) &&\n !Editor.isEditor(value)\n )\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Element: ElementInterface = {\n /**\n * Check if a value implements the 'Ancestor' interface.\n */\n\n isAncestor(value: any): value is Ancestor {\n return isPlainObject(value) && Node.isNodeList(value.children)\n },\n\n /**\n * Check if a value implements the `Element` interface.\n */\n\n isElement,\n /**\n * Check if a value is an array of `Element` objects.\n */\n\n isElementList(value: any): value is Element[] {\n return Array.isArray(value) && value.every(val => Element.isElement(val))\n },\n\n /**\n * Check if a set of props is a partial of Element.\n */\n\n isElementProps(props: any): props is Partial<Element> {\n return (props as Partial<Element>).children !== undefined\n },\n\n /**\n * Check if a value implements the `Element` interface and has elementKey with selected value.\n * Default it check to `type` key value\n */\n\n isElementType: <T extends Element>(\n value: any,\n elementVal: string,\n elementKey: string = 'type'\n ): value is T => {\n return isElement(value) && value[elementKey] === elementVal\n },\n\n /**\n * Check if an element matches set of properties.\n *\n * Note: this checks custom properties, and it does not ensure that any\n * children are equivalent.\n */\n\n matches(element: Element, props: Partial<Element>): boolean {\n for (const key in props) {\n if (key === 'children') {\n continue\n }\n\n if (element[key] !== props[key]) {\n return false\n }\n }\n\n return true\n },\n}\n\n/**\n * `ElementEntry` objects refer to an `Element` and the `Path` where it can be\n * found inside a root node.\n */\n\nexport type ElementEntry = [Element, Path]\n","import { isPlainObject } from 'is-plain-object'\n\nimport {\n Ancestor,\n ExtendedType,\n Location,\n Node,\n NodeEntry,\n Operation,\n Path,\n PathRef,\n Point,\n PointRef,\n Range,\n RangeRef,\n Span,\n Text,\n} from '..'\nimport {\n DIRTY_PATHS,\n DIRTY_PATH_KEYS,\n NORMALIZING,\n PATH_REFS,\n POINT_REFS,\n RANGE_REFS,\n} from '../utils/weak-maps'\nimport {\n getWordDistance,\n getCharacterDistance,\n splitByCharacterDistance,\n} from '../utils/string'\nimport { Descendant } from './node'\nimport { Element } from './element'\nimport {\n LeafEdge,\n SelectionMode,\n TextDirection,\n TextUnit,\n TextUnitAdjustment,\n RangeDirection,\n MaximizeMode,\n} from './types'\n\nexport type BaseSelection = Range | null\n\nexport type Selection = ExtendedType<'Selection', BaseSelection>\n\nexport type EditorMarks = Omit<Text, 'text'>\n\n/**\n * The `Editor` interface stores all the state of a Slate editor. It is extended\n * by plugins that wish to add their own helpers and implement new behaviors.\n */\n\nexport interface BaseEditor {\n children: Descendant[]\n selection: Selection\n operations: Operation[]\n marks: EditorMarks | null\n\n // Schema-specific node behaviors.\n isInline: (element: Element) => boolean\n isVoid: (element: Element) => boolean\n normalizeNode: (entry: NodeEntry) => void\n onChange: () => void\n\n // Overrideable core actions.\n addMark: (key: string, value: any) => void\n apply: (operation: Operation) => void\n deleteBackward: (unit: TextUnit) => void\n deleteForward: (unit: TextUnit) => void\n deleteFragment: (direction?: TextDirection) => void\n getFragment: () => Descendant[]\n insertBreak: () => void\n insertSoftBreak: () => void\n insertFragment: (fragment: Node[]) => void\n insertNode: (node: Node) => void\n insertText: (text: string) => void\n removeMark: (key: string) => void\n getDirtyPaths: (op: Operation) => Path[]\n}\n\nexport type Editor = ExtendedType<'Editor', BaseEditor>\n\nexport interface EditorAboveOptions<T extends Ancestor> {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n voids?: boolean\n}\n\nexport interface EditorAfterOptions {\n distance?: number\n unit?: TextUnitAdjustment\n voids?: boolean\n}\n\nexport interface EditorBeforeOptions {\n distance?: number\n unit?: TextUnitAdjustment\n voids?: boolean\n}\n\nexport interface EditorDirectedDeletionOptions {\n unit?: TextUnit\n}\n\nexport interface EditorFragmentDeletionOptions {\n direction?: TextDirection\n}\n\nexport interface EditorLeafOptions {\n depth?: number\n edge?: LeafEdge\n}\n\nexport interface EditorLevelsOptions<T extends Node> {\n at?: Location\n match?: NodeMatch<T>\n reverse?: boolean\n voids?: boolean\n}\n\nexport interface EditorNextOptions<T extends Descendant> {\n at?: Location\n match?: NodeMatch<T>\n mode?: SelectionMode\n voids?: boolean\n}\n\nexport interface EditorNodeOptions {\n depth?: number\n edge?: LeafEdge\n}\n\nexport interface EditorNodesOptions<T extends Node> {\n at?: Location | Span\n match?: NodeMatch<T>\n mode?: SelectionMode\n universal?: boolean\n reverse?: boolean\n voids?: boolean\n}\n\nexport interface EditorNormalizeOptions {\n force?: boolean\n}\n\nexport interface EditorParentOptions {\n depth?: number\n edge?: LeafEdge\n}\n\nexport interface EditorPathOptions {\n depth?: number\n edge?: LeafEdge\n}\n\nexport interface EditorPathRefOptions {\n affinity?: TextDirection | null\n}\n\nexport interface EditorPointOptions {\n edge?: LeafEdge\n}\n\nexport interface EditorPointRefOptions {\n affinity?: TextDirection | null\n}\n\nexport interface EditorPositionsOptions {\n at?: Location\n unit?: TextUnitAdjustment\n reverse?: boolean\n voids?: boolean\n}\n\nexport interface EditorPreviousOptions<T extends Node> {\n at?: Location\n match?: NodeMatch<T>\n mode?: SelectionMode\n voids?: boolean\n}\n\nexport interface EditorRangeRefOptions {\n affinity?: RangeDirection | null\n}\n\nexport interface EditorStringOptions {\n voids?: boolean\n}\n\nexport interface EditorUnhangRangeOptions {\n voids?: boolean\n}\n\nexport interface EditorVoidOptions {\n at?: Location\n mode?: MaximizeMode\n voids?: boolean\n}\n\nexport interface EditorInterface {\n above: <T extends Ancestor>(\n editor: Editor,\n options?: EditorAboveOptions<T>\n ) => NodeEntry<T> | undefined\n addMark: (editor: Editor, key: string, value: any) => void\n after: (\n editor: Editor,\n at: Location,\n options?: EditorAfterOptions\n ) => Point | undefined\n before: (\n editor: Editor,\n at: Location,\n options?: EditorBeforeOptions\n ) => Point | undefined\n deleteBackward: (\n editor: Editor,\n options?: EditorDirectedDeletionOptions\n ) => void\n deleteForward: (\n editor: Editor,\n options?: EditorDirectedDeletionOptions\n ) => void\n deleteFragment: (\n editor: Editor,\n options?: EditorFragmentDeletionOptions\n ) => void\n edges: (editor: Editor, at: Location) => [Point, Point]\n end: (editor: Editor, at: Location) => Point\n first: (editor: Editor, at: Location) => NodeEntry\n fragment: (editor: Editor, at: Location) => Descendant[]\n hasBlocks: (editor: Editor, element: Element) => boolean\n hasInlines: (editor: Editor, element: Element) => boolean\n hasPath: (editor: Editor, path: Path) => boolean\n hasTexts: (editor: Editor, element: Element) => boolean\n insertBreak: (editor: Editor) => void\n insertSoftBreak: (editor: Editor) => void\n insertFragment: (editor: Editor, fragment: Node[]) => void\n insertNode: (editor: Editor, node: Node) => void\n insertText: (editor: Editor, text: string) => void\n isBlock: (editor: Editor, value: any) => value is Element\n isEditor: (value: any) => value is Editor\n isEnd: (editor: Editor, point: Point, at: Location) => boolean\n isEdge: (editor: Editor, point: Point, at: Location) => boolean\n isEmpty: (editor: Editor, element: Element) => boolean\n isInline: (editor: Editor, value: any) => value is Element\n isNormalizing: (editor: Editor) => boolean\n isStart: (editor: Editor, point: Point, at: Location) => boolean\n isVoid: (editor: Editor, value: any) => value is Element\n last: (editor: Editor, at: Location) => NodeEntry\n leaf: (\n editor: Editor,\n at: Location,\n options?: EditorLeafOptions\n ) => NodeEntry<Text>\n levels: <T extends Node>(\n editor: Editor,\n options?: EditorLevelsOptions<T>\n ) => Generator<NodeEntry<T>, void, undefined>\n marks: (editor: Editor) => Omit<Text, 'text'> | null\n next: <T extends Descendant>(\n editor: Editor,\n options?: EditorNextOptions<T>\n ) => NodeEntry<T> | undefined\n node: (editor: Editor, at: Location, options?: EditorNodeOptions) => NodeEntry\n nodes: <T extends Node>(\n editor: Editor,\n options?: EditorNodesOptions<T>\n ) => Generator<NodeEntry<T>, void, undefined>\n normalize: (editor: Editor, options?: EditorNormalizeOptions) => void\n parent: (\n editor: Editor,\n at: Location,\n options?: EditorParentOptions\n ) => NodeEntry<Ancestor>\n path: (editor: Editor, at: Location, options?: EditorPathOptions) => Path\n pathRef: (\n editor: Editor,\n path: Path,\n options?: EditorPathRefOptions\n ) => PathRef\n pathRefs: (editor: Editor) => Set<PathRef>\n point: (editor: Editor, at: Location, options?: EditorPointOptions) => Point\n pointRef: (\n editor: Editor,\n point: Point,\n options?: EditorPointRefOptions\n ) => PointRef\n pointRefs: (editor: Editor) => Set<PointRef>\n positions: (\n editor: Editor,\n options?: EditorPositionsOptions\n ) => Generator<Point, void, undefined>\n previous: <T extends Node>(\n editor: Editor,\n options?: EditorPreviousOptions<T>\n ) => NodeEntry<T> | undefined\n range: (editor: Editor, at: Location, to?: Location) => Range\n rangeRef: (\n editor: Editor,\n range: Range,\n options?: EditorRangeRefOptions\n ) => RangeRef\n rangeRefs: (editor: Editor) => Set<RangeRef>\n removeMark: (editor: Editor, key: string) => void\n setNormalizing: (editor: Editor, isNormalizing: boolean) => void\n start: (editor: Editor, at: Location) => Point\n string: (\n editor: Editor,\n at: Location,\n options?: EditorStringOptions\n ) => string\n unhangRange: (\n editor: Editor,\n range: Range,\n options?: EditorUnhangRangeOptions\n ) => Range\n void: (\n editor: Editor,\n options?: EditorVoidOptions\n ) => NodeEntry<Element> | undefined\n withoutNormalizing: (editor: Editor, fn: () => void) => void\n}\n\nconst IS_EDITOR_CACHE = new WeakMap<object, boolean>()\n\n// eslint-disable-next-line no-redeclare\nexport const Editor: EditorInterface = {\n /**\n * Get the ancestor above a location in the document.\n */\n\n above<T extends Ancestor>(\n editor: Editor,\n options: EditorAboveOptions<T> = {}\n ): NodeEntry<T> | undefined {\n const {\n voids = false,\n mode = 'lowest',\n at = editor.selection,\n match,\n } = options\n\n if (!at) {\n return\n }\n\n const path = Editor.path(editor, at)\n const reverse = mode === 'lowest'\n\n for (const [n, p] of Editor.levels(editor, {\n at: path,\n voids,\n match,\n reverse,\n })) {\n if (!Text.isText(n) && !Path.equals(path, p)) {\n return [n, p]\n }\n }\n },\n\n /**\n * Add a custom property to the leaf text nodes in the current selection.\n *\n * If the selection is currently collapsed, the marks will be added to the\n * `editor.marks` property instead, and applied when text is inserted next.\n */\n\n addMark(editor: Editor, key: string, value: any): void {\n editor.addMark(key, value)\n },\n\n /**\n * Get the point after a location.\n */\n\n after(\n editor: Editor,\n at: Location,\n options: EditorAfterOptions = {}\n ): Point | undefined {\n const anchor = Editor.point(editor, at, { edge: 'end' })\n const focus = Editor.end(editor, [])\n const range = { anchor, focus }\n const { distance = 1 } = options\n let d = 0\n let target\n\n for (const p of Editor.positions(editor, {\n ...options,\n at: range,\n })) {\n if (d > distance) {\n break\n }\n\n if (d !== 0) {\n target = p\n }\n\n d++\n }\n\n return target\n },\n\n /**\n * Get the point before a location.\n */\n\n before(\n editor: Editor,\n at: Location,\n options: EditorBeforeOptions = {}\n ): Point | undefined {\n const anchor = Editor.start(editor, [])\n const focus = Editor.point(editor, at, { edge: 'start' })\n const range = { anchor, focus }\n const { distance = 1 } = options\n let d = 0\n let target\n\n for (const p of Editor.positions(editor, {\n ...options,\n at: range,\n reverse: true,\n })) {\n if (d > distance) {\n break\n }\n\n if (d !== 0) {\n target = p\n }\n\n d++\n }\n\n return target\n },\n\n /**\n * Delete content in the editor backward from the current selection.\n */\n\n deleteBackward(\n editor: Editor,\n options: EditorDirectedDeletionOptions = {}\n ): void {\n const { unit = 'character' } = options\n editor.deleteBackward(unit)\n },\n\n /**\n * Delete content in the editor forward from the current selection.\n */\n\n deleteForward(\n editor: Editor,\n options: EditorDirectedDeletionOptions = {}\n ): void {\n const { unit = 'character' } = options\n editor.deleteForward(unit)\n },\n\n /**\n * Delete the content in the current selection.\n */\n\n deleteFragment(\n editor: Editor,\n options: EditorFragmentDeletionOptions = {}\n ): void {\n const { direction = 'forward' } = options\n editor.deleteFragment(direction)\n },\n\n /**\n * Get the start and end points of a location.\n */\n\n edges(editor: Editor, at: Location): [Point, Point] {\n return [Editor.start(editor, at), Editor.end(editor, at)]\n },\n\n /**\n * Get the end point of a location.\n */\n\n end(editor: Editor, at: Location): Point {\n return Editor.point(editor, at, { edge: 'end' })\n },\n\n /**\n * Get the first node at a location.\n */\n\n first(editor: Editor, at: Location): NodeEntry {\n const path = Editor.path(editor, at, { edge: 'start' })\n return Editor.node(editor, path)\n },\n\n /**\n * Get the fragment at a location.\n */\n\n fragment(editor: Editor, at: Location): Descendant[] {\n const range = Editor.range(editor, at)\n const fragment = Node.fragment(editor, range)\n return fragment\n },\n /**\n * Check if a node has block children.\n */\n\n hasBlocks(editor: Editor, element: Element): boolean {\n return element.children.some(n => Editor.isBlock(editor, n))\n },\n\n /**\n * Check if a node has inline and text children.\n */\n\n hasInlines(editor: Editor, element: Element): boolean {\n return element.children.some(\n n => Text.isText(n) || Editor.isInline(editor, n)\n )\n },\n\n /**\n * Check if a node has text children.\n */\n\n hasTexts(editor: Editor, element: Element): boolean {\n return element.children.every(n => Text.isText(n))\n },\n\n /**\n * Insert a block break at the current selection.\n *\n * If the selection is currently expanded, it will be deleted first.\n */\n\n insertBreak(editor: Editor): void {\n editor.insertBreak()\n },\n\n /**\n * Insert a soft break at the current selection.\n *\n * If the selection is currently expanded, it will be deleted first.\n */\n\n insertSoftBreak(editor: Editor): void {\n editor.insertSoftBreak()\n },\n\n /**\n * Insert a fragment at the current selection.\n *\n * If the selection is currently expanded, it will be deleted first.\n */\n\n insertFragment(editor: Editor, fragment: Node[]): void {\n editor.insertFragment(fragment)\n },\n\n /**\n * Insert a node at the current selection.\n *\n * If the selection is currently expanded, it will be deleted first.\n */\n\n insertNode(editor: Editor, node: Node): void {\n editor.insertNode(node)\n },\n\n /**\n * Insert text at the current selection.\n *\n * If the selection is currently expanded, it will be deleted first.\n */\n\n insertText(editor: Editor, text: string): void {\n editor.insertText(text)\n },\n\n /**\n * Check if a value is a block `Element` object.\n */\n\n isBlock(editor: Editor, value: any): value is Element {\n return Element.isElement(value) && !editor.isInline(value)\n },\n\n /**\n * Check if a value is an `Editor` object.\n */\n\n isEditor(value: any): value is Editor {\n const cachedIsEditor = IS_EDITOR_CACHE.get(value)\n if (cachedIsEditor !== undefined) {\n return cachedIsEditor\n }\n\n if (!isPlainObject(value)) {\n return false\n }\n\n const isEditor =\n typeof value.addMark === 'function' &&\n typeof value.apply === 'function' &&\n typeof value.deleteBackward === 'function' &&\n typeof value.deleteForward === 'function' &&\n typeof value.deleteFragment === 'function' &&\n typeof value.insertBreak === 'function' &&\n typeof value.insertSoftBreak === 'function' &&\n typeof value.insertFragment === 'function' &&\n typeof value.insertNode === 'function' &&\n typeof value.insertText === 'function' &&\n typeof value.isInline === 'function' &&\n typeof value.isVoid === 'function' &&\n typeof value.normalizeNode === 'function' &&\n typeof value.onChange === 'function' &&\n typeof value.removeMark === 'function' &&\n typeof value.getDirtyPaths === 'function' &&\n (value.marks === null || isPlainObject(value.marks)) &&\n (value.selection === null || Range.isRange(value.selection)) &&\n Node.isNodeList(value.children) &&\n Operation.isOperationList(value.operations)\n IS_EDITOR_CACHE.set(value, isEditor)\n return isEditor\n },\n\n /**\n * Check if a point is the end point of a location.\n */\n\n isEnd(editor: Editor, point: Point, at: Location): boolean {\n const end = Editor.end(editor, at)\n return Point.equals(point, end)\n },\n\n /**\n * Check if a point is an edge of a location.\n */\n\n isEdge(editor: Editor, point: Point, at: Location): boolean {\n return Editor.isStart(editor, point, at) || Editor.isEnd(editor, point, at)\n },\n\n /**\n * Check if an element is empty, accounting for void nodes.\n */\n\n isEmpty(editor: Editor, element: Element): boolean {\n const { children } = element\n const [first] = children\n return (\n children.length === 0 ||\n (children.length === 1 &&\n Text.isText(first) &&\n first.text === '' &&\n !editor.isVoid(element))\n )\n },\n\n /**\n * Check if a value is an inline `Element` object.\n */\n\n isInline(editor: Editor, value: any): value is Element {\n return Element.isElement(value) && editor.isInline(value)\n },\n\n /**\n * Check if the editor is currently normalizing after each operation.\n */\n\n isNormalizing(editor: Editor): boolean {\n const isNormalizing = NORMALIZING.get(editor)\n return isNormalizing === undefined ? true : isNormalizing\n },\n\n /**\n * Check if a point is the start point of a location.\n */\n\n isStart(editor: Editor, point: Point, at: Location): boolean {\n // PERF: If the offset isn't `0` we know it's not the start.\n if (point.offset !== 0) {\n return false\n }\n\n const start = Editor.start(editor, at)\n return Point.equals(point, start)\n },\n\n /**\n * Check if a value is a void `Element` object.\n */\n\n isVoid(editor: Editor, value: any): value is Element {\n return Element.isElement(value) && editor.isVoid(value)\n },\n\n /**\n * Get the last node at a location.\n */\n\n last(editor: Editor, at: Location): NodeEntry {\n const path = Editor.path(editor, at, { edge: 'end' })\n return Editor.node(editor, path)\n },\n\n /**\n * Get the leaf text node at a location.\n */\n\n leaf(\n editor: Editor,\n at: Location,\n options: EditorLeafOptions = {}\n ): NodeEntry<Text> {\n const path = Editor.path(editor, at, options)\n const node = Node.leaf(editor, path)\n return [node, path]\n },\n\n /**\n * Iterate through all of the levels at a location.\n */\n\n *levels<T extends Node>(\n editor: Editor,\n options: EditorLevelsOptions<T> = {}\n ): Generator<NodeEntry<T>, void, undefined> {\n const { at = editor.selection, reverse = false, voids = false } = options\n let { match } = options\n\n if (match == null) {\n match = () => true\n }\n\n if (!at) {\n return\n }\n\n const levels: NodeEntry<T>[] = []\n const path = Editor.path(editor, at)\n\n for (const [n, p] of Node.levels(editor, path)) {\n if (!match(n, p)) {\n continue\n }\n\n levels.push([n, p])\n\n if (!voids && Editor.isVoid(editor, n)) {\n break\n }\n }\n\n if (reverse) {\n levels.reverse()\n }\n\n yield* levels\n },\n\n /**\n * Get the marks that would be added to text at the current selection.\n */\n\n marks(editor: Editor): Omit<Text, 'text'> | null {\n const { marks, selection } = editor\n\n if (!selection) {\n return null\n }\n\n if (marks) {\n return marks\n }\n\n if (Range.isExpanded(selection)) {\n const [match] = Editor.nodes(editor, { match: Text.isText })\n\n if (match) {\n const [node] = match as NodeEntry<Text>\n const { text, ...rest } = node\n return rest\n } else {\n return {}\n }\n }\n\n const { anchor } = selection\n const { path } = anchor\n let [node] = Editor.leaf(editor, path)\n\n if (anchor.offset === 0) {\n const prev = Editor.previous(editor, { at: path, match: Text.isText })\n const block = Editor.above(editor, {\n match: n => Editor.isBlock(editor, n),\n })\n\n if (prev && block) {\n const [prevNode, prevPath] = prev\n const [, blockPath] = block\n\n if (Path.isAncestor(blockPath, prevPath)) {\n node = prevNode as Text\n }\n }\n }\n\n const { text, ...rest } = node\n return rest\n },\n\n /**\n * Get the matching node in the branch of the document after a location.\n */\n\n next<T extends Descendant>(\n editor: Editor,\n options: EditorNextOptions<T> = {}\n ): NodeEntry<T> | undefined {\n const { mode = 'lowest', voids = false } = options\n let { match, at = editor.selection } = options\n\n if (!at) {\n return\n }\n\n const pointAfterLocation = Editor.after(editor, at, { voids })\n\n if (!pointAfterLocation) return\n\n const [, to] = Editor.last(editor, [])\n\n const span: Span = [pointAfterLocation.path, to]\n\n if (Path.isPath(at) && at.length === 0) {\n throw new Error(`Cannot get the next node from the root node!`)\n }\n\n if (match == null) {\n if (Path.isPath(at)) {\n const [parent] = Editor.parent(editor, at)\n match = n => parent.children.includes(n)\n } else {\n match = () => true\n }\n }\n\n const [next] = Editor.nodes(editor, { at: span, match, mode, voids })\n return next\n },\n\n /**\n * Get the node at a location.\n */\n\n node(\n editor: Editor,\n at: Location,\n options: EditorNodeOptions = {}\n ): NodeEntry {\n const path = Editor.path(editor, at, options)\n const node = Node.get(editor, path)\n return [node, path]\n },\n\n /**\n * Iterate through all of the nodes in the Editor.\n */\n\n *nodes<T extends Node>(\n editor: Editor,\n options: EditorNodesOptions<T> = {}\n ): Generator<NodeEntry<T>, void, undefined> {\n const {\n at = editor.selection,\n mode = 'all',\n universal = false,\n reverse = false,\n voids = false,\n } = options\n let { match } = options\n\n if (!match) {\n match = () => true\n }\n\n if (!at) {\n return\n }\n\n let from\n let to\n\n if (Span.isSpan(at)) {\n from = at[0]\n to = at[1]\n } else {\n const first = Editor.path(editor, at, { edge: 'start' })\n const last = Editor.path(editor, at, { edge: 'end' })\n from = reverse ? last : first\n to = reverse ? first : last\n }\n\n const nodeEntries = Node.nodes(editor, {\n reverse,\n from,\n to,\n pass: ([n]) => (voids ? false : Editor.isVoid(editor, n)),\n })\n\n const matches: NodeEntry<T>[] = []\n let hit: NodeEntry<T> | undefined\n\n for (const [node, path] of nodeEntries) {\n const isLower = hit && Path.compare(path, hit[1]) === 0\n\n // In highest mode any node lower than the last hit is not a match.\n if (mode === 'highest' && isLower) {\n continue\n }\n\n if (!match(node, path)) {\n // If we've arrived at a leaf text node that is not lower than the last\n // hit, then we've found a branch that doesn't include a match, which\n // means the match is not universal.\n if (universal && !isLower && Text.isText(node)) {\n return\n } else {\n continue\n }\n }\n\n // If there's a match and it's lower than the last, update the hit.\n if (mode === 'lowest' && isLower) {\n hit = [node, path]\n continue\n }\n\n // In lowest mode we emit the last hit, once it's guaranteed lowest.\n const emit: NodeEntry<T> | undefined =\n mode === 'lowest' ? hit : [node, path]\n\n if (emit) {\n if (universal) {\n matches.push(emit)\n } else {\n yield emit\n }\n }\n\n hit = [node, path]\n }\n\n // Since lowest is always emitting one behind, catch up at the end.\n if (mode === 'lowest' && hit) {\n if (universal) {\n matches.push(hit)\n } else {\n yield hit\n }\n }\n\n // Universal defers to ensure that the match occurs in every branch, so we\n // yield all of the matches after iterating.\n if (universal) {\n yield* matches\n }\n },\n /**\n * Normalize any dirty objects in the editor.\n */\n\n normalize(editor: Editor, options: EditorNormalizeOptions = {}): void {\n const { force = false } = options\n const getDirtyPaths = (editor: Editor) => {\n return DIRTY_PATHS.get(editor) || []\n }\n\n const getDirtyPathKeys = (editor: Editor) => {\n return DIRTY_PATH_KEYS.get(editor) || new Set()\n }\n\n const popDirtyPath = (editor: Editor): Path => {\n const path = getDirtyPaths(editor).pop()!\n const key = path.join(',')\n getDirtyPathKeys(editor).delete(key)\n return path\n }\n\n if (!Editor.isNormalizing(editor)) {\n return\n }\n\n if (force) {\n const allPaths = Array.from(Node.nodes(editor), ([, p]) => p)\n const allPathKeys = new Set(allPaths.map(p => p.join(',')))\n DIRTY_PATHS.set(editor, allPaths)\n DIRTY_PATH_KEYS.set(editor, allPathKeys)\n }\n\n if (getDirtyPaths(editor).length === 0) {\n return\n }\n\n Editor.withoutNormalizing(editor, () => {\n /*\n Fix dirty elements with no children.\n editor.normalizeNode() does fix this, but some normalization fixes also require it to work.\n Running an initial pass avoids the catch-22 race condition.\n */\n for (const dirtyPath of getDirtyPaths(editor)) {\n if (Node.has(editor, dirtyPath)) {\n const entry = Editor.node(editor, dirtyPath)\n const [node, _] = entry\n\n /*\n The default normalizer inserts an empty text node in this scenario, but it can be customised.\n So there is some risk here.\n\n As long as the normalizer only inserts child nodes for this case it is safe to do in any order;\n by definition adding children to an empty node can't cause other paths to change.\n */\n if (Element.isElement(node) && node.children.length === 0) {\n editor.normalizeNode(entry)\n }\n }\n }\n\n const max = getDirtyPaths(editor).length * 42 // HACK: better way?\n let m = 0\n\n while (getDirtyPaths(editor).length !== 0) {\n if (m > max) {\n throw new Error(`\n Could not completely normalize the editor after ${max} iterations! This is usually due to incorrect normalization logic that leaves a node in an invalid state.\n `)\n }\n\n const dirtyPath = popDirtyPath(editor)\n\n // If the node doesn't exist in the tree, it does not need to be normalized.\n if (Node.has(editor, dirtyPath)) {\n const entry = Editor.node(editor, dirtyPath)\n editor.normalizeNode(entry)\n }\n m++\n }\n })\n },\n\n /**\n * Get the parent node of a location.\n */\n\n parent(\n editor: Editor,\n at: Location,\n options: EditorParentOptions = {}\n ): NodeEntry<Ancestor> {\n const path = Editor.path(editor, at, options)\n const parentPath = Path.parent(path)\n const entry = Editor.node(editor, parentPath)\n return entry as NodeEntry<Ancestor>\n },\n\n /**\n * Get the path of a location.\n */\n\n path(editor: Editor, at: Location, options: EditorPathOptions = {}): Path {\n const { depth, edge } = options\n\n if (Path.isPath(at)) {\n if (edge === 'start') {\n const [, firstPath] = Node.first(editor, at)\n at = firstPath\n } else if (edge === 'end') {\n const [, lastPath] = Node.last(editor, at)\n at = lastPath\n }\n }\n\n if (Range.isRange(at)) {\n if (edge === 'start') {\n at = Range.start(at)\n } else if (edge === 'end') {\n at = Range.end(at)\n } else {\n at = Path.common(at.anchor.path, at.focus.path)\n }\n }\n\n if (Point.isPoint(at)) {\n at = at.path\n }\n\n if (depth != null) {\n at = at.slice(0, depth)\n }\n\n return at\n },\n\n hasPath(editor: Editor, path: Path): boolean {\n return Node.has(editor, path)\n },\n\n /**\n * Create a mutable ref for a `Path` object, which will stay in sync as new\n * operations are applied to the editor.\n */\n\n pathRef(\n editor: Editor,\n path: Path,\n options: EditorPathRefOptions = {}\n ): PathRef {\n const { affinity = 'forward' } = options\n const ref: PathRef = {\n current: path,\n affinity,\n unref() {\n const { current } = ref\n const pathRefs = Editor.pathRefs(editor)\n pathRefs.delete(ref)\n ref.current = null\n return current\n },\n }\n\n const refs = Editor.pathRefs(editor)\n refs.add(ref)\n return ref\n },\n\n /**\n * Get the set of currently tracked path refs of the editor.\n */\n\n pathRefs(editor: Editor): Set<PathRef> {\n let refs = PATH_REFS.get(editor)\n\n if (!refs) {\n refs = new Set()\n PATH_REFS.set(editor, refs)\n }\n\n return refs\n },\n\n /**\n * Get the start or end point of a location.\n */\n\n point(editor: Editor, at: Location, options: EditorPointOptions = {}): Point {\n const { edge = 'start' } = options\n\n if (Path.isPath(at)) {\n let path\n\n if (edge === 'end') {\n const [, lastPath] = Node.last(editor, at)\n path = lastPath\n } else {\n const [, firstPath] = Node.first(editor, at)\n path = firstPath\n }\n\n const node = Node.get(editor, path)\n\n if (!Text.isText(node)) {\n throw new Error(\n `Cannot get the ${edge} point in the node at path [${at}] because it has no ${edge} text node.`\n )\n }\n\n return { path, offset: edge === 'end' ? node.text.length : 0 }\n }\n\n if (Range.isRange(at)) {\n const [start, end] = Range.edges(at)\n return edge === 'start' ? start : end\n }\n\n return at\n },\n\n /**\n * Create a mutable ref for a `Point` object, which will stay in sync as new\n * operations are applied to the editor.\n */\n\n pointRef(\n editor: Editor,\n point: Point,\n options: EditorPointRefOptions = {}\n ): PointRef {\n const { affinity = 'forward' } = options\n const ref: PointRef = {\n current: point,\n affinity,\n unref() {\n const { current } = ref\n const pointRefs = Editor.pointRefs(editor)\n pointRefs.delete(ref)\n ref.current = null\n return current\n },\n }\n\n const refs = Editor.pointRefs(editor)\n refs.add(ref)\n return ref\n },\n\n /**\n * Get the set of currently tracked point refs of the editor.\n */\n\n pointRefs(editor: Editor): Set<PointRef> {\n let refs = POINT_REFS.get(editor)\n\n if (!refs) {\n refs = new Set()\n POINT_REFS.set(editor, refs)\n }\n\n return refs\n },\n\n /**\n * Return all the positions in `at` range where a `Point` can be placed.\n *\n * By default, moves forward by individual offsets at a time, but\n * the `unit` option can be used to to move by character, word, line, or block.\n *\n * The `reverse` option can be used to change iteration direction.\n *\n * Note: By default void nodes are treated as a single point and iteration\n * will not happen inside their content unless you pass in true for the\n * `voids` option, then iteration will occur.\n */\n\n *positions(\n editor: Editor,\n options: EditorPositionsOptions = {}\n ): Generator<Point, void, undefined> {\n const {\n at = editor.selection,\n unit = 'offset',\n reverse = false,\n voids = false,\n } = options\n\n if (!at) {\n return\n }\n\n /**\n * Algorithm notes:\n *\n * Each step `distance` is dynamic depending on the underlying text\n * and the `unit` specified. Each step, e.g., a line or word, may\n * span multiple text nodes, so we iterate through the text both on\n * two levels in step-sync:\n *\n * `leafText` stores the text on a text leaf level, and is advanced\n * through using the counters `leafTextOffset` and `leafTextRemaining`.\n *\n * `blockText` stores the text on a block level, and is shortened\n * by `distance` every time it is advanced.\n *\n * We only maintain a window of one blockText and one leafText because\n * a block node always appears before all of its leaf nodes.\n */\n\n const range = Editor.range(editor, at)\n const [start, end] = Range.edges(range)\n const first = reverse ? end : start\n let isNewBlock = false\n let blockText = ''\n let distance = 0 // Distance for leafText to catch up to blockText.\n let leafTextRemaining = 0\n let leafTextOffset = 0\n\n // Iterate through all nodes in range, grabbing entire textual content\n // of block nodes in blockText, and text nodes in leafText.\n // Exploits the fact that nodes are sequenced in such a way that we first\n // encounter the block node, then all of its text nodes, so when iterating\n // through the blockText and leafText we just need to remember a window of\n // one block node and leaf node, respectively.\n for (const [node, path] of Editor.nodes(editor, { at, reverse, voids })) {\n /*\n * ELEMENT NODE - Yield position(s) for voids, collect blockText for blocks\n */\n if (Element.isElement(node)) {\n // Void nodes are a special case, so by default we will always\n // yield their first point. If the `voids` option is set to true,\n // then we will iterate over their content.\n if (!voids && editor.isVoid(node)) {\n yield Editor.start(editor, path)\n continue\n }\n\n // Inline element nodes are ignored as they don't themselves\n // contribute to `blockText` or `leafText` - their parent and\n // children do.\n if (editor.isInline(node)) continue\n\n // Block element node - set `blockText` to its text content.\n if (Editor.hasInlines(editor, node)) {\n // We always exhaust block nodes before encountering a new one:\n // console.assert(blockText === '',\n // `blockText='${blockText}' - `+\n // `not exhausted before new block node`, path)\n\n // Ensure range considered is capped to `range`, in the\n // start/end edge cases where block extends beyond range.\n // Equivalent to this, but presumably more performant:\n // blockRange = Editor.range(editor, ...Editor.edges(editor, path))\n // blockRange = Range.intersection(range, blockRange) // intersect\n // blockText = Editor.string(editor, blockRange, { voids })\n const e = Path.isAncestor(path, end.path)\n ? end\n : Editor.end(editor, path)\n const s = Path.isAncestor(path, start.path)\n ? start\n : Editor.start(editor, path)\n\n blockText = Editor.string(editor, { anchor: s, focus: e }, { voids })\n isNewBlock = true\n }\n }\n\n /*\n * TEXT LEAF NODE - Iterate through text content, yielding\n * positions every `distance` offset according to `unit`.\n */\n if (Text.isText(node)) {\n const isFirst = Path.equals(path, first.path)\n\n // Proof that we always exhaust text nodes before encountering a new one:\n // console.assert(leafTextRemaining <= 0,\n // `leafTextRemaining=${leafTextRemaining} - `+\n // `not exhausted before new leaf text node`, path)\n\n // Reset `leafText` counters for new text node.\n if (isFirst) {\n leafTextRemaining = reverse\n ? first.offset\n : node.text.length - first.offset\n leafTextOffset = first.offset // Works for reverse too.\n } else {\n leafTextRemaining = node.text.length\n leafTextOffset = reverse ? leafTextRemaining : 0\n }\n\n // Yield position at the start of node (potentially).\n if (isFirst || isNewBlock || unit === 'offset') {\n yield { path, offset: leafTextOffset }\n isNewBlock = false\n }\n\n // Yield positions every (dynamically calculated) `distance` offset.\n while (true) {\n // If `leafText` has caught up with `blockText` (distance=0),\n // and if blockText is exhausted, break to get another block node,\n // otherwise advance blockText forward by the new `distance`.\n if (distance === 0) {\n if (blockText === '') break\n distance = calcDistance(blockText, unit, reverse)\n // Split the string at the previously found distance and use the\n // remaining string for the next iteration.\n blockText = splitByCharacterDistance(\n blockText,\n distance,\n reverse\n )[1]\n }\n\n // Advance `leafText` by the current `distance`.\n leafTextOffset = reverse\n ? leafTextOffset - distance\n : leafTextOffset + distance\n leafTextRemaining = leafTextRemaining - distance\n\n // If `leafText` is exhausted, break to get a new leaf node\n // and set distance to the overflow amount, so we'll (maybe)\n // catch up to blockText in the next leaf text node.\n if (leafTextRemaining < 0) {\n distance = -leafTextRemaining\n break\n }\n\n // Successfully walked `distance` offsets through `leafText`\n // to catch up with `blockText`, so we can reset `distance`\n // and yield this position in this node.\n distance = 0\n yield { path, offset: leafTextOffset }\n }\n }\n }\n // Proof that upon completion, we've exahusted both leaf and block text:\n // console.assert(leafTextRemaining <= 0, \"leafText wasn't exhausted\")\n // console.assert(blockText === '', \"blockText wasn't exhausted\")\n\n // Helper:\n // Return the distance in offsets for a step of size `unit` on given string.\n function calcDistance(text: string, unit: string, reverse?: boolean) {\n if (unit === 'character') {\n return getCharacterDistance(text, reverse)\n } else if (unit === 'word') {\n return getWordDistance(text, reverse)\n } else if (unit === 'line' || unit === 'block') {\n return text.length\n }\n return 1\n }\n },\n\n /**\n * Get the matching node in the branch of the document before a location.\n */\n\n previous<T extends Node>(\n editor: Editor,\n options: EditorPreviousOptions<T> = {}\n ): NodeEntry<T> | undefined {\n const { mode = 'lowest', voids = false } = options\n let { match, at = editor.selection } = options\n\n if (!at) {\n return\n }\n\n const pointBeforeLocation = Editor.before(editor, at, { voids })\n\n if (!pointBeforeLocation) {\n return\n }\n\n const [, to] = Editor.first(editor, [])\n\n // The search location is from the start of the document to the path of\n // the point before the location passed in\n const span: Span = [pointBeforeLocation.path, to]\n\n if (Path.isPath(at) && at.length === 0) {\n throw new Error(`Cannot get the previous node from the root node!`)\n }\n\n if (match == null) {\n if (Path.isPath(at)) {\n const [parent] = Editor.parent(editor, at)\n match = n => parent.children.includes(n)\n } else {\n match = () => true\n }\n }\n\n const [previous] = Editor.nodes(editor, {\n reverse: true,\n at: span,\n match,\n mode,\n voids,\n })\n\n return previous\n },\n\n /**\n * Get a range of a location.\n */\n\n range(editor: Editor, at: Location, to?: Location): Range {\n if (Range.isRange(at) && !to) {\n return at\n }\n\n const start = Editor.start(editor, at)\n const end = Editor.end(editor, to || at)\n return { anchor: start, focus: end }\n },\n\n /**\n * Create a mutable ref for a `Range` object, which will stay in sync as new\n * operations are applied to the editor.\n */\n\n rangeRef(\n editor: Editor,\n range: Range,\n options: EditorRangeRefOptions = {}\n ): RangeRef {\n const { affinity = 'forward' } = options\n const ref: RangeRef = {\n current: range,\n affinity,\n unref() {\n const { current } = ref\n const rangeRefs = Editor.rangeRefs(editor)\n rangeRefs.delete(ref)\n ref.current = null\n return current\n },\n }\n\n const refs = Editor.rangeRefs(editor)\n refs.add(ref)\n return ref\n },\n\n /**\n * Get the set of currently tracked range refs of the editor.\n */\n\n rangeRefs(editor: Editor): Set<RangeRef> {\n let refs = RANGE_REFS.get(editor)\n\n if (!refs) {\n refs = new Set()\n RANGE_REFS.set(editor, refs)\n }\n\n return refs\n },\n\n /**\n * Remove a custom property from all of the leaf text nodes in the current\n * selection.\n *\n * If the selection is currently collapsed, the removal will be stored on\n * `editor.marks` and applied to the text inserted next.\n */\n\n removeMark(editor: Editor, key: string): void {\n editor.removeMark(key)\n },\n\n /**\n * Manually set if the editor should currently be normalizing.\n *\n * Note: Using this incorrectly can leave the editor in an invalid state.\n *\n */\n setNormalizing(editor: Editor, isNormalizing: boolean): void {\n NORMALIZING.set(editor, isNormalizing)\n },\n\n /**\n * Get the start point of a location.\n */\n\n start(editor: Editor, at: Location): Point {\n return Editor.point(editor, at, { edge: 'start' })\n },\n\n /**\n * Get the text string content of a location.\n *\n * Note: by default the text of void nodes is considered to be an empty\n * string, regardless of content, unless you pass in true for the voids option\n */\n\n string(\n editor: Editor,\n at: Location,\n options: EditorStringOptions = {}\n ): string {\n const { voids = false } = options\n const range = Editor.range(editor, at)\n const [start, end] = Range.edges(range)\n let text = ''\n\n for (const [node, path] of Editor.nodes(editor, {\n at: range,\n match: Text.isText,\n voids,\n })) {\n let t = node.text\n\n if (Path.equals(path, end.path)) {\n t = t.slice(0, end.offset)\n }\n\n if (Path.equals(path, start.path)) {\n t = t.slice(start.offset)\n }\n\n text += t\n }\n\n return text\n },\n\n /**\n * Convert a range into a non-hanging one.\n */\n\n unhangRange(\n editor: Editor,\n range: Range,\n options: EditorUnhangRangeOptions = {}\n ): Range {\n const { voids = false } = options\n let [start, end] = Range.edges(range)\n\n // PERF: exit early if we can guarantee that the range isn't hanging.\n if (start.offset !== 0 || end.offset !== 0 || Range.isCollapsed(range)) {\n return range\n }\n\n const endBlock = Editor.above(editor, {\n at: end,\n match: n => Editor.isBlock(editor, n),\n })\n const blockPath = endBlock ? endBlock[1] : []\n const first = Editor.start(editor, start)\n const before = { anchor: first, focus: end }\n let skip = true\n\n for (const [node, path] of Editor.nodes(editor, {\n at: before,\n match: Text.isText,\n reverse: true,\n voids,\n })) {\n if (skip) {\n skip = false\n continue\n }\n\n if (node.text !== '' || Path.isBefore(path, blockPath)) {\n end = { path, offset: node.text.length }\n break\n }\n }\n\n return { anchor: start, focus: end }\n },\n\n /**\n * Match a void node in the current branch of the editor.\n */\n\n void(\n editor: Editor,\n options: EditorVoidOptions = {}\n ): NodeEntry<Element> | undefined {\n return Editor.above(editor, {\n ...options,\n match: n => Editor.isVoid(editor, n),\n })\n },\n\n /**\n * Call a function, deferring normalization until after it completes.\n */\n\n withoutNormalizing(editor: Editor, fn: () => void): void {\n const value = Editor.isNormalizing(editor)\n Editor.setNormalizing(editor, false)\n try {\n fn()\n } finally {\n Editor.setNormalizing(editor, value)\n }\n Editor.normalize(editor)\n },\n}\n\n/**\n * A helper type for narrowing matched nodes with a predicate.\n */\n\nexport type NodeMatch<T extends Node> =\n | ((node: Node, path: Path) => node is T)\n | ((node: Node, path: Path) => boolean)\n\nexport type PropsCompare = (prop: Partial<Node>, node: Partial<Node>) => boolean\nexport type PropsMerge = (prop: Partial<Node>, node: Partial<Node>) => object\n","import { Path, Point, Range } from '..'\n\n/**\n * The `Location` interface is a union of the ways to refer to a specific\n * location in a Slate document: paths, points or ranges.\n *\n * Methods will often accept a `Location` instead of requiring only a `Path`,\n * `Point` or `Range`. This eliminates the need for developers to manage\n * converting between the different interfaces in their own code base.\n */\n\nexport type Location = Path | Point | Range\n\nexport interface LocationInterface {\n isLocation: (value: any) => value is Location\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Location: LocationInterface = {\n /**\n * Check if a value implements the `Location` interface.\n */\n\n isLocation(value: any): value is Location {\n return Path.isPath(value) || Point.isPoint(value) || Range.isRange(value)\n },\n}\n\n/**\n * The `Span` interface is a low-level way to refer to locations in nodes\n * without using `Point` which requires leaf text nodes to be present.\n */\n\nexport type Span = [Path, Path]\n\nexport interface SpanInterface {\n isSpan: (value: any) => value is Span\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Span: SpanInterface = {\n /**\n * Check if a value implements the `Span` interface.\n */\n\n isSpan(value: any): value is Span {\n return (\n Array.isArray(value) && value.length === 2 && value.every(Path.isPath)\n )\n },\n}\n","import { produce } from 'immer'\nimport { Editor, Path, Range, Text, Scrubber } from '..'\nimport { Element, ElementEntry } from './element'\n\n/**\n * The `Node` union type represents all of the different types of nodes that\n * occur in a Slate document tree.\n */\n\nexport type BaseNode = Editor | Element | Text\nexport type Node = Editor | Element | Text\n\nexport interface NodeAncestorsOptions {\n reverse?: boolean\n}\n\nexport interface NodeChildrenOptions {\n reverse?: boolean\n}\n\nexport interface NodeDescendantsOptions {\n from?: Path\n to?: Path\n reverse?: boolean\n pass?: (node: NodeEntry) => boolean\n}\n\nexport interface NodeElementsOptions {\n from?: Path\n to?: Path\n reverse?: boolean\n pass?: (node: NodeEntry) => boolean\n}\n\nexport interface NodeLevelsOptions {\n reverse?: boolean\n}\n\nexport interface NodeNodesOptions {\n from?: Path\n to?: Path\n reverse?: boolean\n pass?: (entry: NodeEntry) => boolean\n}\n\nexport interface NodeTextsOptions {\n from?: Path\n to?: Path\n reverse?: boolean\n pass?: (node: NodeEntry) => boolean\n}\n\nexport interface NodeInterface {\n ancestor: (root: Node, path: Path) => Ancestor\n ancestors: (\n root: Node,\n path: Path,\n options?: NodeAncestorsOptions\n ) => Generator<NodeEntry<Ancestor>, void, undefined>\n child: (root: Node, index: number) => Descendant\n children: (\n root: Node,\n path: Path,\n options?: NodeChildrenOptions\n ) => Generator<NodeEntry<Descendant>, void, undefined>\n common: (root: Node, path: Path, another: Path) => NodeEntry\n descendant: (root: Node, path: Path) => Descendant\n descendants: (\n root: Node,\n options?: NodeDescendantsOptions\n ) => Generator<NodeEntry<Descendant>, void, undefined>\n elements: (\n root: Node,\n options?: NodeElementsOptions\n ) => Generator<ElementEntry, void, undefined>\n extractProps: (node: Node) => NodeProps\n first: (root: Node, path: Path) => NodeEntry\n fragment: (root: Node, range: Range) => Descendant[]\n get: (root: Node, path: Path) => Node\n has: (root: Node, path: Path) => boolean\n isNode: (value: any) => value is Node\n isNodeList: (value: any) => value is Node[]\n last: (root: Node, path: Path) => NodeEntry\n leaf: (root: Node, path: Path) => Text\n levels: (\n root: Node,\n path: Path,\n options?: NodeLevelsOptions\n ) => Generator<NodeEntry, void, undefined>\n matches: (node: Node, props: Partial<Node>) => boolean\n nodes: (\n root: Node,\n options?: NodeNodesOptions\n ) => Generator<NodeEntry, void, undefined>\n parent: (root: Node, path: Path) => Ancestor\n string: (node: Node) => string\n texts: (\n root: Node,\n options?: NodeTextsOptions\n ) => Generator<NodeEntry<Text>, void, undefined>\n}\n\nconst IS_NODE_LIST_CACHE = new WeakMap<any[], boolean>()\n\n// eslint-disable-next-line no-redeclare\nexport const Node: NodeInterface = {\n /**\n * Get the node at a specific path, asserting that it's an ancestor node.\n */\n\n ancestor(root: Node, path: Path): Ancestor {\n const node = Node.get(root, path)\n\n if (Text.isText(node)) {\n throw new Error(\n `Cannot get the ancestor node at path [${path}] because it refers to a text node instead: ${Scrubber.stringify(\n node\n )}`\n )\n }\n\n return node\n },\n\n /**\n * Return a generator of all the ancestor nodes above a specific path.\n *\n * By default the order is top-down, from highest to lowest ancestor in\n * the tree, but you can pass the `reverse: true` option to go bottom-up.\n */\n\n *ancestors(\n root: Node,\n path: Path,\n options: NodeAncestorsOptions = {}\n ): Generator<NodeEntry<Ancestor>, void, undefined> {\n for (const p of Path.ancestors(path, options)) {\n const n = Node.ancestor(root, p)\n const entry: NodeEntry<Ancestor> = [n, p]\n yield entry\n }\n },\n\n /**\n * Get the child of a node at a specific index.\n */\n\n child(root: Node, index: number): Descendant {\n if (Text.isText(root)) {\n throw new Error(\n `Cannot get the child of a text node: ${Scrubber.stringify(root)}`\n )\n }\n\n const c = root.children[index] as Descendant\n\n if (c == null) {\n throw new Error(\n `Cannot get child at index \\`${index}\\` in node: ${Scrubber.stringify(\n root\n )}`\n )\n }\n\n return c\n },\n\n /**\n * Iterate over the children of a node at a specific path.\n */\n\n *children(\n root: Node,\n path: Path,\n options: NodeChildrenOptions = {}\n ): Generator<NodeEntry<Descendant>, void, undefined> {\n const { reverse = false } = options\n const ancestor = Node.ancestor(root, path)\n const { children } = ancestor\n let index = reverse ? children.length - 1 : 0\n\n while (reverse ? index >= 0 : index < children.length) {\n const child = Node.child(ancestor, index)\n const childPath = path.concat(index)\n yield [child, childPath]\n index = reverse ? index - 1 : index + 1\n }\n },\n\n /**\n * Get an entry for the common ancesetor node of two paths.\n */\n\n common(root: Node, path: Path, another: Path): NodeEntry {\n const p = Path.common(path, another)\n const n = Node.get(root, p)\n return [n, p]\n },\n\n /**\n * Get the node at a specific path, asserting that it's a descendant node.\n */\n\n descendant(root: Node, path: Path): Descendant {\n const node = Node.get(root, path)\n\n if (Editor.isEditor(node)) {\n throw new Error(\n `Cannot get the descendant node at path [${path}] because it refers to the root editor node instead: ${Scrubber.stringify(\n node\n )}`\n )\n }\n\n return node\n },\n\n /**\n * Return a generator of all the descendant node entries inside a root node.\n */\n\n *descendants(\n root: Node,\n options: NodeDescendantsOptions = {}\n ): Generator<NodeEntry<Descendant>, void, undefined> {\n for (const [node, path] of Node.nodes(root, options)) {\n if (path.length !== 0) {\n // NOTE: we have to coerce here because checking the path's length does\n // guarantee that `node` is not a `Editor`, but TypeScript doesn't know.\n yield [node, path] as NodeEntry<Descendant>\n }\n }\n },\n\n /**\n * Return a generator of all the element nodes inside a root node. Each iteration\n * will return an `ElementEntry` tuple consisting of `[Element, Path]`. If the\n * root node is an element it will be included in the iteration as well.\n */\n\n *elements(\n root: Node,\n options: NodeElementsOptions = {}\n ): Generator<ElementEntry, void, undefined> {\n for (const [node, path] of Node.nodes(root, options)) {\n if (Element.isElement(node)) {\n yield [node, path]\n }\n }\n },\n\n /**\n * Extract props from a Node.\n */\n\n extractProps(node: Node): NodeProps {\n if (Element.isAncestor(node)) {\n const { children, ...properties } = node\n\n return properties\n } else {\n const { text, ...properties } = node\n\n return properties\n }\n },\n\n /**\n * Get the first node entry in a root node from a path.\n */\n\n first(root: Node, path: Path): NodeEntry {\n const p = path.slice()\n let n = Node.get(root, p)\n\n while (n) {\n if (Text.isText(n) || n.children.length === 0) {\n break\n } else {\n n = n.children[0]\n p.push(0)\n }\n }\n\n return [n, p]\n },\n\n /**\n * Get the sliced fragment represented by a range inside a root node.\n */\n\n fragment(root: Node, range: Range): Descendant[] {\n if (Text.isText(root)) {\n throw new Error(\n `Cannot get a fragment starting from a root text node: ${Scrubber.stringify(\n root\n )}`\n )\n }\n\n const newRoot = produce({ children: root.children }, r => {\n const [start, end] = Range.edges(range)\n const nodeEntries = Node.nodes(r, {\n reverse: true,\n pass: ([, path]) => !Range.includes(range, path),\n })\n\n for (const [, path] of nodeEntries) {\n if (!Range.includes(range, path)) {\n const parent = Node.parent(r, path)\n const index = path[path.length - 1]\n parent.children.splice(index, 1)\n }\n\n if (Path.equals(path, end.path)) {\n const leaf = Node.leaf(r, path)\n leaf.text = leaf.text.slice(0, end.offset)\n }\n\n if (Path.equals(path, start.path)) {\n const leaf = Node.leaf(r, path)\n leaf.text = leaf.text.slice(start.offset)\n }\n }\n\n if (Editor.isEditor(r)) {\n r.selection = null\n }\n })\n\n return newRoot.children\n },\n\n /**\n * Get the descendant node referred to by a specific path. If the path is an\n * empty array, it refers to the root node itself.\n */\n\n get(root: Node, path: Path): Node {\n let node = root\n\n for (let i = 0; i < path.length; i++) {\n const p = path[i]\n\n if (Text.isText(node) || !node.children[p]) {\n throw new Error(\n `Cannot find a descendant at path [${path}] in node: ${Scrubber.stringify(\n root\n )}`\n )\n }\n\n node = node.children[p]\n }\n\n return node\n },\n\n /**\n * Check if a descendant node exists at a specific path.\n */\n\n has(root: Node, path: Path): boolean {\n let node = root\n\n for (let i = 0; i < path.length; i++) {\n const p = path[i]\n\n if (Text.isText(node) || !node.children[p]) {\n return false\n }\n\n node = node.children[p]\n }\n\n return true\n },\n\n /**\n * Check if a value implements the `Node` interface.\n */\n\n isNode(value: any): value is Node {\n return (\n Text.isText(value) || Element.isElement(value) || Editor.isEditor(value)\n )\n },\n\n /**\n * Check if a value is a list of `Node` objects.\n */\n\n isNodeList(value: any): value is Node[] {\n if (!Array.isArray(value)) {\n return false\n }\n const cachedResult = IS_NODE_LIST_CACHE.get(value)\n if (cachedResult !== undefined) {\n return cachedResult\n }\n const isNodeList = value.every(val => Node.isNode(val))\n IS_NODE_LIST_CACHE.set(value, isNodeList)\n return isNodeList\n },\n\n /**\n * Get the last node entry in a root node from a path.\n */\n\n last(root: Node, path: Path): NodeEntry {\n const p = path.slice()\n let n = Node.get(root, p)\n\n while (n) {\n if (Text.isText(n) || n.children.length === 0) {\n break\n } else {\n const i = n.children.length - 1\n n = n.children[i]\n p.push(i)\n }\n }\n\n return [n, p]\n },\n\n /**\n * Get the node at a specific path, ensuring it's a leaf text node.\n */\n\n leaf(root: Node, path: Path): Text {\n const node = Node.get(root, path)\n\n if (!Text.isText(node)) {\n throw new Error(\n `Cannot get the leaf node at path [${path}] because it refers to a non-leaf node: ${Scrubber.stringify(\n node\n )}`\n )\n }\n\n return node\n },\n\n /**\n * Return a generator of the in a branch of the tree, from a specific path.\n *\n * By default the order is top-down, from highest to lowest node in the tree,\n * but you can pass the `reverse: true` option to go bottom-up.\n */\n\n *levels(\n root: Node,\n path: Path,\n options: NodeLevelsOptions = {}\n ): Generator<NodeEntry, void, undefined> {\n for (const p of Path.levels(path, options)) {\n const n = Node.get(root, p)\n yield [n, p]\n }\n },\n\n /**\n * Check if a node matches a set of props.\n */\n\n matches(node: Node, props: Partial<Node>): boolean {\n return (\n (Element.isElement(node) &&\n Element.isElementProps(props) &&\n Element.matches(node, props)) ||\n (Text.isText(node) &&\n Text.isTextProps(props) &&\n Text.matches(node, props))\n )\n },\n\n /**\n * Return a generator of all the node entries of a root node. Each entry is\n * returned as a `[Node, Path]` tuple, with the path referring to the node's\n * position inside the root node.\n */\n\n *nodes(\n root: Node,\n options: NodeNodesOptions = {}\n ): Generator<NodeEntry, void, undefined> {\n const { pass, reverse = false } = options\n const { from = [], to } = options\n const visited = new Set()\n let p: Path = []\n let n = root\n\n while (true) {\n if (to && (reverse ? Path.isBefore(p, to) : Path.isAfter(p, to))) {\n break\n }\n\n if (!visited.has(n)) {\n yield [n, p]\n }\n\n // If we're allowed to go downward and we haven't descended yet, do.\n if (\n !visited.has(n) &&\n !Text.isText(n) &&\n n.children.length !== 0 &&\n (pass == null || pass([n, p]) === false)\n ) {\n visited.add(n)\n let nextIndex = reverse ? n.children.length - 1 : 0\n\n if (Path.isAncestor(p, from)) {\n nextIndex = from[p.length]\n }\n\n p = p.concat(nextIndex)\n n = Node.get(root, p)\n continue\n }\n\n // If we're at the root and we can't go down, we're done.\n if (p.length === 0) {\n break\n }\n\n // If we're going forward...\n if (!reverse) {\n const newPath = Path.next(p)\n\n if (Node.has(root, newPath)) {\n p = newPath\n n = Node.get(root, p)\n continue\n }\n }\n\n // If we're going backward...\n if (reverse && p[p.length - 1] !== 0) {\n const newPath = Path.previous(p)\n p = newPath\n n = Node.get(root, p)\n continue\n }\n\n // Otherwise we're going upward...\n p = Path.parent(p)\n n = Node.get(root, p)\n visited.add(n)\n }\n },\n\n /**\n * Get the parent of a node at a specific path.\n */\n\n parent(root: Node, path: Path): Ancestor {\n const parentPath = Path.parent(path)\n const p = Node.get(root, parentPath)\n\n if (Text.isText(p)) {\n throw new Error(\n `Cannot get the parent of path [${path}] because it does not exist in the root.`\n )\n }\n\n return p\n },\n\n /**\n * Get the concatenated text string of a node's content.\n *\n * Note that this will not include spaces or line breaks between block nodes.\n * It is not a user-facing string, but a string for performing offset-related\n * computations for a node.\n */\n\n string(node: Node): string {\n if (Text.isText(node)) {\n return node.text\n } else {\n return node.children.map(Node.string).join('')\n }\n },\n\n /**\n * Return a generator of all leaf text nodes in a root node.\n */\n\n *texts(\n root: Node,\n options: NodeTextsOptions = {}\n ): Generator<NodeEntry<Text>, void, undefined> {\n for (const [node, path] of Node.nodes(root, options)) {\n if (Text.isText(node)) {\n yield [node, path]\n }\n }\n },\n}\n\n/**\n * The `Descendant` union type represents nodes that are descendants in the\n * tree. It is returned as a convenience in certain cases to narrow a value\n * further than the more generic `Node` union.\n */\n\nexport type Descendant = Element | Text\n\n/**\n * The `Ancestor` union type represents nodes that are ancestors in the tree.\n * It is returned as a convenience in certain cases to narrow a value further\n * than the more generic `Node` union.\n */\n\nexport type Ancestor = Editor | Element\n\n/**\n * `NodeEntry` objects are returned when iterating over the nodes in a Slate\n * document tree. They consist of the node and its `Path` relative to the root\n * node in the document.\n */\n\nexport type NodeEntry<T extends Node = Node> = [T, Path]\n\n/**\n * Convenience type for returning the props of a node.\n */\nexport type NodeProps =\n | Omit<Editor, 'children'>\n | Omit<Element, 'children'>\n | Omit<Text, 'text'>\n","import { ExtendedType, Node, Path, Range } from '..'\nimport { isPlainObject } from 'is-plain-object'\n\nexport type BaseInsertNodeOperation = {\n type: 'insert_node'\n path: Path\n node: Node\n}\n\nexport type InsertNodeOperation = ExtendedType<\n 'InsertNodeOperation',\n BaseInsertNodeOperation\n>\n\nexport type BaseInsertTextOperation = {\n type: 'insert_text'\n path: Path\n offset: number\n text: string\n}\n\nexport type InsertTextOperation = ExtendedType<\n 'InsertTextOperation',\n BaseInsertTextOperation\n>\n\nexport type BaseMergeNodeOperation = {\n type: 'merge_node'\n path: Path\n position: number\n properties: Partial<Node>\n}\n\nexport type MergeNodeOperation = ExtendedType<\n 'MergeNodeOperation',\n BaseMergeNodeOperation\n>\n\nexport type BaseMoveNodeOperation = {\n type: 'move_node'\n path: Path\n newPath: Path\n}\n\nexport type MoveNodeOperation = ExtendedType<\n 'MoveNodeOperation',\n BaseMoveNodeOperation\n>\n\nexport type BaseRemoveNodeOperation = {\n type: 'remove_node'\n path: Path\n node: Node\n}\n\nexport type RemoveNodeOperation = ExtendedType<\n 'RemoveNodeOperation',\n BaseRemoveNodeOperation\n>\n\nexport type BaseRemoveTextOperation = {\n type: 'remove_text'\n path: Path\n offset: number\n text: string\n}\n\nexport type RemoveTextOperation = ExtendedType<\n 'RemoveTextOperation',\n BaseRemoveTextOperation\n>\n\nexport type BaseSetNodeOperation = {\n type: 'set_node'\n path: Path\n properties: Partial<Node>\n newProperties: Partial<Node>\n}\n\nexport type SetNodeOperation = ExtendedType<\n 'SetNodeOperation',\n BaseSetNodeOperation\n>\n\nexport type BaseSetSelectionOperation =\n | {\n type: 'set_selection'\n properties: null\n newProperties: Range\n }\n | {\n type: 'set_selection'\n properties: Partial<Range>\n newProperties: Partial<Range>\n }\n | {\n type: 'set_selection'\n properties: Range\n newProperties: null\n }\n\nexport type SetSelectionOperation = ExtendedType<\n 'SetSelectionOperation',\n BaseSetSelectionOperation\n>\n\nexport type BaseSplitNodeOperation = {\n type: 'split_node'\n path: Path\n position: number\n properties: Partial<Node>\n}\n\nexport type SplitNodeOperation = ExtendedType<\n 'SplitNodeOperation',\n BaseSplitNodeOperation\n>\n\nexport type NodeOperation =\n | InsertNodeOperation\n | MergeNodeOperation\n | MoveNodeOperation\n | RemoveNodeOperation\n | SetNodeOperation\n | SplitNodeOperation\n\nexport type SelectionOperation = SetSelectionOperation\n\nexport type TextOperation = InsertTextOperation | RemoveTextOperation\n\n/**\n * `Operation` objects define the low-level instructions that Slate editors use\n * to apply changes to their internal state. Representing all changes as\n * operations is what allows Slate editors to easily implement history,\n * collaboration, and other features.\n */\n\nexport type BaseOperation = NodeOperation | SelectionOperation | TextOperation\nexport type Operation = ExtendedType<'Operation', BaseOperation>\n\nexport interface OperationInterface {\n isNodeOperation: (value: any) => value is NodeOperation\n isOperation: (value: any) => value is Operation\n isOperationList: (value: any) => value is Operation[]\n isSelectionOperation: (value: any) => value is SelectionOperation\n isTextOperation: (value: any) => value is TextOperation\n inverse: (op: Operation) => Operation\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Operation: OperationInterface = {\n /**\n * Check of a value is a `NodeOperation` object.\n */\n\n isNodeOperation(value: any): value is NodeOperation {\n return Operation.isOperation(value) && value.type.endsWith('_node')\n },\n\n /**\n * Check of a value is an `Operation` object.\n */\n\n isOperation(value: any): value is Operation {\n if (!isPlainObject(value)) {\n return false\n }\n\n switch (value.type) {\n case 'insert_node':\n return Path.isPath(value.path) && Node.isNode(value.node)\n case 'insert_text':\n return (\n typeof value.offset === 'number' &&\n typeof value.text === 'string' &&\n Path.isPath(value.path)\n )\n case 'merge_node':\n return (\n typeof value.position === 'number' &&\n Path.isPath(value.path) &&\n isPlainObject(value.properties)\n )\n case 'move_node':\n return Path.isPath(value.path) && Path.isPath(value.newPath)\n case 'remove_node':\n return Path.isPath(value.path) && Node.isNode(value.node)\n case 'remove_text':\n return (\n typeof value.offset === 'number' &&\n typeof value.text === 'string' &&\n Path.isPath(value.path)\n )\n case 'set_node':\n return (\n Path.isPath(value.path) &&\n isPlainObject(value.properties) &&\n isPlainObject(value.newProperties)\n )\n case 'set_selection':\n return (\n (value.properties === null && Range.isRange(value.newProperties)) ||\n (value.newProperties === null && Range.isRange(value.properties)) ||\n (isPlainObject(value.properties) &&\n isPlainObject(value.newProperties))\n )\n case 'split_node':\n return (\n Path.isPath(value.path) &&\n typeof value.position === 'number' &&\n isPlainObject(value.properties)\n )\n default:\n return false\n }\n },\n\n /**\n * Check if a value is a list of `Operation` objects.\n */\n\n isOperationList(value: any): value is Operation[] {\n return (\n Array.isArray(value) && value.every(val => Operation.isOperation(val))\n )\n },\n\n /**\n * Check of a value is a `SelectionOperation` object.\n */\n\n isSelectionOperation(value: any): value is SelectionOperation {\n return Operation.isOperation(value) && value.type.endsWith('_selection')\n },\n\n /**\n * Check of a value is a `TextOperation` object.\n */\n\n isTextOperation(value: any): value is TextOperation {\n return Operation.isOperation(value) && value.type.endsWith('_text')\n },\n\n /**\n * Invert an operation, returning a new operation that will exactly undo the\n * original when applied.\n */\n\n inverse(op: Operation): Operation {\n switch (op.type) {\n case 'insert_node': {\n return { ...op, type: 'remove_node' }\n }\n\n case 'insert_text': {\n return { ...op, type: 'remove_text' }\n }\n\n case 'merge_node': {\n return { ...op, type: 'split_node', path: Path.previous(op.path) }\n }\n\n case 'move_node': {\n const { newPath, path } = op\n\n // PERF: in this case the move operation is a no-op anyways.\n if (Path.equals(newPath, path)) {\n return op\n }\n\n // If the move happens completely within a single parent the path and\n // newPath are stable with respect to each other.\n if (Path.isSibling(path, newPath)) {\n return { ...op, path: newPath, newPath: path }\n }\n\n // If the move does not happen within a single parent it is possible\n // for the move to impact the true path to the location where the node\n // was removed from and where it was inserted. We have to adjust for this\n // and find the original path. We can accomplish this (only in non-sibling)\n // moves by looking at the impact of the move operation on the node\n // after the original move path.\n const inversePath = Path.transform(path, op)!\n const inverseNewPath = Path.transform(Path.next(path), op)!\n return { ...op, path: inversePath, newPath: inverseNewPath }\n }\n\n case 'remove_node': {\n return { ...op, type: 'insert_node' }\n }\n\n case 'remove_text': {\n return { ...op, type: 'insert_text' }\n }\n\n case 'set_node': {\n const { properties, newProperties } = op\n return { ...op, properties: newProperties, newProperties: properties }\n }\n\n case 'set_selection': {\n const { properties, newProperties } = op\n\n if (properties == null) {\n return {\n ...op,\n properties: newProperties as Range,\n newProperties: null,\n }\n } else if (newProperties == null) {\n return {\n ...op,\n properties: null,\n newProperties: properties as Range,\n }\n } else {\n return { ...op, properties: newProperties, newProperties: properties }\n }\n }\n\n case 'split_node': {\n return { ...op, type: 'merge_node', path: Path.next(op.path) }\n }\n }\n },\n}\n","import { produce } from 'immer'\nimport { Operation } from '..'\nimport { TextDirection } from './types'\n\n/**\n * `Path` arrays are a list of indexes that describe a node's exact position in\n * a Slate node tree. Although they are usually relative to the root `Editor`\n * object, they can be relative to any `Node` object.\n */\n\nexport type Path = number[]\n\nexport interface PathAncestorsOptions {\n reverse?: boolean\n}\n\nexport interface PathLevelsOptions {\n reverse?: boolean\n}\n\nexport interface PathTransformOptions {\n affinity?: TextDirection | null\n}\n\nexport interface PathInterface {\n ancestors: (path: Path, options?: PathAncestorsOptions) => Path[]\n common: (path: Path, another: Path) => Path\n compare: (path: Path, another: Path) => -1 | 0 | 1\n endsAfter: (path: Path, another: Path) => boolean\n endsAt: (path: Path, another: Path) => boolean\n endsBefore: (path: Path, another: Path) => boolean\n equals: (path: Path, another: Path) => boolean\n hasPrevious: (path: Path) => boolean\n isAfter: (path: Path, another: Path) => boolean\n isAncestor: (path: Path, another: Path) => boolean\n isBefore: (path: Path, another: Path) => boolean\n isChild: (path: Path, another: Path) => boolean\n isCommon: (path: Path, another: Path) => boolean\n isDescendant: (path: Path, another: Path) => boolean\n isParent: (path: Path, another: Path) => boolean\n isPath: (value: any) => value is Path\n isSibling: (path: Path, another: Path) => boolean\n levels: (path: Path, options?: PathLevelsOptions) => Path[]\n next: (path: Path) => Path\n operationCanTransformPath: (operation: Operation) => boolean\n parent: (path: Path) => Path\n previous: (path: Path) => Path\n relative: (path: Path, ancestor: Path) => Path\n transform: (\n path: Path,\n operation: Operation,\n options?: PathTransformOptions\n ) => Path | null\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Path: PathInterface = {\n /**\n * Get a list of ancestor paths for a given path.\n *\n * The paths are sorted from shallowest to deepest ancestor. However, if the\n * `reverse: true` option is passed, they are reversed.\n */\n\n ancestors(path: Path, options: PathAncestorsOptions = {}): Path[] {\n const { reverse = false } = options\n let paths = Path.levels(path, options)\n\n if (reverse) {\n paths = paths.slice(1)\n } else {\n paths = paths.slice(0, -1)\n }\n\n return paths\n },\n\n /**\n * Get the common ancestor path of two paths.\n */\n\n common(path: Path, another: Path): Path {\n const common: Path = []\n\n for (let i = 0; i < path.length && i < another.length; i++) {\n const av = path[i]\n const bv = another[i]\n\n if (av !== bv) {\n break\n }\n\n common.push(av)\n }\n\n return common\n },\n\n /**\n * Compare a path to another, returning an integer indicating whether the path\n * was before, at, or after the other.\n *\n * Note: Two paths of unequal length can still receive a `0` result if one is\n * directly above or below the other. If you want exact matching, use\n * [[Path.equals]] instead.\n */\n\n compare(path: Path, another: Path): -1 | 0 | 1 {\n const min = Math.min(path.length, another.length)\n\n for (let i = 0; i < min; i++) {\n if (path[i] < another[i]) return -1\n if (path[i] > another[i]) return 1\n }\n\n return 0\n },\n\n /**\n * Check if a path ends after one of the indexes in another.\n */\n\n endsAfter(path: Path, another: Path): boolean {\n const i = path.length - 1\n const as = path.slice(0, i)\n const bs = another.slice(0, i)\n const av = path[i]\n const bv = another[i]\n return Path.equals(as, bs) && av > bv\n },\n\n /**\n * Check if a path ends at one of the indexes in another.\n */\n\n endsAt(path: Path, another: Path): boolean {\n const i = path.length\n const as = path.slice(0, i)\n const bs = another.slice(0, i)\n return Path.equals(as, bs)\n },\n\n /**\n * Check if a path ends before one of the indexes in another.\n */\n\n endsBefore(path: Path, another: Path): boolean {\n const i = path.length - 1\n const as = path.slice(0, i)\n const bs = another.slice(0, i)\n const av = path[i]\n const bv = another[i]\n return Path.equals(as, bs) && av < bv\n },\n\n /**\n * Check if a path is exactly equal to another.\n */\n\n equals(path: Path, another: Path): boolean {\n return (\n path.length === another.length && path.every((n, i) => n === another[i])\n )\n },\n\n /**\n * Check if the path of previous sibling node exists\n */\n\n hasPrevious(path: Path): boolean {\n return path[path.length - 1] > 0\n },\n\n /**\n * Check if a path is after another.\n */\n\n isAfter(path: Path, another: Path): boolean {\n return Path.compare(path, another) === 1\n },\n\n /**\n * Check if a path is an ancestor of another.\n */\n\n isAncestor(path: Path, another: Path): boolean {\n return path.length < another.length && Path.compare(path, another) === 0\n },\n\n /**\n * Check if a path is before another.\n */\n\n isBefore(path: Path, another: Path): boolean {\n return Path.compare(path, another) === -1\n },\n\n /**\n * Check if a path is a child of another.\n */\n\n isChild(path: Path, another: Path): boolean {\n return (\n path.length === another.length + 1 && Path.compare(path, another) === 0\n )\n },\n\n /**\n * Check if a path is equal to or an ancestor of another.\n */\n\n isCommon(path: Path, another: Path): boolean {\n return path.length <= another.length && Path.compare(path, another) === 0\n },\n\n /**\n * Check if a path is a descendant of another.\n */\n\n isDescendant(path: Path, another: Path): boolean {\n return path.length > another.length && Path.compare(path, another) === 0\n },\n\n /**\n * Check if a path is the parent of another.\n */\n\n isParent(path: Path, another: Path): boolean {\n return (\n path.length + 1 === another.length && Path.compare(path, another) === 0\n )\n },\n\n /**\n * Check is a value implements the `Path` interface.\n */\n\n isPath(value: any): value is Path {\n return (\n Array.isArray(value) &&\n (value.length === 0 || typeof value[0] === 'number')\n )\n },\n\n /**\n * Check if a path is a sibling of another.\n */\n\n isSibling(path: Path, another: Path): boolean {\n if (path.length !== another.length) {\n return false\n }\n\n const as = path.slice(0, -1)\n const bs = another.slice(0, -1)\n const al = path[path.length - 1]\n const bl = another[another.length - 1]\n return al !== bl && Path.equals(as, bs)\n },\n\n /**\n * Get a list of paths at every level down to a path. Note: this is the same\n * as `Path.ancestors`, but including the path itself.\n *\n * The paths are sorted from shallowest to deepest. However, if the `reverse:\n * true` option is passed, they are reversed.\n */\n\n levels(path: Path, options: PathLevelsOptions = {}): Path[] {\n const { reverse = false } = options\n const list: Path[] = []\n\n for (let i = 0; i <= path.length; i++) {\n list.push(path.slice(0, i))\n }\n\n if (reverse) {\n list.reverse()\n }\n\n return list\n },\n\n /**\n * Given a path, get the path to the next sibling node.\n */\n\n next(path: Path): Path {\n if (path.length === 0) {\n throw new Error(\n `Cannot get the next path of a root path [${path}], because it has no next index.`\n )\n }\n\n const last = path[path.length - 1]\n return path.slice(0, -1).concat(last + 1)\n },\n\n /**\n * Returns whether this operation can affect paths or not. Used as an\n * optimization when updating dirty paths during normalization\n *\n * NOTE: This *must* be kept in sync with the implementation of 'transform'\n * below\n */\n operationCanTransformPath(operation: Operation): boolean {\n switch (operation.type) {\n case 'insert_node':\n case 'remove_node':\n case 'merge_node':\n case 'split_node':\n case 'move_node':\n return true\n default:\n return false\n }\n },\n\n /**\n * Given a path, return a new path referring to the parent node above it.\n */\n\n parent(path: Path): Path {\n if (path.length === 0) {\n throw new Error(`Cannot get the parent path of the root path [${path}].`)\n }\n\n return path.slice(0, -1)\n },\n\n /**\n * Given a path, get the path to the previous sibling node.\n */\n\n previous(path: Path): Path {\n if (path.length === 0) {\n throw new Error(\n `Cannot get the previous path of a root path [${path}], because it has no previous index.`\n )\n }\n\n const last = path[path.length - 1]\n\n if (last <= 0) {\n throw new Error(\n `Cannot get the previous path of a first child path [${path}] because it would result in a negative index.`\n )\n }\n\n return path.slice(0, -1).concat(last - 1)\n },\n\n /**\n * Get a path relative to an ancestor.\n */\n\n relative(path: Path, ancestor: Path): Path {\n if (!Path.isAncestor(ancestor, path) && !Path.equals(path, ancestor)) {\n throw new Error(\n `Cannot get the relative path of [${path}] inside ancestor [${ancestor}], because it is not above or equal to the path.`\n )\n }\n\n return path.slice(ancestor.length)\n },\n\n /**\n * Transform a path by an operation.\n */\n\n transform(\n path: Path | null,\n operation: Operation,\n options: PathTransformOptions = {}\n ): Path | null {\n return produce(path, p => {\n const { affinity = 'forward' } = options\n\n // PERF: Exit early if the operation is guaranteed not to have an effect.\n if (!path || path?.length === 0) {\n return\n }\n\n if (p === null) {\n return null\n }\n\n switch (operation.type) {\n case 'insert_node': {\n const { path: op } = operation\n\n if (\n Path.equals(op, p) ||\n Path.endsBefore(op, p) ||\n Path.isAncestor(op, p)\n ) {\n p[op.length - 1] += 1\n }\n\n break\n }\n\n case 'remove_node': {\n const { path: op } = operation\n\n if (Path.equals(op, p) || Path.isAncestor(op, p)) {\n return null\n } else if (Path.endsBefore(op, p)) {\n p[op.length - 1] -= 1\n }\n\n break\n }\n\n case 'merge_node': {\n const { path: op, position } = operation\n\n if (Path.equals(op, p) || Path.endsBefore(op, p)) {\n p[op.length - 1] -= 1\n } else if (Path.isAncestor(op, p)) {\n p[op.length - 1] -= 1\n p[op.length] += position\n }\n\n break\n }\n\n case 'split_node': {\n const { path: op, position } = operation\n\n if (Path.equals(op, p)) {\n if (affinity === 'forward') {\n p[p.length - 1] += 1\n } else if (affinity === 'backward') {\n // Nothing, because it still refers to the right path.\n } else {\n return null\n }\n } else if (Path.endsBefore(op, p)) {\n p[op.length - 1] += 1\n } else if (Path.isAncestor(op, p) && path[op.length] >= position) {\n p[op.length - 1] += 1\n p[op.length] -= position\n }\n\n break\n }\n\n case 'move_node': {\n const { path: op, newPath: onp } = operation\n\n // If the old and new path are the same, it's a no-op.\n if (Path.equals(op, onp)) {\n return\n }\n\n if (Path.isAncestor(op, p) || Path.equals(op, p)) {\n const copy = onp.slice()\n\n if (Path.endsBefore(op, onp) && op.length < onp.length) {\n copy[op.length - 1] -= 1\n }\n\n return copy.concat(p.slice(op.length))\n } else if (\n Path.isSibling(op, onp) &&\n (Path.isAncestor(onp, p) || Path.equals(onp, p))\n ) {\n if (Path.endsBefore(op, p)) {\n p[op.length - 1] -= 1\n } else {\n p[op.length - 1] += 1\n }\n } else if (\n Path.endsBefore(onp, p) ||\n Path.equals(onp, p) ||\n Path.isAncestor(onp, p)\n ) {\n if (Path.endsBefore(op, p)) {\n p[op.length - 1] -= 1\n }\n\n p[onp.length - 1] += 1\n } else if (Path.endsBefore(op, p)) {\n if (Path.equals(onp, p)) {\n p[onp.length - 1] += 1\n }\n\n p[op.length - 1] -= 1\n }\n\n break\n }\n }\n })\n },\n}\n","import { Operation, Path } from '..'\n\n/**\n * `PathRef` objects keep a specific path in a document synced over time as new\n * operations are applied to the editor. You can access their `current` property\n * at any time for the up-to-date path value.\n */\n\nexport interface PathRef {\n current: Path | null\n affinity: 'forward' | 'backward' | null\n unref(): Path | null\n}\n\nexport interface PathRefInterface {\n transform: (ref: PathRef, op: Operation) => void\n}\n\n// eslint-disable-next-line no-redeclare\nexport const PathRef: PathRefInterface = {\n /**\n * Transform the path ref's current value by an operation.\n */\n\n transform(ref: PathRef, op: Operation): void {\n const { current, affinity } = ref\n\n if (current == null) {\n return\n }\n\n const path = Path.transform(current, op, { affinity })\n ref.current = path\n\n if (path == null) {\n ref.unref()\n }\n },\n}\n","import { isPlainObject } from 'is-plain-object'\nimport { produce } from 'immer'\nimport { ExtendedType, Operation, Path } from '..'\nimport { TextDirection } from './types'\n\n/**\n * `Point` objects refer to a specific location in a text node in a Slate\n * document. Its path refers to the location of the node in the tree, and its\n * offset refers to the distance into the node's string of text. Points can\n * only refer to `Text` nodes.\n */\n\nexport interface BasePoint {\n path: Path\n offset: number\n}\n\nexport type Point = ExtendedType<'Point', BasePoint>\n\nexport interface PointTransformOptions {\n affinity?: TextDirection | null\n}\n\nexport interface PointInterface {\n compare: (point: Point, another: Point) => -1 | 0 | 1\n isAfter: (point: Point, another: Point) => boolean\n isBefore: (point: Point, another: Point) => boolean\n equals: (point: Point, another: Point) => boolean\n isPoint: (value: any) => value is Point\n transform: (\n point: Point,\n op: Operation,\n options?: PointTransformOptions\n ) => Point | null\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Point: PointInterface = {\n /**\n * Compare a point to another, returning an integer indicating whether the\n * point was before, at, or after the other.\n */\n\n compare(point: Point, another: Point): -1 | 0 | 1 {\n const result = Path.compare(point.path, another.path)\n\n if (result === 0) {\n if (point.offset < another.offset) return -1\n if (point.offset > another.offset) return 1\n return 0\n }\n\n return result\n },\n\n /**\n * Check if a point is after another.\n */\n\n isAfter(point: Point, another: Point): boolean {\n return Point.compare(point, another) === 1\n },\n\n /**\n * Check if a point is before another.\n */\n\n isBefore(point: Point, another: Point): boolean {\n return Point.compare(point, another) === -1\n },\n\n /**\n * Check if a point is exactly equal to another.\n */\n\n equals(point: Point, another: Point): boolean {\n // PERF: ensure the offsets are equal first since they are cheaper to check.\n return (\n point.offset === another.offset && Path.equals(point.path, another.path)\n )\n },\n\n /**\n * Check if a value implements the `Point` interface.\n */\n\n isPoint(value: any): value is Point {\n return (\n isPlainObject(value) &&\n typeof value.offset === 'number' &&\n Path.isPath(value.path)\n )\n },\n\n /**\n * Transform a point by an operation.\n */\n\n transform(\n point: Point | null,\n op: Operation,\n options: PointTransformOptions = {}\n ): Point | null {\n return produce(point, p => {\n if (p === null) {\n return null\n }\n const { affinity = 'forward' } = options\n const { path, offset } = p\n\n switch (op.type) {\n case 'insert_node':\n case 'move_node': {\n p.path = Path.transform(path, op, options)!\n break\n }\n\n case 'insert_text': {\n if (\n Path.equals(op.path, path) &&\n (op.offset < offset ||\n (op.offset === offset && affinity === 'forward'))\n ) {\n p.offset += op.text.length\n }\n\n break\n }\n\n case 'merge_node': {\n if (Path.equals(op.path, path)) {\n p.offset += op.position\n }\n\n p.path = Path.transform(path, op, options)!\n break\n }\n\n case 'remove_text': {\n if (Path.equals(op.path, path) && op.offset <= offset) {\n p.offset -= Math.min(offset - op.offset, op.text.length)\n }\n\n break\n }\n\n case 'remove_node': {\n if (Path.equals(op.path, path) || Path.isAncestor(op.path, path)) {\n return null\n }\n\n p.path = Path.transform(path, op, options)!\n break\n }\n\n case 'split_node': {\n if (Path.equals(op.path, path)) {\n if (op.position === offset && affinity == null) {\n return null\n } else if (\n op.position < offset ||\n (op.position === offset && affinity === 'forward')\n ) {\n p.offset -= op.position\n\n p.path = Path.transform(path, op, {\n ...options,\n affinity: 'forward',\n })!\n }\n } else {\n p.path = Path.transform(path, op, options)!\n }\n\n break\n }\n }\n })\n },\n}\n\n/**\n * `PointEntry` objects are returned when iterating over `Point` objects that\n * belong to a range.\n */\n\nexport type PointEntry = [Point, 'anchor' | 'focus']\n","import { Operation, Point } from '..'\nimport { TextDirection } from './types'\n\n/**\n * `PointRef` objects keep a specific point in a document synced over time as new\n * operations are applied to the editor. You can access their `current` property\n * at any time for the up-to-date point value.\n */\n\nexport interface PointRef {\n current: Point | null\n affinity: TextDirection | null\n unref(): Point | null\n}\n\nexport interface PointRefInterface {\n transform: (ref: PointRef, op: Operation) => void\n}\n\n// eslint-disable-next-line no-redeclare\nexport const PointRef: PointRefInterface = {\n /**\n * Transform the point ref's current value by an operation.\n */\n\n transform(ref: PointRef, op: Operation): void {\n const { current, affinity } = ref\n\n if (current == null) {\n return\n }\n\n const point = Point.transform(current, op, { affinity })\n ref.current = point\n\n if (point == null) {\n ref.unref()\n }\n },\n}\n","import { produce } from 'immer'\nimport { isPlainObject } from 'is-plain-object'\nimport { ExtendedType, Operation, Path, Point, PointEntry } from '..'\nimport { RangeDirection } from './types'\n\n/**\n * `Range` objects are a set of points that refer to a specific span of a Slate\n * document. They can define a span inside a single node or a can span across\n * multiple nodes.\n */\n\nexport interface BaseRange {\n anchor: Point\n focus: Point\n}\n\nexport type Range = ExtendedType<'Range', BaseRange>\n\nexport interface RangeEdgesOptions {\n reverse?: boolean\n}\n\nexport interface RangeTransformOptions {\n affinity?: RangeDirection | null\n}\n\nexport interface RangeInterface {\n edges: (range: Range, options?: RangeEdgesOptions) => [Point, Point]\n end: (range: Range) => Point\n equals: (range: Range, another: Range) => boolean\n includes: (range: Range, target: Path | Point | Range) => boolean\n intersection: (range: Range, another: Range) => Range | null\n isBackward: (range: Range) => boolean\n isCollapsed: (range: Range) => boolean\n isExpanded: (range: Range) => boolean\n isForward: (range: Range) => boolean\n isRange: (value: any) => value is Range\n points: (range: Range) => Generator<PointEntry, void, undefined>\n start: (range: Range) => Point\n transform: (\n range: Range,\n op: Operation,\n options?: RangeTransformOptions\n ) => Range | null\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Range: RangeInterface = {\n /**\n * Get the start and end points of a range, in the order in which they appear\n * in the document.\n */\n\n edges(range: Range, options: RangeEdgesOptions = {}): [Point, Point] {\n const { reverse = false } = options\n const { anchor, focus } = range\n return Range.isBackward(range) === reverse\n ? [anchor, focus]\n : [focus, anchor]\n },\n\n /**\n * Get the end point of a range.\n */\n\n end(range: Range): Point {\n const [, end] = Range.edges(range)\n return end\n },\n\n /**\n * Check if a range is exactly equal to another.\n */\n\n equals(range: Range, another: Range): boolean {\n return (\n Point.equals(range.anchor, another.anchor) &&\n Point.equals(range.focus, another.focus)\n )\n },\n\n /**\n * Check if a range includes a path, a point or part of another range.\n */\n\n includes(range: Range, target: Path | Point | Range): boolean {\n if (Range.isRange(target)) {\n if (\n Range.includes(range, target.anchor) ||\n Range.includes(range, target.focus)\n ) {\n return true\n }\n\n const [rs, re] = Range.edges(range)\n const [ts, te] = Range.edges(target)\n return Point.isBefore(rs, ts) && Point.isAfter(re, te)\n }\n\n const [start, end] = Range.edges(range)\n let isAfterStart = false\n let isBeforeEnd = false\n\n if (Point.isPoint(target)) {\n isAfterStart = Point.compare(target, start) >= 0\n isBeforeEnd = Point.compare(target, end) <= 0\n } else {\n isAfterStart = Path.compare(target, start.path) >= 0\n isBeforeEnd = Path.compare(target, end.path) <= 0\n }\n\n return isAfterStart && isBeforeEnd\n },\n\n /**\n * Get the intersection of a range with another.\n */\n\n intersection(range: Range, another: Range): Range | null {\n const { anchor, focus, ...rest } = range\n const [s1, e1] = Range.edges(range)\n const [s2, e2] = Range.edges(another)\n const start = Point.isBefore(s1, s2) ? s2 : s1\n const end = Point.isBefore(e1, e2) ? e1 : e2\n\n if (Point.isBefore(end, start)) {\n return null\n } else {\n return { anchor: start, focus: end, ...rest }\n }\n },\n\n /**\n * Check if a range is backward, meaning that its anchor point appears in the\n * document _after_ its focus point.\n */\n\n isBackward(range: Range): boolean {\n const { anchor, focus } = range\n return Point.isAfter(anchor, focus)\n },\n\n /**\n * Check if a range is collapsed, meaning that both its anchor and focus\n * points refer to the exact same position in the document.\n */\n\n isCollapsed(range: Range): boolean {\n const { anchor, focus } = range\n return Point.equals(anchor, focus)\n },\n\n /**\n * Check if a range is expanded.\n *\n * This is the opposite of [[Range.isCollapsed]] and is provided for legibility.\n */\n\n isExpanded(range: Range): boolean {\n return !Range.isCollapsed(range)\n },\n\n /**\n * Check if a range is forward.\n *\n * This is the opposite of [[Range.isBackward]] and is provided for legibility.\n */\n\n isForward(range: Range): boolean {\n return !Range.isBackward(range)\n },\n\n /**\n * Check if a value implements the [[Range]] interface.\n */\n\n isRange(value: any): value is Range {\n return (\n isPlainObject(value) &&\n Point.isPoint(value.anchor) &&\n Point.isPoint(value.focus)\n )\n },\n\n /**\n * Iterate through all of the point entries in a range.\n */\n\n *points(range: Range): Generator<PointEntry, void, undefined> {\n yield [range.anchor, 'anchor']\n yield [range.focus, 'focus']\n },\n\n /**\n * Get the start point of a range.\n */\n\n start(range: Range): Point {\n const [start] = Range.edges(range)\n return start\n },\n\n /**\n * Transform a range by an operation.\n */\n\n transform(\n range: Range | null,\n op: Operation,\n options: RangeTransformOptions = {}\n ): Range | null {\n return produce(range, r => {\n if (r === null) {\n return null\n }\n const { affinity = 'inward' } = options\n let affinityAnchor: 'forward' | 'backward' | null\n let affinityFocus: 'forward' | 'backward' | null\n\n if (affinity === 'inward') {\n // If the range is collapsed, make sure to use the same affinity to\n // avoid the two points passing each other and expanding in the opposite\n // direction\n const isCollapsed = Range.isCollapsed(r)\n if (Range.isForward(r)) {\n affinityAnchor = 'forward'\n affinityFocus = isCollapsed ? affinityAnchor : 'backward'\n } else {\n affinityAnchor = 'backward'\n affinityFocus = isCollapsed ? affinityAnchor : 'forward'\n }\n } else if (affinity === 'outward') {\n if (Range.isForward(r)) {\n affinityAnchor = 'backward'\n affinityFocus = 'forward'\n } else {\n affinityAnchor = 'forward'\n affinityFocus = 'backward'\n }\n } else {\n affinityAnchor = affinity\n affinityFocus = affinity\n }\n const anchor = Point.transform(r.anchor, op, { affinity: affinityAnchor })\n const focus = Point.transform(r.focus, op, { affinity: affinityFocus })\n\n if (!anchor || !focus) {\n return null\n }\n\n r.anchor = anchor\n r.focus = focus\n })\n },\n}\n","import { Operation, Range } from '..'\n\n/**\n * `RangeRef` objects keep a specific range in a document synced over time as new\n * operations are applied to the editor. You can access their `current` property\n * at any time for the up-to-date range value.\n */\n\nexport interface RangeRef {\n current: Range | null\n affinity: 'forward' | 'backward' | 'outward' | 'inward' | null\n unref(): Range | null\n}\n\nexport interface RangeRefInterface {\n transform: (ref: RangeRef, op: Operation) => void\n}\n\n// eslint-disable-next-line no-redeclare\nexport const RangeRef: RangeRefInterface = {\n /**\n * Transform the range ref's current value by an operation.\n */\n\n transform(ref: RangeRef, op: Operation): void {\n const { current, affinity } = ref\n\n if (current == null) {\n return\n }\n\n const path = Range.transform(current, op, { affinity })\n ref.current = path\n\n if (path == null) {\n ref.unref()\n }\n },\n}\n","export type Scrubber = (key: string, value: unknown) => unknown\n\nexport interface ScrubberInterface {\n setScrubber(scrubber: Scrubber | undefined): void\n stringify(value: any): string\n}\n\nlet _scrubber: Scrubber | undefined = undefined\n\n/**\n * This interface implements a stringify() function, which is used by Slate\n * internally when generating exceptions containing end user data. Developers\n * using Slate may call Scrubber.setScrubber() to alter the behavior of this\n * stringify() function.\n *\n * For example, to prevent the cleartext logging of 'text' fields within Nodes:\n *\n * import { Scrubber } from 'slate';\n * Scrubber.setScrubber((key, val) => {\n * if (key === 'text') return '...scrubbed...'\n * return val\n * });\n *\n */\n// eslint-disable-next-line no-redeclare\nexport const Scrubber: ScrubberInterface = {\n setScrubber(scrubber: Scrubber | undefined): void {\n _scrubber = scrubber\n },\n\n stringify(value: any): string {\n return JSON.stringify(value, _scrubber)\n },\n}\n","import { isPlainObject } from 'is-plain-object'\n\n/*\n Custom deep equal comparison for Slate nodes.\n\n We don't need general purpose deep equality;\n Slate only supports plain values, Arrays, and nested objects.\n Complex values nested inside Arrays are not supported.\n\n Slate objects are designed to be serialised, so\n missing keys are deliberately normalised to undefined.\n */\nexport const isDeepEqual = (\n node: Record<string, any>,\n another: Record<string, any>\n): boolean => {\n for (const key in node) {\n const a = node[key]\n const b = another[key]\n if (isPlainObject(a) && isPlainObject(b)) {\n if (!isDeepEqual(a, b)) return false\n } else if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false\n }\n } else if (a !== b) {\n return false\n }\n }\n\n /*\n Deep object equality is only necessary in one direction; in the reverse direction\n we are only looking for keys that are missing.\n As above, undefined keys are normalised to missing.\n */\n\n for (const key in another) {\n if (node[key] === undefined && another[key] !== undefined) {\n return false\n }\n }\n\n return true\n}\n","import { isPlainObject } from 'is-plain-object'\nimport { Range } from '..'\nimport { ExtendedType } from './custom-types'\nimport { isDeepEqual } from '../utils/deep-equal'\n\n/**\n * `Text` objects represent the nodes that contain the actual text content of a\n * Slate document along with any formatting properties. They are always leaf\n * nodes in the document tree as they cannot contain any children.\n */\n\nexport interface BaseText {\n text: string\n}\n\nexport type Text = ExtendedType<'Text', BaseText>\n\nexport interface TextEqualsOptions {\n loose?: boolean\n}\n\nexport interface TextInterface {\n equals: (text: Text, another: Text, options?: TextEqualsOptions) => boolean\n isText: (value: any) => value is Text\n isTextList: (value: any) => value is Text[]\n isTextProps: (props: any) => props is Partial<Text>\n matches: (text: Text, props: Partial<Text>) => boolean\n decorations: (node: Text, decorations: Range[]) => Text[]\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Text: TextInterface = {\n /**\n * Check if two text nodes are equal.\n *\n * When loose is set, the text is not compared. This is\n * used to check whether sibling text nodes can be merged.\n */\n equals(text: Text, another: Text, options: TextEqualsOptions = {}): boolean {\n const { loose = false } = options\n\n function omitText(obj: Record<any, any>) {\n const { text, ...rest } = obj\n\n return rest\n }\n\n return isDeepEqual(\n loose ? omitText(text) : text,\n loose ? omitText(another) : another\n )\n },\n\n /**\n * Check if a value implements the `Text` interface.\n */\n\n isText(value: any): value is Text {\n return isPlainObject(value) && typeof value.text === 'string'\n },\n\n /**\n * Check if a value is a list of `Text` objects.\n */\n\n isTextList(value: any): value is Text[] {\n return Array.isArray(value) && value.every(val => Text.isText(val))\n },\n\n /**\n * Check if some props are a partial of Text.\n */\n\n isTextProps(props: any): props is Partial<Text> {\n return (props as Partial<Text>).text !== undefined\n },\n\n /**\n * Check if an text matches set of properties.\n *\n * Note: this is for matching custom properties, and it does not ensure that\n * the `text` property are two nodes equal.\n */\n\n matches(text: Text, props: Partial<Text>): boolean {\n for (const key in props) {\n if (key === 'text') {\n continue\n }\n\n if (!text.hasOwnProperty(key) || text[key] !== props[key]) {\n return false\n }\n }\n\n return true\n },\n\n /**\n * Get the leaves for a text node given decorations.\n */\n\n decorations(node: Text, decorations: Range[]): Text[] {\n let leaves: Text[] = [{ ...node }]\n\n for (const dec of decorations) {\n const { anchor, focus, ...rest } = dec\n const [start, end] = Range.edges(dec)\n const next = []\n let leafEnd = 0\n const decorationStart = start.offset\n const decorationEnd = end.offset\n\n for (const leaf of leaves) {\n const { length } = leaf.text\n const leafStart = leafEnd\n leafEnd += length\n\n // If the range encompasses the entire leaf, add the range.\n if (decorationStart <= leafStart && leafEnd <= decorationEnd) {\n Object.assign(leaf, rest)\n next.push(leaf)\n continue\n }\n\n // If the range expanded and match the leaf, or starts after, or ends before it, continue.\n if (\n (decorationStart !== decorationEnd &&\n (decorationStart === leafEnd || decorationEnd === leafStart)) ||\n decorationStart > leafEnd ||\n decorationEnd < leafStart ||\n (decorationEnd === leafStart && leafStart !== 0)\n ) {\n next.push(leaf)\n continue\n }\n\n // Otherwise we need to split the leaf, at the start, end, or both,\n // and add the range to the middle intersecting section. Do the end\n // split first since we don't need to update the offset that way.\n let middle = leaf\n let before\n let after\n\n if (decorationEnd < leafEnd) {\n const off = decorationEnd - leafStart\n after = { ...middle, text: middle.text.slice(off) }\n middle = { ...middle, text: middle.text.slice(0, off) }\n }\n\n if (decorationStart > leafStart) {\n const off = decorationStart - leafStart\n before = { ...middle, text: middle.text.slice(0, off) }\n middle = { ...middle, text: middle.text.slice(off) }\n }\n\n Object.assign(middle, rest)\n\n if (before) {\n next.push(before)\n }\n\n next.push(middle)\n\n if (after) {\n next.push(after)\n }\n }\n\n leaves = next\n }\n\n return leaves\n },\n}\n","import { createDraft, finishDraft, isDraft } from 'immer'\nimport {\n Ancestor,\n Descendant,\n Editor,\n Element,\n Node,\n NodeEntry,\n Operation,\n Path,\n Point,\n Range,\n Scrubber,\n Selection,\n Text,\n} from '..'\n\nexport interface GeneralTransforms {\n transform: (editor: Editor, op: Operation) => void\n}\n\nconst applyToDraft = (editor: Editor, selection: Selection, op: Operation) => {\n switch (op.type) {\n case 'insert_node': {\n const { path, node } = op\n const parent = Node.parent(editor, path)\n const index = path[path.length - 1]\n\n if (index > parent.children.length) {\n throw new Error(\n `Cannot apply an \"insert_node\" operation at path [${path}] because the destination is past the end of the node.`\n )\n }\n\n parent.children.splice(index, 0, node)\n\n if (selection) {\n for (const [point, key] of Range.points(selection)) {\n selection[key] = Point.transform(point, op)!\n }\n }\n\n break\n }\n\n case 'insert_text': {\n const { path, offset, text } = op\n if (text.length === 0) break\n const node = Node.leaf(editor, path)\n const before = node.text.slice(0, offset)\n const after = node.text.slice(offset)\n node.text = before + text + after\n\n if (selection) {\n for (const [point, key] of Range.points(selection)) {\n selection[key] = Point.transform(point, op)!\n }\n }\n\n break\n }\n\n case 'merge_node': {\n const { path } = op\n const node = Node.get(editor, path)\n const prevPath = Path.previous(path)\n const prev = Node.get(editor, prevPath)\n const parent = Node.parent(editor, path)\n const index = path[path.length - 1]\n\n if (Text.isText(node) && Text.isText(prev)) {\n prev.text += node.text\n } else if (!Text.isText(node) && !Text.isText(prev)) {\n prev.children.push(...node.children)\n } else {\n throw new Error(\n `Cannot apply a \"merge_node\" operation at path [${path}] to nodes of different interfaces: ${Scrubber.stringify(\n node\n )} ${Scrubber.stringify(prev)}`\n )\n }\n\n parent.children.splice(index, 1)\n\n if (selection) {\n for (const [point, key] of Range.points(selection)) {\n selection[key] = Point.transform(point, op)!\n }\n }\n\n break\n }\n\n case 'move_node': {\n const { path, newPath } = op\n\n if (Path.isAncestor(path, newPath)) {\n throw new Error(\n `Cannot move a path [${path}] to new path [${newPath}] because the destination is inside itself.`\n )\n }\n\n const node = Node.get(editor, path)\n const parent = Node.parent(editor, path)\n const index = path[path.length - 1]\n\n // This is tricky, but since the `path` and `newPath` both refer to\n // the same snapshot in time, there's a mismatch. After either\n // removing the original position, the second step's path can be out\n // of date. So instead of using the `op.newPath` directly, we\n // transform `op.path` to ascertain what the `newPath` would be after\n // the operation was applied.\n parent.children.splice(index, 1)\n const truePath = Path.transform(path, op)!\n const newParent = Node.get(editor, Path.parent(truePath)) as Ancestor\n const newIndex = truePath[truePath.length - 1]\n\n newParent.children.splice(newIndex, 0, node)\n\n if (selection) {\n for (const [point, key] of Range.points(selection)) {\n selection[key] = Point.transform(point, op)!\n }\n }\n\n break\n }\n\n case 'remove_node': {\n const { path } = op\n const index = path[path.length - 1]\n const parent = Node.parent(editor, path)\n parent.children.splice(index, 1)\n\n // Transform all of the points in the value, but if the point was in the\n // node that was removed we need to update the range or remove it.\n if (selection) {\n for (const [point, key] of Range.points(selection)) {\n const result = Point.transform(point, op)\n\n if (selection != null && result != null) {\n selection[key] = result\n } else {\n let prev: NodeEntry<Text> | undefined\n let next: NodeEntry<Text> | undefined\n\n for (const [n, p] of Node.texts(editor)) {\n if (Path.compare(p, path) === -1) {\n prev = [n, p]\n } else {\n next = [n, p]\n break\n }\n }\n\n let preferNext = false\n if (prev && next) {\n if (Path.equals(next[1], path)) {\n preferNext = !Path.hasPrevious(next[1])\n } else {\n preferNext =\n Path.common(prev[1], path).length <\n Path.common(next[1], path).length\n }\n }\n\n if (prev && !preferNext) {\n point.path = prev[1]\n point.offset = prev[0].text.length\n } else if (next) {\n point.path = next[1]\n point.offset = 0\n } else {\n selection = null\n }\n }\n }\n }\n\n break\n }\n\n case 'remove_text': {\n const { path, offset, text } = op\n if (text.length === 0) break\n const node = Node.leaf(editor, path)\n const before = node.text.slice(0, offset)\n const after = node.text.slice(offset + text.length)\n node.text = before + after\n\n if (selection) {\n for (const [point, key] of Range.points(selection)) {\n selection[key] = Point.transform(point, op)!\n }\n }\n\n break\n }\n\n case 'set_node': {\n const { path, properties, newProperties } = op\n\n if (path.length === 0) {\n throw new Error(`Cannot set properties on the root node!`)\n }\n\n const node = Node.get(editor, path)\n\n for (const key in newProperties) {\n if (key === 'children' || key === 'text') {\n throw new Error(`Cannot set the \"${key}\" property of nodes!`)\n }\n\n const value = newProperties[key]\n\n if (value == null) {\n delete node[key]\n } else {\n node[key] = value\n }\n }\n\n // properties that were previously defined, but are now missing, must be deleted\n for (const key in properties) {\n if (!newProperties.hasOwnProperty(key)) {\n delete node[key]\n }\n }\n\n break\n }\n\n case 'set_selection': {\n const { newProperties } = op\n\n if (newProperties == null) {\n selection = newProperties\n } else {\n if (selection == null) {\n if (!Range.isRange(newProperties)) {\n throw new Error(\n `Cannot apply an incomplete \"set_selection\" operation properties ${Scrubber.stringify(\n newProperties\n )} when there is no current selection.`\n )\n }\n\n selection = { ...newProperties }\n }\n\n for (const key in newProperties) {\n const value = newProperties[key]\n\n if (value == null) {\n if (key === 'anchor' || key === 'focus') {\n throw new Error(`Cannot remove the \"${key}\" selection property`)\n }\n\n delete selection[key]\n } else {\n selection[key] = value\n }\n }\n }\n\n break\n }\n\n case 'split_node': {\n const { path, position, properties } = op\n\n if (path.length === 0) {\n throw new Error(\n `Cannot apply a \"split_node\" operation at path [${path}] because the root node cannot be split.`\n )\n }\n\n const node = Node.get(editor, path)\n const parent = Node.parent(editor, path)\n const index = path[path.length - 1]\n let newNode: Descendant\n\n if (Text.isText(node)) {\n const before = node.text.slice(0, position)\n const after = node.text.slice(position)\n node.text = before\n newNode = {\n ...(properties as Partial<Text>),\n text: after,\n }\n } else {\n const before = node.children.slice(0, position)\n const after = node.children.slice(position)\n node.children = before\n\n newNode = {\n ...(properties as Partial<Element>),\n children: after,\n }\n }\n\n parent.children.splice(index + 1, 0, newNode)\n\n if (selection) {\n for (const [point, key] of Range.points(selection)) {\n selection[key] = Point.transform(point, op)!\n }\n }\n\n break\n }\n }\n return selection\n}\n\n// eslint-disable-next-line no-redeclare\nexport const GeneralTransforms: GeneralTransforms = {\n /**\n * Transform the editor by an operation.\n */\n\n transform(editor: Editor, op: Operation): void {\n editor.children = createDraft(editor.children)\n let selection = editor.selection && createDraft(editor.selection)\n\n try {\n selection = applyToDraft(editor, selection, op)\n } finally {\n editor.children = finishDraft(editor.children)\n\n if (selection) {\n editor.selection = isDraft(selection)\n ? (finishDraft(selection) as Range)\n : selection\n } else {\n editor.selection = null\n }\n }\n },\n}\n","import {\n Ancestor,\n Editor,\n Element,\n Location,\n Node,\n NodeEntry,\n Path,\n Point,\n Range,\n Scrubber,\n Text,\n Transforms,\n} from '..'\nimport { NodeMatch, PropsCompare, PropsMerge } from '../interfaces/editor'\nimport { PointRef } from '../interfaces/point-ref'\nimport { RangeMode, MaximizeMode } from '../interfaces/types'\n\nexport interface NodeTransforms {\n insertNodes: <T extends Node>(\n editor: Editor,\n nodes: Node | Node[],\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: RangeMode\n hanging?: boolean\n select?: boolean\n voids?: boolean\n }\n ) => void\n liftNodes: <T extends Node>(\n editor: Editor,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n voids?: boolean\n }\n ) => void\n mergeNodes: <T extends Node>(\n editor: Editor,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: RangeMode\n hanging?: boolean\n voids?: boolean\n }\n ) => void\n moveNodes: <T extends Node>(\n editor: Editor,\n options: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n to: Path\n voids?: boolean\n }\n ) => void\n removeNodes: <T extends Node>(\n editor: Editor,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: RangeMode\n hanging?: boolean\n voids?: boolean\n }\n ) => void\n setNodes: <T extends Node>(\n editor: Editor,\n props: Partial<T>,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n hanging?: boolean\n split?: boolean\n voids?: boolean\n compare?: PropsCompare\n merge?: PropsMerge\n }\n ) => void\n splitNodes: <T extends Node>(\n editor: Editor,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: RangeMode\n always?: boolean\n height?: number\n voids?: boolean\n }\n ) => void\n unsetNodes: <T extends Node>(\n editor: Editor,\n props: string | string[],\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n split?: boolean\n voids?: boolean\n }\n ) => void\n unwrapNodes: <T extends Node>(\n editor: Editor,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n split?: boolean\n voids?: boolean\n }\n ) => void\n wrapNodes: <T extends Node>(\n editor: Editor,\n element: Element,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n split?: boolean\n voids?: boolean\n }\n ) => void\n}\n\n// eslint-disable-next-line no-redeclare\nexport const NodeTransforms: NodeTransforms = {\n /**\n * Insert nodes at a specific location in the Editor.\n */\n\n insertNodes<T extends Node>(\n editor: Editor,\n nodes: Node | Node[],\n options: {\n at?: Location\n match?: NodeMatch<T>\n mode?: RangeMode\n hanging?: boolean\n select?: boolean\n voids?: boolean\n } = {}\n ): void {\n Editor.withoutNormalizing(editor, () => {\n const { hanging = false, voids = false, mode = 'lowest' } = options\n let { at, match, select } = options\n\n if (Node.isNode(nodes)) {\n nodes = [nodes]\n }\n\n if (nodes.length === 0) {\n return\n }\n\n const [node] = nodes\n\n // By default, use the selection as the target location. But if there is\n // no selection, insert at the end of the document since that is such a\n // common use case when inserting from a non-selected state.\n if (!at) {\n if (editor.selection) {\n at = editor.selection\n } else if (editor.children.length > 0) {\n at = Editor.end(editor, [])\n } else {\n at = [0]\n }\n\n select = true\n }\n\n if (select == null) {\n select = false\n }\n\n if (Range.isRange(at)) {\n if (!hanging) {\n at = Editor.unhangRange(editor, at)\n }\n\n if (Range.isCollapsed(at)) {\n at = at.anchor\n } else {\n const [, end] = Range.edges(at)\n const pointRef = Editor.pointRef(editor, end)\n Transforms.delete(editor, { at })\n at = pointRef.unref()!\n }\n }\n\n if (Point.isPoint(at)) {\n if (match == null) {\n if (Text.isText(node)) {\n match = n => Text.isText(n)\n } else if (editor.isInline(node)) {\n match = n => Text.isText(n) || Editor.isInline(editor, n)\n } else {\n match = n => Editor.isBlock(editor, n)\n }\n }\n\n const [entry] = Editor.nodes(editor, {\n at: at.path,\n match,\n mode,\n voids,\n })\n\n if (entry) {\n const [, matchPath] = entry\n const pathRef = Editor.pathRef(editor, matchPath)\n const isAtEnd = Editor.isEnd(editor, at, matchPath)\n Transforms.splitNodes(editor, { at, match, mode, voids })\n const path = pathRef.unref()!\n at = isAtEnd ? Path.next(path) : path\n } else {\n return\n }\n }\n\n const parentPath = Path.parent(at)\n let index = at[at.length - 1]\n\n if (!voids && Editor.void(editor, { at: parentPath })) {\n return\n }\n\n for (const node of nodes) {\n const path = parentPath.concat(index)\n index++\n editor.apply({ type: 'insert_node', path, node })\n at = Path.next(at)\n }\n at = Path.previous(at)\n\n if (select) {\n const point = Editor.end(editor, at)\n\n if (point) {\n Transforms.select(editor, point)\n }\n }\n })\n },\n\n /**\n * Lift nodes at a specific location upwards in the document tree, splitting\n * their parent in two if necessary.\n */\n\n liftNodes<T extends Node>(\n editor: Editor,\n options: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n voids?: boolean\n } = {}\n ): void {\n Editor.withoutNormalizing(editor, () => {\n const { at = editor.selection, mode = 'lowest', voids = false } = options\n let { match } = options\n\n if (match == null) {\n match = Path.isPath(at)\n ? matchPath(editor, at)\n : n => Editor.isBlock(editor, n)\n }\n\n if (!at) {\n return\n }\n\n const matches = Editor.nodes(editor, { at, match, mode, voids })\n const pathRefs = Array.from(matches, ([, p]) => Editor.pathRef(editor, p))\n\n for (const pathRef of pathRefs) {\n const path = pathRef.unref()!\n\n if (path.length < 2) {\n throw new Error(\n `Cannot lift node at a path [${path}] because it has a depth of less than \\`2\\`.`\n )\n }\n\n const parentNodeEntry = Editor.node(editor, Path.parent(path))\n const [parent, parentPath] = parentNodeEntry as NodeEntry<Ancestor>\n const index = path[path.length - 1]\n const { length } = parent.children\n\n if (length === 1) {\n const toPath = Path.next(parentPath)\n Transforms.moveNodes(editor, { at: path, to: toPath, voids })\n Transforms.removeNodes(editor, { at: parentPath, voids })\n } else if (index === 0) {\n Transforms.moveNodes(editor, { at: path, to: parentPath, voids })\n } else if (index === length - 1) {\n const toPath = Path.next(parentPath)\n Transforms.moveNodes(editor, { at: path, to: toPath, voids })\n } else {\n const splitPath = Path.next(path)\n const toPath = Path.next(parentPath)\n Transforms.splitNodes(editor, { at: splitPath, voids })\n Transforms.moveNodes(editor, { at: path, to: toPath, voids })\n }\n }\n })\n },\n\n /**\n * Merge a node at a location with the previous node of the same depth,\n * removing any empty containing nodes after the merge if necessary.\n */\n\n mergeNodes<T extends Node>(\n editor: Editor,\n options: {\n at?: Location\n match?: NodeMatch<T>\n mode?: RangeMode\n hanging?: boolean\n voids?: boolean\n } = {}\n ): void {\n Editor.withoutNormalizing(editor, () => {\n let { match, at = editor.selection } = options\n const { hanging = false, voids = false, mode = 'lowest' } = options\n\n if (!at) {\n return\n }\n\n if (match == null) {\n if (Path.isPath(at)) {\n const [parent] = Editor.parent(editor, at)\n match = n => parent.children.includes(n)\n } else {\n match = n => Editor.isBlock(editor, n)\n }\n }\n\n if (!hanging && Range.isRange(at)) {\n at = Editor.unhangRange(editor, at)\n }\n\n if (Range.isRange(at)) {\n if (Range.isCollapsed(at)) {\n at = at.anchor\n } else {\n const [, end] = Range.edges(at)\n const pointRef = Editor.pointRef(editor, end)\n Transforms.delete(editor, { at })\n at = pointRef.unref()!\n\n if (options.at == null) {\n Transforms.select(editor, at)\n }\n }\n }\n\n const [current] = Editor.nodes(editor, { at, match, voids, mode })\n const prev = Editor.previous(editor, { at, match, voids, mode })\n\n if (!current || !prev) {\n return\n }\n\n const [node, path] = current\n const [prevNode, prevPath] = prev\n\n if (path.length === 0 || prevPath.length === 0) {\n return\n }\n\n const newPath = Path.next(prevPath)\n const commonPath = Path.common(path, prevPath)\n const isPreviousSibling = Path.isSibling(path, prevPath)\n const levels = Array.from(Editor.levels(editor, { at: path }), ([n]) => n)\n .slice(commonPath.length)\n .slice(0, -1)\n\n // Determine if the merge will leave an ancestor of the path empty as a\n // result, in which case we'll want to remove it after merging.\n const emptyAncestor = Editor.above(editor, {\n at: path,\n mode: 'highest',\n match: n => levels.includes(n) && hasSingleChildNest(editor, n),\n })\n\n const emptyRef = emptyAncestor && Editor.pathRef(editor, emptyAncestor[1])\n let properties\n let position\n\n // Ensure that the nodes are equivalent, and figure out what the position\n // and extra properties of the merge will be.\n if (Text.isText(node) && Text.isText(prevNode)) {\n const { text, ...rest } = node\n position = prevNode.text.length\n properties = rest as Partial<Text>\n } else if (Element.isElement(node) && Element.isElement(prevNode)) {\n const { children, ...rest } = node\n position = prevNode.children.length\n properties = rest as Partial<Element>\n } else {\n throw new Error(\n `Cannot merge the node at path [${path}] with the previous sibling because it is not the same kind: ${Scrubber.stringify(\n node\n )} ${Scrubber.stringify(prevNode)}`\n )\n }\n\n // If the node isn't already the next sibling of the previous node, move\n // it so that it is before merging.\n if (!isPreviousSibling) {\n Transforms.moveNodes(editor, { at: path, to: newPath, voids })\n }\n\n // If there was going to be an empty ancestor of the node that was merged,\n // we remove it from the tree.\n if (emptyRef) {\n Transforms.removeNodes(editor, { at: emptyRef.current!, voids })\n }\n\n // If the target node that we're merging with is empty, remove it instead\n // of merging the two. This is a common rich text editor behavior to\n // prevent losing formatting when deleting entire nodes when you have a\n // hanging selection.\n // if prevNode is first child in parent,don't remove it.\n if (\n (Element.isElement(prevNode) && Editor.isEmpty(editor, prevNode)) ||\n (Text.isText(prevNode) &&\n prevNode.text === '' &&\n prevPath[prevPath.length - 1] !== 0)\n ) {\n Transforms.removeNodes(editor, { at: prevPath, voids })\n } else {\n editor.apply({\n type: 'merge_node',\n path: newPath,\n position,\n properties,\n })\n }\n\n if (emptyRef) {\n emptyRef.unref()\n }\n })\n },\n\n /**\n * Move the nodes at a location to a new location.\n */\n\n moveNodes<T extends Node>(\n editor: Editor,\n options: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n to: Path\n voids?: boolean\n }\n ): void {\n Editor.withoutNormalizing(editor, () => {\n const {\n to,\n at = editor.selection,\n mode = 'lowest',\n voids = false,\n } = options\n let { match } = options\n\n if (!at) {\n return\n }\n\n if (match == null) {\n match = Path.isPath(at)\n ? matchPath(editor, at)\n : n => Editor.isBlock(editor, n)\n }\n\n const toRef = Editor.pathRef(editor, to)\n const targets = Editor.nodes(editor, { at, match, mode, voids })\n const pathRefs = Array.from(targets, ([, p]) => Editor.pathRef(editor, p))\n\n for (const pathRef of pathRefs) {\n const path = pathRef.unref()!\n const newPath = toRef.current!\n\n if (path.length !== 0) {\n editor.apply({ type: 'move_node', path, newPath })\n }\n\n if (\n toRef.current &&\n Path.isSibling(newPath, path) &&\n Path.isAfter(newPath, path)\n ) {\n // When performing a sibling move to a later index, the path at the destination is shifted\n // to before the insertion point instead of after. To ensure our group of nodes are inserted\n // in the correct order we increment toRef to account for that\n toRef.current = Path.next(toRef.current)\n }\n }\n\n toRef.unref()\n })\n },\n\n /**\n * Remove the nodes at a specific location in the document.\n */\n\n removeNodes<T extends Node>(\n editor: Editor,\n options: {\n at?: Location\n match?: NodeMatch<T>\n mode?: RangeMode\n hanging?: boolean\n voids?: boolean\n } = {}\n ): void {\n Editor.withoutNormalizing(editor, () => {\n const { hanging = false, voids = false, mode = 'lowest' } = options\n let { at = editor.selection, match } = options\n\n if (!at) {\n return\n }\n\n if (match == null) {\n match = Path.isPath(at)\n ? matchPath(editor, at)\n : n => Editor.isBlock(editor, n)\n }\n\n if (!hanging && Range.isRange(at)) {\n at = Editor.unhangRange(editor, at)\n }\n\n const depths = Editor.nodes(editor, { at, match, mode, voids })\n const pathRefs = Array.from(depths, ([, p]) => Editor.pathRef(editor, p))\n\n for (const pathRef of pathRefs) {\n const path = pathRef.unref()!\n\n if (path) {\n const [node] = Editor.node(editor, path)\n editor.apply({ type: 'remove_node', path, node })\n }\n }\n })\n },\n\n /**\n * Set new properties on the nodes at a location.\n */\n\n setNodes<T extends Node>(\n editor: Editor,\n props: Partial<Node>,\n options: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n hanging?: boolean\n split?: boolean\n voids?: boolean\n compare?: PropsCompare\n merge?: PropsMerge\n } = {}\n ): void {\n Editor.withoutNormalizing(editor, () => {\n let { match, at = editor.selection, compare, merge } = options\n const {\n hanging = false,\n mode = 'lowest',\n split = false,\n voids = false,\n } = options\n\n if (!at) {\n return\n }\n\n if (match == null) {\n match = Path.isPath(at)\n ? matchPath(editor, at)\n : n => Editor.isBlock(editor, n)\n }\n\n if (!hanging && Range.isRange(at)) {\n at = Editor.unhangRange(editor, at)\n }\n\n if (split && Range.isRange(at)) {\n if (\n Range.isCollapsed(at) &&\n Editor.leaf(editor, at.anchor)[0].text.length > 0\n ) {\n // If the range is collapsed in a non-empty node and 'split' is true, there's nothing to\n // set that won't get normalized away\n return\n }\n const rangeRef = Editor.rangeRef(editor, at, { affinity: 'inward' })\n const [start, end] = Range.edges(at)\n const splitMode = mode === 'lowest' ? 'lowest' : 'highest'\n const endAtEndOfNode = Editor.isEnd(editor, end, end.path)\n Transforms.splitNodes(editor, {\n at: end,\n match,\n mode: splitMode,\n voids,\n always: !endAtEndOfNode,\n })\n const startAtStartOfNode = Editor.isStart(editor, start, start.path)\n Transforms.splitNodes(editor, {\n at: start,\n match,\n mode: splitMode,\n voids,\n always: !startAtStartOfNode,\n })\n at = rangeRef.unref()!\n\n if (options.at == null) {\n Transforms.select(editor, at)\n }\n }\n\n if (!compare) {\n compare = (prop, nodeProp) => prop !== nodeProp\n }\n\n for (const [node, path] of Editor.nodes(editor, {\n at,\n match,\n mode,\n voids,\n })) {\n const properties: Partial<Node> = {}\n const newProperties: Partial<Node> = {}\n\n // You can't set properties on the editor node.\n if (path.length === 0) {\n continue\n }\n\n let hasChanges = false\n\n for (const k in props) {\n if (k === 'children' || k === 'text') {\n continue\n }\n\n if (compare(props[k], node[k])) {\n hasChanges = true\n // Omit new properties from the old properties list\n if (node.hasOwnProperty(k)) properties[k] = node[k]\n // Omit properties that have been removed from the new properties list\n if (merge) {\n if (props[k] != null) newProperties[k] = merge(node[k], props[k])\n } else {\n if (props[k] != null) newProperties[k] = props[k]\n }\n }\n }\n\n if (hasChanges) {\n editor.apply({\n type: 'set_node',\n path,\n properties,\n newProperties,\n })\n }\n }\n })\n },\n\n /**\n * Split the nodes at a specific location.\n */\n\n splitNodes<T extends Node>(\n editor: Editor,\n options: {\n at?: Location\n match?: NodeMatch<T>\n mode?: RangeMode\n always?: boolean\n height?: number\n voids?: boolean\n } = {}\n ): void {\n Editor.withoutNormalizing(editor, () => {\n const { mode = 'lowest', voids = false } = options\n let { match, at = editor.selection, height = 0, always = false } = options\n\n if (match == null) {\n match = n => Editor.isBlock(editor, n)\n }\n\n if (Range.isRange(at)) {\n at = deleteRange(editor, at)\n }\n\n // If the target is a path, the default height-skipping and position\n // counters need to account for us potentially splitting at a non-leaf.\n if (Path.isPath(at)) {\n const path = at\n const point = Editor.point(editor, path)\n const [parent] = Editor.parent(editor, path)\n match = n => n === parent\n height = point.path.length - path.length + 1\n at = point\n always = true\n }\n\n if (!at) {\n return\n }\n\n const beforeRef = Editor.pointRef(editor, at, {\n affinity: 'backward',\n })\n let afterRef: PointRef | undefined\n try {\n const [highest] = Editor.nodes(editor, { at, match, mode, voids })\n\n if (!highest) {\n return\n }\n\n const voidMatch = Editor.void(editor, { at, mode: 'highest' })\n const nudge = 0\n\n if (!voids && voidMatch) {\n const [voidNode, voidPath] = voidMatch\n\n if (Element.isElement(voidNode) && editor.isInline(voidNode)) {\n let after = Editor.after(editor, voidPath)\n\n if (!after) {\n const text = { text: '' }\n const afterPath = Path.next(voidPath)\n Transforms.insertNodes(editor, text, { at: afterPath, voids })\n after = Editor.point(editor, afterPath)!\n }\n\n at = after\n always = true\n }\n\n const siblingHeight = at.path.length - voidPath.length\n height = siblingHeight + 1\n always = true\n }\n\n afterRef = Editor.pointRef(editor, at)\n const depth = at.path.length - height\n const [, highestPath] = highest\n const lowestPath = at.path.slice(0, depth)\n let position = height === 0 ? at.offset : at.path[depth] + nudge\n\n for (const [node, path] of Editor.levels(editor, {\n at: lowestPath,\n reverse: true,\n voids,\n })) {\n let split = false\n\n if (\n path.length < highestPath.length ||\n path.length === 0 ||\n (!voids && Editor.isVoid(editor, node))\n ) {\n break\n }\n\n const point = beforeRef.current!\n const isEnd = Editor.isEnd(editor, point, path)\n\n if (always || !beforeRef || !Editor.isEdge(editor, point, path)) {\n split = true\n const properties = Node.extractProps(node)\n editor.apply({\n type: 'split_node',\n path,\n position,\n properties,\n })\n }\n\n position = path[path.length - 1] + (split || isEnd ? 1 : 0)\n }\n\n if (options.at == null) {\n const point = afterRef.current || Editor.end(editor, [])\n Transforms.select(editor, point)\n }\n } finally {\n beforeRef.unref()\n afterRef?.unref()\n }\n })\n },\n\n /**\n * Unset properties on the nodes at a location.\n */\n\n unsetNodes<T extends Node>(\n editor: Editor,\n props: string | string[],\n options: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n split?: boolean\n voids?: boolean\n } = {}\n ): void {\n if (!Array.isArray(props)) {\n props = [props]\n }\n\n const obj = {}\n\n for (const key of props) {\n obj[key] = null\n }\n\n Transforms.setNodes(editor, obj, options)\n },\n\n /**\n * Unwrap the nodes at a location from a parent node, splitting the parent if\n * necessary to ensure that only the content in the range is unwrapped.\n */\n\n unwrapNodes<T extends Node>(\n editor: Editor,\n options: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n split?: boolean\n voids?: boolean\n } = {}\n ): void {\n Editor.withoutNormalizing(editor, () => {\n const { mode = 'lowest', split = false, voids = false } = options\n let { at = editor.selection, match } = options\n\n if (!at) {\n return\n }\n\n if (match == null) {\n match = Path.isPath(at)\n ? matchPath(editor, at)\n : n => Editor.isBlock(editor, n)\n }\n\n if (Path.isPath(at)) {\n at = Editor.range(editor, at)\n }\n\n const rangeRef = Range.isRange(at) ? Editor.rangeRef(editor, at) : null\n const matches = Editor.nodes(editor, { at, match, mode, voids })\n const pathRefs = Array.from(\n matches,\n ([, p]) => Editor.pathRef(editor, p)\n // unwrapNode will call liftNode which does not support splitting the node when nested.\n // If we do not reverse the order and call it from top to the bottom, it will remove all blocks\n // that wrap target node. So we reverse the order.\n ).reverse()\n\n for (const pathRef of pathRefs) {\n const path = pathRef.unref()!\n const [node] = Editor.node(editor, path)\n let range = Editor.range(editor, path)\n\n if (split && rangeRef) {\n range = Range.intersection(rangeRef.current!, range)!\n }\n\n Transforms.liftNodes(editor, {\n at: range,\n match: n => Element.isAncestor(node) && node.children.includes(n),\n voids,\n })\n }\n\n if (rangeRef) {\n rangeRef.unref()\n }\n })\n },\n\n /**\n * Wrap the nodes at a location in a new container node, splitting the edges\n * of the range first to ensure that only the content in the range is wrapped.\n */\n\n wrapNodes<T extends Node>(\n editor: Editor,\n element: Element,\n options: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n split?: boolean\n voids?: boolean\n } = {}\n ): void {\n Editor.withoutNormalizing(editor, () => {\n const { mode = 'lowest', split = false, voids = false } = options\n let { match, at = editor.selection } = options\n\n if (!at) {\n return\n }\n\n if (match == null) {\n if (Path.isPath(at)) {\n match = matchPath(editor, at)\n } else if (editor.isInline(element)) {\n match = n => Editor.isInline(editor, n) || Text.isText(n)\n } else {\n match = n => Editor.isBlock(editor, n)\n }\n }\n\n if (split && Range.isRange(at)) {\n const [start, end] = Range.edges(at)\n const rangeRef = Editor.rangeRef(editor, at, {\n affinity: 'inward',\n })\n Transforms.splitNodes(editor, { at: end, match, voids })\n Transforms.splitNodes(editor, { at: start, match, voids })\n at = rangeRef.unref()!\n\n if (options.at == null) {\n Transforms.select(editor, at)\n }\n }\n\n const roots = Array.from(\n Editor.nodes(editor, {\n at,\n match: editor.isInline(element)\n ? n => Editor.isBlock(editor, n)\n : n => Editor.isEditor(n),\n mode: 'lowest',\n voids,\n })\n )\n\n for (const [, rootPath] of roots) {\n const a = Range.isRange(at)\n ? Range.intersection(at, Editor.range(editor, rootPath))\n : at\n\n if (!a) {\n continue\n }\n\n const matches = Array.from(\n Editor.nodes(editor, { at: a, match, mode, voids })\n )\n\n if (matches.length > 0) {\n const [first] = matches\n const last = matches[matches.length - 1]\n const [, firstPath] = first\n const [, lastPath] = last\n\n if (firstPath.length === 0 && lastPath.length === 0) {\n // if there's no matching parent - usually means the node is an editor - don't do anything\n continue\n }\n\n const commonPath = Path.equals(firstPath, lastPath)\n ? Path.parent(firstPath)\n : Path.common(firstPath, lastPath)\n\n const range = Editor.range(editor, firstPath, lastPath)\n const commonNodeEntry = Editor.node(editor, commonPath)\n const [commonNode] = commonNodeEntry\n const depth = commonPath.length + 1\n const wrapperPath = Path.next(lastPath.slice(0, depth))\n const wrapper = { ...element, children: [] }\n Transforms.insertNodes(editor, wrapper, { at: wrapperPath, voids })\n\n Transforms.moveNodes(editor, {\n at: range,\n match: n =>\n Element.isAncestor(commonNode) && commonNode.children.includes(n),\n to: wrapperPath.concat(0),\n voids,\n })\n }\n }\n })\n },\n}\n\nconst hasSingleChildNest = (editor: Editor, node: Node): boolean => {\n if (Element.isElement(node)) {\n const element = node as Element\n if (Editor.isVoid(editor, node)) {\n return true\n } else if (element.children.length === 1) {\n return hasSingleChildNest(editor, element.children[0])\n } else {\n return false\n }\n } else if (Editor.isEditor(node)) {\n return false\n } else {\n return true\n }\n}\n\n/**\n * Convert a range into a point by deleting it's content.\n */\n\nconst deleteRange = (editor: Editor, range: Range): Point | null => {\n if (Range.isCollapsed(range)) {\n return range.anchor\n } else {\n const [, end] = Range.edges(range)\n const pointRef = Editor.pointRef(editor, end)\n Transforms.delete(editor, { at: range })\n return pointRef.unref()\n }\n}\n\nconst matchPath = (editor: Editor, path: Path): ((node: Node) => boolean) => {\n const [node] = Editor.node(editor, path)\n return n => n === node\n}\n","import { Editor, Location, Point, Range, Scrubber, Transforms } from '..'\nimport { SelectionEdge, MoveUnit } from '../interfaces/types'\n\nexport interface SelectionCollapseOptions {\n edge?: SelectionEdge\n}\n\nexport interface SelectionMoveOptions {\n distance?: number\n unit?: MoveUnit\n reverse?: boolean\n edge?: SelectionEdge\n}\n\nexport interface SelectionSetPointOptions {\n edge?: SelectionEdge\n}\n\nexport interface SelectionTransforms {\n collapse: (editor: Editor, options?: SelectionCollapseOptions) => void\n deselect: (editor: Editor) => void\n move: (editor: Editor, options?: SelectionMoveOptions) => void\n select: (editor: Editor, target: Location) => void\n setPoint: (\n editor: Editor,\n props: Partial<Point>,\n options?: SelectionSetPointOptions\n ) => void\n setSelection: (editor: Editor, props: Partial<Range>) => void\n}\n\n// eslint-disable-next-line no-redeclare\nexport const SelectionTransforms: SelectionTransforms = {\n /**\n * Collapse the selection.\n */\n\n collapse(editor: Editor, options: SelectionCollapseOptions = {}): void {\n const { edge = 'anchor' } = options\n const { selection } = editor\n\n if (!selection) {\n return\n } else if (edge === 'anchor') {\n Transforms.select(editor, selection.anchor)\n } else if (edge === 'focus') {\n Transforms.select(editor, selection.focus)\n } else if (edge === 'start') {\n const [start] = Range.edges(selection)\n Transforms.select(editor, start)\n } else if (edge === 'end') {\n const [, end] = Range.edges(selection)\n Transforms.select(editor, end)\n }\n },\n\n /**\n * Unset the selection.\n */\n\n deselect(editor: Editor): void {\n const { selection } = editor\n\n if (selection) {\n editor.apply({\n type: 'set_selection',\n properties: selection,\n newProperties: null,\n })\n }\n },\n\n /**\n * Move the selection's point forward or backward.\n */\n\n move(editor: Editor, options: SelectionMoveOptions = {}): void {\n const { selection } = editor\n const { distance = 1, unit = 'character', reverse = false } = options\n let { edge = null } = options\n\n if (!selection) {\n return\n }\n\n if (edge === 'start') {\n edge = Range.isBackward(selection) ? 'focus' : 'anchor'\n }\n\n if (edge === 'end') {\n edge = Range.isBackward(selection) ? 'anchor' : 'focus'\n }\n\n const { anchor, focus } = selection\n const opts = { distance, unit }\n const props: Partial<Range> = {}\n\n if (edge == null || edge === 'anchor') {\n const point = reverse\n ? Editor.before(editor, anchor, opts)\n : Editor.after(editor, anchor, opts)\n\n if (point) {\n props.anchor = point\n }\n }\n\n if (edge == null || edge === 'focus') {\n const point = reverse\n ? Editor.before(editor, focus, opts)\n : Editor.after(editor, focus, opts)\n\n if (point) {\n props.focus = point\n }\n }\n\n Transforms.setSelection(editor, props)\n },\n\n /**\n * Set the selection to a new value.\n */\n\n select(editor: Editor, target: Location): void {\n const { selection } = editor\n target = Editor.range(editor, target)\n\n if (selection) {\n Transforms.setSelection(editor, target)\n return\n }\n\n if (!Range.isRange(target)) {\n throw new Error(\n `When setting the selection and the current selection is \\`null\\` you must provide at least an \\`anchor\\` and \\`focus\\`, but you passed: ${Scrubber.stringify(\n target\n )}`\n )\n }\n\n editor.apply({\n type: 'set_selection',\n properties: selection,\n newProperties: target,\n })\n },\n\n /**\n * Set new properties on one of the selection's points.\n */\n\n setPoint(\n editor: Editor,\n props: Partial<Point>,\n options: SelectionSetPointOptions = {}\n ): void {\n const { selection } = editor\n let { edge = 'both' } = options\n\n if (!selection) {\n return\n }\n\n if (edge === 'start') {\n edge = Range.isBackward(selection) ? 'focus' : 'anchor'\n }\n\n if (edge === 'end') {\n edge = Range.isBackward(selection) ? 'anchor' : 'focus'\n }\n\n const { anchor, focus } = selection\n const point = edge === 'anchor' ? anchor : focus\n\n Transforms.setSelection(editor, {\n [edge === 'anchor' ? 'anchor' : 'focus']: { ...point, ...props },\n })\n },\n\n /**\n * Set new properties on the selection.\n */\n\n setSelection(editor: Editor, props: Partial<Range>): void {\n const { selection } = editor\n const oldProps: Partial<Range> | null = {}\n const newProps: Partial<Range> = {}\n\n if (!selection) {\n return\n }\n\n for (const k in props) {\n if (\n (k === 'anchor' &&\n props.anchor != null &&\n !Point.equals(props.anchor, selection.anchor)) ||\n (k === 'focus' &&\n props.focus != null &&\n !Point.equals(props.focus, selection.focus)) ||\n (k !== 'anchor' && k !== 'focus' && props[k] !== selection[k])\n ) {\n oldProps[k] = selection[k]\n newProps[k] = props[k]\n }\n }\n\n if (Object.keys(oldProps).length > 0) {\n editor.apply({\n type: 'set_selection',\n properties: oldProps,\n newProperties: newProps,\n })\n }\n },\n}\n","import {\n Editor,\n Element,\n Location,\n Node,\n NodeEntry,\n Path,\n Text,\n Point,\n Range,\n Transforms,\n} from '..'\nimport { TextUnit } from '../interfaces/types'\n\nexport interface TextDeleteOptions {\n at?: Location\n distance?: number\n unit?: TextUnit\n reverse?: boolean\n hanging?: boolean\n voids?: boolean\n}\n\nexport interface TextInsertFragmentOptions {\n at?: Location\n hanging?: boolean\n voids?: boolean\n}\n\nexport interface TextInsertTextOptions {\n at?: Location\n voids?: boolean\n}\n\nexport interface TextTransforms {\n delete: (editor: Editor, options?: TextDeleteOptions) => void\n insertFragment: (\n editor: Editor,\n fragment: Node[],\n options?: TextInsertFragmentOptions\n ) => void\n insertText: (\n editor: Editor,\n text: string,\n options?: TextInsertTextOptions\n ) => void\n}\n\n// eslint-disable-next-line no-redeclare\nexport const TextTransforms: TextTransforms = {\n /**\n * Delete content in the editor.\n */\n\n delete(editor: Editor, options: TextDeleteOptions = {}): void {\n Editor.withoutNormalizing(editor, () => {\n const {\n reverse = false,\n unit = 'character',\n distance = 1,\n voids = false,\n } = options\n let { at = editor.selection, hanging = false } = options\n\n if (!at) {\n return\n }\n\n let isCollapsed = false\n if (Range.isRange(at) && Range.isCollapsed(at)) {\n isCollapsed = true\n at = at.anchor\n }\n\n if (Point.isPoint(at)) {\n const furthestVoid = Editor.void(editor, { at, mode: 'highest' })\n\n if (!voids && furthestVoid) {\n const [, voidPath] = furthestVoid\n at = voidPath\n } else {\n const opts = { unit, distance }\n const target = reverse\n ? Editor.before(editor, at, opts) || Editor.start(editor, [])\n : Editor.after(editor, at, opts) || Editor.end(editor, [])\n at = { anchor: at, focus: target }\n hanging = true\n }\n }\n\n if (Path.isPath(at)) {\n Transforms.removeNodes(editor, { at, voids })\n return\n }\n\n if (Range.isCollapsed(at)) {\n return\n }\n\n if (!hanging) {\n const [, end] = Range.edges(at)\n const endOfDoc = Editor.end(editor, [])\n\n if (!Point.equals(end, endOfDoc)) {\n at = Editor.unhangRange(editor, at, { voids })\n }\n }\n\n let [start, end] = Range.edges(at)\n const startBlock = Editor.above(editor, {\n match: n => Editor.isBlock(editor, n),\n at: start,\n voids,\n })\n const endBlock = Editor.above(editor, {\n match: n => Editor.isBlock(editor, n),\n at: end,\n voids,\n })\n const isAcrossBlocks =\n startBlock && endBlock && !Path.equals(startBlock[1], endBlock[1])\n const isSingleText = Path.equals(start.path, end.path)\n const startVoid = voids\n ? null\n : Editor.void(editor, { at: start, mode: 'highest' })\n const endVoid = voids\n ? null\n : Editor.void(editor, { at: end, mode: 'highest' })\n\n // If the start or end points are inside an inline void, nudge them out.\n if (startVoid) {\n const before = Editor.before(editor, start)\n\n if (\n before &&\n startBlock &&\n Path.isAncestor(startBlock[1], before.path)\n ) {\n start = before\n }\n }\n\n if (endVoid) {\n const after = Editor.after(editor, end)\n\n if (after && endBlock && Path.isAncestor(endBlock[1], after.path)) {\n end = after\n }\n }\n\n // Get the highest nodes that are completely inside the range, as well as\n // the start and end nodes.\n const matches: NodeEntry[] = []\n let lastPath: Path | undefined\n\n for (const entry of Editor.nodes(editor, { at, voids })) {\n const [node, path] = entry\n\n if (lastPath && Path.compare(path, lastPath) === 0) {\n continue\n }\n\n if (\n (!voids && Editor.isVoid(editor, node)) ||\n (!Path.isCommon(path, start.path) && !Path.isCommon(path, end.path))\n ) {\n matches.push(entry)\n lastPath = path\n }\n }\n\n const pathRefs = Array.from(matches, ([, p]) => Editor.pathRef(editor, p))\n const startRef = Editor.pointRef(editor, start)\n const endRef = Editor.pointRef(editor, end)\n\n let removedText = ''\n\n if (!isSingleText && !startVoid) {\n const point = startRef.current!\n const [node] = Editor.leaf(editor, point)\n const { path } = point\n const { offset } = start\n const text = node.text.slice(offset)\n if (text.length > 0) {\n editor.apply({ type: 'remove_text', path, offset, text })\n removedText = text\n }\n }\n\n for (const pathRef of pathRefs) {\n const path = pathRef.unref()!\n Transforms.removeNodes(editor, { at: path, voids })\n }\n\n if (!endVoid) {\n const point = endRef.current!\n const [node] = Editor.leaf(editor, point)\n const { path } = point\n const offset = isSingleText ? start.offset : 0\n const text = node.text.slice(offset, end.offset)\n if (text.length > 0) {\n editor.apply({ type: 'remove_text', path, offset, text })\n removedText = text\n }\n }\n\n if (\n !isSingleText &&\n isAcrossBlocks &&\n endRef.current &&\n startRef.current\n ) {\n Transforms.mergeNodes(editor, {\n at: endRef.current,\n hanging: true,\n voids,\n })\n }\n\n // For Thai script, deleting N character(s) backward should delete\n // N code point(s) instead of an entire grapheme cluster.\n // Therefore, the remaining code points should be inserted back.\n if (\n isCollapsed &&\n reverse &&\n unit === 'character' &&\n removedText.length > 1 &&\n removedText.match(/[\\u0E00-\\u0E7F]+/)\n ) {\n Transforms.insertText(\n editor,\n removedText.slice(0, removedText.length - distance)\n )\n }\n\n const startUnref = startRef.unref()\n const endUnref = endRef.unref()\n const point = reverse ? startUnref || endUnref : endUnref || startUnref\n\n if (options.at == null && point) {\n Transforms.select(editor, point)\n }\n })\n },\n\n /**\n * Insert a fragment at a specific location in the editor.\n */\n\n insertFragment(\n editor: Editor,\n fragment: Node[],\n options: TextInsertFragmentOptions = {}\n ): void {\n Editor.withoutNormalizing(editor, () => {\n const { hanging = false, voids = false } = options\n let { at = editor.selection } = options\n\n if (!fragment.length) {\n return\n }\n\n if (!at) {\n return\n } else if (Range.isRange(at)) {\n if (!hanging) {\n at = Editor.unhangRange(editor, at)\n }\n\n if (Range.isCollapsed(at)) {\n at = at.anchor\n } else {\n const [, end] = Range.edges(at)\n\n if (!voids && Editor.void(editor, { at: end })) {\n return\n }\n\n const pointRef = Editor.pointRef(editor, end)\n Transforms.delete(editor, { at })\n at = pointRef.unref()!\n }\n } else if (Path.isPath(at)) {\n at = Editor.start(editor, at)\n }\n\n if (!voids && Editor.void(editor, { at })) {\n return\n }\n\n // If the insert point is at the edge of an inline node, move it outside\n // instead since it will need to be split otherwise.\n const inlineElementMatch = Editor.above(editor, {\n at,\n match: n => Editor.isInline(editor, n),\n mode: 'highest',\n voids,\n })\n\n if (inlineElementMatch) {\n const [, inlinePath] = inlineElementMatch\n\n if (Editor.isEnd(editor, at, inlinePath)) {\n const after = Editor.after(editor, inlinePath)!\n at = after\n } else if (Editor.isStart(editor, at, inlinePath)) {\n const before = Editor.before(editor, inlinePath)!\n at = before\n }\n }\n\n const blockMatch = Editor.above(editor, {\n match: n => Editor.isBlock(editor, n),\n at,\n voids,\n })!\n const [, blockPath] = blockMatch\n const isBlockStart = Editor.isStart(editor, at, blockPath)\n const isBlockEnd = Editor.isEnd(editor, at, blockPath)\n const isBlockEmpty = isBlockStart && isBlockEnd\n const mergeStart = !isBlockStart || (isBlockStart && isBlockEnd)\n const mergeEnd = !isBlockEnd\n const [, firstPath] = Node.first({ children: fragment }, [])\n const [, lastPath] = Node.last({ children: fragment }, [])\n\n const matches: NodeEntry[] = []\n const matcher = ([n, p]: NodeEntry) => {\n const isRoot = p.length === 0\n if (isRoot) {\n return false\n }\n\n if (isBlockEmpty) {\n return true\n }\n\n if (\n mergeStart &&\n Path.isAncestor(p, firstPath) &&\n Element.isElement(n) &&\n !editor.isVoid(n) &&\n !editor.isInline(n)\n ) {\n return false\n }\n\n if (\n mergeEnd &&\n Path.isAncestor(p, lastPath) &&\n Element.isElement(n) &&\n !editor.isVoid(n) &&\n !editor.isInline(n)\n ) {\n return false\n }\n\n return true\n }\n\n for (const entry of Node.nodes(\n { children: fragment },\n { pass: matcher }\n )) {\n if (matcher(entry)) {\n matches.push(entry)\n }\n }\n\n const starts = []\n const middles = []\n const ends = []\n let starting = true\n let hasBlocks = false\n\n for (const [node] of matches) {\n if (Element.isElement(node) && !editor.isInline(node)) {\n starting = false\n hasBlocks = true\n middles.push(node)\n } else if (starting) {\n starts.push(node)\n } else {\n ends.push(node)\n }\n }\n\n const [inlineMatch] = Editor.nodes(editor, {\n at,\n match: n => Text.isText(n) || Editor.isInline(editor, n),\n mode: 'highest',\n voids,\n })!\n\n const [, inlinePath] = inlineMatch\n const isInlineStart = Editor.isStart(editor, at, inlinePath)\n const isInlineEnd = Editor.isEnd(editor, at, inlinePath)\n\n const middleRef = Editor.pathRef(\n editor,\n isBlockEnd && !ends.length ? Path.next(blockPath) : blockPath\n )\n\n const endRef = Editor.pathRef(\n editor,\n isInlineEnd ? Path.next(inlinePath) : inlinePath\n )\n\n Transforms.splitNodes(editor, {\n at,\n match: n =>\n hasBlocks\n ? Editor.isBlock(editor, n)\n : Text.isText(n) || Editor.isInline(editor, n),\n mode: hasBlocks ? 'lowest' : 'highest',\n always:\n hasBlocks &&\n (!isBlockStart || starts.length > 0) &&\n (!isBlockEnd || ends.length > 0),\n voids,\n })\n\n const startRef = Editor.pathRef(\n editor,\n !isInlineStart || (isInlineStart && isInlineEnd)\n ? Path.next(inlinePath)\n : inlinePath\n )\n\n Transforms.insertNodes(editor, starts, {\n at: startRef.current!,\n match: n => Text.isText(n) || Editor.isInline(editor, n),\n mode: 'highest',\n voids,\n })\n\n if (isBlockEmpty && !starts.length && middles.length && !ends.length) {\n Transforms.delete(editor, { at: blockPath, voids })\n }\n\n Transforms.insertNodes(editor, middles, {\n at: middleRef.current!,\n match: n => Editor.isBlock(editor, n),\n mode: 'lowest',\n voids,\n })\n\n Transforms.insertNodes(editor, ends, {\n at: endRef.current!,\n match: n => Text.isText(n) || Editor.isInline(editor, n),\n mode: 'highest',\n voids,\n })\n\n if (!options.at) {\n let path\n\n if (ends.length > 0 && endRef.current) {\n path = Path.previous(endRef.current)\n } else if (middles.length > 0 && middleRef.current) {\n path = Path.previous(middleRef.current)\n } else if (startRef.current) {\n path = Path.previous(startRef.current)\n }\n\n if (path) {\n const end = Editor.end(editor, path)\n Transforms.select(editor, end)\n }\n }\n\n startRef.unref()\n middleRef.unref()\n endRef.unref()\n })\n },\n\n /**\n * Insert a string of text in the Editor.\n */\n\n insertText(\n editor: Editor,\n text: string,\n options: TextInsertTextOptions = {}\n ): void {\n Editor.withoutNormalizing(editor, () => {\n const { voids = false } = options\n let { at = editor.selection } = options\n\n if (!at) {\n return\n }\n\n if (Path.isPath(at)) {\n at = Editor.range(editor, at)\n }\n\n if (Range.isRange(at)) {\n if (Range.isCollapsed(at)) {\n at = at.anchor\n } else {\n const end = Range.end(at)\n if (!voids && Editor.void(editor, { at: end })) {\n return\n }\n const start = Range.start(at)\n const startRef = Editor.pointRef(editor, start)\n const endRef = Editor.pointRef(editor, end)\n Transforms.delete(editor, { at, voids })\n const startPoint = startRef.unref()\n const endPoint = endRef.unref()\n\n at = startPoint || endPoint!\n Transforms.setSelection(editor, { anchor: at, focus: at })\n }\n }\n\n if (!voids && Editor.void(editor, { at })) {\n return\n }\n\n const { path, offset } = at\n if (text.length > 0)\n editor.apply({ type: 'insert_text', path, offset, text })\n })\n },\n}\n","import { GeneralTransforms } from './general'\nimport { NodeTransforms } from './node'\nimport { SelectionTransforms } from './selection'\nimport { TextTransforms } from './text'\n\nexport const Transforms: GeneralTransforms &\n NodeTransforms &\n SelectionTransforms &\n TextTransforms = {\n ...GeneralTransforms,\n ...NodeTransforms,\n ...SelectionTransforms,\n ...TextTransforms,\n}\n","/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map<any, any>}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template X,Y\n * @param {Map<X,Y>} m\n * @return {Map<X,Y>}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template T,K\n * @param {Map<K, T>} map\n * @param {K} key\n * @param {function():T} createT\n * @return {T}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map<K,V>} m\n * @param {function(V,K):R} f\n * @return {Array<R>}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map<K,V>} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map<K,V>} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set<T>} set\n * @return {Array<T>}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set<T>} set\n * @return {T}\n */\nexport const first = set => {\n return set.values().next().value || undefined\n}\n\n/**\n * @template T\n * @param {Iterable<T>} entries\n * @return {Set<T>}\n */\nexport const from = entries => {\n return new Set(entries)\n}\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {Array<L>} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array<C>}\n */\nexport const create = () => /** @type {Array<C>} */ ([])\n\n/**\n * @template D\n * @param {Array<D>} a\n * @return {Array<D>}\n */\nexport const copy = a => /** @type {Array<D>} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array<M>} dest\n * @param {Array<M>} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike<T>|Iterable<T>} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n *\n * @param {Array<ITEM>} arr\n * @param {function(ITEM, number, Array<ITEM>):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => arr.every(f)\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @param {Array<S>} arr\n * @param {function(S, number, Array<S>):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => arr.some(f)\n\n/**\n * @template ELEM\n *\n * @param {Array<ELEM>} a\n * @param {Array<ELEM>} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array<Array<ELEM>>} arr\n * @return {Array<ELEM>}\n */\nexport const flatten = arr => arr.reduce((acc, val) => acc.concat(val), [])\n\nexport const isArray = Array.isArray\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n *\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map<N, any>}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array<any>} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* istanbul ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* istanbul ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* istanbul ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* istanbul ignore next */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* istanbul ignore next */\n utf8TextDecoder = null\n}\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* istanbul ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n","/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* istanbul ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n","/* global localStorage, addEventListener */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* istanbul ignore next */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} newValue\n */\n setItem (key, newValue) {\n this.map.set(key, newValue)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n\n/* istanbul ignore next */\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\nlet usePolyfill = true\n\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n /* istanbul ignore next */\n if (typeof localStorage !== 'undefined') {\n _localStorage = localStorage\n usePolyfill = false\n }\n} catch (e) { }\n\n/* istanbul ignore next */\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\nexport const varStorage = _localStorage\n\n/* istanbul ignore next */\n/**\n * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\nexport const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))\n","/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module map\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\n\n/* istanbul ignore next */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release && /node|io\\.js/.test(process.release.name)\n/* istanbul ignore next */\nexport const isBrowser = typeof window !== 'undefined' && !isNode\n/* istanbul ignore next */\nexport const isMac = typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false\n\n/**\n * @type {Map<string,string>}\n */\nlet params\nconst args = []\n\n/* istanbul ignore next */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n /* istanbul ignore next */\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create()\n // eslint-disable-next-line no-undef\n ;(location.search || '?').slice(1).split('&').forEach(kv => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* istanbul ignore next */\nexport const hasParam = name => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* istanbul ignore next */\nexport const getParam = (name, defaultVal) => computeParams().get(name) || defaultVal\n// export const getArgs = name => computeParams() && args\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* istanbul ignore next */\nexport const getVariable = name => isNode ? conditions.undefinedToNull(process.env[name.toUpperCase()]) : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\nexport const getConf = name => computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* istanbul ignore next */\nexport const hasConf = name => hasParam('--' + name) || getVariable(name) !== null\n\n/* istanbul ignore next */\nexport const production = hasConf('production')\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = new encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = new decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as binary from './binary.js'\nimport * as math from './math.js'\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = buffer.createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let len = 0\n while (true) {\n const r = decoder.arr[decoder.pos++]\n num = num | ((r & binary.BITS7) << len)\n len += 7\n if (r < binary.BIT8) {\n return num >>> 0 // return unsigned number!\n }\n /* istanbul ignore if */\n if (len > 35) {\n throw new Error('Integer out of range!')\n }\n }\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let len = 6\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n while (true) {\n r = decoder.arr[decoder.pos++]\n num = num | ((r & binary.BITS7) << len)\n len += 7\n if (r < binary.BIT8) {\n return sign * (num >>> 0)\n }\n /* istanbul ignore if */\n if (len > 41) {\n throw new Error('Integer out of range!')\n }\n }\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\nexport const readVarString = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array<function(Decoder):any>}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object<string,any>\n const len = readVarUint(decoder)\n /**\n * @type {Object<string,any>}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array<any>\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = diff >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* istanbul ignore next */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* istanbul ignore next */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* istanbul ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* istanbul ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data => {\n const encoder = encoding.createEncoder()\n encoding.writeAny(encoder, data)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\n/**\n * @type {number}\n */\nexport const HIGHEST_INT32 = binary.BITS31\n\n/**\n * @module number\n */\n\n/* istanbul ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = new encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = new decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array<Uint8Array>}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nconst verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer.\n *\n * Encodes integers in the range from [0, 4294967295] / [0, 0xffffffff]. (max 32 bit unsigned integer)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num >>>= 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * Encodes integers in the range from [-2147483648, -2147483647].\n *\n * We don't use zig-zag encoding because we want to keep the option open\n * to use the same function for BigInt and 53bit integers (doubles).\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num >>>= 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num >>>= 7\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeVarString = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object<string,any> | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array<any> | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object<string,any>|Array<any>|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && data <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (data instanceof Array) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n /* istanbul ignore else */\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array<string>}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/* eslint-env browser */\nexport const performance = typeof window === 'undefined' ? null : (typeof window.performance !== 'undefined' && window.performance) || null\n\nconst isoCrypto = typeof crypto === 'undefined' ? null : crypto\n\n/**\n * @type {function(number):ArrayBuffer}\n */\nexport const cryptoRandomBuffer = isoCrypto !== null\n ? len => {\n // browser\n const buf = new ArrayBuffer(len)\n const arr = new Uint8Array(buf)\n isoCrypto.getRandomValues(arr)\n return buf\n }\n : len => {\n // polyfill\n const buf = new ArrayBuffer(len)\n const arr = new Uint8Array(buf)\n for (let i = 0; i < len; i++) {\n arr[i] = Math.ceil((Math.random() * 0xFFFFFFFF) >>> 0)\n }\n return buf\n }\n","\n/**\n * Isomorphic module for true random numbers / buffers / uuids.\n *\n * Attention: falls back to Math.random if the browser does not support crypto.\n *\n * @module random\n */\n\nimport * as math from './math.js'\nimport { cryptoRandomBuffer } from './isomorphic.js'\n\nexport const rand = Math.random\n\n/* istanbul ignore next */\nexport const uint32 = () => new Uint32Array(cryptoRandomBuffer(4))[0]\n\n/**\n * @template T\n * @param {Array<T>} arr\n * @return {T}\n */\nexport const oneOf = arr => arr[math.floor(rand() * arr.length)]\n\n// @ts-ignore\nconst uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11\nexport const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c =>\n (c ^ uint32() & 15 >> c / 4).toString(16)\n)\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* istanbul ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Utility helpers to work with promises.\n *\n * @module promise\n */\n\nimport * as time from './time.js'\n\n/**\n * @template T\n * @callback PromiseResolve\n * @param {T|PromiseLike<T>} [result]\n */\n\n/**\n * @template T\n * @param {function(PromiseResolve<T>,function(Error):void):any} f\n * @return {Promise<T>}\n */\nexport const create = f => /** @type {Promise<T>} */ (new Promise(f))\n\n/**\n * @param {function(function():void,function(Error):void):void} f\n * @return {Promise<void>}\n */\nexport const createEmpty = f => new Promise(f)\n\n/**\n * `Promise.all` wait for all promises in the array to resolve and return the result\n * @template T\n * @param {Array<Promise<T>>} arrp\n * @return {Promise<Array<T>>}\n */\nexport const all = arrp => Promise.all(arrp)\n\n/**\n * @param {Error} [reason]\n * @return {Promise<never>}\n */\nexport const reject = reason => Promise.reject(reason)\n\n/**\n * @template T\n * @param {T|void} res\n * @return {Promise<T|void>}\n */\nexport const resolve = res => Promise.resolve(res)\n\n/**\n * @template T\n * @param {T} res\n * @return {Promise<T>}\n */\nexport const resolveWith = res => Promise.resolve(res)\n\n/**\n * @todo Next version, reorder parameters: check, [timeout, [intervalResolution]]\n *\n * @param {number} timeout\n * @param {function():boolean} check\n * @param {number} [intervalResolution]\n * @return {Promise<void>}\n */\nexport const until = (timeout, check, intervalResolution = 10) => create((resolve, reject) => {\n const startTime = time.getUnixTime()\n const hasTimeout = timeout > 0\n const untilInterval = () => {\n if (check()) {\n clearInterval(intervalHandle)\n resolve()\n } else if (hasTimeout) {\n /* istanbul ignore else */\n if (time.getUnixTime() - startTime > timeout) {\n clearInterval(intervalHandle)\n reject(new Error('Timeout'))\n }\n }\n }\n const intervalHandle = setInterval(untilInterval, intervalResolution)\n})\n\n/**\n * @param {number} timeout\n * @return {Promise<undefined>}\n */\nexport const wait = timeout => create((resolve, reject) => setTimeout(resolve, timeout))\n\n/**\n * Checks if an object is a promise using ducktyping.\n *\n * Promises are often polyfilled, so it makes sense to add some additional guarantees if the user of this\n * library has some insane environment where global Promise objects are overwritten.\n *\n * @param {any} p\n * @return {boolean}\n */\nexport const isPromise = p => p instanceof Promise || (p && p.then && p.catch && p.finally)\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/* istanbul ignore next */\n/**\n * @param {string} s\n * @return {Error}\n */\nexport const create = s => new Error(s)\n\n/* istanbul ignore next */\n/**\n * @throws {Error}\n * @return {never}\n */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/* istanbul ignore next */\n/**\n * @throws {Error}\n * @return {never}\n */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n","/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object<string,any>} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object<string,any>} obj\n */\nexport const keys = Object.keys\n\n/**\n * @param {Object<string,any>} obj\n * @param {function(any,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @template R\n * @param {Object<string,any>} obj\n * @param {function(any,string):R} f\n * @return {Array<R>}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @param {Object<string,any>} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object<string,any>} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object<string,any>} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object<string,any>} a\n * @param {Object<string,any>} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array<function>} fs\n * @param {Array<any>} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array<T>|object} a\n * @param {Array<T>|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((a instanceof Array && array.equalFlat(a, /** @type {Array<T>} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n","/**\n * Utility module to work with EcmaScript Symbols.\n *\n * @module symbol\n */\n\n/**\n * Return fresh symbol.\n *\n * @return {Symbol}\n */\nexport const create = Symbol\n\n/**\n * @param {any} s\n * @return {boolean}\n */\nexport const isSymbol = s => typeof s === 'symbol'\n","/**\n * Working with value pairs.\n *\n * @module pair\n */\n\n/**\n * @template L,R\n */\nexport class Pair {\n /**\n * @param {L} left\n * @param {R} right\n */\n constructor (left, right) {\n this.left = left\n this.right = right\n }\n}\n\n/**\n * @template L,R\n * @param {L} left\n * @param {R} right\n * @return {Pair<L,R>}\n */\nexport const create = (left, right) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {R} right\n * @param {L} left\n * @return {Pair<L,R>}\n */\nexport const createReversed = (right, left) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {Array<Pair<L,R>>} arr\n * @param {function(L, R):any} f\n */\nexport const forEach = (arr, f) => arr.forEach(p => f(p.left, p.right))\n\n/**\n * @template L,R,X\n * @param {Array<Pair<L,R>>} arr\n * @param {function(L, R):X} f\n * @return {Array<X>}\n */\nexport const map = (arr, f) => arr.map(p => f(p.left, p.right))\n","/* eslint-env browser */\n\n/**\n * Utility module to work with the DOM.\n *\n * @module dom\n */\n\nimport * as pair from './pair.js'\nimport * as map from './map.js'\n\n/* istanbul ignore next */\n/**\n * @type {Document}\n */\nexport const doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {})\n\n/**\n * @param {string} name\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nexport const createElement = name => doc.createElement(name)\n\n/**\n * @return {DocumentFragment}\n */\n/* istanbul ignore next */\nexport const createDocumentFragment = () => doc.createDocumentFragment()\n\n/**\n * @param {string} text\n * @return {Text}\n */\n/* istanbul ignore next */\nexport const createTextNode = text => doc.createTextNode(text)\n\n/* istanbul ignore next */\nexport const domParser = /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null)\n\n/**\n * @param {HTMLElement} el\n * @param {string} name\n * @param {Object} opts\n */\n/* istanbul ignore next */\nexport const emitCustomEvent = (el, name, opts) => el.dispatchEvent(new CustomEvent(name, opts))\n\n/**\n * @param {Element} el\n * @param {Array<pair.Pair<string,string|boolean>>} attrs Array of key-value pairs\n * @return {Element}\n */\n/* istanbul ignore next */\nexport const setAttributes = (el, attrs) => {\n pair.forEach(attrs, (key, value) => {\n if (value === false) {\n el.removeAttribute(key)\n } else if (value === true) {\n el.setAttribute(key, '')\n } else {\n // @ts-ignore\n el.setAttribute(key, value)\n }\n })\n return el\n}\n\n/**\n * @param {Element} el\n * @param {Map<string, string>} attrs Array of key-value pairs\n * @return {Element}\n */\n/* istanbul ignore next */\nexport const setAttributesMap = (el, attrs) => {\n attrs.forEach((value, key) => { el.setAttribute(key, value) })\n return el\n}\n\n/**\n * @param {Array<Node>|HTMLCollection} children\n * @return {DocumentFragment}\n */\n/* istanbul ignore next */\nexport const fragment = children => {\n const fragment = createDocumentFragment()\n for (let i = 0; i < children.length; i++) {\n appendChild(fragment, children[i])\n }\n return fragment\n}\n\n/**\n * @param {Element} parent\n * @param {Array<Node>} nodes\n * @return {Element}\n */\n/* istanbul ignore next */\nexport const append = (parent, nodes) => {\n appendChild(parent, fragment(nodes))\n return parent\n}\n\n/**\n * @param {HTMLElement} el\n */\n/* istanbul ignore next */\nexport const remove = el => el.remove()\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\n/* istanbul ignore next */\nexport const addEventListener = (el, name, f) => el.addEventListener(name, f)\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\n/* istanbul ignore next */\nexport const removeEventListener = (el, name, f) => el.removeEventListener(name, f)\n\n/**\n * @param {Node} node\n * @param {Array<pair.Pair<string,EventListener>>} listeners\n * @return {Node}\n */\n/* istanbul ignore next */\nexport const addEventListeners = (node, listeners) => {\n pair.forEach(listeners, (name, f) => addEventListener(node, name, f))\n return node\n}\n\n/**\n * @param {Node} node\n * @param {Array<pair.Pair<string,EventListener>>} listeners\n * @return {Node}\n */\n/* istanbul ignore next */\nexport const removeEventListeners = (node, listeners) => {\n pair.forEach(listeners, (name, f) => removeEventListener(node, name, f))\n return node\n}\n\n/**\n * @param {string} name\n * @param {Array<pair.Pair<string,string>|pair.Pair<string,boolean>>} attrs Array of key-value pairs\n * @param {Array<Node>} children\n * @return {Element}\n */\n/* istanbul ignore next */\nexport const element = (name, attrs = [], children = []) =>\n append(setAttributes(createElement(name), attrs), children)\n\n/**\n * @param {number} width\n * @param {number} height\n */\n/* istanbul ignore next */\nexport const canvas = (width, height) => {\n const c = /** @type {HTMLCanvasElement} */ (createElement('canvas'))\n c.height = height\n c.width = width\n return c\n}\n\n/**\n * @param {string} t\n * @return {Text}\n */\n/* istanbul ignore next */\nexport const text = createTextNode\n\n/**\n * @param {pair.Pair<string,string>} pair\n */\n/* istanbul ignore next */\nexport const pairToStyleString = pair => `${pair.left}:${pair.right};`\n\n/**\n * @param {Array<pair.Pair<string,string>>} pairs\n * @return {string}\n */\n/* istanbul ignore next */\nexport const pairsToStyleString = pairs => pairs.map(pairToStyleString).join('')\n\n/**\n * @param {Map<string,string>} m\n * @return {string}\n */\n/* istanbul ignore next */\nexport const mapToStyleString = m => map.map(m, (value, key) => `${key}:${value};`).join('')\n\n/**\n * @todo should always query on a dom element\n *\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {HTMLElement | null}\n */\n/* istanbul ignore next */\nexport const querySelector = (el, query) => el.querySelector(query)\n\n/**\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {NodeListOf<HTMLElement>}\n */\n/* istanbul ignore next */\nexport const querySelectorAll = (el, query) => el.querySelectorAll(query)\n\n/**\n * @param {string} id\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nexport const getElementById = id => /** @type {HTMLElement} */ (doc.getElementById(id))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nconst _parse = html => domParser.parseFromString(`<html><body>${html}</body></html>`, 'text/html').body\n\n/**\n * @param {string} html\n * @return {DocumentFragment}\n */\n/* istanbul ignore next */\nexport const parseFragment = html => fragment(/** @type {any} */ (_parse(html).childNodes))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nexport const parseElement = html => /** @type HTMLElement */ (_parse(html).firstElementChild)\n\n/**\n * @param {HTMLElement} oldEl\n * @param {HTMLElement|DocumentFragment} newEl\n */\n/* istanbul ignore next */\nexport const replaceWith = (oldEl, newEl) => oldEl.replaceWith(newEl)\n\n/**\n * @param {HTMLElement} parent\n * @param {HTMLElement} el\n * @param {Node|null} ref\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nexport const insertBefore = (parent, el, ref) => parent.insertBefore(el, ref)\n\n/**\n * @param {Node} parent\n * @param {Node} child\n * @return {Node}\n */\n/* istanbul ignore next */\nexport const appendChild = (parent, child) => parent.appendChild(child)\n\nexport const ELEMENT_NODE = doc.ELEMENT_NODE\nexport const TEXT_NODE = doc.TEXT_NODE\nexport const CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE\nexport const COMMENT_NODE = doc.COMMENT_NODE\nexport const DOCUMENT_NODE = doc.DOCUMENT_NODE\nexport const DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE\nexport const DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE\n\n/**\n * @param {any} node\n * @param {number} type\n */\nexport const checkNodeType = (node, type) => node.nodeType === type\n\n/**\n * @param {Node} parent\n * @param {HTMLElement} child\n */\nexport const isParentOf = (parent, child) => {\n let p = child.parentNode\n while (p && p !== parent) {\n p = p.parentNode\n }\n return p === parent\n}\n","/**\n * Isomorphic logging module with support for colors!\n *\n * @module logging\n */\n\nimport * as env from './environment.js'\nimport * as symbol from './symbol.js'\nimport * as pair from './pair.js'\nimport * as dom from './dom.js'\nimport * as json from './json.js'\nimport * as map from './map.js'\nimport * as eventloop from './eventloop.js'\nimport * as math from './math.js'\nimport * as time from './time.js'\nimport * as func from './function.js'\n\nexport const BOLD = symbol.create()\nexport const UNBOLD = symbol.create()\nexport const BLUE = symbol.create()\nexport const GREY = symbol.create()\nexport const GREEN = symbol.create()\nexport const RED = symbol.create()\nexport const PURPLE = symbol.create()\nexport const ORANGE = symbol.create()\nexport const UNCOLOR = symbol.create()\n\n/**\n * @type {Object<Symbol,pair.Pair<string,string>>}\n */\nconst _browserStyleMap = {\n [BOLD]: pair.create('font-weight', 'bold'),\n [UNBOLD]: pair.create('font-weight', 'normal'),\n [BLUE]: pair.create('color', 'blue'),\n [GREEN]: pair.create('color', 'green'),\n [GREY]: pair.create('color', 'grey'),\n [RED]: pair.create('color', 'red'),\n [PURPLE]: pair.create('color', 'purple'),\n [ORANGE]: pair.create('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate\n [UNCOLOR]: pair.create('color', 'black')\n}\n\nconst _nodeStyleMap = {\n [BOLD]: '\\u001b[1m',\n [UNBOLD]: '\\u001b[2m',\n [BLUE]: '\\x1b[34m',\n [GREEN]: '\\x1b[32m',\n [GREY]: '\\u001b[37m',\n [RED]: '\\x1b[31m',\n [PURPLE]: '\\x1b[35m',\n [ORANGE]: '\\x1b[38;5;208m',\n [UNCOLOR]: '\\x1b[0m'\n}\n\n/* istanbul ignore next */\n/**\n * @param {Array<string|Symbol|Object|number>} args\n * @return {Array<string|object|number>}\n */\nconst computeBrowserLoggingArgs = args => {\n const strBuilder = []\n const styles = []\n const currentStyle = map.create()\n /**\n * @type {Array<string|Object|number>}\n */\n let logArgs = []\n // try with formatting until we find something unsupported\n let i = 0\n\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _browserStyleMap[arg]\n if (style !== undefined) {\n currentStyle.set(style.left, style.right)\n } else {\n if (arg.constructor === String || arg.constructor === Number) {\n const style = dom.mapToStyleString(currentStyle)\n if (i > 0 || style.length > 0) {\n strBuilder.push('%c' + arg)\n styles.push(style)\n } else {\n strBuilder.push(arg)\n }\n } else {\n break\n }\n }\n }\n\n if (i > 0) {\n // create logArgs with what we have so far\n logArgs = styles\n logArgs.unshift(strBuilder.join(''))\n }\n // append the rest\n for (; i < args.length; i++) {\n const arg = args[i]\n if (!(arg instanceof Symbol)) {\n logArgs.push(arg)\n }\n }\n return logArgs\n}\n\n/**\n * @param {Array<string|Symbol|Object|number>} args\n * @return {Array<string|object|number>}\n */\nconst computeNodeLoggingArgs = args => {\n const strBuilder = []\n const logArgs = []\n\n // try with formatting until we find something unsupported\n let i = 0\n\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _nodeStyleMap[arg]\n if (style !== undefined) {\n strBuilder.push(style)\n } else {\n if (arg.constructor === String || arg.constructor === Number) {\n strBuilder.push(arg)\n } else {\n break\n }\n }\n }\n if (i > 0) {\n // create logArgs with what we have so far\n strBuilder.push('\\x1b[0m')\n logArgs.push(strBuilder.join(''))\n }\n // append the rest\n for (; i < args.length; i++) {\n const arg = args[i]\n /* istanbul ignore else */\n if (!(arg instanceof Symbol)) {\n logArgs.push(arg)\n }\n }\n return logArgs\n}\n\n/* istanbul ignore next */\nconst computeLoggingArgs = env.isNode ? computeNodeLoggingArgs : computeBrowserLoggingArgs\n\n/**\n * @param {Array<string|Symbol|Object|number>} args\n */\nexport const print = (...args) => {\n console.log(...computeLoggingArgs(args))\n /* istanbul ignore next */\n vconsoles.forEach(vc => vc.print(args))\n}\n\n/* istanbul ignore next */\n/**\n * @param {Array<string|Symbol|Object|number>} args\n */\nexport const warn = (...args) => {\n console.warn(...computeLoggingArgs(args))\n args.unshift(ORANGE)\n vconsoles.forEach(vc => vc.print(args))\n}\n\n/* istanbul ignore next */\n/**\n * @param {Error} err\n */\nexport const printError = err => {\n console.error(err)\n vconsoles.forEach(vc => vc.printError(err))\n}\n\n/* istanbul ignore next */\n/**\n * @param {string} url image location\n * @param {number} height height of the image in pixel\n */\nexport const printImg = (url, height) => {\n if (env.isBrowser) {\n console.log('%c ', `font-size: ${height}px; background-size: contain; background-repeat: no-repeat; background-image: url(${url})`)\n // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`)\n }\n vconsoles.forEach(vc => vc.printImg(url, height))\n}\n\n/* istanbul ignore next */\n/**\n * @param {string} base64\n * @param {number} height\n */\nexport const printImgBase64 = (base64, height) => printImg(`data:image/gif;base64,${base64}`, height)\n\n/**\n * @param {Array<string|Symbol|Object|number>} args\n */\nexport const group = (...args) => {\n console.group(...computeLoggingArgs(args))\n /* istanbul ignore next */\n vconsoles.forEach(vc => vc.group(args))\n}\n\n/**\n * @param {Array<string|Symbol|Object|number>} args\n */\nexport const groupCollapsed = (...args) => {\n console.groupCollapsed(...computeLoggingArgs(args))\n /* istanbul ignore next */\n vconsoles.forEach(vc => vc.groupCollapsed(args))\n}\n\nexport const groupEnd = () => {\n console.groupEnd()\n /* istanbul ignore next */\n vconsoles.forEach(vc => vc.groupEnd())\n}\n\n/* istanbul ignore next */\n/**\n * @param {function():Node} createNode\n */\nexport const printDom = createNode =>\n vconsoles.forEach(vc => vc.printDom(createNode()))\n\n/* istanbul ignore next */\n/**\n * @param {HTMLCanvasElement} canvas\n * @param {number} height\n */\nexport const printCanvas = (canvas, height) => printImg(canvas.toDataURL(), height)\n\nexport const vconsoles = new Set()\n\n/* istanbul ignore next */\n/**\n * @param {Array<string|Symbol|Object|number>} args\n * @return {Array<Element>}\n */\nconst _computeLineSpans = args => {\n const spans = []\n const currentStyle = new Map()\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _browserStyleMap[arg]\n if (style !== undefined) {\n currentStyle.set(style.left, style.right)\n } else {\n if (arg.constructor === String || arg.constructor === Number) {\n // @ts-ignore\n const span = dom.element('span', [pair.create('style', dom.mapToStyleString(currentStyle))], [dom.text(arg)])\n if (span.innerHTML === '') {\n span.innerHTML = '&nbsp;'\n }\n spans.push(span)\n } else {\n break\n }\n }\n }\n // append the rest\n for (; i < args.length; i++) {\n let content = args[i]\n if (!(content instanceof Symbol)) {\n if (content.constructor !== String && content.constructor !== Number) {\n content = ' ' + json.stringify(content) + ' '\n }\n spans.push(dom.element('span', [], [dom.text(/** @type {string} */ (content))]))\n }\n }\n return spans\n}\n\nconst lineStyle = 'font-family:monospace;border-bottom:1px solid #e2e2e2;padding:2px;'\n\n/* istanbul ignore next */\nexport class VConsole {\n /**\n * @param {Element} dom\n */\n constructor (dom) {\n this.dom = dom\n /**\n * @type {Element}\n */\n this.ccontainer = this.dom\n this.depth = 0\n vconsoles.add(this)\n }\n\n /**\n * @param {Array<string|Symbol|Object|number>} args\n * @param {boolean} collapsed\n */\n group (args, collapsed = false) {\n eventloop.enqueue(() => {\n const triangleDown = dom.element('span', [pair.create('hidden', collapsed), pair.create('style', 'color:grey;font-size:120%;')], [dom.text('▼')])\n const triangleRight = dom.element('span', [pair.create('hidden', !collapsed), pair.create('style', 'color:grey;font-size:125%;')], [dom.text('▶')])\n const content = dom.element('div', [pair.create('style', `${lineStyle};padding-left:${this.depth * 10}px`)], [triangleDown, triangleRight, dom.text(' ')].concat(_computeLineSpans(args)))\n const nextContainer = dom.element('div', [pair.create('hidden', collapsed)])\n const nextLine = dom.element('div', [], [content, nextContainer])\n dom.append(this.ccontainer, [nextLine])\n this.ccontainer = nextContainer\n this.depth++\n // when header is clicked, collapse/uncollapse container\n dom.addEventListener(content, 'click', event => {\n nextContainer.toggleAttribute('hidden')\n triangleDown.toggleAttribute('hidden')\n triangleRight.toggleAttribute('hidden')\n })\n })\n }\n\n /**\n * @param {Array<string|Symbol|Object|number>} args\n */\n groupCollapsed (args) {\n this.group(args, true)\n }\n\n groupEnd () {\n eventloop.enqueue(() => {\n if (this.depth > 0) {\n this.depth--\n // @ts-ignore\n this.ccontainer = this.ccontainer.parentElement.parentElement\n }\n })\n }\n\n /**\n * @param {Array<string|Symbol|Object|number>} args\n */\n print (args) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [dom.element('div', [pair.create('style', `${lineStyle};padding-left:${this.depth * 10}px`)], _computeLineSpans(args))])\n })\n }\n\n /**\n * @param {Error} err\n */\n printError (err) {\n this.print([RED, BOLD, err.toString()])\n }\n\n /**\n * @param {string} url\n * @param {number} height\n */\n printImg (url, height) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [dom.element('img', [pair.create('src', url), pair.create('height', `${math.round(height * 1.5)}px`)])])\n })\n }\n\n /**\n * @param {Node} node\n */\n printDom (node) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [node])\n })\n }\n\n destroy () {\n eventloop.enqueue(() => {\n vconsoles.delete(this)\n })\n }\n}\n\n/* istanbul ignore next */\n/**\n * @param {Element} dom\n */\nexport const createVConsole = dom => new VConsole(dom)\n\nconst loggingColors = [GREEN, PURPLE, ORANGE, BLUE]\nlet nextColor = 0\nlet lastLoggingTime = time.getUnixTime()\n\n/**\n * @param {string} moduleName\n * @return {function(...any):void}\n */\nexport const createModuleLogger = moduleName => {\n const color = loggingColors[nextColor]\n const debugRegexVar = env.getVariable('log')\n const doLogging = debugRegexVar !== null && (debugRegexVar === '*' || debugRegexVar === 'true' || new RegExp(debugRegexVar, 'gi').test(moduleName))\n nextColor = (nextColor + 1) % loggingColors.length\n moduleName += ': '\n\n return !doLogging ? func.nop : (...args) => {\n const timeNow = time.getUnixTime()\n const timeDiff = timeNow - lastLoggingTime\n lastLoggingTime = timeNow\n print(color, moduleName, UNCOLOR, ...args.map(arg => (typeof arg === 'string' || typeof arg === 'symbol') ? arg : JSON.stringify(arg)), color, ' +' + timeDiff + 'ms')\n }\n}\n","/**\n * Utility module to create and manipulate Iterators.\n *\n * @module iterator\n */\n\n/**\n * @template T,R\n * @param {Iterator<T>} iterator\n * @param {function(T):R} f\n * @return {IterableIterator<R>}\n */\nexport const mapIterator = (iterator, f) => ({\n /**\n * @param {function(T):R} f\n */\n [Symbol.iterator] () {\n return this\n },\n // @ts-ignore\n next () {\n const r = iterator.next()\n return { value: r.done ? undefined : f(r.value), done: r.done }\n }\n})\n\n/**\n * @template T\n * @param {function():IteratorResult<T>} next\n * @return {IterableIterator<T>}\n */\nexport const createIterator = next => ({\n /**\n * @return {IterableIterator<T>}\n */\n [Symbol.iterator] () {\n return this\n },\n // @ts-ignore\n next\n})\n\n/**\n * @template T\n * @param {Iterator<T>} iterator\n * @param {function(T):boolean} filter\n */\nexport const iteratorFilter = (iterator, filter) => createIterator(() => {\n let res\n do {\n res = iterator.next()\n } while (!res.done && !filter(res.value))\n return res\n})\n\n/**\n * @template T,M\n * @param {Iterator<T>} iterator\n * @param {function(T):M} fmap\n */\nexport const iteratorMap = (iterator, fmap) => createIterator(() => {\n const { done, value } = iterator.next()\n return { done, value: done ? undefined : fmap(value) }\n})\n","\nimport { Observable } from 'lib0/observable'\n\nimport {\n Doc // eslint-disable-line\n} from '../internals.js'\n\n/**\n * This is an abstract interface that all Connectors should implement to keep them interchangeable.\n *\n * @note This interface is experimental and it is not advised to actually inherit this class.\n * It just serves as typing information.\n *\n * @extends {Observable<any>}\n */\nexport class AbstractConnector extends Observable {\n /**\n * @param {Doc} ydoc\n * @param {any} awareness\n */\n constructor (ydoc, awareness) {\n super()\n this.doc = ydoc\n this.awareness = awareness\n }\n}\n","\nimport {\n findIndexSS,\n getState,\n splitItem,\n iterateStructs,\n UpdateEncoderV2,\n DSDecoderV1, DSEncoderV1, DSDecoderV2, DSEncoderV2, Item, GC, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\n\nimport * as array from 'lib0/array'\nimport * as math from 'lib0/math'\nimport * as map from 'lib0/map'\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\n\nexport class DeleteItem {\n /**\n * @param {number} clock\n * @param {number} len\n */\n constructor (clock, len) {\n /**\n * @type {number}\n */\n this.clock = clock\n /**\n * @type {number}\n */\n this.len = len\n }\n}\n\n/**\n * We no longer maintain a DeleteStore. DeleteSet is a temporary object that is created when needed.\n * - When created in a transaction, it must only be accessed after sorting, and merging\n * - This DeleteSet is send to other clients\n * - We do not create a DeleteSet when we send a sync message. The DeleteSet message is created directly from StructStore\n * - We read a DeleteSet as part of a sync/update message. In this case the DeleteSet is already sorted and merged.\n */\nexport class DeleteSet {\n constructor () {\n /**\n * @type {Map<number,Array<DeleteItem>>}\n */\n this.clients = new Map()\n }\n}\n\n/**\n * Iterate over all structs that the DeleteSet gc's.\n *\n * @param {Transaction} transaction\n * @param {DeleteSet} ds\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nexport const iterateDeletedStructs = (transaction, ds, f) =>\n ds.clients.forEach((deletes, clientid) => {\n const structs = /** @type {Array<GC|Item>} */ (transaction.doc.store.clients.get(clientid))\n for (let i = 0; i < deletes.length; i++) {\n const del = deletes[i]\n iterateStructs(transaction, structs, del.clock, del.len, f)\n }\n })\n\n/**\n * @param {Array<DeleteItem>} dis\n * @param {number} clock\n * @return {number|null}\n *\n * @private\n * @function\n */\nexport const findIndexDS = (dis, clock) => {\n let left = 0\n let right = dis.length - 1\n while (left <= right) {\n const midindex = math.floor((left + right) / 2)\n const mid = dis[midindex]\n const midclock = mid.clock\n if (midclock <= clock) {\n if (clock < midclock + mid.len) {\n return midindex\n }\n left = midindex + 1\n } else {\n right = midindex - 1\n }\n }\n return null\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {ID} id\n * @return {boolean}\n *\n * @private\n * @function\n */\nexport const isDeleted = (ds, id) => {\n const dis = ds.clients.get(id.client)\n return dis !== undefined && findIndexDS(dis, id.clock) !== null\n}\n\n/**\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nexport const sortAndMergeDeleteSet = ds => {\n ds.clients.forEach(dels => {\n dels.sort((a, b) => a.clock - b.clock)\n // merge items without filtering or splicing the array\n // i is the current pointer\n // j refers to the current insert position for the pointed item\n // try to merge dels[i] into dels[j-1] or set dels[j]=dels[i]\n let i, j\n for (i = 1, j = 1; i < dels.length; i++) {\n const left = dels[j - 1]\n const right = dels[i]\n if (left.clock + left.len >= right.clock) {\n left.len = math.max(left.len, right.clock + right.len - left.clock)\n } else {\n if (j < i) {\n dels[j] = right\n }\n j++\n }\n }\n dels.length = j\n })\n}\n\n/**\n * @param {Array<DeleteSet>} dss\n * @return {DeleteSet} A fresh DeleteSet\n */\nexport const mergeDeleteSets = dss => {\n const merged = new DeleteSet()\n for (let dssI = 0; dssI < dss.length; dssI++) {\n dss[dssI].clients.forEach((delsLeft, client) => {\n if (!merged.clients.has(client)) {\n // Write all missing keys from current ds and all following.\n // If merged already contains `client` current ds has already been added.\n /**\n * @type {Array<DeleteItem>}\n */\n const dels = delsLeft.slice()\n for (let i = dssI + 1; i < dss.length; i++) {\n array.appendTo(dels, dss[i].clients.get(client) || [])\n }\n merged.clients.set(client, dels)\n }\n })\n }\n sortAndMergeDeleteSet(merged)\n return merged\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {number} client\n * @param {number} clock\n * @param {number} length\n *\n * @private\n * @function\n */\nexport const addToDeleteSet = (ds, client, clock, length) => {\n map.setIfUndefined(ds.clients, client, () => []).push(new DeleteItem(clock, length))\n}\n\nexport const createDeleteSet = () => new DeleteSet()\n\n/**\n * @param {StructStore} ss\n * @return {DeleteSet} Merged and sorted DeleteSet\n *\n * @private\n * @function\n */\nexport const createDeleteSetFromStructStore = ss => {\n const ds = createDeleteSet()\n ss.clients.forEach((structs, client) => {\n /**\n * @type {Array<DeleteItem>}\n */\n const dsitems = []\n for (let i = 0; i < structs.length; i++) {\n const struct = structs[i]\n if (struct.deleted) {\n const clock = struct.id.clock\n let len = struct.length\n if (i + 1 < structs.length) {\n for (let next = structs[i + 1]; i + 1 < structs.length && next.deleted; next = structs[++i + 1]) {\n len += next.length\n }\n }\n dsitems.push(new DeleteItem(clock, len))\n }\n }\n if (dsitems.length > 0) {\n ds.clients.set(client, dsitems)\n }\n })\n return ds\n}\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nexport const writeDeleteSet = (encoder, ds) => {\n encoding.writeVarUint(encoder.restEncoder, ds.clients.size)\n ds.clients.forEach((dsitems, client) => {\n encoder.resetDsCurVal()\n encoding.writeVarUint(encoder.restEncoder, client)\n const len = dsitems.length\n encoding.writeVarUint(encoder.restEncoder, len)\n for (let i = 0; i < len; i++) {\n const item = dsitems[i]\n encoder.writeDsClock(item.clock)\n encoder.writeDsLen(item.len)\n }\n })\n}\n\n/**\n * @param {DSDecoderV1 | DSDecoderV2} decoder\n * @return {DeleteSet}\n *\n * @private\n * @function\n */\nexport const readDeleteSet = decoder => {\n const ds = new DeleteSet()\n const numClients = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal()\n const client = decoding.readVarUint(decoder.restDecoder)\n const numberOfDeletes = decoding.readVarUint(decoder.restDecoder)\n if (numberOfDeletes > 0) {\n const dsField = map.setIfUndefined(ds.clients, client, () => [])\n for (let i = 0; i < numberOfDeletes; i++) {\n dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen()))\n }\n }\n }\n return ds\n}\n\n/**\n * @todo YDecoder also contains references to String and other Decoders. Would make sense to exchange YDecoder.toUint8Array for YDecoder.DsToUint8Array()..\n */\n\n/**\n * @param {DSDecoderV1 | DSDecoderV2} decoder\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {Uint8Array|null} Returns a v2 update containing all deletes that couldn't be applied yet; or null if all deletes were applied successfully.\n *\n * @private\n * @function\n */\nexport const readAndApplyDeleteSet = (decoder, transaction, store) => {\n const unappliedDS = new DeleteSet()\n const numClients = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal()\n const client = decoding.readVarUint(decoder.restDecoder)\n const numberOfDeletes = decoding.readVarUint(decoder.restDecoder)\n const structs = store.clients.get(client) || []\n const state = getState(store, client)\n for (let i = 0; i < numberOfDeletes; i++) {\n const clock = decoder.readDsClock()\n const clockEnd = clock + decoder.readDsLen()\n if (clock < state) {\n if (state < clockEnd) {\n addToDeleteSet(unappliedDS, client, state, clockEnd - state)\n }\n let index = findIndexSS(structs, clock)\n /**\n * We can ignore the case of GC and Delete structs, because we are going to skip them\n * @type {Item}\n */\n // @ts-ignore\n let struct = structs[index]\n // split the first item if necessary\n if (!struct.deleted && struct.id.clock < clock) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock))\n index++ // increase we now want to use the next struct\n }\n while (index < structs.length) {\n // @ts-ignore\n struct = structs[index++]\n if (struct.id.clock < clockEnd) {\n if (!struct.deleted) {\n if (clockEnd < struct.id.clock + struct.length) {\n structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock))\n }\n struct.delete(transaction)\n }\n } else {\n break\n }\n }\n } else {\n addToDeleteSet(unappliedDS, client, clock, clockEnd - clock)\n }\n }\n }\n if (unappliedDS.clients.size > 0) {\n const ds = new UpdateEncoderV2()\n encoding.writeVarUint(ds.restEncoder, 0) // encode 0 structs\n writeDeleteSet(ds, unappliedDS)\n return ds.toUint8Array()\n }\n return null\n}\n","/**\n * @module Y\n */\n\nimport {\n StructStore,\n AbstractType,\n YArray,\n YText,\n YMap,\n YXmlFragment,\n transact,\n ContentDoc, Item, Transaction, YEvent // eslint-disable-line\n} from '../internals.js'\n\nimport { Observable } from 'lib0/observable'\nimport * as random from 'lib0/random'\nimport * as map from 'lib0/map'\nimport * as array from 'lib0/array'\nimport * as promise from 'lib0/promise'\n\nexport const generateNewClientId = random.uint32\n\n/**\n * @typedef {Object} DocOpts\n * @property {boolean} [DocOpts.gc=true] Disable garbage collection (default: gc=true)\n * @property {function(Item):boolean} [DocOpts.gcFilter] Will be called before an Item is garbage collected. Return false to keep the Item.\n * @property {string} [DocOpts.guid] Define a globally unique identifier for this document\n * @property {string | null} [DocOpts.collectionid] Associate this document with a collection. This only plays a role if your provider has a concept of collection.\n * @property {any} [DocOpts.meta] Any kind of meta information you want to associate with this document. If this is a subdocument, remote peers will store the meta information as well.\n * @property {boolean} [DocOpts.autoLoad] If a subdocument, automatically load document. If this is a subdocument, remote peers will load the document as well automatically.\n * @property {boolean} [DocOpts.shouldLoad] Whether the document should be synced by the provider now. This is toggled to true when you call ydoc.load()\n */\n\n/**\n * A Yjs instance handles the state of shared data.\n * @extends Observable<string>\n */\nexport class Doc extends Observable {\n /**\n * @param {DocOpts} [opts] configuration\n */\n constructor ({ guid = random.uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta = null, autoLoad = false, shouldLoad = true } = {}) {\n super()\n this.gc = gc\n this.gcFilter = gcFilter\n this.clientID = generateNewClientId()\n this.guid = guid\n this.collectionid = collectionid\n /**\n * @type {Map<string, AbstractType<YEvent<any>>>}\n */\n this.share = new Map()\n this.store = new StructStore()\n /**\n * @type {Transaction | null}\n */\n this._transaction = null\n /**\n * @type {Array<Transaction>}\n */\n this._transactionCleanups = []\n /**\n * @type {Set<Doc>}\n */\n this.subdocs = new Set()\n /**\n * If this document is a subdocument - a document integrated into another document - then _item is defined.\n * @type {Item?}\n */\n this._item = null\n this.shouldLoad = shouldLoad\n this.autoLoad = autoLoad\n this.meta = meta\n this.isLoaded = false\n this.whenLoaded = promise.create(resolve => {\n this.on('load', () => {\n this.isLoaded = true\n resolve(this)\n })\n })\n }\n\n /**\n * Notify the parent document that you request to load data into this subdocument (if it is a subdocument).\n *\n * `load()` might be used in the future to request any provider to load the most current data.\n *\n * It is safe to call `load()` multiple times.\n */\n load () {\n const item = this._item\n if (item !== null && !this.shouldLoad) {\n transact(/** @type {any} */ (item.parent).doc, transaction => {\n transaction.subdocsLoaded.add(this)\n }, null, true)\n }\n this.shouldLoad = true\n }\n\n getSubdocs () {\n return this.subdocs\n }\n\n getSubdocGuids () {\n return new Set(Array.from(this.subdocs).map(doc => doc.guid))\n }\n\n /**\n * Changes that happen inside of a transaction are bundled. This means that\n * the observer fires _after_ the transaction is finished and that all changes\n * that happened inside of the transaction are sent as one message to the\n * other peers.\n *\n * @param {function(Transaction):void} f The function that should be executed as a transaction\n * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin\n *\n * @public\n */\n transact (f, origin = null) {\n transact(this, f, origin)\n }\n\n /**\n * Define a shared data type.\n *\n * Multiple calls of `y.get(name, TypeConstructor)` yield the same result\n * and do not overwrite each other. I.e.\n * `y.define(name, Y.Array) === y.define(name, Y.Array)`\n *\n * After this method is called, the type is also available on `y.share.get(name)`.\n *\n * *Best Practices:*\n * Define all types right after the Yjs instance is created and store them in a separate object.\n * Also use the typed methods `getText(name)`, `getArray(name)`, ..\n *\n * @example\n * const y = new Y(..)\n * const appState = {\n * document: y.getText('document')\n * comments: y.getArray('comments')\n * }\n *\n * @param {string} name\n * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...\n * @return {AbstractType<any>} The created type. Constructed with TypeConstructor\n *\n * @public\n */\n get (name, TypeConstructor = AbstractType) {\n const type = map.setIfUndefined(this.share, name, () => {\n // @ts-ignore\n const t = new TypeConstructor()\n t._integrate(this, null)\n return t\n })\n const Constr = type.constructor\n if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) {\n if (Constr === AbstractType) {\n // @ts-ignore\n const t = new TypeConstructor()\n t._map = type._map\n type._map.forEach(/** @param {Item?} n */ n => {\n for (; n !== null; n = n.left) {\n // @ts-ignore\n n.parent = t\n }\n })\n t._start = type._start\n for (let n = t._start; n !== null; n = n.right) {\n n.parent = t\n }\n t._length = type._length\n this.share.set(name, t)\n t._integrate(this, null)\n return t\n } else {\n throw new Error(`Type with the name ${name} has already been defined with a different constructor`)\n }\n }\n return type\n }\n\n /**\n * @template T\n * @param {string} [name]\n * @return {YArray<T>}\n *\n * @public\n */\n getArray (name = '') {\n // @ts-ignore\n return this.get(name, YArray)\n }\n\n /**\n * @param {string} [name]\n * @return {YText}\n *\n * @public\n */\n getText (name = '') {\n // @ts-ignore\n return this.get(name, YText)\n }\n\n /**\n * @template T\n * @param {string} [name]\n * @return {YMap<T>}\n *\n * @public\n */\n getMap (name = '') {\n // @ts-ignore\n return this.get(name, YMap)\n }\n\n /**\n * @param {string} [name]\n * @return {YXmlFragment}\n *\n * @public\n */\n getXmlFragment (name = '') {\n // @ts-ignore\n return this.get(name, YXmlFragment)\n }\n\n /**\n * Converts the entire document into a js object, recursively traversing each yjs type\n * Doesn't log types that have not been defined (using ydoc.getType(..)).\n *\n * @deprecated Do not use this method and rather call toJSON directly on the shared types.\n *\n * @return {Object<string, any>}\n */\n toJSON () {\n /**\n * @type {Object<string, any>}\n */\n const doc = {}\n\n this.share.forEach((value, key) => {\n doc[key] = value.toJSON()\n })\n\n return doc\n }\n\n /**\n * Emit `destroy` event and unregister all event handlers.\n */\n destroy () {\n array.from(this.subdocs).forEach(subdoc => subdoc.destroy())\n const item = this._item\n if (item !== null) {\n this._item = null\n const content = /** @type {ContentDoc} */ (item.content)\n content.doc = new Doc({ guid: this.guid, ...content.opts, shouldLoad: false })\n content.doc._item = item\n transact(/** @type {any} */ (item).parent.doc, transaction => {\n const doc = content.doc\n if (!item.deleted) {\n transaction.subdocsAdded.add(doc)\n }\n transaction.subdocsRemoved.add(this)\n }, null, true)\n }\n this.emit('destroyed', [true])\n this.emit('destroy', [this])\n super.destroy()\n }\n\n /**\n * @param {string} eventName\n * @param {function(...any):any} f\n */\n on (eventName, f) {\n super.on(eventName, f)\n }\n\n /**\n * @param {string} eventName\n * @param {function} f\n */\n off (eventName, f) {\n super.off(eventName, f)\n }\n}\n","import * as buffer from 'lib0/buffer'\nimport * as decoding from 'lib0/decoding'\nimport {\n ID, createID\n} from '../internals.js'\n\nexport class DSDecoderV1 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n this.restDecoder = decoder\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @return {number}\n */\n readDsClock () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n return decoding.readVarUint(this.restDecoder)\n }\n}\n\nexport class UpdateDecoderV1 extends DSDecoderV1 {\n /**\n * @return {ID}\n */\n readLeftID () {\n return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder))\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder))\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return decoding.readUint8(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readString () {\n return decoding.readVarString(this.restDecoder)\n }\n\n /**\n * @return {boolean} isKey\n */\n readParentInfo () {\n return decoding.readVarUint(this.restDecoder) === 1\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readTypeRef () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number} len\n */\n readLen () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return buffer.copyUint8Array(decoding.readVarUint8Array(this.restDecoder))\n }\n\n /**\n * Legacy implementation uses JSON parse. We use any-decoding in v2.\n *\n * @return {any}\n */\n readJSON () {\n return JSON.parse(decoding.readVarString(this.restDecoder))\n }\n\n /**\n * @return {string}\n */\n readKey () {\n return decoding.readVarString(this.restDecoder)\n }\n}\n\nexport class DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n /**\n * @private\n */\n this.dsCurrVal = 0\n this.restDecoder = decoder\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0\n }\n\n /**\n * @return {number}\n */\n readDsClock () {\n this.dsCurrVal += decoding.readVarUint(this.restDecoder)\n return this.dsCurrVal\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n const diff = decoding.readVarUint(this.restDecoder) + 1\n this.dsCurrVal += diff\n return diff\n }\n}\n\nexport class UpdateDecoderV2 extends DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n super(decoder)\n /**\n * List of cached keys. If the keys[id] does not exist, we read a new key\n * from stringEncoder and push it to keys.\n *\n * @type {Array<string>}\n */\n this.keys = []\n decoding.readVarUint(decoder) // read feature flag - currently unused\n this.keyClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.clientDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.leftClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.rightClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.infoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8)\n this.stringDecoder = new decoding.StringDecoder(decoding.readVarUint8Array(decoder))\n this.parentInfoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8)\n this.typeRefDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.lenDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n }\n\n /**\n * @return {ID}\n */\n readLeftID () {\n return new ID(this.clientDecoder.read(), this.leftClockDecoder.read())\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return new ID(this.clientDecoder.read(), this.rightClockDecoder.read())\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return this.clientDecoder.read()\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return /** @type {number} */ (this.infoDecoder.read())\n }\n\n /**\n * @return {string}\n */\n readString () {\n return this.stringDecoder.read()\n }\n\n /**\n * @return {boolean}\n */\n readParentInfo () {\n return this.parentInfoDecoder.read() === 1\n }\n\n /**\n * @return {number} An unsigned 8-bit integer\n */\n readTypeRef () {\n return this.typeRefDecoder.read()\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number}\n */\n readLen () {\n return this.lenDecoder.read()\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return decoding.readVarUint8Array(this.restDecoder)\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @return {any}\n */\n readJSON () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readKey () {\n const keyClock = this.keyClockDecoder.read()\n if (keyClock < this.keys.length) {\n return this.keys[keyClock]\n } else {\n const key = this.stringDecoder.read()\n this.keys.push(key)\n return key\n }\n }\n}\n","\nimport * as error from 'lib0/error'\nimport * as encoding from 'lib0/encoding'\n\nimport {\n ID // eslint-disable-line\n} from '../internals.js'\n\nexport class DSEncoderV1 {\n constructor () {\n this.restEncoder = encoding.createEncoder()\n }\n\n toUint8Array () {\n return encoding.toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n encoding.writeVarUint(this.restEncoder, clock)\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n encoding.writeVarUint(this.restEncoder, len)\n }\n}\n\nexport class UpdateEncoderV1 extends DSEncoderV1 {\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n encoding.writeVarUint(this.restEncoder, id.client)\n encoding.writeVarUint(this.restEncoder, id.clock)\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n encoding.writeVarUint(this.restEncoder, id.client)\n encoding.writeVarUint(this.restEncoder, id.clock)\n }\n\n /**\n * Use writeClient and writeClock instead of writeID if possible.\n * @param {number} client\n */\n writeClient (client) {\n encoding.writeVarUint(this.restEncoder, client)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n encoding.writeUint8(this.restEncoder, info)\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n encoding.writeVarString(this.restEncoder, s)\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n encoding.writeVarUint(this.restEncoder, isYKey ? 1 : 0)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n encoding.writeVarUint(this.restEncoder, info)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n encoding.writeVarUint(this.restEncoder, len)\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n encoding.writeAny(this.restEncoder, any)\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n encoding.writeVarUint8Array(this.restEncoder, buf)\n }\n\n /**\n * @param {any} embed\n */\n writeJSON (embed) {\n encoding.writeVarString(this.restEncoder, JSON.stringify(embed))\n }\n\n /**\n * @param {string} key\n */\n writeKey (key) {\n encoding.writeVarString(this.restEncoder, key)\n }\n}\n\nexport class DSEncoderV2 {\n constructor () {\n this.restEncoder = encoding.createEncoder() // encodes all the rest / non-optimized\n this.dsCurrVal = 0\n }\n\n toUint8Array () {\n return encoding.toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n const diff = clock - this.dsCurrVal\n this.dsCurrVal = clock\n encoding.writeVarUint(this.restEncoder, diff)\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n if (len === 0) {\n error.unexpectedCase()\n }\n encoding.writeVarUint(this.restEncoder, len - 1)\n this.dsCurrVal += len\n }\n}\n\nexport class UpdateEncoderV2 extends DSEncoderV2 {\n constructor () {\n super()\n /**\n * @type {Map<string,number>}\n */\n this.keyMap = new Map()\n /**\n * Refers to the next uniqe key-identifier to me used.\n * See writeKey method for more information.\n *\n * @type {number}\n */\n this.keyClock = 0\n this.keyClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.clientEncoder = new encoding.UintOptRleEncoder()\n this.leftClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.rightClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.infoEncoder = new encoding.RleEncoder(encoding.writeUint8)\n this.stringEncoder = new encoding.StringEncoder()\n this.parentInfoEncoder = new encoding.RleEncoder(encoding.writeUint8)\n this.typeRefEncoder = new encoding.UintOptRleEncoder()\n this.lenEncoder = new encoding.UintOptRleEncoder()\n }\n\n toUint8Array () {\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, 0) // this is a feature flag that we might use in the future\n encoding.writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.clientEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.infoEncoder))\n encoding.writeVarUint8Array(encoder, this.stringEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.parentInfoEncoder))\n encoding.writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.lenEncoder.toUint8Array())\n // @note The rest encoder is appended! (note the missing var)\n encoding.writeUint8Array(encoder, encoding.toUint8Array(this.restEncoder))\n return encoding.toUint8Array(encoder)\n }\n\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n this.clientEncoder.write(id.client)\n this.leftClockEncoder.write(id.clock)\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n this.clientEncoder.write(id.client)\n this.rightClockEncoder.write(id.clock)\n }\n\n /**\n * @param {number} client\n */\n writeClient (client) {\n this.clientEncoder.write(client)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n this.infoEncoder.write(info)\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n this.stringEncoder.write(s)\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n this.parentInfoEncoder.write(isYKey ? 1 : 0)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n this.typeRefEncoder.write(info)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n this.lenEncoder.write(len)\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n encoding.writeAny(this.restEncoder, any)\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n encoding.writeVarUint8Array(this.restEncoder, buf)\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @param {any} embed\n */\n writeJSON (embed) {\n encoding.writeAny(this.restEncoder, embed)\n }\n\n /**\n * Property keys are often reused. For example, in y-prosemirror the key `bold` might\n * occur very often. For a 3d application, the key `position` might occur very often.\n *\n * We cache these keys in a Map and refer to them via a unique number.\n *\n * @param {string} key\n */\n writeKey (key) {\n const clock = this.keyMap.get(key)\n if (clock === undefined) {\n /**\n * @todo uncomment to introduce this feature finally\n *\n * Background. The ContentFormat object was always encoded using writeKey, but the decoder used to use readString.\n * Furthermore, I forgot to set the keyclock. So everything was working fine.\n *\n * However, this feature here is basically useless as it is not being used (it actually only consumes extra memory).\n *\n * I don't know yet how to reintroduce this feature..\n *\n * Older clients won't be able to read updates when we reintroduce this feature. So this should probably be done using a flag.\n *\n */\n // this.keyMap.set(key, this.keyClock)\n this.keyClockEncoder.write(this.keyClock++)\n this.stringEncoder.write(key)\n } else {\n this.keyClockEncoder.write(clock)\n }\n }\n}\n","\n/**\n * @module encoding\n */\n/*\n * We use the first five bits in the info flag for determining the type of the struct.\n *\n * 0: GC\n * 1: Item with Deleted content\n * 2: Item with JSON content\n * 3: Item with Binary content\n * 4: Item with String content\n * 5: Item with Embed content (for richtext content)\n * 6: Item with Format content (a formatting marker for richtext content)\n * 7: Item with Type\n */\n\nimport {\n findIndexSS,\n getState,\n createID,\n getStateVector,\n readAndApplyDeleteSet,\n writeDeleteSet,\n createDeleteSetFromStructStore,\n transact,\n readItemContent,\n UpdateDecoderV1,\n UpdateDecoderV2,\n UpdateEncoderV1,\n UpdateEncoderV2,\n DSEncoderV2,\n DSDecoderV1,\n DSEncoderV1,\n mergeUpdates,\n mergeUpdatesV2,\n Skip,\n diffUpdateV2,\n convertUpdateFormatV2ToV1,\n DSDecoderV2, Doc, Transaction, GC, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as binary from 'lib0/binary'\nimport * as map from 'lib0/map'\nimport * as math from 'lib0/math'\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Array<GC|Item>} structs All structs by `client`\n * @param {number} client\n * @param {number} clock write structs starting with `ID(client,clock)`\n *\n * @function\n */\nconst writeStructs = (encoder, structs, client, clock) => {\n // write first id\n clock = math.max(clock, structs[0].id.clock) // make sure the first id exists\n const startNewStructs = findIndexSS(structs, clock)\n // write # encoded structs\n encoding.writeVarUint(encoder.restEncoder, structs.length - startNewStructs)\n encoder.writeClient(client)\n encoding.writeVarUint(encoder.restEncoder, clock)\n const firstStruct = structs[startNewStructs]\n // write first struct with an offset\n firstStruct.write(encoder, clock - firstStruct.id.clock)\n for (let i = startNewStructs + 1; i < structs.length; i++) {\n structs[i].write(encoder, 0)\n }\n}\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {StructStore} store\n * @param {Map<number,number>} _sm\n *\n * @private\n * @function\n */\nexport const writeClientsStructs = (encoder, store, _sm) => {\n // we filter all valid _sm entries into sm\n const sm = new Map()\n _sm.forEach((clock, client) => {\n // only write if new structs are available\n if (getState(store, client) > clock) {\n sm.set(client, clock)\n }\n })\n getStateVector(store).forEach((clock, client) => {\n if (!_sm.has(client)) {\n sm.set(client, 0)\n }\n })\n // write # states that were updated\n encoding.writeVarUint(encoder.restEncoder, sm.size)\n // Write items with higher client ids first\n // This heavily improves the conflict algorithm.\n Array.from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n // @ts-ignore\n writeStructs(encoder, store.clients.get(client), client, clock)\n })\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder The decoder object to read data from.\n * @param {Doc} doc\n * @return {Map<number, { i: number, refs: Array<Item | GC> }>}\n *\n * @private\n * @function\n */\nexport const readClientsStructRefs = (decoder, doc) => {\n /**\n * @type {Map<number, { i: number, refs: Array<Item | GC> }>}\n */\n const clientRefs = map.create()\n const numOfStateUpdates = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numOfStateUpdates; i++) {\n const numberOfStructs = decoding.readVarUint(decoder.restDecoder)\n /**\n * @type {Array<GC|Item>}\n */\n const refs = new Array(numberOfStructs)\n const client = decoder.readClient()\n let clock = decoding.readVarUint(decoder.restDecoder)\n // const start = performance.now()\n clientRefs.set(client, { i: 0, refs })\n for (let i = 0; i < numberOfStructs; i++) {\n const info = decoder.readInfo()\n switch (binary.BITS5 & info) {\n case 0: { // GC\n const len = decoder.readLen()\n refs[i] = new GC(createID(client, clock), len)\n clock += len\n break\n }\n case 10: { // Skip Struct (nothing to apply)\n // @todo we could reduce the amount of checks by adding Skip struct to clientRefs so we know that something is missing.\n const len = decoding.readVarUint(decoder.restDecoder)\n refs[i] = new Skip(createID(client, clock), len)\n clock += len\n break\n }\n default: { // Item with content\n /**\n * The optimized implementation doesn't use any variables because inlining variables is faster.\n * Below a non-optimized version is shown that implements the basic algorithm with\n * a few comments\n */\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const struct = new Item(\n createID(client, clock),\n null, // leftd\n (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null, // origin\n null, // right\n (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null, // right origin\n cantCopyParentInfo ? (decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID()) : null, // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n /* A non-optimized implementation of the above algorithm:\n\n // The item that was originally to the left of this item.\n const origin = (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null\n // The item that was originally to the right of this item.\n const rightOrigin = (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n const hasParentYKey = cantCopyParentInfo ? decoder.readParentInfo() : false\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const parentYKey = cantCopyParentInfo && hasParentYKey ? decoder.readString() : null\n\n const struct = new Item(\n createID(client, clock),\n null, // leftd\n origin, // origin\n null, // right\n rightOrigin, // right origin\n cantCopyParentInfo && !hasParentYKey ? decoder.readLeftID() : (parentYKey !== null ? doc.get(parentYKey) : null), // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n */\n refs[i] = struct\n clock += struct.length\n }\n }\n }\n // console.log('time to read: ', performance.now() - start) // @todo remove\n }\n return clientRefs\n}\n\n/**\n * Resume computing structs generated by struct readers.\n *\n * While there is something to do, we integrate structs in this order\n * 1. top element on stack, if stack is not empty\n * 2. next element from current struct reader (if empty, use next struct reader)\n *\n * If struct causally depends on another struct (ref.missing), we put next reader of\n * `ref.id.client` on top of stack.\n *\n * At some point we find a struct that has no causal dependencies,\n * then we start emptying the stack.\n *\n * It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2)\n * depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`.\n *\n * This method is implemented in a way so that we can resume computation if this update\n * causally depends on another update.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @param {Map<number, { i: number, refs: (GC | Item)[] }>} clientsStructRefs\n * @return { null | { update: Uint8Array, missing: Map<number,number> } }\n *\n * @private\n * @function\n */\nconst integrateStructs = (transaction, store, clientsStructRefs) => {\n /**\n * @type {Array<Item | GC>}\n */\n const stack = []\n // sort them so that we take the higher id first, in case of conflicts the lower id will probably not conflict with the id from the higher user.\n let clientsStructRefsIds = Array.from(clientsStructRefs.keys()).sort((a, b) => a - b)\n if (clientsStructRefsIds.length === 0) {\n return null\n }\n const getNextStructTarget = () => {\n if (clientsStructRefsIds.length === 0) {\n return null\n }\n let nextStructsTarget = /** @type {{i:number,refs:Array<GC|Item>}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]))\n while (nextStructsTarget.refs.length === nextStructsTarget.i) {\n clientsStructRefsIds.pop()\n if (clientsStructRefsIds.length > 0) {\n nextStructsTarget = /** @type {{i:number,refs:Array<GC|Item>}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]))\n } else {\n return null\n }\n }\n return nextStructsTarget\n }\n let curStructsTarget = getNextStructTarget()\n if (curStructsTarget === null && stack.length === 0) {\n return null\n }\n\n /**\n * @type {StructStore}\n */\n const restStructs = new StructStore()\n const missingSV = new Map()\n /**\n * @param {number} client\n * @param {number} clock\n */\n const updateMissingSv = (client, clock) => {\n const mclock = missingSV.get(client)\n if (mclock == null || mclock > clock) {\n missingSV.set(client, clock)\n }\n }\n /**\n * @type {GC|Item}\n */\n let stackHead = /** @type {any} */ (curStructsTarget).refs[/** @type {any} */ (curStructsTarget).i++]\n // caching the state because it is used very often\n const state = new Map()\n\n const addStackToRestSS = () => {\n for (const item of stack) {\n const client = item.id.client\n const unapplicableItems = clientsStructRefs.get(client)\n if (unapplicableItems) {\n // decrement because we weren't able to apply previous operation\n unapplicableItems.i--\n restStructs.clients.set(client, unapplicableItems.refs.slice(unapplicableItems.i))\n clientsStructRefs.delete(client)\n unapplicableItems.i = 0\n unapplicableItems.refs = []\n } else {\n // item was the last item on clientsStructRefs and the field was already cleared. Add item to restStructs and continue\n restStructs.clients.set(client, [item])\n }\n // remove client from clientsStructRefsIds to prevent users from applying the same update again\n clientsStructRefsIds = clientsStructRefsIds.filter(c => c !== client)\n }\n stack.length = 0\n }\n\n // iterate over all struct readers until we are done\n while (true) {\n if (stackHead.constructor !== Skip) {\n const localClock = map.setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client))\n const offset = localClock - stackHead.id.clock\n if (offset < 0) {\n // update from the same client is missing\n stack.push(stackHead)\n updateMissingSv(stackHead.id.client, stackHead.id.clock - 1)\n // hid a dead wall, add all items from stack to restSS\n addStackToRestSS()\n } else {\n const missing = stackHead.getMissing(transaction, store)\n if (missing !== null) {\n stack.push(stackHead)\n // get the struct reader that has the missing struct\n /**\n * @type {{ refs: Array<GC|Item>, i: number }}\n */\n const structRefs = clientsStructRefs.get(/** @type {number} */ (missing)) || { refs: [], i: 0 }\n if (structRefs.refs.length === structRefs.i) {\n // This update message causally depends on another update message that doesn't exist yet\n updateMissingSv(/** @type {number} */ (missing), getState(store, missing))\n addStackToRestSS()\n } else {\n stackHead = structRefs.refs[structRefs.i++]\n continue\n }\n } else if (offset === 0 || offset < stackHead.length) {\n // all fine, apply the stackhead\n stackHead.integrate(transaction, offset)\n state.set(stackHead.id.client, stackHead.id.clock + stackHead.length)\n }\n }\n }\n // iterate to next stackHead\n if (stack.length > 0) {\n stackHead = /** @type {GC|Item} */ (stack.pop())\n } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++])\n } else {\n curStructsTarget = getNextStructTarget()\n if (curStructsTarget === null) {\n // we are done!\n break\n } else {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++])\n }\n }\n }\n if (restStructs.clients.size > 0) {\n const encoder = new UpdateEncoderV2()\n writeClientsStructs(encoder, restStructs, new Map())\n // write empty deleteset\n // writeDeleteSet(encoder, new DeleteSet())\n encoding.writeVarUint(encoder.restEncoder, 0) // => no need for an extra function call, just write 0 deletes\n return { missing: missingSV, update: encoder.toUint8Array() }\n }\n return null\n}\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Transaction} transaction\n *\n * @private\n * @function\n */\nexport const writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState)\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts an decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {UpdateDecoderV1 | UpdateDecoderV2} [structDecoder]\n *\n * @function\n */\nexport const readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) =>\n transact(ydoc, transaction => {\n // force that transaction.local is set to non-local\n transaction.local = false\n let retry = false\n const doc = transaction.doc\n const store = doc.store\n // let start = performance.now()\n const ss = readClientsStructRefs(structDecoder, doc)\n // console.log('time to read structs: ', performance.now() - start) // @todo remove\n // start = performance.now()\n // console.log('time to merge: ', performance.now() - start) // @todo remove\n // start = performance.now()\n const restStructs = integrateStructs(transaction, store, ss)\n const pending = store.pendingStructs\n if (pending) {\n // check if we can apply something\n for (const [client, clock] of pending.missing) {\n if (clock < getState(store, client)) {\n retry = true\n break\n }\n }\n if (restStructs) {\n // merge restStructs into store.pending\n for (const [client, clock] of restStructs.missing) {\n const mclock = pending.missing.get(client)\n if (mclock == null || mclock > clock) {\n pending.missing.set(client, clock)\n }\n }\n pending.update = mergeUpdatesV2([pending.update, restStructs.update])\n }\n } else {\n store.pendingStructs = restStructs\n }\n // console.log('time to integrate: ', performance.now() - start) // @todo remove\n // start = performance.now()\n const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store)\n if (store.pendingDs) {\n // @todo we could make a lower-bound state-vector check as we do above\n const pendingDSUpdate = new UpdateDecoderV2(decoding.createDecoder(store.pendingDs))\n decoding.readVarUint(pendingDSUpdate.restDecoder) // read 0 structs, because we only encode deletes in pendingdsupdate\n const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store)\n if (dsRest && dsRest2) {\n // case 1: ds1 != null && ds2 != null\n store.pendingDs = mergeUpdatesV2([dsRest, dsRest2])\n } else {\n // case 2: ds1 != null\n // case 3: ds2 != null\n // case 4: ds1 == null && ds2 == null\n store.pendingDs = dsRest || dsRest2\n }\n } else {\n // Either dsRest == null && pendingDs == null OR dsRest != null\n store.pendingDs = dsRest\n }\n // console.log('time to cleanup: ', performance.now() - start) // @todo remove\n // start = performance.now()\n\n // console.log('time to resume delete readers: ', performance.now() - start) // @todo remove\n // start = performance.now()\n if (retry) {\n const update = /** @type {{update: Uint8Array}} */ (store.pendingStructs).update\n store.pendingStructs = null\n applyUpdateV2(transaction.doc, update)\n }\n }, transactionOrigin, false)\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts an decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nexport const readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new UpdateDecoderV1(decoder))\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n *\n * @function\n */\nexport const applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {\n const decoder = decoding.createDecoder(update)\n readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder))\n}\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nexport const applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1)\n\n/**\n * Write all the document as a single update message. If you specify the state of the remote client (`targetStateVector`) it will\n * only write the operations that are missing.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Doc} doc\n * @param {Map<number,number>} [targetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n *\n * @function\n */\nexport const writeStateAsUpdate = (encoder, doc, targetStateVector = new Map()) => {\n writeClientsStructs(encoder, doc.store, targetStateVector)\n writeDeleteSet(encoder, createDeleteSetFromStructStore(doc.store))\n}\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @param {UpdateEncoderV1 | UpdateEncoderV2} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateAsUpdateV2 = (doc, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => {\n const targetStateVector = decodeStateVector(encodedTargetStateVector)\n writeStateAsUpdate(encoder, doc, targetStateVector)\n const updates = [encoder.toUint8Array()]\n // also add the pending updates (if there are any)\n if (doc.store.pendingDs) {\n updates.push(doc.store.pendingDs)\n }\n if (doc.store.pendingStructs) {\n updates.push(diffUpdateV2(doc.store.pendingStructs.update, encodedTargetStateVector))\n }\n if (updates.length > 1) {\n if (encoder.constructor === UpdateEncoderV1) {\n return mergeUpdates(updates.map((update, i) => i === 0 ? update : convertUpdateFormatV2ToV1(update)))\n } else if (encoder.constructor === UpdateEncoderV2) {\n return mergeUpdatesV2(updates)\n }\n }\n return updates[0]\n}\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateAsUpdate = (doc, encodedTargetStateVector) => encodeStateAsUpdateV2(doc, encodedTargetStateVector, new UpdateEncoderV1())\n\n/**\n * Read state vector from Decoder and return as Map\n *\n * @param {DSDecoderV1 | DSDecoderV2} decoder\n * @return {Map<number,number>} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nexport const readStateVector = decoder => {\n const ss = new Map()\n const ssLength = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < ssLength; i++) {\n const client = decoding.readVarUint(decoder.restDecoder)\n const clock = decoding.readVarUint(decoder.restDecoder)\n ss.set(client, clock)\n }\n return ss\n}\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map<number,number>} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\n// export const decodeStateVectorV2 = decodedState => readStateVector(new DSDecoderV2(decoding.createDecoder(decodedState)))\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map<number,number>} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nexport const decodeStateVector = decodedState => readStateVector(new DSDecoderV1(decoding.createDecoder(decodedState)))\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {Map<number,number>} sv\n * @function\n */\nexport const writeStateVector = (encoder, sv) => {\n encoding.writeVarUint(encoder.restEncoder, sv.size)\n Array.from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n encoding.writeVarUint(encoder.restEncoder, client) // @todo use a special client decoder that is based on mapping\n encoding.writeVarUint(encoder.restEncoder, clock)\n })\n return encoder\n}\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {Doc} doc\n *\n * @function\n */\nexport const writeDocumentStateVector = (encoder, doc) => writeStateVector(encoder, getStateVector(doc.store))\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc|Map<number,number>} doc\n * @param {DSEncoderV1 | DSEncoderV2} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateVectorV2 = (doc, encoder = new DSEncoderV2()) => {\n if (doc instanceof Map) {\n writeStateVector(encoder, doc)\n } else {\n writeDocumentStateVector(encoder, doc)\n }\n return encoder.toUint8Array()\n}\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc|Map<number,number>} doc\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateVector = doc => encodeStateVectorV2(doc, new DSEncoderV1())\n","import * as f from 'lib0/function'\n\n/**\n * General event handler implementation.\n *\n * @template ARG0, ARG1\n *\n * @private\n */\nexport class EventHandler {\n constructor () {\n /**\n * @type {Array<function(ARG0, ARG1):void>}\n */\n this.l = []\n }\n}\n\n/**\n * @template ARG0,ARG1\n * @returns {EventHandler<ARG0,ARG1>}\n *\n * @private\n * @function\n */\nexport const createEventHandler = () => new EventHandler()\n\n/**\n * Adds an event listener that is called when\n * {@link EventHandler#callEventListeners} is called.\n *\n * @template ARG0,ARG1\n * @param {EventHandler<ARG0,ARG1>} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler.\n *\n * @private\n * @function\n */\nexport const addEventHandlerListener = (eventHandler, f) =>\n eventHandler.l.push(f)\n\n/**\n * Removes an event listener.\n *\n * @template ARG0,ARG1\n * @param {EventHandler<ARG0,ARG1>} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler that was added with\n * {@link EventHandler#addEventListener}\n *\n * @private\n * @function\n */\nexport const removeEventHandlerListener = (eventHandler, f) => {\n const l = eventHandler.l\n const len = l.length\n eventHandler.l = l.filter(g => f !== g)\n if (len === eventHandler.l.length) {\n console.error('[yjs] Tried to remove event handler that doesn\\'t exist.')\n }\n}\n\n/**\n * Removes all event listeners.\n * @template ARG0,ARG1\n * @param {EventHandler<ARG0,ARG1>} eventHandler\n *\n * @private\n * @function\n */\nexport const removeAllEventHandlerListeners = eventHandler => {\n eventHandler.l.length = 0\n}\n\n/**\n * Call all event listeners that were added via\n * {@link EventHandler#addEventListener}.\n *\n * @template ARG0,ARG1\n * @param {EventHandler<ARG0,ARG1>} eventHandler\n * @param {ARG0} arg0\n * @param {ARG1} arg1\n *\n * @private\n * @function\n */\nexport const callEventHandlerListeners = (eventHandler, arg0, arg1) =>\n f.callAll(eventHandler.l, [arg0, arg1])\n","\nimport { AbstractType } from '../internals.js' // eslint-disable-line\n\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\nimport * as error from 'lib0/error'\n\nexport class ID {\n /**\n * @param {number} client client id\n * @param {number} clock unique per client id, continuous number\n */\n constructor (client, clock) {\n /**\n * Client id\n * @type {number}\n */\n this.client = client\n /**\n * unique per client id, continuous number\n * @type {number}\n */\n this.clock = clock\n }\n}\n\n/**\n * @param {ID | null} a\n * @param {ID | null} b\n * @return {boolean}\n *\n * @function\n */\nexport const compareIDs = (a, b) => a === b || (a !== null && b !== null && a.client === b.client && a.clock === b.clock)\n\n/**\n * @param {number} client\n * @param {number} clock\n *\n * @private\n * @function\n */\nexport const createID = (client, clock) => new ID(client, clock)\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {ID} id\n *\n * @private\n * @function\n */\nexport const writeID = (encoder, id) => {\n encoding.writeVarUint(encoder, id.client)\n encoding.writeVarUint(encoder, id.clock)\n}\n\n/**\n * Read ID.\n * * If first varUint read is 0xFFFFFF a RootID is returned.\n * * Otherwise an ID is returned\n *\n * @param {decoding.Decoder} decoder\n * @return {ID}\n *\n * @private\n * @function\n */\nexport const readID = decoder =>\n createID(decoding.readVarUint(decoder), decoding.readVarUint(decoder))\n\n/**\n * The top types are mapped from y.share.get(keyname) => type.\n * `type` does not store any information about the `keyname`.\n * This function finds the correct `keyname` for `type` and throws otherwise.\n *\n * @param {AbstractType<any>} type\n * @return {string}\n *\n * @private\n * @function\n */\nexport const findRootTypeKey = type => {\n // @ts-ignore _y must be defined, otherwise unexpected case\n for (const [key, value] of type.doc.share.entries()) {\n if (value === type) {\n return key\n }\n }\n throw error.unexpectedCase()\n}\n","\nimport { AbstractType, Item } from '../internals.js' // eslint-disable-line\n\n/**\n * Check if `parent` is a parent of `child`.\n *\n * @param {AbstractType<any>} parent\n * @param {Item|null} child\n * @return {Boolean} Whether `parent` is a parent of `child`.\n *\n * @private\n * @function\n */\nexport const isParentOf = (parent, child) => {\n while (child !== null) {\n if (child.parent === parent) {\n return true\n }\n child = /** @type {AbstractType<any>} */ (child.parent)._item\n }\n return false\n}\n","\nimport {\n AbstractType // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Convenient helper to log type information.\n *\n * Do not use in productive systems as the output can be immense!\n *\n * @param {AbstractType<any>} type\n */\nexport const logType = type => {\n const res = []\n let n = type._start\n while (n) {\n res.push(n)\n n = n.right\n }\n console.log('Children: ', res)\n console.log('Children content: ', res.filter(m => !m.deleted).map(m => m.content))\n}\n","\nimport {\n YArray,\n YMap,\n readDeleteSet,\n writeDeleteSet,\n createDeleteSet,\n DSEncoderV1, DSDecoderV1, ID, DeleteSet, YArrayEvent, Transaction, Doc // eslint-disable-line\n} from '../internals.js'\n\nimport * as decoding from 'lib0/decoding'\n\nimport { mergeDeleteSets, isDeleted } from './DeleteSet.js'\n\nexport class PermanentUserData {\n /**\n * @param {Doc} doc\n * @param {YMap<any>} [storeType]\n */\n constructor (doc, storeType = doc.getMap('users')) {\n /**\n * @type {Map<string,DeleteSet>}\n */\n const dss = new Map()\n this.yusers = storeType\n this.doc = doc\n /**\n * Maps from clientid to userDescription\n *\n * @type {Map<number,string>}\n */\n this.clients = new Map()\n this.dss = dss\n /**\n * @param {YMap<any>} user\n * @param {string} userDescription\n */\n const initUser = (user, userDescription) => {\n /**\n * @type {YArray<Uint8Array>}\n */\n const ds = user.get('ds')\n const ids = user.get('ids')\n const addClientId = /** @param {number} clientid */ clientid => this.clients.set(clientid, userDescription)\n ds.observe(/** @param {YArrayEvent<any>} event */ event => {\n event.changes.added.forEach(item => {\n item.content.getContent().forEach(encodedDs => {\n if (encodedDs instanceof Uint8Array) {\n this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs)))]))\n }\n })\n })\n })\n this.dss.set(userDescription, mergeDeleteSets(ds.map(encodedDs => readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs))))))\n ids.observe(/** @param {YArrayEvent<any>} event */ event =>\n event.changes.added.forEach(item => item.content.getContent().forEach(addClientId))\n )\n ids.forEach(addClientId)\n }\n // observe users\n storeType.observe(event => {\n event.keysChanged.forEach(userDescription =>\n initUser(storeType.get(userDescription), userDescription)\n )\n })\n // add intial data\n storeType.forEach(initUser)\n }\n\n /**\n * @param {Doc} doc\n * @param {number} clientid\n * @param {string} userDescription\n * @param {Object} [conf]\n * @param {function(Transaction, DeleteSet):boolean} [conf.filter]\n */\n setUserMapping (doc, clientid, userDescription, { filter = () => true } = {}) {\n const users = this.yusers\n let user = users.get(userDescription)\n if (!user) {\n user = new YMap()\n user.set('ids', new YArray())\n user.set('ds', new YArray())\n users.set(userDescription, user)\n }\n user.get('ids').push([clientid])\n users.observe(event => {\n setTimeout(() => {\n const userOverwrite = users.get(userDescription)\n if (userOverwrite !== user) {\n // user was overwritten, port all data over to the next user object\n // @todo Experiment with Y.Sets here\n user = userOverwrite\n // @todo iterate over old type\n this.clients.forEach((_userDescription, clientid) => {\n if (userDescription === _userDescription) {\n user.get('ids').push([clientid])\n }\n })\n const encoder = new DSEncoderV1()\n const ds = this.dss.get(userDescription)\n if (ds) {\n writeDeleteSet(encoder, ds)\n user.get('ds').push([encoder.toUint8Array()])\n }\n }\n }, 0)\n })\n doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => {\n setTimeout(() => {\n const yds = user.get('ds')\n const ds = transaction.deleteSet\n if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) {\n const encoder = new DSEncoderV1()\n writeDeleteSet(encoder, ds)\n yds.push([encoder.toUint8Array()])\n }\n })\n })\n }\n\n /**\n * @param {number} clientid\n * @return {any}\n */\n getUserByClientId (clientid) {\n return this.clients.get(clientid) || null\n }\n\n /**\n * @param {ID} id\n * @return {string | null}\n */\n getUserByDeletedId (id) {\n for (const [userDescription, ds] of this.dss.entries()) {\n if (isDeleted(ds, id)) {\n return userDescription\n }\n }\n return null\n }\n}\n","\nimport {\n writeID,\n readID,\n compareIDs,\n getState,\n findRootTypeKey,\n Item,\n createID,\n ContentType,\n followRedone,\n ID, Doc, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as error from 'lib0/error'\n\n/**\n * A relative position is based on the Yjs model and is not affected by document changes.\n * E.g. If you place a relative position before a certain character, it will always point to this character.\n * If you place a relative position at the end of a type, it will always point to the end of the type.\n *\n * A numeric position is often unsuited for user selections, because it does not change when content is inserted\n * before or after.\n *\n * ```Insert(0, 'x')('a|bc') = 'xa|bc'``` Where | is the relative position.\n *\n * One of the properties must be defined.\n *\n * @example\n * // Current cursor position is at position 10\n * const relativePosition = createRelativePositionFromIndex(yText, 10)\n * // modify yText\n * yText.insert(0, 'abc')\n * yText.delete(3, 10)\n * // Compute the cursor position\n * const absolutePosition = createAbsolutePositionFromRelativePosition(y, relativePosition)\n * absolutePosition.type === yText // => true\n * console.log('cursor location is ' + absolutePosition.index) // => cursor location is 3\n *\n */\nexport class RelativePosition {\n /**\n * @param {ID|null} type\n * @param {string|null} tname\n * @param {ID|null} item\n * @param {number} assoc\n */\n constructor (type, tname, item, assoc = 0) {\n /**\n * @type {ID|null}\n */\n this.type = type\n /**\n * @type {string|null}\n */\n this.tname = tname\n /**\n * @type {ID | null}\n */\n this.item = item\n /**\n * A relative position is associated to a specific character. By default\n * assoc >= 0, the relative position is associated to the character\n * after the meant position.\n * I.e. position 1 in 'ab' is associated to character 'b'.\n *\n * If assoc < 0, then the relative position is associated to the caharacter\n * before the meant position.\n *\n * @type {number}\n */\n this.assoc = assoc\n }\n}\n\n/**\n * @param {RelativePosition} rpos\n * @return {any}\n */\nexport const relativePositionToJSON = rpos => {\n const json = {}\n if (rpos.type) {\n json.type = rpos.type\n }\n if (rpos.tname) {\n json.tname = rpos.tname\n }\n if (rpos.item) {\n json.item = rpos.item\n }\n if (rpos.assoc != null) {\n json.assoc = rpos.assoc\n }\n return json\n}\n\n/**\n * @param {any} json\n * @return {RelativePosition}\n *\n * @function\n */\nexport const createRelativePositionFromJSON = json => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname || null, json.item == null ? null : createID(json.item.client, json.item.clock), json.assoc == null ? 0 : json.assoc)\n\nexport class AbsolutePosition {\n /**\n * @param {AbstractType<any>} type\n * @param {number} index\n * @param {number} [assoc]\n */\n constructor (type, index, assoc = 0) {\n /**\n * @type {AbstractType<any>}\n */\n this.type = type\n /**\n * @type {number}\n */\n this.index = index\n this.assoc = assoc\n }\n}\n\n/**\n * @param {AbstractType<any>} type\n * @param {number} index\n * @param {number} [assoc]\n *\n * @function\n */\nexport const createAbsolutePosition = (type, index, assoc = 0) => new AbsolutePosition(type, index, assoc)\n\n/**\n * @param {AbstractType<any>} type\n * @param {ID|null} item\n * @param {number} [assoc]\n *\n * @function\n */\nexport const createRelativePosition = (type, item, assoc) => {\n let typeid = null\n let tname = null\n if (type._item === null) {\n tname = findRootTypeKey(type)\n } else {\n typeid = createID(type._item.id.client, type._item.id.clock)\n }\n return new RelativePosition(typeid, tname, item, assoc)\n}\n\n/**\n * Create a relativePosition based on a absolute position.\n *\n * @param {AbstractType<any>} type The base type (e.g. YText or YArray).\n * @param {number} index The absolute position.\n * @param {number} [assoc]\n * @return {RelativePosition}\n *\n * @function\n */\nexport const createRelativePositionFromTypeIndex = (type, index, assoc = 0) => {\n let t = type._start\n if (assoc < 0) {\n // associated to the left character or the beginning of a type, increment index if possible.\n if (index === 0) {\n return createRelativePosition(type, null, assoc)\n }\n index--\n }\n while (t !== null) {\n if (!t.deleted && t.countable) {\n if (t.length > index) {\n // case 1: found position somewhere in the linked list\n return createRelativePosition(type, createID(t.id.client, t.id.clock + index), assoc)\n }\n index -= t.length\n }\n if (t.right === null && assoc < 0) {\n // left-associated position, return last available id\n return createRelativePosition(type, t.lastId, assoc)\n }\n t = t.right\n }\n return createRelativePosition(type, null, assoc)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {RelativePosition} rpos\n *\n * @function\n */\nexport const writeRelativePosition = (encoder, rpos) => {\n const { type, tname, item, assoc } = rpos\n if (item !== null) {\n encoding.writeVarUint(encoder, 0)\n writeID(encoder, item)\n } else if (tname !== null) {\n // case 2: found position at the end of the list and type is stored in y.share\n encoding.writeUint8(encoder, 1)\n encoding.writeVarString(encoder, tname)\n } else if (type !== null) {\n // case 3: found position at the end of the list and type is attached to an item\n encoding.writeUint8(encoder, 2)\n writeID(encoder, type)\n } else {\n throw error.unexpectedCase()\n }\n encoding.writeVarInt(encoder, assoc)\n return encoder\n}\n\n/**\n * @param {RelativePosition} rpos\n * @return {Uint8Array}\n */\nexport const encodeRelativePosition = rpos => {\n const encoder = encoding.createEncoder()\n writeRelativePosition(encoder, rpos)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {decoding.Decoder} decoder\n * @return {RelativePosition}\n *\n * @function\n */\nexport const readRelativePosition = decoder => {\n let type = null\n let tname = null\n let itemID = null\n switch (decoding.readVarUint(decoder)) {\n case 0:\n // case 1: found position somewhere in the linked list\n itemID = readID(decoder)\n break\n case 1:\n // case 2: found position at the end of the list and type is stored in y.share\n tname = decoding.readVarString(decoder)\n break\n case 2: {\n // case 3: found position at the end of the list and type is attached to an item\n type = readID(decoder)\n }\n }\n const assoc = decoding.hasContent(decoder) ? decoding.readVarInt(decoder) : 0\n return new RelativePosition(type, tname, itemID, assoc)\n}\n\n/**\n * @param {Uint8Array} uint8Array\n * @return {RelativePosition}\n */\nexport const decodeRelativePosition = uint8Array => readRelativePosition(decoding.createDecoder(uint8Array))\n\n/**\n * @param {RelativePosition} rpos\n * @param {Doc} doc\n * @return {AbsolutePosition|null}\n *\n * @function\n */\nexport const createAbsolutePositionFromRelativePosition = (rpos, doc) => {\n const store = doc.store\n const rightID = rpos.item\n const typeID = rpos.type\n const tname = rpos.tname\n const assoc = rpos.assoc\n let type = null\n let index = 0\n if (rightID !== null) {\n if (getState(store, rightID.client) <= rightID.clock) {\n return null\n }\n const res = followRedone(store, rightID)\n const right = res.item\n if (!(right instanceof Item)) {\n return null\n }\n type = /** @type {AbstractType<any>} */ (right.parent)\n if (type._item === null || !type._item.deleted) {\n index = (right.deleted || !right.countable) ? 0 : (res.diff + (assoc >= 0 ? 0 : 1)) // adjust position based on left association if necessary\n let n = right.left\n while (n !== null) {\n if (!n.deleted && n.countable) {\n index += n.length\n }\n n = n.left\n }\n }\n } else {\n if (tname !== null) {\n type = doc.get(tname)\n } else if (typeID !== null) {\n if (getState(store, typeID.client) <= typeID.clock) {\n // type does not exist yet\n return null\n }\n const { item } = followRedone(store, typeID)\n if (item instanceof Item && item.content instanceof ContentType) {\n type = item.content.type\n } else {\n // struct is garbage collected\n return null\n }\n } else {\n throw error.unexpectedCase()\n }\n if (assoc >= 0) {\n index = type._length\n } else {\n index = 0\n }\n }\n return createAbsolutePosition(type, index, rpos.assoc)\n}\n\n/**\n * @param {RelativePosition|null} a\n * @param {RelativePosition|null} b\n * @return {boolean}\n *\n * @function\n */\nexport const compareRelativePositions = (a, b) => a === b || (\n a !== null && b !== null && a.tname === b.tname && compareIDs(a.item, b.item) && compareIDs(a.type, b.type) && a.assoc === b.assoc\n)\n","\nimport {\n isDeleted,\n createDeleteSetFromStructStore,\n getStateVector,\n getItemCleanStart,\n iterateDeletedStructs,\n writeDeleteSet,\n writeStateVector,\n readDeleteSet,\n readStateVector,\n createDeleteSet,\n createID,\n getState,\n findIndexSS,\n UpdateEncoderV2,\n applyUpdateV2,\n DSEncoderV1, DSEncoderV2, DSDecoderV1, DSDecoderV2, Transaction, Doc, DeleteSet, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map'\nimport * as set from 'lib0/set'\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\n\nexport class Snapshot {\n /**\n * @param {DeleteSet} ds\n * @param {Map<number,number>} sv state map\n */\n constructor (ds, sv) {\n /**\n * @type {DeleteSet}\n */\n this.ds = ds\n /**\n * State Map\n * @type {Map<number,number>}\n */\n this.sv = sv\n }\n}\n\n/**\n * @param {Snapshot} snap1\n * @param {Snapshot} snap2\n * @return {boolean}\n */\nexport const equalSnapshots = (snap1, snap2) => {\n const ds1 = snap1.ds.clients\n const ds2 = snap2.ds.clients\n const sv1 = snap1.sv\n const sv2 = snap2.sv\n if (sv1.size !== sv2.size || ds1.size !== ds2.size) {\n return false\n }\n for (const [key, value] of sv1.entries()) {\n if (sv2.get(key) !== value) {\n return false\n }\n }\n for (const [client, dsitems1] of ds1.entries()) {\n const dsitems2 = ds2.get(client) || []\n if (dsitems1.length !== dsitems2.length) {\n return false\n }\n for (let i = 0; i < dsitems1.length; i++) {\n const dsitem1 = dsitems1[i]\n const dsitem2 = dsitems2[i]\n if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) {\n return false\n }\n }\n }\n return true\n}\n\n/**\n * @param {Snapshot} snapshot\n * @param {DSEncoderV1 | DSEncoderV2} [encoder]\n * @return {Uint8Array}\n */\nexport const encodeSnapshotV2 = (snapshot, encoder = new DSEncoderV2()) => {\n writeDeleteSet(encoder, snapshot.ds)\n writeStateVector(encoder, snapshot.sv)\n return encoder.toUint8Array()\n}\n\n/**\n * @param {Snapshot} snapshot\n * @return {Uint8Array}\n */\nexport const encodeSnapshot = snapshot => encodeSnapshotV2(snapshot, new DSEncoderV1())\n\n/**\n * @param {Uint8Array} buf\n * @param {DSDecoderV1 | DSDecoderV2} [decoder]\n * @return {Snapshot}\n */\nexport const decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(decoding.createDecoder(buf))) => {\n return new Snapshot(readDeleteSet(decoder), readStateVector(decoder))\n}\n\n/**\n * @param {Uint8Array} buf\n * @return {Snapshot}\n */\nexport const decodeSnapshot = buf => decodeSnapshotV2(buf, new DSDecoderV1(decoding.createDecoder(buf)))\n\n/**\n * @param {DeleteSet} ds\n * @param {Map<number,number>} sm\n * @return {Snapshot}\n */\nexport const createSnapshot = (ds, sm) => new Snapshot(ds, sm)\n\nexport const emptySnapshot = createSnapshot(createDeleteSet(), new Map())\n\n/**\n * @param {Doc} doc\n * @return {Snapshot}\n */\nexport const snapshot = doc => createSnapshot(createDeleteSetFromStructStore(doc.store), getStateVector(doc.store))\n\n/**\n * @param {Item} item\n * @param {Snapshot|undefined} snapshot\n *\n * @protected\n * @function\n */\nexport const isVisible = (item, snapshot) => snapshot === undefined\n ? !item.deleted\n : snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id)\n\n/**\n * @param {Transaction} transaction\n * @param {Snapshot} snapshot\n */\nexport const splitSnapshotAffectedStructs = (transaction, snapshot) => {\n const meta = map.setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, set.create)\n const store = transaction.doc.store\n // check if we already split for this snapshot\n if (!meta.has(snapshot)) {\n snapshot.sv.forEach((clock, client) => {\n if (clock < getState(store, client)) {\n getItemCleanStart(transaction, createID(client, clock))\n }\n })\n iterateDeletedStructs(transaction, snapshot.ds, item => {})\n meta.add(snapshot)\n }\n}\n\n/**\n * @param {Doc} originDoc\n * @param {Snapshot} snapshot\n * @param {Doc} [newDoc] Optionally, you may define the Yjs document that receives the data from originDoc\n * @return {Doc}\n */\nexport const createDocFromSnapshot = (originDoc, snapshot, newDoc = new Doc()) => {\n if (originDoc.gc) {\n // we should not try to restore a GC-ed document, because some of the restored items might have their content deleted\n throw new Error('originDoc must not be garbage collected')\n }\n const { sv, ds } = snapshot\n\n const encoder = new UpdateEncoderV2()\n originDoc.transact(transaction => {\n let size = 0\n sv.forEach(clock => {\n if (clock > 0) {\n size++\n }\n })\n encoding.writeVarUint(encoder.restEncoder, size)\n // splitting the structs before writing them to the encoder\n for (const [client, clock] of sv) {\n if (clock === 0) {\n continue\n }\n if (clock < getState(originDoc.store, client)) {\n getItemCleanStart(transaction, createID(client, clock))\n }\n const structs = originDoc.store.clients.get(client) || []\n const lastStructIndex = findIndexSS(structs, clock - 1)\n // write # encoded structs\n encoding.writeVarUint(encoder.restEncoder, lastStructIndex + 1)\n encoder.writeClient(client)\n // first clock written is 0\n encoding.writeVarUint(encoder.restEncoder, 0)\n for (let i = 0; i <= lastStructIndex; i++) {\n structs[i].write(encoder, 0)\n }\n }\n writeDeleteSet(encoder, ds)\n })\n\n applyUpdateV2(newDoc, encoder.toUint8Array(), 'snapshot')\n return newDoc\n}\n","\nimport {\n GC,\n splitItem,\n Transaction, ID, Item, DSDecoderV2 // eslint-disable-line\n} from '../internals.js'\n\nimport * as math from 'lib0/math'\nimport * as error from 'lib0/error'\n\nexport class StructStore {\n constructor () {\n /**\n * @type {Map<number,Array<GC|Item>>}\n */\n this.clients = new Map()\n /**\n * @type {null | { missing: Map<number, number>, update: Uint8Array }}\n */\n this.pendingStructs = null\n /**\n * @type {null | Uint8Array}\n */\n this.pendingDs = null\n }\n}\n\n/**\n * Return the states as a Map<client,clock>.\n * Note that clock refers to the next expected clock id.\n *\n * @param {StructStore} store\n * @return {Map<number,number>}\n *\n * @public\n * @function\n */\nexport const getStateVector = store => {\n const sm = new Map()\n store.clients.forEach((structs, client) => {\n const struct = structs[structs.length - 1]\n sm.set(client, struct.id.clock + struct.length)\n })\n return sm\n}\n\n/**\n * @param {StructStore} store\n * @param {number} client\n * @return {number}\n *\n * @public\n * @function\n */\nexport const getState = (store, client) => {\n const structs = store.clients.get(client)\n if (structs === undefined) {\n return 0\n }\n const lastStruct = structs[structs.length - 1]\n return lastStruct.id.clock + lastStruct.length\n}\n\n/**\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nexport const integretyCheck = store => {\n store.clients.forEach(structs => {\n for (let i = 1; i < structs.length; i++) {\n const l = structs[i - 1]\n const r = structs[i]\n if (l.id.clock + l.length !== r.id.clock) {\n throw new Error('StructStore failed integrety check')\n }\n }\n })\n}\n\n/**\n * @param {StructStore} store\n * @param {GC|Item} struct\n *\n * @private\n * @function\n */\nexport const addStruct = (store, struct) => {\n let structs = store.clients.get(struct.id.client)\n if (structs === undefined) {\n structs = []\n store.clients.set(struct.id.client, structs)\n } else {\n const lastStruct = structs[structs.length - 1]\n if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) {\n throw error.unexpectedCase()\n }\n }\n structs.push(struct)\n}\n\n/**\n * Perform a binary search on a sorted array\n * @param {Array<Item|GC>} structs\n * @param {number} clock\n * @return {number}\n *\n * @private\n * @function\n */\nexport const findIndexSS = (structs, clock) => {\n let left = 0\n let right = structs.length - 1\n let mid = structs[right]\n let midclock = mid.id.clock\n if (midclock === clock) {\n return right\n }\n // @todo does it even make sense to pivot the search?\n // If a good split misses, it might actually increase the time to find the correct item.\n // Currently, the only advantage is that search with pivoting might find the item on the first try.\n let midindex = math.floor((clock / (midclock + mid.length - 1)) * right) // pivoting the search\n while (left <= right) {\n mid = structs[midindex]\n midclock = mid.id.clock\n if (midclock <= clock) {\n if (clock < midclock + mid.length) {\n return midindex\n }\n left = midindex + 1\n } else {\n right = midindex - 1\n }\n midindex = math.floor((left + right) / 2)\n }\n // Always check state before looking for a struct in StructStore\n // Therefore the case of not finding a struct is unexpected\n throw error.unexpectedCase()\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {GC|Item}\n *\n * @private\n * @function\n */\nexport const find = (store, id) => {\n /**\n * @type {Array<GC|Item>}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client)\n return structs[findIndexSS(structs, id.clock)]\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n * @private\n * @function\n */\nexport const getItem = /** @type {function(StructStore,ID):Item} */ (find)\n\n/**\n * @param {Transaction} transaction\n * @param {Array<Item|GC>} structs\n * @param {number} clock\n */\nexport const findIndexCleanStart = (transaction, structs, clock) => {\n const index = findIndexSS(structs, clock)\n const struct = structs[index]\n if (struct.id.clock < clock && struct instanceof Item) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock))\n return index + 1\n }\n return index\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nexport const getItemCleanStart = (transaction, id) => {\n const structs = /** @type {Array<Item>} */ (transaction.doc.store.clients.get(id.client))\n return structs[findIndexCleanStart(transaction, structs, id.clock)]\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nexport const getItemCleanEnd = (transaction, store, id) => {\n /**\n * @type {Array<Item>}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client)\n const index = findIndexSS(structs, id.clock)\n const struct = structs[index]\n if (id.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, id.clock - struct.id.clock + 1))\n }\n return struct\n}\n\n/**\n * Replace `item` with `newitem` in store\n * @param {StructStore} store\n * @param {GC|Item} struct\n * @param {GC|Item} newStruct\n *\n * @private\n * @function\n */\nexport const replaceStruct = (store, struct, newStruct) => {\n const structs = /** @type {Array<GC|Item>} */ (store.clients.get(struct.id.client))\n structs[findIndexSS(structs, struct.id.clock)] = newStruct\n}\n\n/**\n * Iterate over a range of structs\n *\n * @param {Transaction} transaction\n * @param {Array<Item|GC>} structs\n * @param {number} clockStart Inclusive start\n * @param {number} len\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nexport const iterateStructs = (transaction, structs, clockStart, len, f) => {\n if (len === 0) {\n return\n }\n const clockEnd = clockStart + len\n let index = findIndexCleanStart(transaction, structs, clockStart)\n let struct\n do {\n struct = structs[index++]\n if (clockEnd < struct.id.clock + struct.length) {\n findIndexCleanStart(transaction, structs, clockEnd)\n }\n f(struct)\n } while (index < structs.length && structs[index].id.clock < clockEnd)\n}\n","\nimport {\n getState,\n writeStructsFromTransaction,\n writeDeleteSet,\n DeleteSet,\n sortAndMergeDeleteSet,\n getStateVector,\n findIndexSS,\n callEventHandlerListeners,\n Item,\n generateNewClientId,\n createID,\n UpdateEncoderV1, UpdateEncoderV2, GC, StructStore, AbstractType, AbstractStruct, YEvent, Doc // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map'\nimport * as math from 'lib0/math'\nimport * as set from 'lib0/set'\nimport * as logging from 'lib0/logging'\nimport { callAll } from 'lib0/function'\n\n/**\n * A transaction is created for every change on the Yjs model. It is possible\n * to bundle changes on the Yjs model in a single transaction to\n * minimize the number on messages sent and the number of observer calls.\n * If possible the user of this library should bundle as many changes as\n * possible. Here is an example to illustrate the advantages of bundling:\n *\n * @example\n * const map = y.define('map', YMap)\n * // Log content when change is triggered\n * map.observe(() => {\n * console.log('change triggered')\n * })\n * // Each change on the map type triggers a log message:\n * map.set('a', 0) // => \"change triggered\"\n * map.set('b', 0) // => \"change triggered\"\n * // When put in a transaction, it will trigger the log after the transaction:\n * y.transact(() => {\n * map.set('a', 1)\n * map.set('b', 1)\n * }) // => \"change triggered\"\n *\n * @public\n */\nexport class Transaction {\n /**\n * @param {Doc} doc\n * @param {any} origin\n * @param {boolean} local\n */\n constructor (doc, origin, local) {\n /**\n * The Yjs instance.\n * @type {Doc}\n */\n this.doc = doc\n /**\n * Describes the set of deleted items by ids\n * @type {DeleteSet}\n */\n this.deleteSet = new DeleteSet()\n /**\n * Holds the state before the transaction started.\n * @type {Map<Number,Number>}\n */\n this.beforeState = getStateVector(doc.store)\n /**\n * Holds the state after the transaction.\n * @type {Map<Number,Number>}\n */\n this.afterState = new Map()\n /**\n * All types that were directly modified (property added or child\n * inserted/deleted). New types are not included in this Set.\n * Maps from type to parentSubs (`item.parentSub = null` for YArray)\n * @type {Map<AbstractType<YEvent<any>>,Set<String|null>>}\n */\n this.changed = new Map()\n /**\n * Stores the events for the types that observe also child elements.\n * It is mainly used by `observeDeep`.\n * @type {Map<AbstractType<YEvent<any>>,Array<YEvent<any>>>}\n */\n this.changedParentTypes = new Map()\n /**\n * @type {Array<AbstractStruct>}\n */\n this._mergeStructs = []\n /**\n * @type {any}\n */\n this.origin = origin\n /**\n * Stores meta information on the transaction\n * @type {Map<any,any>}\n */\n this.meta = new Map()\n /**\n * Whether this change originates from this doc.\n * @type {boolean}\n */\n this.local = local\n /**\n * @type {Set<Doc>}\n */\n this.subdocsAdded = new Set()\n /**\n * @type {Set<Doc>}\n */\n this.subdocsRemoved = new Set()\n /**\n * @type {Set<Doc>}\n */\n this.subdocsLoaded = new Set()\n }\n}\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Transaction} transaction\n * @return {boolean} Whether data was written.\n */\nexport const writeUpdateMessageFromTransaction = (encoder, transaction) => {\n if (transaction.deleteSet.clients.size === 0 && !map.any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {\n return false\n }\n sortAndMergeDeleteSet(transaction.deleteSet)\n writeStructsFromTransaction(encoder, transaction)\n writeDeleteSet(encoder, transaction.deleteSet)\n return true\n}\n\n/**\n * @param {Transaction} transaction\n *\n * @private\n * @function\n */\nexport const nextID = transaction => {\n const y = transaction.doc\n return createID(y.clientID, getState(y.store, y.clientID))\n}\n\n/**\n * If `type.parent` was added in current transaction, `type` technically\n * did not change, it was just added and we should not fire events for `type`.\n *\n * @param {Transaction} transaction\n * @param {AbstractType<YEvent<any>>} type\n * @param {string|null} parentSub\n */\nexport const addChangedTypeToTransaction = (transaction, type, parentSub) => {\n const item = type._item\n if (item === null || (item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted)) {\n map.setIfUndefined(transaction.changed, type, set.create).add(parentSub)\n }\n}\n\n/**\n * @param {Array<AbstractStruct>} structs\n * @param {number} pos\n */\nconst tryToMergeWithLeft = (structs, pos) => {\n const left = structs[pos - 1]\n const right = structs[pos]\n if (left.deleted === right.deleted && left.constructor === right.constructor) {\n if (left.mergeWith(right)) {\n structs.splice(pos, 1)\n if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType<any>} */ (right.parent)._map.get(right.parentSub) === right) {\n /** @type {AbstractType<any>} */ (right.parent)._map.set(right.parentSub, /** @type {Item} */ (left))\n }\n }\n }\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nconst tryGcDeleteSet = (ds, store, gcFilter) => {\n for (const [client, deleteItems] of ds.clients.entries()) {\n const structs = /** @type {Array<GC|Item>} */ (store.clients.get(client))\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di]\n const endDeleteItemClock = deleteItem.clock + deleteItem.len\n for (\n let si = findIndexSS(structs, deleteItem.clock), struct = structs[si];\n si < structs.length && struct.id.clock < endDeleteItemClock;\n struct = structs[++si]\n ) {\n const struct = structs[si]\n if (deleteItem.clock + deleteItem.len <= struct.id.clock) {\n break\n }\n if (struct instanceof Item && struct.deleted && !struct.keep && gcFilter(struct)) {\n struct.gc(store, false)\n }\n }\n }\n }\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n */\nconst tryMergeDeleteSet = (ds, store) => {\n // try to merge deleted / gc'd items\n // merge from right to left for better efficiecy and so we don't miss any merge targets\n ds.clients.forEach((deleteItems, client) => {\n const structs = /** @type {Array<GC|Item>} */ (store.clients.get(client))\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di]\n // start with merging the item next to the last deleted item\n const mostRightIndexToCheck = math.min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1))\n for (\n let si = mostRightIndexToCheck, struct = structs[si];\n si > 0 && struct.id.clock >= deleteItem.clock;\n struct = structs[--si]\n ) {\n tryToMergeWithLeft(structs, si)\n }\n }\n })\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nexport const tryGc = (ds, store, gcFilter) => {\n tryGcDeleteSet(ds, store, gcFilter)\n tryMergeDeleteSet(ds, store)\n}\n\n/**\n * @param {Array<Transaction>} transactionCleanups\n * @param {number} i\n */\nconst cleanupTransactions = (transactionCleanups, i) => {\n if (i < transactionCleanups.length) {\n const transaction = transactionCleanups[i]\n const doc = transaction.doc\n const store = doc.store\n const ds = transaction.deleteSet\n const mergeStructs = transaction._mergeStructs\n try {\n sortAndMergeDeleteSet(ds)\n transaction.afterState = getStateVector(transaction.doc.store)\n doc._transaction = null\n doc.emit('beforeObserverCalls', [transaction, doc])\n /**\n * An array of event callbacks.\n *\n * Each callback is called even if the other ones throw errors.\n *\n * @type {Array<function():void>}\n */\n const fs = []\n // observe events on changed types\n transaction.changed.forEach((subs, itemtype) =>\n fs.push(() => {\n if (itemtype._item === null || !itemtype._item.deleted) {\n itemtype._callObserver(transaction, subs)\n }\n })\n )\n fs.push(() => {\n // deep observe events\n transaction.changedParentTypes.forEach((events, type) =>\n fs.push(() => {\n // We need to think about the possibility that the user transforms the\n // Y.Doc in the event.\n if (type._item === null || !type._item.deleted) {\n events = events\n .filter(event =>\n event.target._item === null || !event.target._item.deleted\n )\n events\n .forEach(event => {\n event.currentTarget = type\n })\n // sort events by path length so that top-level events are fired first.\n events\n .sort((event1, event2) => event1.path.length - event2.path.length)\n // We don't need to check for events.length\n // because we know it has at least one element\n callEventHandlerListeners(type._dEH, events, transaction)\n }\n })\n )\n fs.push(() => doc.emit('afterTransaction', [transaction, doc]))\n })\n callAll(fs, [])\n } finally {\n // Replace deleted items with ItemDeleted / GC.\n // This is where content is actually remove from the Yjs Doc.\n if (doc.gc) {\n tryGcDeleteSet(ds, store, doc.gcFilter)\n }\n tryMergeDeleteSet(ds, store)\n\n // on all affected store.clients props, try to merge\n transaction.afterState.forEach((clock, client) => {\n const beforeClock = transaction.beforeState.get(client) || 0\n if (beforeClock !== clock) {\n const structs = /** @type {Array<GC|Item>} */ (store.clients.get(client))\n // we iterate from right to left so we can safely remove entries\n const firstChangePos = math.max(findIndexSS(structs, beforeClock), 1)\n for (let i = structs.length - 1; i >= firstChangePos; i--) {\n tryToMergeWithLeft(structs, i)\n }\n }\n })\n // try to merge mergeStructs\n // @todo: it makes more sense to transform mergeStructs to a DS, sort it, and merge from right to left\n // but at the moment DS does not handle duplicates\n for (let i = 0; i < mergeStructs.length; i++) {\n const { client, clock } = mergeStructs[i].id\n const structs = /** @type {Array<GC|Item>} */ (store.clients.get(client))\n const replacedStructPos = findIndexSS(structs, clock)\n if (replacedStructPos + 1 < structs.length) {\n tryToMergeWithLeft(structs, replacedStructPos + 1)\n }\n if (replacedStructPos > 0) {\n tryToMergeWithLeft(structs, replacedStructPos)\n }\n }\n if (!transaction.local && transaction.afterState.get(doc.clientID) !== transaction.beforeState.get(doc.clientID)) {\n logging.print(logging.ORANGE, logging.BOLD, '[yjs] ', logging.UNBOLD, logging.RED, 'Changed the client-id because another client seems to be using it.')\n doc.clientID = generateNewClientId()\n }\n // @todo Merge all the transactions into one and provide send the data as a single update message\n doc.emit('afterTransactionCleanup', [transaction, doc])\n if (doc._observers.has('update')) {\n const encoder = new UpdateEncoderV1()\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction)\n if (hasContent) {\n doc.emit('update', [encoder.toUint8Array(), transaction.origin, doc, transaction])\n }\n }\n if (doc._observers.has('updateV2')) {\n const encoder = new UpdateEncoderV2()\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction)\n if (hasContent) {\n doc.emit('updateV2', [encoder.toUint8Array(), transaction.origin, doc, transaction])\n }\n }\n const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction\n if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) {\n subdocsAdded.forEach(subdoc => {\n subdoc.clientID = doc.clientID\n if (subdoc.collectionid == null) {\n subdoc.collectionid = doc.collectionid\n }\n doc.subdocs.add(subdoc)\n })\n subdocsRemoved.forEach(subdoc => doc.subdocs.delete(subdoc))\n doc.emit('subdocs', [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc, transaction])\n subdocsRemoved.forEach(subdoc => subdoc.destroy())\n }\n\n if (transactionCleanups.length <= i + 1) {\n doc._transactionCleanups = []\n doc.emit('afterAllTransactions', [doc, transactionCleanups])\n } else {\n cleanupTransactions(transactionCleanups, i + 1)\n }\n }\n }\n}\n\n/**\n * Implements the functionality of `y.transact(()=>{..})`\n *\n * @param {Doc} doc\n * @param {function(Transaction):void} f\n * @param {any} [origin=true]\n *\n * @function\n */\nexport const transact = (doc, f, origin = null, local = true) => {\n const transactionCleanups = doc._transactionCleanups\n let initialCall = false\n if (doc._transaction === null) {\n initialCall = true\n doc._transaction = new Transaction(doc, origin, local)\n transactionCleanups.push(doc._transaction)\n if (transactionCleanups.length === 1) {\n doc.emit('beforeAllTransactions', [doc])\n }\n doc.emit('beforeTransaction', [doc._transaction, doc])\n }\n try {\n f(doc._transaction)\n } finally {\n if (initialCall && transactionCleanups[0] === doc._transaction) {\n // The first transaction ended, now process observer calls.\n // Observer call may create new transactions for which we need to call the observers and do cleanup.\n // We don't want to nest these calls, so we execute these calls one after\n // another.\n // Also we need to ensure that all cleanups are called, even if the\n // observes throw errors.\n // This file is full of hacky try {} finally {} blocks to ensure that an\n // event can throw errors and also that the cleanup is called.\n cleanupTransactions(transactionCleanups, 0)\n }\n }\n}\n","import {\n mergeDeleteSets,\n iterateDeletedStructs,\n keepItem,\n transact,\n createID,\n redoItem,\n isParentOf,\n followRedone,\n getItemCleanStart,\n isDeleted,\n addToDeleteSet,\n Transaction, Doc, Item, GC, DeleteSet, AbstractType, YEvent // eslint-disable-line\n} from '../internals.js'\n\nimport * as time from 'lib0/time'\nimport * as array from 'lib0/array'\nimport { Observable } from 'lib0/observable'\n\nclass StackItem {\n /**\n * @param {DeleteSet} deletions\n * @param {DeleteSet} insertions\n */\n constructor (deletions, insertions) {\n this.insertions = insertions\n this.deletions = deletions\n /**\n * Use this to save and restore metadata like selection range\n */\n this.meta = new Map()\n }\n}\n/**\n * @param {Transaction} tr\n * @param {UndoManager} um\n * @param {StackItem} stackItem\n */\nconst clearUndoManagerStackItem = (tr, um, stackItem) => {\n iterateDeletedStructs(tr, stackItem.deletions, item => {\n if (item instanceof Item && um.scope.some(type => isParentOf(type, item))) {\n keepItem(item, false)\n }\n })\n}\n\n/**\n * @param {UndoManager} undoManager\n * @param {Array<StackItem>} stack\n * @param {string} eventType\n * @return {StackItem?}\n */\nconst popStackItem = (undoManager, stack, eventType) => {\n /**\n * Whether a change happened\n * @type {StackItem?}\n */\n let result = null\n /**\n * Keep a reference to the transaction so we can fire the event with the changedParentTypes\n * @type {any}\n */\n let _tr = null\n const doc = undoManager.doc\n const scope = undoManager.scope\n transact(doc, transaction => {\n while (stack.length > 0 && result === null) {\n const store = doc.store\n const stackItem = /** @type {StackItem} */ (stack.pop())\n /**\n * @type {Set<Item>}\n */\n const itemsToRedo = new Set()\n /**\n * @type {Array<Item>}\n */\n const itemsToDelete = []\n let performedChange = false\n iterateDeletedStructs(transaction, stackItem.insertions, struct => {\n if (struct instanceof Item) {\n if (struct.redone !== null) {\n let { item, diff } = followRedone(store, struct.id)\n if (diff > 0) {\n item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff))\n }\n struct = item\n }\n if (!struct.deleted && scope.some(type => isParentOf(type, /** @type {Item} */ (struct)))) {\n itemsToDelete.push(struct)\n }\n }\n })\n iterateDeletedStructs(transaction, stackItem.deletions, struct => {\n if (\n struct instanceof Item &&\n scope.some(type => isParentOf(type, struct)) &&\n // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval.\n !isDeleted(stackItem.insertions, struct.id)\n ) {\n itemsToRedo.add(struct)\n }\n })\n itemsToRedo.forEach(struct => {\n performedChange = redoItem(transaction, struct, itemsToRedo, stackItem.insertions) !== null || performedChange\n })\n // We want to delete in reverse order so that children are deleted before\n // parents, so we have more information available when items are filtered.\n for (let i = itemsToDelete.length - 1; i >= 0; i--) {\n const item = itemsToDelete[i]\n if (undoManager.deleteFilter(item)) {\n item.delete(transaction)\n performedChange = true\n }\n }\n result = performedChange ? stackItem : null\n }\n transaction.changed.forEach((subProps, type) => {\n // destroy search marker if necessary\n if (subProps.has(null) && type._searchMarker) {\n type._searchMarker.length = 0\n }\n })\n _tr = transaction\n }, undoManager)\n if (result != null) {\n const changedParentTypes = _tr.changedParentTypes\n undoManager.emit('stack-item-popped', [{ stackItem: result, type: eventType, changedParentTypes }, undoManager])\n }\n return result\n}\n\n/**\n * @typedef {Object} UndoManagerOptions\n * @property {number} [UndoManagerOptions.captureTimeout=500]\n * @property {function(Item):boolean} [UndoManagerOptions.deleteFilter=()=>true] Sometimes\n * it is necessary to filter whan an Undo/Redo operation can delete. If this\n * filter returns false, the type/item won't be deleted even it is in the\n * undo/redo scope.\n * @property {Set<any>} [UndoManagerOptions.trackedOrigins=new Set([null])]\n */\n\n/**\n * Fires 'stack-item-added' event when a stack item was added to either the undo- or\n * the redo-stack. You may store additional stack information via the\n * metadata property on `event.stackItem.meta` (it is a `Map` of metadata properties).\n * Fires 'stack-item-popped' event when a stack item was popped from either the\n * undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`.\n *\n * @extends {Observable<'stack-item-added'|'stack-item-popped'|'stack-cleared'|'stack-item-updated'>}\n */\nexport class UndoManager extends Observable {\n /**\n * @param {AbstractType<any>|Array<AbstractType<any>>} typeScope Accepts either a single type, or an array of types\n * @param {UndoManagerOptions} options\n */\n constructor (typeScope, { captureTimeout = 500, deleteFilter = () => true, trackedOrigins = new Set([null]) } = {}) {\n super()\n /**\n * @type {Array<AbstractType<any>>}\n */\n this.scope = []\n this.addToScope(typeScope)\n this.deleteFilter = deleteFilter\n trackedOrigins.add(this)\n this.trackedOrigins = trackedOrigins\n /**\n * @type {Array<StackItem>}\n */\n this.undoStack = []\n /**\n * @type {Array<StackItem>}\n */\n this.redoStack = []\n /**\n * Whether the client is currently undoing (calling UndoManager.undo)\n *\n * @type {boolean}\n */\n this.undoing = false\n this.redoing = false\n this.doc = /** @type {Doc} */ (this.scope[0].doc)\n this.lastChange = 0\n this.doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => {\n // Only track certain transactions\n if (!this.scope.some(type => transaction.changedParentTypes.has(type)) || (!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor)))) {\n return\n }\n const undoing = this.undoing\n const redoing = this.redoing\n const stack = undoing ? this.redoStack : this.undoStack\n if (undoing) {\n this.stopCapturing() // next undo should not be appended to last stack item\n } else if (!redoing) {\n // neither undoing nor redoing: delete redoStack\n this.clear(false, true)\n }\n const insertions = new DeleteSet()\n transaction.afterState.forEach((endClock, client) => {\n const startClock = transaction.beforeState.get(client) || 0\n const len = endClock - startClock\n if (len > 0) {\n addToDeleteSet(insertions, client, startClock, len)\n }\n })\n const now = time.getUnixTime()\n let didAdd = false\n if (now - this.lastChange < captureTimeout && stack.length > 0 && !undoing && !redoing) {\n // append change to last stack op\n const lastOp = stack[stack.length - 1]\n lastOp.deletions = mergeDeleteSets([lastOp.deletions, transaction.deleteSet])\n lastOp.insertions = mergeDeleteSets([lastOp.insertions, insertions])\n } else {\n // create a new stack op\n stack.push(new StackItem(transaction.deleteSet, insertions))\n didAdd = true\n }\n if (!undoing && !redoing) {\n this.lastChange = now\n }\n // make sure that deleted structs are not gc'd\n iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => {\n if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) {\n keepItem(item, true)\n }\n })\n const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo', changedParentTypes: transaction.changedParentTypes }, this]\n if (didAdd) {\n this.emit('stack-item-added', changeEvent)\n } else {\n this.emit('stack-item-updated', changeEvent)\n }\n })\n this.doc.on('destroy', () => {\n this.destroy()\n })\n }\n\n /**\n * @param {Array<AbstractType<any>> | AbstractType<any>} ytypes\n */\n addToScope (ytypes) {\n ytypes = array.isArray(ytypes) ? ytypes : [ytypes]\n ytypes.forEach(ytype => {\n if (this.scope.every(yt => yt !== ytype)) {\n this.scope.push(ytype)\n }\n })\n }\n\n clear (clearUndoStack = true, clearRedoStack = true) {\n if ((clearUndoStack && this.canUndo()) || (clearRedoStack && this.canRedo())) {\n this.doc.transact(tr => {\n if (clearUndoStack) {\n this.undoStack.forEach(item => clearUndoManagerStackItem(tr, this, item))\n this.undoStack = []\n }\n if (clearRedoStack) {\n this.redoStack.forEach(item => clearUndoManagerStackItem(tr, this, item))\n this.redoStack = []\n }\n this.emit('stack-cleared', [{ undoStackCleared: clearUndoStack, redoStackCleared: clearRedoStack }])\n })\n }\n }\n\n /**\n * UndoManager merges Undo-StackItem if they are created within time-gap\n * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next\n * StackItem won't be merged.\n *\n *\n * @example\n * // without stopCapturing\n * ytext.insert(0, 'a')\n * ytext.insert(1, 'b')\n * um.undo()\n * ytext.toString() // => '' (note that 'ab' was removed)\n * // with stopCapturing\n * ytext.insert(0, 'a')\n * um.stopCapturing()\n * ytext.insert(0, 'b')\n * um.undo()\n * ytext.toString() // => 'a' (note that only 'b' was removed)\n *\n */\n stopCapturing () {\n this.lastChange = 0\n }\n\n /**\n * Undo last changes on type.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n undo () {\n this.undoing = true\n let res\n try {\n res = popStackItem(this, this.undoStack, 'undo')\n } finally {\n this.undoing = false\n }\n return res\n }\n\n /**\n * Redo last undo operation.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n redo () {\n this.redoing = true\n let res\n try {\n res = popStackItem(this, this.redoStack, 'redo')\n } finally {\n this.redoing = false\n }\n return res\n }\n\n /**\n * Are undo steps available?\n *\n * @return {boolean} `true` if undo is possible\n */\n canUndo () {\n return this.undoStack.length > 0\n }\n\n /**\n * Are redo steps available?\n *\n * @return {boolean} `true` if redo is possible\n */\n canRedo () {\n return this.redoStack.length > 0\n }\n}\n","\nimport * as binary from 'lib0/binary'\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\nimport * as logging from 'lib0/logging'\nimport * as math from 'lib0/math'\nimport {\n createID,\n readItemContent,\n readDeleteSet,\n writeDeleteSet,\n Skip,\n mergeDeleteSets,\n DSEncoderV1,\n DSEncoderV2,\n decodeStateVector,\n Item, GC, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2 // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n */\nfunction * lazyStructReaderGenerator (decoder) {\n const numOfStateUpdates = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numOfStateUpdates; i++) {\n const numberOfStructs = decoding.readVarUint(decoder.restDecoder)\n const client = decoder.readClient()\n let clock = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numberOfStructs; i++) {\n const info = decoder.readInfo()\n // @todo use switch instead of ifs\n if (info === 10) {\n const len = decoding.readVarUint(decoder.restDecoder)\n yield new Skip(createID(client, clock), len)\n clock += len\n } else if ((binary.BITS5 & info) !== 0) {\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const struct = new Item(\n createID(client, clock),\n null, // left\n (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null, // origin\n null, // right\n (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null, // right origin\n // @ts-ignore Force writing a string here.\n cantCopyParentInfo ? (decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID()) : null, // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n yield struct\n clock += struct.length\n } else {\n const len = decoder.readLen()\n yield new GC(createID(client, clock), len)\n clock += len\n }\n }\n }\n}\n\nexport class LazyStructReader {\n /**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @param {boolean} filterSkips\n */\n constructor (decoder, filterSkips) {\n this.gen = lazyStructReaderGenerator(decoder)\n /**\n * @type {null | Item | Skip | GC}\n */\n this.curr = null\n this.done = false\n this.filterSkips = filterSkips\n this.next()\n }\n\n /**\n * @return {Item | GC | Skip |null}\n */\n next () {\n // ignore \"Skip\" structs\n do {\n this.curr = this.gen.next().value || null\n } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip)\n return this.curr\n }\n}\n\n/**\n * @param {Uint8Array} update\n *\n */\nexport const logUpdate = update => logUpdateV2(update, UpdateDecoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} [YDecoder]\n *\n */\nexport const logUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {\n const structs = []\n const updateDecoder = new YDecoder(decoding.createDecoder(update))\n const lazyDecoder = new LazyStructReader(updateDecoder, false)\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n structs.push(curr)\n }\n logging.print('Structs: ', structs)\n const ds = readDeleteSet(updateDecoder)\n logging.print('DeleteSet: ', ds)\n}\n\n/**\n * @param {Uint8Array} update\n *\n */\nexport const decodeUpdate = (update) => decodeUpdateV2(update, UpdateDecoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} [YDecoder]\n *\n */\nexport const decodeUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {\n const structs = []\n const updateDecoder = new YDecoder(decoding.createDecoder(update))\n const lazyDecoder = new LazyStructReader(updateDecoder, false)\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n structs.push(curr)\n }\n return {\n structs,\n ds: readDeleteSet(updateDecoder)\n }\n}\n\nexport class LazyStructWriter {\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n constructor (encoder) {\n this.currClient = 0\n this.startClock = 0\n this.written = 0\n this.encoder = encoder\n /**\n * We want to write operations lazily, but also we need to know beforehand how many operations we want to write for each client.\n *\n * This kind of meta-information (#clients, #structs-per-client-written) is written to the restEncoder.\n *\n * We fragment the restEncoder and store a slice of it per-client until we know how many clients there are.\n * When we flush (toUint8Array) we write the restEncoder using the fragments and the meta-information.\n *\n * @type {Array<{ written: number, restEncoder: Uint8Array }>}\n */\n this.clientStructs = []\n }\n}\n\n/**\n * @param {Array<Uint8Array>} updates\n * @return {Uint8Array}\n */\nexport const mergeUpdates = updates => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {typeof DSEncoderV1 | typeof DSEncoderV2} YEncoder\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} YDecoder\n * @return {Uint8Array}\n */\nexport const encodeStateVectorFromUpdateV2 = (update, YEncoder = DSEncoderV2, YDecoder = UpdateDecoderV2) => {\n const encoder = new YEncoder()\n const updateDecoder = new LazyStructReader(new YDecoder(decoding.createDecoder(update)), false)\n let curr = updateDecoder.curr\n if (curr !== null) {\n let size = 0\n let currClient = curr.id.client\n let stopCounting = curr.id.clock !== 0 // must start at 0\n let currClock = stopCounting ? 0 : curr.id.clock + curr.length\n for (; curr !== null; curr = updateDecoder.next()) {\n if (currClient !== curr.id.client) {\n if (currClock !== 0) {\n size++\n // We found a new client\n // write what we have to the encoder\n encoding.writeVarUint(encoder.restEncoder, currClient)\n encoding.writeVarUint(encoder.restEncoder, currClock)\n }\n currClient = curr.id.client\n currClock = 0\n stopCounting = curr.id.clock !== 0\n }\n // we ignore skips\n if (curr.constructor === Skip) {\n stopCounting = true\n }\n if (!stopCounting) {\n currClock = curr.id.clock + curr.length\n }\n }\n // write what we have\n if (currClock !== 0) {\n size++\n encoding.writeVarUint(encoder.restEncoder, currClient)\n encoding.writeVarUint(encoder.restEncoder, currClock)\n }\n // prepend the size of the state vector\n const enc = encoding.createEncoder()\n encoding.writeVarUint(enc, size)\n encoding.writeBinaryEncoder(enc, encoder.restEncoder)\n encoder.restEncoder = enc\n return encoder.toUint8Array()\n } else {\n encoding.writeVarUint(encoder.restEncoder, 0)\n return encoder.toUint8Array()\n }\n}\n\n/**\n * @param {Uint8Array} update\n * @return {Uint8Array}\n */\nexport const encodeStateVectorFromUpdate = update => encodeStateVectorFromUpdateV2(update, DSEncoderV1, UpdateDecoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} YDecoder\n * @return {{ from: Map<number,number>, to: Map<number,number> }}\n */\nexport const parseUpdateMetaV2 = (update, YDecoder = UpdateDecoderV2) => {\n /**\n * @type {Map<number, number>}\n */\n const from = new Map()\n /**\n * @type {Map<number, number>}\n */\n const to = new Map()\n const updateDecoder = new LazyStructReader(new YDecoder(decoding.createDecoder(update)), false)\n let curr = updateDecoder.curr\n if (curr !== null) {\n let currClient = curr.id.client\n let currClock = curr.id.clock\n // write the beginning to `from`\n from.set(currClient, currClock)\n for (; curr !== null; curr = updateDecoder.next()) {\n if (currClient !== curr.id.client) {\n // We found a new client\n // write the end to `to`\n to.set(currClient, currClock)\n // write the beginning to `from`\n from.set(curr.id.client, curr.id.clock)\n // update currClient\n currClient = curr.id.client\n }\n currClock = curr.id.clock + curr.length\n }\n // write the end to `to`\n to.set(currClient, currClock)\n }\n return { from, to }\n}\n\n/**\n * @param {Uint8Array} update\n * @return {{ from: Map<number,number>, to: Map<number,number> }}\n */\nexport const parseUpdateMeta = update => parseUpdateMetaV2(update, UpdateDecoderV1)\n\n/**\n * This method is intended to slice any kind of struct and retrieve the right part.\n * It does not handle side-effects, so it should only be used by the lazy-encoder.\n *\n * @param {Item | GC | Skip} left\n * @param {number} diff\n * @return {Item | GC}\n */\nconst sliceStruct = (left, diff) => {\n if (left.constructor === GC) {\n const { client, clock } = left.id\n return new GC(createID(client, clock + diff), left.length - diff)\n } else if (left.constructor === Skip) {\n const { client, clock } = left.id\n return new Skip(createID(client, clock + diff), left.length - diff)\n } else {\n const leftItem = /** @type {Item} */ (left)\n const { client, clock } = leftItem.id\n return new Item(\n createID(client, clock + diff),\n null,\n createID(client, clock + diff - 1),\n null,\n leftItem.rightOrigin,\n leftItem.parent,\n leftItem.parentSub,\n leftItem.content.splice(diff)\n )\n }\n}\n\n/**\n *\n * This function works similarly to `readUpdateV2`.\n *\n * @param {Array<Uint8Array>} updates\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n * @param {typeof UpdateEncoderV1 | typeof UpdateEncoderV2} [YEncoder]\n * @return {Uint8Array}\n */\nexport const mergeUpdatesV2 = (updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {\n if (updates.length === 1) {\n return updates[0]\n }\n const updateDecoders = updates.map(update => new YDecoder(decoding.createDecoder(update)))\n let lazyStructDecoders = updateDecoders.map(decoder => new LazyStructReader(decoder, true))\n\n /**\n * @todo we don't need offset because we always slice before\n * @type {null | { struct: Item | GC | Skip, offset: number }}\n */\n let currWrite = null\n\n const updateEncoder = new YEncoder()\n // write structs lazily\n const lazyStructEncoder = new LazyStructWriter(updateEncoder)\n\n // Note: We need to ensure that all lazyStructDecoders are fully consumed\n // Note: Should merge document updates whenever possible - even from different updates\n // Note: Should handle that some operations cannot be applied yet ()\n\n while (true) {\n // Write higher clients first ⇒ sort by clientID & clock and remove decoders without content\n lazyStructDecoders = lazyStructDecoders.filter(dec => dec.curr !== null)\n lazyStructDecoders.sort(\n /** @type {function(any,any):number} */ (dec1, dec2) => {\n if (dec1.curr.id.client === dec2.curr.id.client) {\n const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock\n if (clockDiff === 0) {\n // @todo remove references to skip since the structDecoders must filter Skips.\n return dec1.curr.constructor === dec2.curr.constructor\n ? 0\n : dec1.curr.constructor === Skip ? 1 : -1 // we are filtering skips anyway.\n } else {\n return clockDiff\n }\n } else {\n return dec2.curr.id.client - dec1.curr.id.client\n }\n }\n )\n if (lazyStructDecoders.length === 0) {\n break\n }\n const currDecoder = lazyStructDecoders[0]\n // write from currDecoder until the next operation is from another client or if filler-struct\n // then we need to reorder the decoders and find the next operation to write\n const firstClient = /** @type {Item | GC} */ (currDecoder.curr).id.client\n\n if (currWrite !== null) {\n let curr = /** @type {Item | GC | null} */ (currDecoder.curr)\n let iterated = false\n\n // iterate until we find something that we haven't written already\n // remember: first the high client-ids are written\n while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) {\n curr = currDecoder.next()\n iterated = true\n }\n if (\n curr === null || // current decoder is empty\n curr.id.client !== firstClient || // check whether there is another decoder that has has updates from `firstClient`\n (iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) // the above while loop was used and we are potentially missing updates\n ) {\n continue\n }\n\n if (firstClient !== currWrite.struct.id.client) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n currWrite = { struct: curr, offset: 0 }\n currDecoder.next()\n } else {\n if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) {\n // @todo write currStruct & set currStruct = Skip(clock = currStruct.id.clock + currStruct.length, length = curr.id.clock - self.clock)\n if (currWrite.struct.constructor === Skip) {\n // extend existing skip\n currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock\n } else {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n const diff = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length\n /**\n * @type {Skip}\n */\n const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff)\n currWrite = { struct, offset: 0 }\n }\n } else { // if (currWrite.struct.id.clock + currWrite.struct.length >= curr.id.clock) {\n const diff = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock\n if (diff > 0) {\n if (currWrite.struct.constructor === Skip) {\n // prefer to slice Skip because the other struct might contain more information\n currWrite.struct.length -= diff\n } else {\n curr = sliceStruct(curr, diff)\n }\n }\n if (!currWrite.struct.mergeWith(/** @type {any} */ (curr))) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n currWrite = { struct: curr, offset: 0 }\n currDecoder.next()\n }\n }\n }\n } else {\n currWrite = { struct: /** @type {Item | GC} */ (currDecoder.curr), offset: 0 }\n currDecoder.next()\n }\n for (\n let next = currDecoder.curr;\n next !== null && next.id.client === firstClient && next.id.clock === currWrite.struct.id.clock + currWrite.struct.length && next.constructor !== Skip;\n next = currDecoder.next()\n ) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n currWrite = { struct: next, offset: 0 }\n }\n }\n if (currWrite !== null) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n currWrite = null\n }\n finishLazyStructWriting(lazyStructEncoder)\n\n const dss = updateDecoders.map(decoder => readDeleteSet(decoder))\n const ds = mergeDeleteSets(dss)\n writeDeleteSet(updateEncoder, ds)\n return updateEncoder.toUint8Array()\n}\n\n/**\n * @param {Uint8Array} update\n * @param {Uint8Array} sv\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n * @param {typeof UpdateEncoderV1 | typeof UpdateEncoderV2} [YEncoder]\n */\nexport const diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {\n const state = decodeStateVector(sv)\n const encoder = new YEncoder()\n const lazyStructWriter = new LazyStructWriter(encoder)\n const decoder = new YDecoder(decoding.createDecoder(update))\n const reader = new LazyStructReader(decoder, false)\n while (reader.curr) {\n const curr = reader.curr\n const currClient = curr.id.client\n const svClock = state.get(currClient) || 0\n if (reader.curr.constructor === Skip) {\n // the first written struct shouldn't be a skip\n reader.next()\n continue\n }\n if (curr.id.clock + curr.length > svClock) {\n writeStructToLazyStructWriter(lazyStructWriter, curr, math.max(svClock - curr.id.clock, 0))\n reader.next()\n while (reader.curr && reader.curr.id.client === currClient) {\n writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0)\n reader.next()\n }\n } else {\n // read until something new comes up\n while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) {\n reader.next()\n }\n }\n }\n finishLazyStructWriting(lazyStructWriter)\n // write ds\n const ds = readDeleteSet(decoder)\n writeDeleteSet(encoder, ds)\n return encoder.toUint8Array()\n}\n\n/**\n * @param {Uint8Array} update\n * @param {Uint8Array} sv\n */\nexport const diffUpdate = (update, sv) => diffUpdateV2(update, sv, UpdateDecoderV1, UpdateEncoderV1)\n\n/**\n * @param {LazyStructWriter} lazyWriter\n */\nconst flushLazyStructWriter = lazyWriter => {\n if (lazyWriter.written > 0) {\n lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: encoding.toUint8Array(lazyWriter.encoder.restEncoder) })\n lazyWriter.encoder.restEncoder = encoding.createEncoder()\n lazyWriter.written = 0\n }\n}\n\n/**\n * @param {LazyStructWriter} lazyWriter\n * @param {Item | GC} struct\n * @param {number} offset\n */\nconst writeStructToLazyStructWriter = (lazyWriter, struct, offset) => {\n // flush curr if we start another client\n if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) {\n flushLazyStructWriter(lazyWriter)\n }\n if (lazyWriter.written === 0) {\n lazyWriter.currClient = struct.id.client\n // write next client\n lazyWriter.encoder.writeClient(struct.id.client)\n // write startClock\n encoding.writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset)\n }\n struct.write(lazyWriter.encoder, offset)\n lazyWriter.written++\n}\n/**\n * Call this function when we collected all parts and want to\n * put all the parts together. After calling this method,\n * you can continue using the UpdateEncoder.\n *\n * @param {LazyStructWriter} lazyWriter\n */\nconst finishLazyStructWriting = (lazyWriter) => {\n flushLazyStructWriter(lazyWriter)\n\n // this is a fresh encoder because we called flushCurr\n const restEncoder = lazyWriter.encoder.restEncoder\n\n /**\n * Now we put all the fragments together.\n * This works similarly to `writeClientsStructs`\n */\n\n // write # states that were updated - i.e. the clients\n encoding.writeVarUint(restEncoder, lazyWriter.clientStructs.length)\n\n for (let i = 0; i < lazyWriter.clientStructs.length; i++) {\n const partStructs = lazyWriter.clientStructs[i]\n /**\n * Works similarly to `writeStructs`\n */\n // write # encoded structs\n encoding.writeVarUint(restEncoder, partStructs.written)\n // write the rest of the fragment\n encoding.writeUint8Array(restEncoder, partStructs.restEncoder)\n }\n}\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} YDecoder\n * @param {typeof UpdateEncoderV2 | typeof UpdateEncoderV1 } YEncoder\n */\nexport const convertUpdateFormat = (update, YDecoder, YEncoder) => {\n const updateDecoder = new YDecoder(decoding.createDecoder(update))\n const lazyDecoder = new LazyStructReader(updateDecoder, false)\n const updateEncoder = new YEncoder()\n const lazyWriter = new LazyStructWriter(updateEncoder)\n\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n writeStructToLazyStructWriter(lazyWriter, curr, 0)\n }\n finishLazyStructWriting(lazyWriter)\n const ds = readDeleteSet(updateDecoder)\n writeDeleteSet(updateEncoder, ds)\n return updateEncoder.toUint8Array()\n}\n\n/**\n * @param {Uint8Array} update\n */\nexport const convertUpdateFormatV1ToV2 = update => convertUpdateFormat(update, UpdateDecoderV1, UpdateEncoderV2)\n\n/**\n * @param {Uint8Array} update\n */\nexport const convertUpdateFormatV2ToV1 = update => convertUpdateFormat(update, UpdateDecoderV2, UpdateEncoderV1)\n","\nimport {\n isDeleted,\n Item, AbstractType, Transaction, AbstractStruct // eslint-disable-line\n} from '../internals.js'\n\nimport * as set from 'lib0/set'\nimport * as array from 'lib0/array'\n\n/**\n * @template {AbstractType<any>} T\n * YEvent describes the changes on a YType.\n */\nexport class YEvent {\n /**\n * @param {T} target The changed type.\n * @param {Transaction} transaction\n */\n constructor (target, transaction) {\n /**\n * The type on which this event was created on.\n * @type {T}\n */\n this.target = target\n /**\n * The current target on which the observe callback is called.\n * @type {AbstractType<any>}\n */\n this.currentTarget = target\n /**\n * The transaction that triggered this event.\n * @type {Transaction}\n */\n this.transaction = transaction\n /**\n * @type {Object|null}\n */\n this._changes = null\n /**\n * @type {null | Map<string, { action: 'add' | 'update' | 'delete', oldValue: any, newValue: any }>}\n */\n this._keys = null\n /**\n * @type {null | Array<{ insert?: string | Array<any> | object | AbstractType<any>, retain?: number, delete?: number, attributes?: Object<string, any> }>}\n */\n this._delta = null\n }\n\n /**\n * Computes the path from `y` to the changed type.\n *\n * @todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with.\n *\n * The following property holds:\n * @example\n * let type = y\n * event.path.forEach(dir => {\n * type = type.get(dir)\n * })\n * type === event.target // => true\n */\n get path () {\n // @ts-ignore _item is defined because target is integrated\n return getPathTo(this.currentTarget, this.target)\n }\n\n /**\n * Check if a struct is deleted by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n deletes (struct) {\n return isDeleted(this.transaction.deleteSet, struct.id)\n }\n\n /**\n * @type {Map<string, { action: 'add' | 'update' | 'delete', oldValue: any, newValue: any }>}\n */\n get keys () {\n if (this._keys === null) {\n const keys = new Map()\n const target = this.target\n const changed = /** @type Set<string|null> */ (this.transaction.changed.get(target))\n changed.forEach(key => {\n if (key !== null) {\n const item = /** @type {Item} */ (target._map.get(key))\n /**\n * @type {'delete' | 'add' | 'update'}\n */\n let action\n let oldValue\n if (this.adds(item)) {\n let prev = item.left\n while (prev !== null && this.adds(prev)) {\n prev = prev.left\n }\n if (this.deletes(item)) {\n if (prev !== null && this.deletes(prev)) {\n action = 'delete'\n oldValue = array.last(prev.content.getContent())\n } else {\n return\n }\n } else {\n if (prev !== null && this.deletes(prev)) {\n action = 'update'\n oldValue = array.last(prev.content.getContent())\n } else {\n action = 'add'\n oldValue = undefined\n }\n }\n } else {\n if (this.deletes(item)) {\n action = 'delete'\n oldValue = array.last(/** @type {Item} */ item.content.getContent())\n } else {\n return // nop\n }\n }\n keys.set(key, { action, oldValue })\n }\n })\n this._keys = keys\n }\n return this._keys\n }\n\n /**\n * @type {Array<{insert?: string | Array<any> | object | AbstractType<any>, retain?: number, delete?: number, attributes?: Object<string, any>}>}\n */\n get delta () {\n return this.changes.delta\n }\n\n /**\n * Check if a struct is added by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n adds (struct) {\n return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0)\n }\n\n /**\n * @type {{added:Set<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert?:Array<any>|string, delete?:number, retain?:number}>}}\n */\n get changes () {\n let changes = this._changes\n if (changes === null) {\n const target = this.target\n const added = set.create()\n const deleted = set.create()\n /**\n * @type {Array<{insert:Array<any>}|{delete:number}|{retain:number}>}\n */\n const delta = []\n changes = {\n added,\n deleted,\n delta,\n keys: this.keys\n }\n const changed = /** @type Set<string|null> */ (this.transaction.changed.get(target))\n if (changed.has(null)) {\n /**\n * @type {any}\n */\n let lastOp = null\n const packOp = () => {\n if (lastOp) {\n delta.push(lastOp)\n }\n }\n for (let item = target._start; item !== null; item = item.right) {\n if (item.deleted) {\n if (this.deletes(item) && !this.adds(item)) {\n if (lastOp === null || lastOp.delete === undefined) {\n packOp()\n lastOp = { delete: 0 }\n }\n lastOp.delete += item.length\n deleted.add(item)\n } // else nop\n } else {\n if (this.adds(item)) {\n if (lastOp === null || lastOp.insert === undefined) {\n packOp()\n lastOp = { insert: [] }\n }\n lastOp.insert = lastOp.insert.concat(item.content.getContent())\n added.add(item)\n } else {\n if (lastOp === null || lastOp.retain === undefined) {\n packOp()\n lastOp = { retain: 0 }\n }\n lastOp.retain += item.length\n }\n }\n }\n if (lastOp !== null && lastOp.retain === undefined) {\n packOp()\n }\n }\n this._changes = changes\n }\n return /** @type {any} */ (changes)\n }\n}\n\n/**\n * Compute the path from this type to the specified target.\n *\n * @example\n * // `child` should be accessible via `type.get(path[0]).get(path[1])..`\n * const path = type.getPathTo(child)\n * // assuming `type instanceof YArray`\n * console.log(path) // might look like => [2, 'key1']\n * child === type.get(path[0]).get(path[1])\n *\n * @param {AbstractType<any>} parent\n * @param {AbstractType<any>} child target\n * @return {Array<string|number>} Path to the target\n *\n * @private\n * @function\n */\nconst getPathTo = (parent, child) => {\n const path = []\n while (child._item !== null && child !== parent) {\n if (child._item.parentSub !== null) {\n // parent is map-ish\n path.unshift(child._item.parentSub)\n } else {\n // parent is array-ish\n let i = 0\n let c = /** @type {AbstractType<any>} */ (child._item.parent)._start\n while (c !== child._item && c !== null) {\n if (!c.deleted) {\n i++\n }\n c = c.right\n }\n path.unshift(i)\n }\n child = /** @type {AbstractType<any>} */ (child._item.parent)\n }\n return path\n}\n","\nimport {\n removeEventHandlerListener,\n callEventHandlerListeners,\n addEventHandlerListener,\n createEventHandler,\n getState,\n isVisible,\n ContentType,\n createID,\n ContentAny,\n ContentBinary,\n getItemCleanStart,\n ContentDoc, YText, YArray, UpdateEncoderV1, UpdateEncoderV2, Doc, Snapshot, Transaction, EventHandler, YEvent, Item, // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map'\nimport * as iterator from 'lib0/iterator'\nimport * as error from 'lib0/error'\nimport * as math from 'lib0/math'\n\nconst maxSearchMarker = 80\n\n/**\n * A unique timestamp that identifies each marker.\n *\n * Time is relative,.. this is more like an ever-increasing clock.\n *\n * @type {number}\n */\nlet globalSearchMarkerTimestamp = 0\n\nexport class ArraySearchMarker {\n /**\n * @param {Item} p\n * @param {number} index\n */\n constructor (p, index) {\n p.marker = true\n this.p = p\n this.index = index\n this.timestamp = globalSearchMarkerTimestamp++\n }\n}\n\n/**\n * @param {ArraySearchMarker} marker\n */\nconst refreshMarkerTimestamp = marker => { marker.timestamp = globalSearchMarkerTimestamp++ }\n\n/**\n * This is rather complex so this function is the only thing that should overwrite a marker\n *\n * @param {ArraySearchMarker} marker\n * @param {Item} p\n * @param {number} index\n */\nconst overwriteMarker = (marker, p, index) => {\n marker.p.marker = false\n marker.p = p\n p.marker = true\n marker.index = index\n marker.timestamp = globalSearchMarkerTimestamp++\n}\n\n/**\n * @param {Array<ArraySearchMarker>} searchMarker\n * @param {Item} p\n * @param {number} index\n */\nconst markPosition = (searchMarker, p, index) => {\n if (searchMarker.length >= maxSearchMarker) {\n // override oldest marker (we don't want to create more objects)\n const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b)\n overwriteMarker(marker, p, index)\n return marker\n } else {\n // create new marker\n const pm = new ArraySearchMarker(p, index)\n searchMarker.push(pm)\n return pm\n }\n}\n\n/**\n * Search marker help us to find positions in the associative array faster.\n *\n * They speed up the process of finding a position without much bookkeeping.\n *\n * A maximum of `maxSearchMarker` objects are created.\n *\n * This function always returns a refreshed marker (updated timestamp)\n *\n * @param {AbstractType<any>} yarray\n * @param {number} index\n */\nexport const findMarker = (yarray, index) => {\n if (yarray._start === null || index === 0 || yarray._searchMarker === null) {\n return null\n }\n const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => math.abs(index - a.index) < math.abs(index - b.index) ? a : b)\n let p = yarray._start\n let pindex = 0\n if (marker !== null) {\n p = marker.p\n pindex = marker.index\n refreshMarkerTimestamp(marker) // we used it, we might need to use it again\n }\n // iterate to right if possible\n while (p.right !== null && pindex < index) {\n if (!p.deleted && p.countable) {\n if (index < pindex + p.length) {\n break\n }\n pindex += p.length\n }\n p = p.right\n }\n // iterate to left if necessary (might be that pindex > index)\n while (p.left !== null && pindex > index) {\n p = p.left\n if (!p.deleted && p.countable) {\n pindex -= p.length\n }\n }\n // we want to make sure that p can't be merged with left, because that would screw up everything\n // in that cas just return what we have (it is most likely the best marker anyway)\n // iterate to left until p can't be merged with left\n while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) {\n p = p.left\n if (!p.deleted && p.countable) {\n pindex -= p.length\n }\n }\n\n // @todo remove!\n // assure position\n // {\n // let start = yarray._start\n // let pos = 0\n // while (start !== p) {\n // if (!start.deleted && start.countable) {\n // pos += start.length\n // }\n // start = /** @type {Item} */ (start.right)\n // }\n // if (pos !== pindex) {\n // debugger\n // throw new Error('Gotcha position fail!')\n // }\n // }\n // if (marker) {\n // if (window.lengthes == null) {\n // window.lengthes = []\n // window.getLengthes = () => window.lengthes.sort((a, b) => a - b)\n // }\n // window.lengthes.push(marker.index - pindex)\n // console.log('distance', marker.index - pindex, 'len', p && p.parent.length)\n // }\n if (marker !== null && math.abs(marker.index - pindex) < /** @type {YText|YArray<any>} */ (p.parent).length / maxSearchMarker) {\n // adjust existing marker\n overwriteMarker(marker, p, pindex)\n return marker\n } else {\n // create new marker\n return markPosition(yarray._searchMarker, p, pindex)\n }\n}\n\n/**\n * Update markers when a change happened.\n *\n * This should be called before doing a deletion!\n *\n * @param {Array<ArraySearchMarker>} searchMarker\n * @param {number} index\n * @param {number} len If insertion, len is positive. If deletion, len is negative.\n */\nexport const updateMarkerChanges = (searchMarker, index, len) => {\n for (let i = searchMarker.length - 1; i >= 0; i--) {\n const m = searchMarker[i]\n if (len > 0) {\n /**\n * @type {Item|null}\n */\n let p = m.p\n p.marker = false\n // Ideally we just want to do a simple position comparison, but this will only work if\n // search markers don't point to deleted items for formats.\n // Iterate marker to prev undeleted countable position so we know what to do when updating a position\n while (p && (p.deleted || !p.countable)) {\n p = p.left\n if (p && !p.deleted && p.countable) {\n // adjust position. the loop should break now\n m.index -= p.length\n }\n }\n if (p === null || p.marker === true) {\n // remove search marker if updated position is null or if position is already marked\n searchMarker.splice(i, 1)\n continue\n }\n m.p = p\n p.marker = true\n }\n if (index < m.index || (len > 0 && index === m.index)) { // a simple index <= m.index check would actually suffice\n m.index = math.max(index, m.index + len)\n }\n }\n}\n\n/**\n * Accumulate all (list) children of a type and return them as an Array.\n *\n * @param {AbstractType<any>} t\n * @return {Array<Item>}\n */\nexport const getTypeChildren = t => {\n let s = t._start\n const arr = []\n while (s) {\n arr.push(s)\n s = s.right\n }\n return arr\n}\n\n/**\n * Call event listeners with an event. This will also add an event to all\n * parents (for `.observeDeep` handlers).\n *\n * @template EventType\n * @param {AbstractType<EventType>} type\n * @param {Transaction} transaction\n * @param {EventType} event\n */\nexport const callTypeObservers = (type, transaction, event) => {\n const changedType = type\n const changedParentTypes = transaction.changedParentTypes\n while (true) {\n // @ts-ignore\n map.setIfUndefined(changedParentTypes, type, () => []).push(event)\n if (type._item === null) {\n break\n }\n type = /** @type {AbstractType<any>} */ (type._item.parent)\n }\n callEventHandlerListeners(changedType._eH, event, transaction)\n}\n\n/**\n * @template EventType\n * Abstract Yjs Type class\n */\nexport class AbstractType {\n constructor () {\n /**\n * @type {Item|null}\n */\n this._item = null\n /**\n * @type {Map<string,Item>}\n */\n this._map = new Map()\n /**\n * @type {Item|null}\n */\n this._start = null\n /**\n * @type {Doc|null}\n */\n this.doc = null\n this._length = 0\n /**\n * Event handlers\n * @type {EventHandler<EventType,Transaction>}\n */\n this._eH = createEventHandler()\n /**\n * Deep event handlers\n * @type {EventHandler<Array<YEvent<any>>,Transaction>}\n */\n this._dEH = createEventHandler()\n /**\n * @type {null | Array<ArraySearchMarker>}\n */\n this._searchMarker = null\n }\n\n /**\n * @return {AbstractType<any>|null}\n */\n get parent () {\n return this._item ? /** @type {AbstractType<any>} */ (this._item.parent) : null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item|null} item\n */\n _integrate (y, item) {\n this.doc = y\n this._item = item\n }\n\n /**\n * @return {AbstractType<EventType>}\n */\n _copy () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {AbstractType<EventType>}\n */\n clone () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) { }\n\n /**\n * The first non-deleted item\n */\n get _first () {\n let n = this._start\n while (n !== null && n.deleted) {\n n = n.right\n }\n return n\n }\n\n /**\n * Creates YEvent and calls all type observers.\n * Must be implemented by each type.\n *\n * @param {Transaction} transaction\n * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n if (!transaction.local && this._searchMarker) {\n this._searchMarker.length = 0\n }\n }\n\n /**\n * Observe all events that are created on this type.\n *\n * @param {function(EventType, Transaction):void} f Observer function\n */\n observe (f) {\n addEventHandlerListener(this._eH, f)\n }\n\n /**\n * Observe all events that are created by this type and its children.\n *\n * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function\n */\n observeDeep (f) {\n addEventHandlerListener(this._dEH, f)\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(EventType,Transaction):void} f Observer function\n */\n unobserve (f) {\n removeEventHandlerListener(this._eH, f)\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function\n */\n unobserveDeep (f) {\n removeEventHandlerListener(this._dEH, f)\n }\n\n /**\n * @abstract\n * @return {any}\n */\n toJSON () {}\n}\n\n/**\n * @param {AbstractType<any>} type\n * @param {number} start\n * @param {number} end\n * @return {Array<any>}\n *\n * @private\n * @function\n */\nexport const typeListSlice = (type, start, end) => {\n if (start < 0) {\n start = type._length + start\n }\n if (end < 0) {\n end = type._length + end\n }\n let len = end - start\n const cs = []\n let n = type._start\n while (n !== null && len > 0) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n if (c.length <= start) {\n start -= c.length\n } else {\n for (let i = start; i < c.length && len > 0; i++) {\n cs.push(c[i])\n len--\n }\n start = 0\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * @param {AbstractType<any>} type\n * @return {Array<any>}\n *\n * @private\n * @function\n */\nexport const typeListToArray = type => {\n const cs = []\n let n = type._start\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i])\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * @param {AbstractType<any>} type\n * @param {Snapshot} snapshot\n * @return {Array<any>}\n *\n * @private\n * @function\n */\nexport const typeListToArraySnapshot = (type, snapshot) => {\n const cs = []\n let n = type._start\n while (n !== null) {\n if (n.countable && isVisible(n, snapshot)) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i])\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * Executes a provided function on once on overy element of this YArray.\n *\n * @param {AbstractType<any>} type\n * @param {function(any,number,any):void} f A function to execute on every element of this YArray.\n *\n * @private\n * @function\n */\nexport const typeListForEach = (type, f) => {\n let index = 0\n let n = type._start\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n f(c[i], index++, type)\n }\n }\n n = n.right\n }\n}\n\n/**\n * @template C,R\n * @param {AbstractType<any>} type\n * @param {function(C,number,AbstractType<any>):R} f\n * @return {Array<R>}\n *\n * @private\n * @function\n */\nexport const typeListMap = (type, f) => {\n /**\n * @type {Array<any>}\n */\n const result = []\n typeListForEach(type, (c, i) => {\n result.push(f(c, i, type))\n })\n return result\n}\n\n/**\n * @param {AbstractType<any>} type\n * @return {IterableIterator<any>}\n *\n * @private\n * @function\n */\nexport const typeListCreateIterator = type => {\n let n = type._start\n /**\n * @type {Array<any>|null}\n */\n let currentContent = null\n let currentContentIndex = 0\n return {\n [Symbol.iterator] () {\n return this\n },\n next: () => {\n // find some content\n if (currentContent === null) {\n while (n !== null && n.deleted) {\n n = n.right\n }\n // check if we reached the end, no need to check currentContent, because it does not exist\n if (n === null) {\n return {\n done: true,\n value: undefined\n }\n }\n // we found n, so we can set currentContent\n currentContent = n.content.getContent()\n currentContentIndex = 0\n n = n.right // we used the content of n, now iterate to next\n }\n const value = currentContent[currentContentIndex++]\n // check if we need to empty currentContent\n if (currentContent.length <= currentContentIndex) {\n currentContent = null\n }\n return {\n done: false,\n value\n }\n }\n }\n}\n\n/**\n * Executes a provided function on once on overy element of this YArray.\n * Operates on a snapshotted state of the document.\n *\n * @param {AbstractType<any>} type\n * @param {function(any,number,AbstractType<any>):void} f A function to execute on every element of this YArray.\n * @param {Snapshot} snapshot\n *\n * @private\n * @function\n */\nexport const typeListForEachSnapshot = (type, f, snapshot) => {\n let index = 0\n let n = type._start\n while (n !== null) {\n if (n.countable && isVisible(n, snapshot)) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n f(c[i], index++, type)\n }\n }\n n = n.right\n }\n}\n\n/**\n * @param {AbstractType<any>} type\n * @param {number} index\n * @return {any}\n *\n * @private\n * @function\n */\nexport const typeListGet = (type, index) => {\n const marker = findMarker(type, index)\n let n = type._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n return n.content.getContent()[index]\n }\n index -= n.length\n }\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType<any>} parent\n * @param {Item?} referenceItem\n * @param {Array<Object<string,any>|Array<any>|boolean|number|null|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => {\n let left = referenceItem\n const doc = transaction.doc\n const ownClientId = doc.clientID\n const store = doc.store\n const right = referenceItem === null ? parent._start : referenceItem.right\n /**\n * @type {Array<Object|Array<any>|number|null>}\n */\n let jsonContent = []\n const packJsonContent = () => {\n if (jsonContent.length > 0) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent))\n left.integrate(transaction, 0)\n jsonContent = []\n }\n }\n content.forEach(c => {\n if (c === null) {\n jsonContent.push(c)\n } else {\n switch (c.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n jsonContent.push(c)\n break\n default:\n packJsonContent()\n switch (c.constructor) {\n case Uint8Array:\n case ArrayBuffer:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(/** @type {Uint8Array} */ (c))))\n left.integrate(transaction, 0)\n break\n case Doc:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(/** @type {Doc} */ (c)))\n left.integrate(transaction, 0)\n break\n default:\n if (c instanceof AbstractType) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c))\n left.integrate(transaction, 0)\n } else {\n throw new Error('Unexpected content type in insert operation')\n }\n }\n }\n }\n })\n packJsonContent()\n}\n\nconst lengthExceeded = error.create('Length exceeded!')\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType<any>} parent\n * @param {number} index\n * @param {Array<Object<string,any>|Array<any>|number|null|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListInsertGenerics = (transaction, parent, index, content) => {\n if (index > parent._length) {\n throw lengthExceeded\n }\n if (index === 0) {\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, index, content.length)\n }\n return typeListInsertGenericsAfter(transaction, parent, null, content)\n }\n const startIndex = index\n const marker = findMarker(parent, index)\n let n = parent._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n // we need to iterate one to the left so that the algorithm works\n if (index === 0) {\n // @todo refactor this as it actually doesn't consider formats\n n = n.prev // important! get the left undeleted item so that we can actually decrease index\n index += (n && n.countable && !n.deleted) ? n.length : 0\n }\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index <= n.length) {\n if (index < n.length) {\n // insert in-between\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index))\n }\n break\n }\n index -= n.length\n }\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, content.length)\n }\n return typeListInsertGenericsAfter(transaction, parent, n, content)\n}\n\n/**\n * Pushing content is special as we generally want to push after the last item. So we don't have to update\n * the serach marker.\n *\n * @param {Transaction} transaction\n * @param {AbstractType<any>} parent\n * @param {Array<Object<string,any>|Array<any>|number|null|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListPushGenerics = (transaction, parent, content) => {\n // Use the marker with the highest index and iterate to the right.\n const marker = (parent._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent._start })\n let n = marker.p\n if (n) {\n while (n.right) {\n n = n.right\n }\n }\n return typeListInsertGenericsAfter(transaction, parent, n, content)\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType<any>} parent\n * @param {number} index\n * @param {number} length\n *\n * @private\n * @function\n */\nexport const typeListDelete = (transaction, parent, index, length) => {\n if (length === 0) { return }\n const startIndex = index\n const startLength = length\n const marker = findMarker(parent, index)\n let n = parent._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n }\n // compute the first item to be deleted\n for (; n !== null && index > 0; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index))\n }\n index -= n.length\n }\n }\n // delete all items until done\n while (length > 0 && n !== null) {\n if (!n.deleted) {\n if (length < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length))\n }\n n.delete(transaction)\n length -= n.length\n }\n n = n.right\n }\n if (length > 0) {\n throw lengthExceeded\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, -startLength + length /* in case we remove the above exception */)\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType<any>} parent\n * @param {string} key\n *\n * @private\n * @function\n */\nexport const typeMapDelete = (transaction, parent, key) => {\n const c = parent._map.get(key)\n if (c !== undefined) {\n c.delete(transaction)\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType<any>} parent\n * @param {string} key\n * @param {Object|number|null|Array<any>|string|Uint8Array|AbstractType<any>} value\n *\n * @private\n * @function\n */\nexport const typeMapSet = (transaction, parent, key, value) => {\n const left = parent._map.get(key) || null\n const doc = transaction.doc\n const ownClientId = doc.clientID\n let content\n if (value == null) {\n content = new ContentAny([value])\n } else {\n switch (value.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n content = new ContentAny([value])\n break\n case Uint8Array:\n content = new ContentBinary(/** @type {Uint8Array} */ (value))\n break\n case Doc:\n content = new ContentDoc(/** @type {Doc} */ (value))\n break\n default:\n if (value instanceof AbstractType) {\n content = new ContentType(value)\n } else {\n throw new Error('Unexpected content type')\n }\n }\n }\n new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0)\n}\n\n/**\n * @param {AbstractType<any>} parent\n * @param {string} key\n * @return {Object<string,any>|number|null|Array<any>|string|Uint8Array|AbstractType<any>|undefined}\n *\n * @private\n * @function\n */\nexport const typeMapGet = (parent, key) => {\n const val = parent._map.get(key)\n return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined\n}\n\n/**\n * @param {AbstractType<any>} parent\n * @return {Object<string,Object<string,any>|number|null|Array<any>|string|Uint8Array|AbstractType<any>|undefined>}\n *\n * @private\n * @function\n */\nexport const typeMapGetAll = (parent) => {\n /**\n * @type {Object<string,any>}\n */\n const res = {}\n parent._map.forEach((value, key) => {\n if (!value.deleted) {\n res[key] = value.content.getContent()[value.length - 1]\n }\n })\n return res\n}\n\n/**\n * @param {AbstractType<any>} parent\n * @param {string} key\n * @return {boolean}\n *\n * @private\n * @function\n */\nexport const typeMapHas = (parent, key) => {\n const val = parent._map.get(key)\n return val !== undefined && !val.deleted\n}\n\n/**\n * @param {AbstractType<any>} parent\n * @param {string} key\n * @param {Snapshot} snapshot\n * @return {Object<string,any>|number|null|Array<any>|string|Uint8Array|AbstractType<any>|undefined}\n *\n * @private\n * @function\n */\nexport const typeMapGetSnapshot = (parent, key, snapshot) => {\n let v = parent._map.get(key) || null\n while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) {\n v = v.left\n }\n return v !== null && isVisible(v, snapshot) ? v.content.getContent()[v.length - 1] : undefined\n}\n\n/**\n * @param {Map<string,Item>} map\n * @return {IterableIterator<Array<any>>}\n *\n * @private\n * @function\n */\nexport const createMapIterator = map => iterator.iteratorFilter(map.entries(), /** @param {any} entry */ entry => !entry[1].deleted)\n","/**\n * @module YArray\n */\n\nimport {\n YEvent,\n AbstractType,\n typeListGet,\n typeListToArray,\n typeListForEach,\n typeListCreateIterator,\n typeListInsertGenerics,\n typeListPushGenerics,\n typeListDelete,\n typeListMap,\n YArrayRefID,\n callTypeObservers,\n transact,\n ArraySearchMarker, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Transaction, Item // eslint-disable-line\n} from '../internals.js'\nimport { typeListSlice } from './AbstractType.js'\n\n/**\n * Event that describes the changes on a YArray\n * @template T\n * @extends YEvent<YArray<T>>\n */\nexport class YArrayEvent extends YEvent {\n /**\n * @param {YArray<T>} yarray The changed type\n * @param {Transaction} transaction The transaction object\n */\n constructor (yarray, transaction) {\n super(yarray, transaction)\n this._transaction = transaction\n }\n}\n\n/**\n * A shared Array implementation.\n * @template T\n * @extends AbstractType<YArrayEvent<T>>\n * @implements {Iterable<T>}\n */\nexport class YArray extends AbstractType {\n constructor () {\n super()\n /**\n * @type {Array<any>?}\n * @private\n */\n this._prelimContent = []\n /**\n * @type {Array<ArraySearchMarker>}\n */\n this._searchMarker = []\n }\n\n /**\n * Construct a new YArray containing the specified items.\n * @template T\n * @param {Array<T>} items\n * @return {YArray<T>}\n */\n static from (items) {\n const a = new YArray()\n a.push(items)\n return a\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n this.insert(0, /** @type {Array<any>} */ (this._prelimContent))\n this._prelimContent = null\n }\n\n _copy () {\n return new YArray()\n }\n\n /**\n * @return {YArray<T>}\n */\n clone () {\n const arr = new YArray()\n arr.insert(0, this.toArray().map(el =>\n el instanceof AbstractType ? el.clone() : el\n ))\n return arr\n }\n\n get length () {\n return this._prelimContent === null ? this._length : this._prelimContent.length\n }\n\n /**\n * Creates YArrayEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs)\n callTypeObservers(this, transaction, new YArrayEvent(this, transaction))\n }\n\n /**\n * Inserts new content at an index.\n *\n * Important: This function expects an array of content. Not just a content\n * object. The reason for this \"weirdness\" is that inserting several elements\n * is very efficient when it is done as a single operation.\n *\n * @example\n * // Insert character 'a' at position 0\n * yarray.insert(0, ['a'])\n * // Insert numbers 1, 2 at position 1\n * yarray.insert(1, [1, 2])\n *\n * @param {number} index The index to insert content at.\n * @param {Array<T>} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, content)\n })\n } else {\n /** @type {Array<any>} */ (this._prelimContent).splice(index, 0, ...content)\n }\n }\n\n /**\n * Appends content to this YArray.\n *\n * @param {Array<T>} content Array of content to append.\n *\n * @todo Use the following implementation in all types.\n */\n push (content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListPushGenerics(transaction, this, content)\n })\n } else {\n /** @type {Array<any>} */ (this._prelimContent).push(...content)\n }\n }\n\n /**\n * Preppends content to this YArray.\n *\n * @param {Array<T>} content Array of content to preppend.\n */\n unshift (content) {\n this.insert(0, content)\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} length The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length)\n })\n } else {\n /** @type {Array<any>} */ (this._prelimContent).splice(index, length)\n }\n }\n\n /**\n * Returns the i-th element from a YArray.\n *\n * @param {number} index The index of the element to return from the YArray\n * @return {T}\n */\n get (index) {\n return typeListGet(this, index)\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array<T>}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @param {number} [start]\n * @param {number} [end]\n * @return {Array<T>}\n */\n slice (start = 0, end = this.length) {\n return typeListSlice(this, start, end)\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Array<any>}\n */\n toJSON () {\n return this.map(c => c instanceof AbstractType ? c.toJSON() : c)\n }\n\n /**\n * Returns an Array with the result of calling a provided function on every\n * element of this YArray.\n *\n * @template M\n * @param {function(T,number,YArray<T>):M} f Function that produces an element of the new Array\n * @return {Array<M>} A new array with each element being the result of the\n * callback function\n */\n map (f) {\n return typeListMap(this, /** @type {any} */ (f))\n }\n\n /**\n * Executes a provided function on once on overy element of this YArray.\n *\n * @param {function(T,number,YArray<T>):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n typeListForEach(this, f)\n }\n\n /**\n * @return {IterableIterator<T>}\n */\n [Symbol.iterator] () {\n return typeListCreateIterator(this)\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YArrayRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n *\n * @private\n * @function\n */\nexport const readYArray = decoder => new YArray()\n","\n/**\n * @module YMap\n */\n\nimport {\n YEvent,\n AbstractType,\n typeMapDelete,\n typeMapSet,\n typeMapGet,\n typeMapHas,\n createMapIterator,\n YMapRefID,\n callTypeObservers,\n transact,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Transaction, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as iterator from 'lib0/iterator'\n\n/**\n * @template T\n * @extends YEvent<YMap<T>>\n * Event that describes the changes on a YMap.\n */\nexport class YMapEvent extends YEvent {\n /**\n * @param {YMap<T>} ymap The YArray that changed.\n * @param {Transaction} transaction\n * @param {Set<any>} subs The keys that changed.\n */\n constructor (ymap, transaction, subs) {\n super(ymap, transaction)\n this.keysChanged = subs\n }\n}\n\n/**\n * @template MapType\n * A shared Map implementation.\n *\n * @extends AbstractType<YMapEvent<MapType>>\n * @implements {Iterable<MapType>}\n */\nexport class YMap extends AbstractType {\n /**\n *\n * @param {Iterable<readonly [string, any]>=} entries - an optional iterable to initialize the YMap\n */\n constructor (entries) {\n super()\n /**\n * @type {Map<string,any>?}\n * @private\n */\n this._prelimContent = null\n\n if (entries === undefined) {\n this._prelimContent = new Map()\n } else {\n this._prelimContent = new Map(entries)\n }\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;/** @type {Map<string, any>} */ (this._prelimContent).forEach((value, key) => {\n this.set(key, value)\n })\n this._prelimContent = null\n }\n\n _copy () {\n return new YMap()\n }\n\n /**\n * @return {YMap<MapType>}\n */\n clone () {\n const map = new YMap()\n this.forEach((value, key) => {\n map.set(key, value instanceof AbstractType ? value.clone() : value)\n })\n return map\n }\n\n /**\n * Creates YMapEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs))\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Object<string,any>}\n */\n toJSON () {\n /**\n * @type {Object<string,MapType>}\n */\n const map = {}\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n const v = item.content.getContent()[item.length - 1]\n map[key] = v instanceof AbstractType ? v.toJSON() : v\n }\n })\n return map\n }\n\n /**\n * Returns the size of the YMap (count of key/value pairs)\n *\n * @return {number}\n */\n get size () {\n return [...createMapIterator(this._map)].length\n }\n\n /**\n * Returns the keys for each element in the YMap Type.\n *\n * @return {IterableIterator<string>}\n */\n keys () {\n return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[0])\n }\n\n /**\n * Returns the values for each element in the YMap Type.\n *\n * @return {IterableIterator<any>}\n */\n values () {\n return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1])\n }\n\n /**\n * Returns an Iterator of [key, value] pairs\n *\n * @return {IterableIterator<any>}\n */\n entries () {\n return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => [v[0], v[1].content.getContent()[v[1].length - 1]])\n }\n\n /**\n * Executes a provided function on once on every key-value pair.\n *\n * @param {function(MapType,string,YMap<MapType>):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n /**\n * @type {Object<string,MapType>}\n */\n const map = {}\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n f(item.content.getContent()[item.length - 1], key, this)\n }\n })\n return map\n }\n\n /**\n * @return {IterableIterator<MapType>}\n */\n [Symbol.iterator] () {\n return this.entries()\n }\n\n /**\n * Remove a specified element from this YMap.\n *\n * @param {string} key The key of the element to remove.\n */\n delete (key) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, key)\n })\n } else {\n /** @type {Map<string, any>} */ (this._prelimContent).delete(key)\n }\n }\n\n /**\n * Adds or updates an element with a specified key and value.\n *\n * @param {string} key The key of the element to add to this YMap\n * @param {MapType} value The value of the element to add\n */\n set (key, value) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, key, value)\n })\n } else {\n /** @type {Map<string, any>} */ (this._prelimContent).set(key, value)\n }\n return value\n }\n\n /**\n * Returns a specified element from this YMap.\n *\n * @param {string} key\n * @return {MapType|undefined}\n */\n get (key) {\n return /** @type {any} */ (typeMapGet(this, key))\n }\n\n /**\n * Returns a boolean indicating whether the specified key exists or not.\n *\n * @param {string} key The key to test.\n * @return {boolean}\n */\n has (key) {\n return typeMapHas(this, key)\n }\n\n /**\n * Removes all elements from this YMap.\n */\n clear () {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n this.forEach(function (value, key, map) {\n typeMapDelete(transaction, map, key)\n })\n })\n } else {\n /** @type {Map<string, any>} */ (this._prelimContent).clear()\n }\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YMapRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n *\n * @private\n * @function\n */\nexport const readYMap = decoder => new YMap()\n","\n/**\n * @module YText\n */\n\nimport {\n YEvent,\n AbstractType,\n getItemCleanStart,\n getState,\n isVisible,\n createID,\n YTextRefID,\n callTypeObservers,\n transact,\n ContentEmbed,\n GC,\n ContentFormat,\n ContentString,\n splitSnapshotAffectedStructs,\n iterateDeletedStructs,\n iterateStructs,\n findMarker,\n typeMapDelete,\n typeMapSet,\n typeMapGet,\n typeMapGetAll,\n updateMarkerChanges,\n ContentType,\n ArraySearchMarker, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, ID, Doc, Item, Snapshot, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as object from 'lib0/object'\nimport * as map from 'lib0/map'\nimport * as error from 'lib0/error'\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nconst equalAttrs = (a, b) => a === b || (typeof a === 'object' && typeof b === 'object' && a && b && object.equalFlat(a, b))\n\nexport class ItemTextListPosition {\n /**\n * @param {Item|null} left\n * @param {Item|null} right\n * @param {number} index\n * @param {Map<string,any>} currentAttributes\n */\n constructor (left, right, index, currentAttributes) {\n this.left = left\n this.right = right\n this.index = index\n this.currentAttributes = currentAttributes\n }\n\n /**\n * Only call this if you know that this.right is defined\n */\n forward () {\n if (this.right === null) {\n error.unexpectedCase()\n }\n switch (this.right.content.constructor) {\n case ContentFormat:\n if (!this.right.deleted) {\n updateCurrentAttributes(this.currentAttributes, /** @type {ContentFormat} */ (this.right.content))\n }\n break\n default:\n if (!this.right.deleted) {\n this.index += this.right.length\n }\n break\n }\n this.left = this.right\n this.right = this.right.right\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} pos\n * @param {number} count steps to move forward\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findNextPosition = (transaction, pos, count) => {\n while (pos.right !== null && count > 0) {\n switch (pos.right.content.constructor) {\n case ContentFormat:\n if (!pos.right.deleted) {\n updateCurrentAttributes(pos.currentAttributes, /** @type {ContentFormat} */ (pos.right.content))\n }\n break\n default:\n if (!pos.right.deleted) {\n if (count < pos.right.length) {\n // split right\n getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count))\n }\n pos.index += pos.right.length\n count -= pos.right.length\n }\n break\n }\n pos.left = pos.right\n pos.right = pos.right.right\n // pos.forward() - we don't forward because that would halve the performance because we already do the checks above\n }\n return pos\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType<any>} parent\n * @param {number} index\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findPosition = (transaction, parent, index) => {\n const currentAttributes = new Map()\n const marker = findMarker(parent, index)\n if (marker) {\n const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes)\n return findNextPosition(transaction, pos, index - marker.index)\n } else {\n const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes)\n return findNextPosition(transaction, pos, index)\n }\n}\n\n/**\n * Negate applied formats\n *\n * @param {Transaction} transaction\n * @param {AbstractType<any>} parent\n * @param {ItemTextListPosition} currPos\n * @param {Map<string,any>} negatedAttributes\n *\n * @private\n * @function\n */\nconst insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => {\n // check if we really need to remove attributes\n while (\n currPos.right !== null && (\n currPos.right.deleted === true || (\n currPos.right.content.constructor === ContentFormat &&\n equalAttrs(negatedAttributes.get(/** @type {ContentFormat} */ (currPos.right.content).key), /** @type {ContentFormat} */ (currPos.right.content).value)\n )\n )\n ) {\n if (!currPos.right.deleted) {\n negatedAttributes.delete(/** @type {ContentFormat} */ (currPos.right.content).key)\n }\n currPos.forward()\n }\n const doc = transaction.doc\n const ownClientId = doc.clientID\n negatedAttributes.forEach((val, key) => {\n const left = currPos.left\n const right = currPos.right\n const nextFormat = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val))\n nextFormat.integrate(transaction, 0)\n currPos.right = nextFormat\n currPos.forward()\n })\n}\n\n/**\n * @param {Map<string,any>} currentAttributes\n * @param {ContentFormat} format\n *\n * @private\n * @function\n */\nconst updateCurrentAttributes = (currentAttributes, format) => {\n const { key, value } = format\n if (value === null) {\n currentAttributes.delete(key)\n } else {\n currentAttributes.set(key, value)\n }\n}\n\n/**\n * @param {ItemTextListPosition} currPos\n * @param {Object<string,any>} attributes\n *\n * @private\n * @function\n */\nconst minimizeAttributeChanges = (currPos, attributes) => {\n // go right while attributes[right.key] === right.value (or right is deleted)\n while (true) {\n if (currPos.right === null) {\n break\n } else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] || null, /** @type {ContentFormat} */ (currPos.right.content).value))) {\n //\n } else {\n break\n }\n currPos.forward()\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType<any>} parent\n * @param {ItemTextListPosition} currPos\n * @param {Object<string,any>} attributes\n * @return {Map<string,any>}\n *\n * @private\n * @function\n **/\nconst insertAttributes = (transaction, parent, currPos, attributes) => {\n const doc = transaction.doc\n const ownClientId = doc.clientID\n const negatedAttributes = new Map()\n // insert format-start items\n for (const key in attributes) {\n const val = attributes[key]\n const currentVal = currPos.currentAttributes.get(key) || null\n if (!equalAttrs(currentVal, val)) {\n // save negated attribute (set null if currentVal undefined)\n negatedAttributes.set(key, currentVal)\n const { left, right } = currPos\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val))\n currPos.right.integrate(transaction, 0)\n currPos.forward()\n }\n }\n return negatedAttributes\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType<any>} parent\n * @param {ItemTextListPosition} currPos\n * @param {string|object|AbstractType<any>} text\n * @param {Object<string,any>} attributes\n *\n * @private\n * @function\n **/\nconst insertText = (transaction, parent, currPos, text, attributes) => {\n currPos.currentAttributes.forEach((val, key) => {\n if (attributes[key] === undefined) {\n attributes[key] = null\n }\n })\n const doc = transaction.doc\n const ownClientId = doc.clientID\n minimizeAttributeChanges(currPos, attributes)\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes)\n // insert content\n const content = text.constructor === String ? new ContentString(/** @type {string} */ (text)) : (text instanceof AbstractType ? new ContentType(text) : new ContentEmbed(text))\n let { left, right, index } = currPos\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength())\n }\n right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content)\n right.integrate(transaction, 0)\n currPos.right = right\n currPos.index = index\n currPos.forward()\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes)\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType<any>} parent\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @param {Object<string,any>} attributes\n *\n * @private\n * @function\n */\nconst formatText = (transaction, parent, currPos, length, attributes) => {\n const doc = transaction.doc\n const ownClientId = doc.clientID\n minimizeAttributeChanges(currPos, attributes)\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes)\n // iterate until first non-format or null is found\n // delete all formats with attributes[format.key] != null\n // also check the attributes after the first non-format as we do not want to insert redundant negated attributes there\n while (currPos.right !== null && (length > 0 || currPos.right.content.constructor === ContentFormat)) {\n if (!currPos.right.deleted) {\n switch (currPos.right.content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (currPos.right.content)\n const attr = attributes[key]\n if (attr !== undefined) {\n if (equalAttrs(attr, value)) {\n negatedAttributes.delete(key)\n } else {\n negatedAttributes.set(key, value)\n }\n currPos.right.delete(transaction)\n }\n break\n }\n default:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length))\n }\n length -= currPos.right.length\n break\n }\n }\n currPos.forward()\n }\n // Quill just assumes that the editor starts with a newline and that it always\n // ends with a newline. We only insert that newline when a new newline is\n // inserted - i.e when length is bigger than type.length\n if (length > 0) {\n let newlines = ''\n for (; length > 0; length--) {\n newlines += '\\n'\n }\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines))\n currPos.right.integrate(transaction, 0)\n currPos.forward()\n }\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes)\n}\n\n/**\n * Call this function after string content has been deleted in order to\n * clean up formatting Items.\n *\n * @param {Transaction} transaction\n * @param {Item} start\n * @param {Item|null} curr exclusive end, automatically iterates to the next Content Item\n * @param {Map<string,any>} startAttributes\n * @param {Map<string,any>} currAttributes\n * @return {number} The amount of formatting Items deleted.\n *\n * @function\n */\nconst cleanupFormattingGap = (transaction, start, curr, startAttributes, currAttributes) => {\n let end = curr\n const endAttributes = map.copy(currAttributes)\n while (end && (!end.countable || end.deleted)) {\n if (!end.deleted && end.content.constructor === ContentFormat) {\n updateCurrentAttributes(endAttributes, /** @type {ContentFormat} */ (end.content))\n }\n end = end.right\n }\n let cleanups = 0\n let reachedEndOfCurr = false\n while (start !== end) {\n if (curr === start) {\n reachedEndOfCurr = true\n }\n if (!start.deleted) {\n const content = start.content\n switch (content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (content)\n if ((endAttributes.get(key) || null) !== value || (startAttributes.get(key) || null) === value) {\n // Either this format is overwritten or it is not necessary because the attribute already existed.\n start.delete(transaction)\n cleanups++\n if (!reachedEndOfCurr && (currAttributes.get(key) || null) === value && (startAttributes.get(key) || null) !== value) {\n currAttributes.delete(key)\n }\n }\n break\n }\n }\n }\n start = /** @type {Item} */ (start.right)\n }\n return cleanups\n}\n\n/**\n * @param {Transaction} transaction\n * @param {Item | null} item\n */\nconst cleanupContextlessFormattingGap = (transaction, item) => {\n // iterate until item.right is null or content\n while (item && item.right && (item.right.deleted || !item.right.countable)) {\n item = item.right\n }\n const attrs = new Set()\n // iterate back until a content item is found\n while (item && (item.deleted || !item.countable)) {\n if (!item.deleted && item.content.constructor === ContentFormat) {\n const key = /** @type {ContentFormat} */ (item.content).key\n if (attrs.has(key)) {\n item.delete(transaction)\n } else {\n attrs.add(key)\n }\n }\n item = item.left\n }\n}\n\n/**\n * This function is experimental and subject to change / be removed.\n *\n * Ideally, we don't need this function at all. Formatting attributes should be cleaned up\n * automatically after each change. This function iterates twice over the complete YText type\n * and removes unnecessary formatting attributes. This is also helpful for testing.\n *\n * This function won't be exported anymore as soon as there is confidence that the YText type works as intended.\n *\n * @param {YText} type\n * @return {number} How many formatting attributes have been cleaned up.\n */\nexport const cleanupYTextFormatting = type => {\n let res = 0\n transact(/** @type {Doc} */ (type.doc), transaction => {\n let start = /** @type {Item} */ (type._start)\n let end = type._start\n let startAttributes = map.create()\n const currentAttributes = map.copy(startAttributes)\n while (end) {\n if (end.deleted === false) {\n switch (end.content.constructor) {\n case ContentFormat:\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (end.content))\n break\n default:\n res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes)\n startAttributes = map.copy(currentAttributes)\n start = end\n break\n }\n }\n end = end.right\n }\n })\n return res\n}\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst deleteText = (transaction, currPos, length) => {\n const startLength = length\n const startAttrs = map.copy(currPos.currentAttributes)\n const start = currPos.right\n while (length > 0 && currPos.right !== null) {\n if (currPos.right.deleted === false) {\n switch (currPos.right.content.constructor) {\n case ContentType:\n case ContentEmbed:\n case ContentString:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length))\n }\n length -= currPos.right.length\n currPos.right.delete(transaction)\n break\n }\n }\n currPos.forward()\n }\n if (start) {\n cleanupFormattingGap(transaction, start, currPos.right, startAttrs, currPos.currentAttributes)\n }\n const parent = /** @type {AbstractType<any>} */ (/** @type {Item} */ (currPos.left || currPos.right).parent)\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length)\n }\n return currPos\n}\n\n/**\n * The Quill Delta format represents changes on a text document with\n * formatting information. For mor information visit {@link https://quilljs.com/docs/delta/|Quill Delta}\n *\n * @example\n * {\n * ops: [\n * { insert: 'Gandalf', attributes: { bold: true } },\n * { insert: ' the ' },\n * { insert: 'Grey', attributes: { color: '#cccccc' } }\n * ]\n * }\n *\n */\n\n/**\n * Attributes that can be assigned to a selection of text.\n *\n * @example\n * {\n * bold: true,\n * font-size: '40px'\n * }\n *\n * @typedef {Object} TextAttributes\n */\n\n/**\n * @extends YEvent<YText>\n * Event that describes the changes on a YText type.\n */\nexport class YTextEvent extends YEvent {\n /**\n * @param {YText} ytext\n * @param {Transaction} transaction\n * @param {Set<any>} subs The keys that changed\n */\n constructor (ytext, transaction, subs) {\n super(ytext, transaction)\n /**\n * Whether the children changed.\n * @type {Boolean}\n * @private\n */\n this.childListChanged = false\n /**\n * Set of all changed attributes.\n * @type {Set<string>}\n */\n this.keysChanged = new Set()\n subs.forEach((sub) => {\n if (sub === null) {\n this.childListChanged = true\n } else {\n this.keysChanged.add(sub)\n }\n })\n }\n\n /**\n * @type {{added:Set<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert?:Array<any>|string, delete?:number, retain?:number}>}}\n */\n get changes () {\n if (this._changes === null) {\n /**\n * @type {{added:Set<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert?:Array<any>|string|AbstractType<any>|object, delete?:number, retain?:number}>}}\n */\n const changes = {\n keys: this.keys,\n delta: this.delta,\n added: new Set(),\n deleted: new Set()\n }\n this._changes = changes\n }\n return /** @type {any} */ (this._changes)\n }\n\n /**\n * Compute the changes in the delta format.\n * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document.\n *\n * @type {Array<{insert?:string|object|AbstractType<any>, delete?:number, retain?:number, attributes?: Object<string,any>}>}\n *\n * @public\n */\n get delta () {\n if (this._delta === null) {\n const y = /** @type {Doc} */ (this.target.doc)\n /**\n * @type {Array<{insert?:string|object|AbstractType<any>, delete?:number, retain?:number, attributes?: Object<string,any>}>}\n */\n const delta = []\n transact(y, transaction => {\n const currentAttributes = new Map() // saves all current attributes for insert\n const oldAttributes = new Map()\n let item = this.target._start\n /**\n * @type {string?}\n */\n let action = null\n /**\n * @type {Object<string,any>}\n */\n const attributes = {} // counts added or removed new attributes for retain\n /**\n * @type {string|object}\n */\n let insert = ''\n let retain = 0\n let deleteLen = 0\n const addOp = () => {\n if (action !== null) {\n /**\n * @type {any}\n */\n let op\n switch (action) {\n case 'delete':\n op = { delete: deleteLen }\n deleteLen = 0\n break\n case 'insert':\n op = { insert }\n if (currentAttributes.size > 0) {\n op.attributes = {}\n currentAttributes.forEach((value, key) => {\n if (value !== null) {\n op.attributes[key] = value\n }\n })\n }\n insert = ''\n break\n case 'retain':\n op = { retain }\n if (Object.keys(attributes).length > 0) {\n op.attributes = {}\n for (const key in attributes) {\n op.attributes[key] = attributes[key]\n }\n }\n retain = 0\n break\n }\n delta.push(op)\n action = null\n }\n }\n while (item !== null) {\n switch (item.content.constructor) {\n case ContentType:\n case ContentEmbed:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n addOp()\n action = 'insert'\n insert = item.content.getContent()[0]\n addOp()\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp()\n action = 'delete'\n }\n deleteLen += 1\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp()\n action = 'retain'\n }\n retain += 1\n }\n break\n case ContentString:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n if (action !== 'insert') {\n addOp()\n action = 'insert'\n }\n insert += /** @type {ContentString} */ (item.content).str\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp()\n action = 'delete'\n }\n deleteLen += item.length\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp()\n action = 'retain'\n }\n retain += item.length\n }\n break\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (item.content)\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n const curVal = currentAttributes.get(key) || null\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp()\n }\n if (equalAttrs(value, (oldAttributes.get(key) || null))) {\n delete attributes[key]\n } else {\n attributes[key] = value\n }\n } else if (value !== null) {\n item.delete(transaction)\n }\n }\n } else if (this.deletes(item)) {\n oldAttributes.set(key, value)\n const curVal = currentAttributes.get(key) || null\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp()\n }\n attributes[key] = curVal\n }\n } else if (!item.deleted) {\n oldAttributes.set(key, value)\n const attr = attributes[key]\n if (attr !== undefined) {\n if (!equalAttrs(attr, value)) {\n if (action === 'retain') {\n addOp()\n }\n if (value === null) {\n delete attributes[key]\n } else {\n attributes[key] = value\n }\n } else if (attr !== null) { // this will be cleaned up automatically by the contextless cleanup function\n item.delete(transaction)\n }\n }\n }\n if (!item.deleted) {\n if (action === 'insert') {\n addOp()\n }\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content))\n }\n break\n }\n }\n item = item.right\n }\n addOp()\n while (delta.length > 0) {\n const lastOp = delta[delta.length - 1]\n if (lastOp.retain !== undefined && lastOp.attributes === undefined) {\n // retain delta's if they don't assign attributes\n delta.pop()\n } else {\n break\n }\n }\n })\n this._delta = delta\n }\n return /** @type {any} */ (this._delta)\n }\n}\n\n/**\n * Type that represents text with formatting information.\n *\n * This type replaces y-richtext as this implementation is able to handle\n * block formats (format information on a paragraph), embeds (complex elements\n * like pictures and videos), and text formats (**bold**, *italic*).\n *\n * @extends AbstractType<YTextEvent>\n */\nexport class YText extends AbstractType {\n /**\n * @param {String} [string] The initial value of the YText.\n */\n constructor (string) {\n super()\n /**\n * Array of pending operations on this type\n * @type {Array<function():void>?}\n */\n this._pending = string !== undefined ? [() => this.insert(0, string)] : []\n /**\n * @type {Array<ArraySearchMarker>}\n */\n this._searchMarker = []\n }\n\n /**\n * Number of characters of this text type.\n *\n * @type {number}\n */\n get length () {\n return this._length\n }\n\n /**\n * @param {Doc} y\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n try {\n /** @type {Array<function>} */ (this._pending).forEach(f => f())\n } catch (e) {\n console.error(e)\n }\n this._pending = null\n }\n\n _copy () {\n return new YText()\n }\n\n /**\n * @return {YText}\n */\n clone () {\n const text = new YText()\n text.applyDelta(this.toDelta())\n return text\n }\n\n /**\n * Creates YTextEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs)\n const event = new YTextEvent(this, transaction, parentSubs)\n const doc = transaction.doc\n callTypeObservers(this, transaction, event)\n // If a remote change happened, we try to cleanup potential formatting duplicates.\n if (!transaction.local) {\n // check if another formatting item was inserted\n let foundFormattingItem = false\n for (const [client, afterClock] of transaction.afterState.entries()) {\n const clock = transaction.beforeState.get(client) || 0\n if (afterClock === clock) {\n continue\n }\n iterateStructs(transaction, /** @type {Array<Item|GC>} */ (doc.store.clients.get(client)), clock, afterClock, item => {\n if (!item.deleted && /** @type {Item} */ (item).content.constructor === ContentFormat) {\n foundFormattingItem = true\n }\n })\n if (foundFormattingItem) {\n break\n }\n }\n if (!foundFormattingItem) {\n iterateDeletedStructs(transaction, transaction.deleteSet, item => {\n if (item instanceof GC || foundFormattingItem) {\n return\n }\n if (item.parent === this && item.content.constructor === ContentFormat) {\n foundFormattingItem = true\n }\n })\n }\n transact(doc, (t) => {\n if (foundFormattingItem) {\n // If a formatting item was inserted, we simply clean the whole type.\n // We need to compute currentAttributes for the current position anyway.\n cleanupYTextFormatting(this)\n } else {\n // If no formatting attribute was inserted, we can make due with contextless\n // formatting cleanups.\n // Contextless: it is not necessary to compute currentAttributes for the affected position.\n iterateDeletedStructs(t, t.deleteSet, item => {\n if (item instanceof GC) {\n return\n }\n if (item.parent === this) {\n cleanupContextlessFormattingGap(t, item)\n }\n })\n }\n })\n }\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @public\n */\n toString () {\n let str = ''\n /**\n * @type {Item|null}\n */\n let n = this._start\n while (n !== null) {\n if (!n.deleted && n.countable && n.content.constructor === ContentString) {\n str += /** @type {ContentString} */ (n.content).str\n }\n n = n.right\n }\n return str\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @return {string}\n * @public\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Apply a {@link Delta} on this shared YText type.\n *\n * @param {any} delta The changes to apply on this element.\n * @param {object} [opts]\n * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.\n *\n *\n * @public\n */\n applyDelta (delta, { sanitize = true } = {}) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n const currPos = new ItemTextListPosition(null, this._start, 0, new Map())\n for (let i = 0; i < delta.length; i++) {\n const op = delta[i]\n if (op.insert !== undefined) {\n // Quill assumes that the content starts with an empty paragraph.\n // Yjs/Y.Text assumes that it starts empty. We always hide that\n // there is a newline at the end of the content.\n // If we omit this step, clients will see a different number of\n // paragraphs, but nothing bad will happen.\n const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\\n') ? op.insert.slice(0, -1) : op.insert\n if (typeof ins !== 'string' || ins.length > 0) {\n insertText(transaction, this, currPos, ins, op.attributes || {})\n }\n } else if (op.retain !== undefined) {\n formatText(transaction, this, currPos, op.retain, op.attributes || {})\n } else if (op.delete !== undefined) {\n deleteText(transaction, currPos, op.delete)\n }\n }\n })\n } else {\n /** @type {Array<function>} */ (this._pending).push(() => this.applyDelta(delta))\n }\n }\n\n /**\n * Returns the Delta representation of this YText type.\n *\n * @param {Snapshot} [snapshot]\n * @param {Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', ID):any} [computeYChange]\n * @return {any} The Delta representation of this type.\n *\n * @public\n */\n toDelta (snapshot, prevSnapshot, computeYChange) {\n /**\n * @type{Array<any>}\n */\n const ops = []\n const currentAttributes = new Map()\n const doc = /** @type {Doc} */ (this.doc)\n let str = ''\n let n = this._start\n function packStr () {\n if (str.length > 0) {\n // pack str with attributes to ops\n /**\n * @type {Object<string,any>}\n */\n const attributes = {}\n let addAttributes = false\n currentAttributes.forEach((value, key) => {\n addAttributes = true\n attributes[key] = value\n })\n /**\n * @type {Object<string,any>}\n */\n const op = { insert: str }\n if (addAttributes) {\n op.attributes = attributes\n }\n ops.push(op)\n str = ''\n }\n }\n // snapshots are merged again after the transaction, so we need to keep the\n // transalive until we are done\n transact(doc, transaction => {\n if (snapshot) {\n splitSnapshotAffectedStructs(transaction, snapshot)\n }\n if (prevSnapshot) {\n splitSnapshotAffectedStructs(transaction, prevSnapshot)\n }\n while (n !== null) {\n if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) {\n switch (n.content.constructor) {\n case ContentString: {\n const cur = currentAttributes.get('ychange')\n if (snapshot !== undefined && !isVisible(n, snapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.state !== 'removed') {\n packStr()\n currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' })\n }\n } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.state !== 'added') {\n packStr()\n currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' })\n }\n } else if (cur !== undefined) {\n packStr()\n currentAttributes.delete('ychange')\n }\n str += /** @type {ContentString} */ (n.content).str\n break\n }\n case ContentType:\n case ContentEmbed: {\n packStr()\n /**\n * @type {Object<string,any>}\n */\n const op = {\n insert: n.content.getContent()[0]\n }\n if (currentAttributes.size > 0) {\n const attrs = /** @type {Object<string,any>} */ ({})\n op.attributes = attrs\n currentAttributes.forEach((value, key) => {\n attrs[key] = value\n })\n }\n ops.push(op)\n break\n }\n case ContentFormat:\n if (isVisible(n, snapshot)) {\n packStr()\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content))\n }\n break\n }\n }\n n = n.right\n }\n packStr()\n }, splitSnapshotAffectedStructs)\n return ops\n }\n\n /**\n * Insert text at a given index.\n *\n * @param {number} index The index at which to start inserting.\n * @param {String} text The text to insert at the specified position.\n * @param {TextAttributes} [attributes] Optionally define some formatting\n * information to apply on the inserted\n * Text.\n * @public\n */\n insert (index, text, attributes) {\n if (text.length <= 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index)\n if (!attributes) {\n attributes = {}\n // @ts-ignore\n pos.currentAttributes.forEach((v, k) => { attributes[k] = v })\n }\n insertText(transaction, this, pos, text, attributes)\n })\n } else {\n /** @type {Array<function>} */ (this._pending).push(() => this.insert(index, text, attributes))\n }\n }\n\n /**\n * Inserts an embed at a index.\n *\n * @param {number} index The index to insert the embed at.\n * @param {Object | AbstractType<any>} embed The Object that represents the embed.\n * @param {TextAttributes} attributes Attribute information to apply on the\n * embed\n *\n * @public\n */\n insertEmbed (index, embed, attributes = {}) {\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index)\n insertText(transaction, this, pos, embed, attributes)\n })\n } else {\n /** @type {Array<function>} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes))\n }\n }\n\n /**\n * Deletes text starting from an index.\n *\n * @param {number} index Index at which to start deleting.\n * @param {number} length The number of characters to remove. Defaults to 1.\n *\n * @public\n */\n delete (index, length) {\n if (length === 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n deleteText(transaction, findPosition(transaction, this, index), length)\n })\n } else {\n /** @type {Array<function>} */ (this._pending).push(() => this.delete(index, length))\n }\n }\n\n /**\n * Assigns properties to a range of text.\n *\n * @param {number} index The position where to start formatting.\n * @param {number} length The amount of characters to assign properties to.\n * @param {TextAttributes} attributes Attribute information to apply on the\n * text.\n *\n * @public\n */\n format (index, length, attributes) {\n if (length === 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index)\n if (pos.right === null) {\n return\n }\n formatText(transaction, this, pos, length, attributes)\n })\n } else {\n /** @type {Array<function>} */ (this._pending).push(() => this.format(index, length, attributes))\n }\n }\n\n /**\n * Removes an attribute.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {String} attributeName The attribute name that is to be removed.\n *\n * @public\n */\n removeAttribute (attributeName) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, attributeName)\n })\n } else {\n /** @type {Array<function>} */ (this._pending).push(() => this.removeAttribute(attributeName))\n }\n }\n\n /**\n * Sets or updates an attribute.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {String} attributeName The attribute name that is to be set.\n * @param {any} attributeValue The attribute value that is to be set.\n *\n * @public\n */\n setAttribute (attributeName, attributeValue) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, attributeName, attributeValue)\n })\n } else {\n /** @type {Array<function>} */ (this._pending).push(() => this.setAttribute(attributeName, attributeValue))\n }\n }\n\n /**\n * Returns an attribute value that belongs to the attribute name.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {String} attributeName The attribute name that identifies the\n * queried value.\n * @return {any} The queried attribute value.\n *\n * @public\n */\n getAttribute (attributeName) {\n return /** @type {any} */ (typeMapGet(this, attributeName))\n }\n\n /**\n * Returns all attribute name/value pairs in a JSON Object.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {Snapshot} [snapshot]\n * @return {Object<string, any>} A JSON Object that describes the attributes.\n *\n * @public\n */\n getAttributes (snapshot) {\n return typeMapGetAll(this)\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YTextRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YText}\n *\n * @private\n * @function\n */\nexport const readYText = decoder => new YText()\n","/**\n * @module YXml\n */\n\nimport {\n YXmlEvent,\n YXmlElement,\n AbstractType,\n typeListMap,\n typeListForEach,\n typeListInsertGenerics,\n typeListInsertGenericsAfter,\n typeListDelete,\n typeListToArray,\n YXmlFragmentRefID,\n callTypeObservers,\n transact,\n typeListGet,\n typeListSlice,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, ContentType, Transaction, Item, YXmlText, YXmlHook, Snapshot // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * Define the elements to which a set of CSS queries apply.\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|CSS_Selectors}\n *\n * @example\n * query = '.classSelector'\n * query = 'nodeSelector'\n * query = '#idSelector'\n *\n * @typedef {string} CSS_Selector\n */\n\n/**\n * Dom filter function.\n *\n * @callback domFilter\n * @param {string} nodeName The nodeName of the element\n * @param {Map} attributes The map of attributes.\n * @return {boolean} Whether to include the Dom node in the YXmlElement.\n */\n\n/**\n * Represents a subset of the nodes of a YXmlElement / YXmlFragment and a\n * position within them.\n *\n * Can be created with {@link YXmlFragment#createTreeWalker}\n *\n * @public\n * @implements {Iterable<YXmlElement|YXmlText|YXmlElement|YXmlHook>}\n */\nexport class YXmlTreeWalker {\n /**\n * @param {YXmlFragment | YXmlElement} root\n * @param {function(AbstractType<any>):boolean} [f]\n */\n constructor (root, f = () => true) {\n this._filter = f\n this._root = root\n /**\n * @type {Item}\n */\n this._currentNode = /** @type {Item} */ (root._start)\n this._firstCall = true\n }\n\n [Symbol.iterator] () {\n return this\n }\n\n /**\n * Get the next node.\n *\n * @return {IteratorResult<YXmlElement|YXmlText|YXmlHook>} The next node.\n *\n * @public\n */\n next () {\n /**\n * @type {Item|null}\n */\n let n = this._currentNode\n let type = n && n.content && /** @type {any} */ (n.content).type\n if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item\n do {\n type = /** @type {any} */ (n.content).type\n if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {\n // walk down in the tree\n n = type._start\n } else {\n // walk right or up in the tree\n while (n !== null) {\n if (n.right !== null) {\n n = n.right\n break\n } else if (n.parent === this._root) {\n n = null\n } else {\n n = /** @type {AbstractType<any>} */ (n.parent)._item\n }\n }\n }\n } while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type)))\n }\n this._firstCall = false\n if (n === null) {\n // @ts-ignore\n return { value: undefined, done: true }\n }\n this._currentNode = n\n return { value: /** @type {any} */ (n.content).type, done: false }\n }\n}\n\n/**\n * Represents a list of {@link YXmlElement}.and {@link YXmlText} types.\n * A YxmlFragment is similar to a {@link YXmlElement}, but it does not have a\n * nodeName and it does not have attributes. Though it can be bound to a DOM\n * element - in this case the attributes and the nodeName are not shared.\n *\n * @public\n * @extends AbstractType<YXmlEvent>\n */\nexport class YXmlFragment extends AbstractType {\n constructor () {\n super()\n /**\n * @type {Array<any>|null}\n */\n this._prelimContent = []\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get firstChild () {\n const first = this._first\n return first ? first.content.getContent()[0] : null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n this.insert(0, /** @type {Array<any>} */ (this._prelimContent))\n this._prelimContent = null\n }\n\n _copy () {\n return new YXmlFragment()\n }\n\n /**\n * @return {YXmlFragment}\n */\n clone () {\n const el = new YXmlFragment()\n // @ts-ignore\n el.insert(0, this.toArray().map(item => item instanceof AbstractType ? item.clone() : item))\n return el\n }\n\n get length () {\n return this._prelimContent === null ? this._length : this._prelimContent.length\n }\n\n /**\n * Create a subtree of childNodes.\n *\n * @example\n * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div')\n * for (let node in walker) {\n * // `node` is a div node\n * nop(node)\n * }\n *\n * @param {function(AbstractType<any>):boolean} filter Function that is called on each child element and\n * returns a Boolean indicating whether the child\n * is to be included in the subtree.\n * @return {YXmlTreeWalker} A subtree and a position within it.\n *\n * @public\n */\n createTreeWalker (filter) {\n return new YXmlTreeWalker(this, filter)\n }\n\n /**\n * Returns the first YXmlElement that matches the query.\n * Similar to DOM's {@link querySelector}.\n *\n * Query support:\n * - tagname\n * TODO:\n * - id\n * - attribute\n *\n * @param {CSS_Selector} query The query on the children.\n * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null.\n *\n * @public\n */\n querySelector (query) {\n query = query.toUpperCase()\n // @ts-ignore\n const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query)\n const next = iterator.next()\n if (next.done) {\n return null\n } else {\n return next.value\n }\n }\n\n /**\n * Returns all YXmlElements that match the query.\n * Similar to Dom's {@link querySelectorAll}.\n *\n * @todo Does not yet support all queries. Currently only query by tagName.\n *\n * @param {CSS_Selector} query The query on the children\n * @return {Array<YXmlElement|YXmlText|YXmlHook|null>} The elements that match this query.\n *\n * @public\n */\n querySelectorAll (query) {\n query = query.toUpperCase()\n // @ts-ignore\n return Array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query))\n }\n\n /**\n * Creates YXmlEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction))\n }\n\n /**\n * Get the string representation of all the children of this YXmlFragment.\n *\n * @return {string} The string representation of all children.\n */\n toString () {\n return typeListMap(this, xml => xml.toString()).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const fragment = _document.createDocumentFragment()\n if (binding !== undefined) {\n binding._createAssociation(fragment, this)\n }\n typeListForEach(this, xmlType => {\n fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null)\n })\n return fragment\n }\n\n /**\n * Inserts new content at an index.\n *\n * @example\n * // Insert character 'a' at position 0\n * xml.insert(0, [new Y.XmlText('text')])\n *\n * @param {number} index The index to insert content at\n * @param {Array<YXmlElement|YXmlText>} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, content)\n })\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, 0, ...content)\n }\n }\n\n /**\n * Inserts new content at an index.\n *\n * @example\n * // Insert character 'a' at position 0\n * xml.insert(0, [new Y.XmlText('text')])\n *\n * @param {null|Item|YXmlElement|YXmlText} ref The index to insert content at\n * @param {Array<YXmlElement|YXmlText>} content The array of content\n */\n insertAfter (ref, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n const refItem = (ref && ref instanceof AbstractType) ? ref._item : ref\n typeListInsertGenericsAfter(transaction, this, refItem, content)\n })\n } else {\n const pc = /** @type {Array<any>} */ (this._prelimContent)\n const index = ref === null ? 0 : pc.findIndex(el => el === ref) + 1\n if (index === 0 && ref !== null) {\n throw error.create('Reference item not found')\n }\n pc.splice(index, 0, ...content)\n }\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} [length=1] The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length)\n })\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, length)\n }\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array<YXmlElement|YXmlText|YXmlHook>}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Appends content to this YArray.\n *\n * @param {Array<YXmlElement|YXmlText>} content Array of content to append.\n */\n push (content) {\n this.insert(this.length, content)\n }\n\n /**\n * Preppends content to this YArray.\n *\n * @param {Array<YXmlElement|YXmlText>} content Array of content to preppend.\n */\n unshift (content) {\n this.insert(0, content)\n }\n\n /**\n * Returns the i-th element from a YArray.\n *\n * @param {number} index The index of the element to return from the YArray\n * @return {YXmlElement|YXmlText}\n */\n get (index) {\n return typeListGet(this, index)\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @param {number} [start]\n * @param {number} [end]\n * @return {Array<YXmlElement|YXmlText>}\n */\n slice (start = 0, end = this.length) {\n return typeListSlice(this, start, end)\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlFragmentRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlFragment}\n *\n * @private\n * @function\n */\nexport const readYXmlFragment = decoder => new YXmlFragment()\n","\nimport {\n YXmlFragment,\n transact,\n typeMapDelete,\n typeMapHas,\n typeMapSet,\n typeMapGet,\n typeMapGetAll,\n typeListForEach,\n YXmlElementRefID,\n YXmlText, ContentType, AbstractType, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Snapshot, Doc, Item // eslint-disable-line\n} from '../internals.js'\n\n/**\n * An YXmlElement imitates the behavior of a\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}.\n *\n * * An YXmlElement has attributes (key value pairs)\n * * An YXmlElement has childElements that must inherit from YXmlElement\n */\nexport class YXmlElement extends YXmlFragment {\n constructor (nodeName = 'UNDEFINED') {\n super()\n this.nodeName = nodeName\n /**\n * @type {Map<string, any>|null}\n */\n this._prelimAttrs = new Map()\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get nextSibling () {\n const n = this._item ? this._item.next : null\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get prevSibling () {\n const n = this._item ? this._item.prev : null\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;(/** @type {Map<string, any>} */ (this._prelimAttrs)).forEach((value, key) => {\n this.setAttribute(key, value)\n })\n this._prelimAttrs = null\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n *\n * @return {YXmlElement}\n */\n _copy () {\n return new YXmlElement(this.nodeName)\n }\n\n /**\n * @return {YXmlElement}\n */\n clone () {\n const el = new YXmlElement(this.nodeName)\n const attrs = this.getAttributes()\n for (const key in attrs) {\n el.setAttribute(key, attrs[key])\n }\n // @ts-ignore\n el.insert(0, this.toArray().map(item => item instanceof AbstractType ? item.clone() : item))\n return el\n }\n\n /**\n * Returns the XML serialization of this YXmlElement.\n * The attributes are ordered by attribute-name, so you can easily use this\n * method to compare YXmlElements\n *\n * @return {string} The string representation of this type.\n *\n * @public\n */\n toString () {\n const attrs = this.getAttributes()\n const stringBuilder = []\n const keys = []\n for (const key in attrs) {\n keys.push(key)\n }\n keys.sort()\n const keysLen = keys.length\n for (let i = 0; i < keysLen; i++) {\n const key = keys[i]\n stringBuilder.push(key + '=\"' + attrs[key] + '\"')\n }\n const nodeName = this.nodeName.toLocaleLowerCase()\n const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : ''\n return `<${nodeName}${attrsString}>${super.toString()}</${nodeName}>`\n }\n\n /**\n * Removes an attribute from this YXmlElement.\n *\n * @param {String} attributeName The attribute name that is to be removed.\n *\n * @public\n */\n removeAttribute (attributeName) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, attributeName)\n })\n } else {\n /** @type {Map<string,any>} */ (this._prelimAttrs).delete(attributeName)\n }\n }\n\n /**\n * Sets or updates an attribute.\n *\n * @param {String} attributeName The attribute name that is to be set.\n * @param {String} attributeValue The attribute value that is to be set.\n *\n * @public\n */\n setAttribute (attributeName, attributeValue) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, attributeName, attributeValue)\n })\n } else {\n /** @type {Map<string, any>} */ (this._prelimAttrs).set(attributeName, attributeValue)\n }\n }\n\n /**\n * Returns an attribute value that belongs to the attribute name.\n *\n * @param {String} attributeName The attribute name that identifies the\n * queried value.\n * @return {String} The queried attribute value.\n *\n * @public\n */\n getAttribute (attributeName) {\n return /** @type {any} */ (typeMapGet(this, attributeName))\n }\n\n /**\n * Returns whether an attribute exists\n *\n * @param {String} attributeName The attribute name to check for existence.\n * @return {boolean} whether the attribute exists.\n *\n * @public\n */\n hasAttribute (attributeName) {\n return /** @type {any} */ (typeMapHas(this, attributeName))\n }\n\n /**\n * Returns all attribute name/value pairs in a JSON Object.\n *\n * @param {Snapshot} [snapshot]\n * @return {Object<string, any>} A JSON Object that describes the attributes.\n *\n * @public\n */\n getAttributes (snapshot) {\n return typeMapGetAll(this)\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const dom = _document.createElement(this.nodeName)\n const attrs = this.getAttributes()\n for (const key in attrs) {\n dom.setAttribute(key, attrs[key])\n }\n typeListForEach(this, yxml => {\n dom.appendChild(yxml.toDOM(_document, hooks, binding))\n })\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlElementRefID)\n encoder.writeKey(this.nodeName)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlElement}\n *\n * @function\n */\nexport const readYXmlElement = decoder => new YXmlElement(decoder.readKey())\n","\nimport {\n YEvent,\n YXmlText, YXmlElement, YXmlFragment, Transaction // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @extends YEvent<YXmlElement|YXmlText|YXmlFragment>\n * An Event that describes changes on a YXml Element or Yxml Fragment\n */\nexport class YXmlEvent extends YEvent {\n /**\n * @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created.\n * @param {Set<string|null>} subs The set of changed attributes. `null` is included if the\n * child list changed.\n * @param {Transaction} transaction The transaction instance with wich the\n * change was created.\n */\n constructor (target, subs, transaction) {\n super(target, transaction)\n /**\n * Whether the children changed.\n * @type {Boolean}\n * @private\n */\n this.childListChanged = false\n /**\n * Set of all changed attributes.\n * @type {Set<string>}\n */\n this.attributesChanged = new Set()\n subs.forEach((sub) => {\n if (sub === null) {\n this.childListChanged = true\n } else {\n this.attributesChanged.add(sub)\n }\n })\n }\n}\n","\nimport {\n YMap,\n YXmlHookRefID,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2 // eslint-disable-line\n} from '../internals.js'\n\n/**\n * You can manage binding to a custom type with YXmlHook.\n *\n * @extends {YMap<any>}\n */\nexport class YXmlHook extends YMap {\n /**\n * @param {string} hookName nodeName of the Dom Node.\n */\n constructor (hookName) {\n super()\n /**\n * @type {string}\n */\n this.hookName = hookName\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n */\n _copy () {\n return new YXmlHook(this.hookName)\n }\n\n /**\n * @return {YXmlHook}\n */\n clone () {\n const el = new YXmlHook(this.hookName)\n this.forEach((value, key) => {\n el.set(key, value)\n })\n return el\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object.<string, any>} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type\n * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const hook = hooks[this.hookName]\n let dom\n if (hook !== undefined) {\n dom = hook.createDom(this)\n } else {\n dom = document.createElement(this.hookName)\n }\n dom.setAttribute('data-yjs-hook', this.hookName)\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlHookRefID)\n encoder.writeKey(this.hookName)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlHook}\n *\n * @private\n * @function\n */\nexport const readYXmlHook = decoder =>\n new YXmlHook(decoder.readKey())\n","\nimport {\n YText,\n YXmlTextRefID,\n ContentType, YXmlElement, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Represents text in a Dom Element. In the future this type will also handle\n * simple formatting information like bold and italic.\n */\nexport class YXmlText extends YText {\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get nextSibling () {\n const n = this._item ? this._item.next : null\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get prevSibling () {\n const n = this._item ? this._item.prev : null\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n _copy () {\n return new YXmlText()\n }\n\n /**\n * @return {YXmlText}\n */\n clone () {\n const text = new YXmlText()\n text.applyDelta(this.toDelta())\n return text\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlText.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object<string, any>} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks, binding) {\n const dom = _document.createTextNode(this.toString())\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n toString () {\n // @ts-ignore\n return this.toDelta().map(delta => {\n const nestedNodes = []\n for (const nodeName in delta.attributes) {\n const attrs = []\n for (const key in delta.attributes[nodeName]) {\n attrs.push({ key, value: delta.attributes[nodeName][key] })\n }\n // sort attributes to get a unique order\n attrs.sort((a, b) => a.key < b.key ? -1 : 1)\n nestedNodes.push({ nodeName, attrs })\n }\n // sort node order to get a unique order\n nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1)\n // now convert to dom string\n let str = ''\n for (let i = 0; i < nestedNodes.length; i++) {\n const node = nestedNodes[i]\n str += `<${node.nodeName}`\n for (let j = 0; j < node.attrs.length; j++) {\n const attr = node.attrs[j]\n str += ` ${attr.key}=\"${attr.value}\"`\n }\n str += '>'\n }\n str += delta.insert\n for (let i = nestedNodes.length - 1; i >= 0; i--) {\n str += `</${nestedNodes[i].nodeName}>`\n }\n return str\n }).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlTextRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlText}\n *\n * @private\n * @function\n */\nexport const readYXmlText = decoder => new YXmlText()\n","\nimport {\n UpdateEncoderV1, UpdateEncoderV2, ID, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\nexport class AbstractStruct {\n /**\n * @param {ID} id\n * @param {number} length\n */\n constructor (id, length) {\n this.id = id\n this.length = length\n }\n\n /**\n * @type {boolean}\n */\n get deleted () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Merge this struct with the item to the right.\n * This method is already assuming that `this.id.clock + this.length === this.id.clock`.\n * Also this method does *not* remove right from StructStore!\n * @param {AbstractStruct} right\n * @return {boolean} wether this merged with right\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n * @param {number} offset\n * @param {number} encodingRef\n */\n write (encoder, offset, encodingRef) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n throw error.methodUnimplemented()\n }\n}\n","\nimport {\n AbstractStruct,\n addStruct,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\n\nexport const structGCRefNumber = 0\n\n/**\n * @private\n */\nexport class GC extends AbstractStruct {\n get deleted () {\n return true\n }\n\n delete () {}\n\n /**\n * @param {GC} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (this.constructor !== right.constructor) {\n return false\n }\n this.length += right.length\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset\n this.length -= offset\n }\n addStruct(transaction.doc.store, this)\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeInfo(structGCRefNumber)\n encoder.writeLen(this.length - offset)\n }\n\n /**\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n return null\n }\n}\n","import {\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\nexport class ContentBinary {\n /**\n * @param {Uint8Array} content\n */\n constructor (content) {\n this.content = content\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array<any>}\n */\n getContent () {\n return [this.content]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentBinary}\n */\n copy () {\n return new ContentBinary(this.content)\n }\n\n /**\n * @param {number} offset\n * @return {ContentBinary}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentBinary} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeBuf(this.content)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 3\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2 } decoder\n * @return {ContentBinary}\n */\nexport const readContentBinary = decoder => new ContentBinary(decoder.readBuf())\n","\nimport {\n addToDeleteSet,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nexport class ContentDeleted {\n /**\n * @param {number} len\n */\n constructor (len) {\n this.len = len\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.len\n }\n\n /**\n * @return {Array<any>}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentDeleted}\n */\n copy () {\n return new ContentDeleted(this.len)\n }\n\n /**\n * @param {number} offset\n * @return {ContentDeleted}\n */\n splice (offset) {\n const right = new ContentDeleted(this.len - offset)\n this.len = offset\n return right\n }\n\n /**\n * @param {ContentDeleted} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.len += right.len\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len)\n item.markDeleted()\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeLen(this.len - offset)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 1\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2 } decoder\n * @return {ContentDeleted}\n */\nexport const readContentDeleted = decoder => new ContentDeleted(decoder.readLen())\n","\nimport {\n Doc, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * @param {string} guid\n * @param {Object<string, any>} opts\n */\nconst createDocFromOpts = (guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false })\n\n/**\n * @private\n */\nexport class ContentDoc {\n /**\n * @param {Doc} doc\n */\n constructor (doc) {\n if (doc._item) {\n console.error('This document was already integrated as a sub-document. You should create a second instance instead with the same guid.')\n }\n /**\n * @type {Doc}\n */\n this.doc = doc\n /**\n * @type {any}\n */\n const opts = {}\n this.opts = opts\n if (!doc.gc) {\n opts.gc = false\n }\n if (doc.autoLoad) {\n opts.autoLoad = true\n }\n if (doc.meta !== null) {\n opts.meta = doc.meta\n }\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array<any>}\n */\n getContent () {\n return [this.doc]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentDoc}\n */\n copy () {\n return new ContentDoc(createDocFromOpts(this.doc.guid, this.opts))\n }\n\n /**\n * @param {number} offset\n * @return {ContentDoc}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentDoc} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n // this needs to be reflected in doc.destroy as well\n this.doc._item = item\n transaction.subdocsAdded.add(this.doc)\n if (this.doc.shouldLoad) {\n transaction.subdocsLoaded.add(this.doc)\n }\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (transaction.subdocsAdded.has(this.doc)) {\n transaction.subdocsAdded.delete(this.doc)\n } else {\n transaction.subdocsRemoved.add(this.doc)\n }\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) { }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(this.doc.guid)\n encoder.writeAny(this.opts)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 9\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentDoc}\n */\nexport const readContentDoc = decoder => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny()))\n","\nimport {\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * @private\n */\nexport class ContentEmbed {\n /**\n * @param {Object} embed\n */\n constructor (embed) {\n this.embed = embed\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array<any>}\n */\n getContent () {\n return [this.embed]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentEmbed}\n */\n copy () {\n return new ContentEmbed(this.embed)\n }\n\n /**\n * @param {number} offset\n * @return {ContentEmbed}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentEmbed} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeJSON(this.embed)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 5\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentEmbed}\n */\nexport const readContentEmbed = decoder => new ContentEmbed(decoder.readJSON())\n","\nimport {\n AbstractType, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Item, StructStore, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * @private\n */\nexport class ContentFormat {\n /**\n * @param {string} key\n * @param {Object} value\n */\n constructor (key, value) {\n this.key = key\n this.value = value\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array<any>}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentFormat}\n */\n copy () {\n return new ContentFormat(this.key, this.value)\n }\n\n /**\n * @param {number} offset\n * @return {ContentFormat}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentFormat} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n // @todo searchmarker are currently unsupported for rich text documents\n /** @type {AbstractType<any>} */ (item.parent)._searchMarker = null\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeKey(this.key)\n encoder.writeJSON(this.value)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 6\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentFormat}\n */\nexport const readContentFormat = decoder => new ContentFormat(decoder.readKey(), decoder.readJSON())\n","import {\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @private\n */\nexport class ContentJSON {\n /**\n * @param {Array<any>} arr\n */\n constructor (arr) {\n /**\n * @type {Array<any>}\n */\n this.arr = arr\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array<any>}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentJSON}\n */\n copy () {\n return new ContentJSON(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentJSON}\n */\n splice (offset) {\n const right = new ContentJSON(this.arr.slice(offset))\n this.arr = this.arr.slice(0, offset)\n return right\n }\n\n /**\n * @param {ContentJSON} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr)\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length\n encoder.writeLen(len - offset)\n for (let i = offset; i < len; i++) {\n const c = this.arr[i]\n encoder.writeString(c === undefined ? 'undefined' : JSON.stringify(c))\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 2\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentJSON}\n */\nexport const readContentJSON = decoder => {\n const len = decoder.readLen()\n const cs = []\n for (let i = 0; i < len; i++) {\n const c = decoder.readString()\n if (c === 'undefined') {\n cs.push(undefined)\n } else {\n cs.push(JSON.parse(c))\n }\n }\n return new ContentJSON(cs)\n}\n","import {\n UpdateEncoderV1, UpdateEncoderV2, UpdateDecoderV1, UpdateDecoderV2, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\nexport class ContentAny {\n /**\n * @param {Array<any>} arr\n */\n constructor (arr) {\n /**\n * @type {Array<any>}\n */\n this.arr = arr\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array<any>}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentAny}\n */\n copy () {\n return new ContentAny(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentAny}\n */\n splice (offset) {\n const right = new ContentAny(this.arr.slice(offset))\n this.arr = this.arr.slice(0, offset)\n return right\n }\n\n /**\n * @param {ContentAny} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr)\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length\n encoder.writeLen(len - offset)\n for (let i = offset; i < len; i++) {\n const c = this.arr[i]\n encoder.writeAny(c)\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 8\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentAny}\n */\nexport const readContentAny = decoder => {\n const len = decoder.readLen()\n const cs = []\n for (let i = 0; i < len; i++) {\n cs.push(decoder.readAny())\n }\n return new ContentAny(cs)\n}\n","import {\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @private\n */\nexport class ContentString {\n /**\n * @param {string} str\n */\n constructor (str) {\n /**\n * @type {string}\n */\n this.str = str\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.str.length\n }\n\n /**\n * @return {Array<any>}\n */\n getContent () {\n return this.str.split('')\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentString}\n */\n copy () {\n return new ContentString(this.str)\n }\n\n /**\n * @param {number} offset\n * @return {ContentString}\n */\n splice (offset) {\n const right = new ContentString(this.str.slice(offset))\n this.str = this.str.slice(0, offset)\n\n // Prevent encoding invalid documents because of splitting of surrogate pairs: https://github.com/yjs/yjs/issues/248\n const firstCharCode = this.str.charCodeAt(offset - 1)\n if (firstCharCode >= 0xD800 && firstCharCode <= 0xDBFF) {\n // Last character of the left split is the start of a surrogate utf16/ucs2 pair.\n // We don't support splitting of surrogate pairs because this may lead to invalid documents.\n // Replace the invalid character with a unicode replacement character (� / U+FFFD)\n this.str = this.str.slice(0, offset - 1) + '�'\n // replace right as well\n right.str = '�' + right.str.slice(1)\n }\n return right\n }\n\n /**\n * @param {ContentString} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.str += right.str\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(offset === 0 ? this.str : this.str.slice(offset))\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 4\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentString}\n */\nexport const readContentString = decoder => new ContentString(decoder.readString())\n","\nimport {\n readYArray,\n readYMap,\n readYText,\n readYXmlElement,\n readYXmlFragment,\n readYXmlHook,\n readYXmlText,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, Item, YEvent, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * @type {Array<function(UpdateDecoderV1 | UpdateDecoderV2):AbstractType<any>>}\n * @private\n */\nexport const typeRefs = [\n readYArray,\n readYMap,\n readYText,\n readYXmlElement,\n readYXmlFragment,\n readYXmlHook,\n readYXmlText\n]\n\nexport const YArrayRefID = 0\nexport const YMapRefID = 1\nexport const YTextRefID = 2\nexport const YXmlElementRefID = 3\nexport const YXmlFragmentRefID = 4\nexport const YXmlHookRefID = 5\nexport const YXmlTextRefID = 6\n\n/**\n * @private\n */\nexport class ContentType {\n /**\n * @param {AbstractType<any>} type\n */\n constructor (type) {\n /**\n * @type {AbstractType<any>}\n */\n this.type = type\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array<any>}\n */\n getContent () {\n return [this.type]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentType}\n */\n copy () {\n return new ContentType(this.type._copy())\n }\n\n /**\n * @param {number} offset\n * @return {ContentType}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentType} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n this.type._integrate(transaction.doc, item)\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n let item = this.type._start\n while (item !== null) {\n if (!item.deleted) {\n item.delete(transaction)\n } else {\n // This will be gc'd later and we want to merge it if possible\n // We try to merge all deleted items after each transaction,\n // but we have no knowledge about that this needs to be merged\n // since it is not in transaction.ds. Hence we add it to transaction._mergeStructs\n transaction._mergeStructs.push(item)\n }\n item = item.right\n }\n this.type._map.forEach(item => {\n if (!item.deleted) {\n item.delete(transaction)\n } else {\n // same as above\n transaction._mergeStructs.push(item)\n }\n })\n transaction.changed.delete(this.type)\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) {\n let item = this.type._start\n while (item !== null) {\n item.gc(store, true)\n item = item.right\n }\n this.type._start = null\n this.type._map.forEach(/** @param {Item | null} item */ (item) => {\n while (item !== null) {\n item.gc(store, true)\n item = item.left\n }\n })\n this.type._map = new Map()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n this.type._write(encoder)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 7\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentType}\n */\nexport const readContentType = decoder => new ContentType(typeRefs[decoder.readTypeRef()](decoder))\n","\nimport {\n GC,\n getState,\n AbstractStruct,\n replaceStruct,\n addStruct,\n addToDeleteSet,\n findRootTypeKey,\n compareIDs,\n getItem,\n getItemCleanEnd,\n getItemCleanStart,\n readContentDeleted,\n readContentBinary,\n readContentJSON,\n readContentAny,\n readContentString,\n readContentEmbed,\n readContentDoc,\n createID,\n readContentFormat,\n readContentType,\n addChangedTypeToTransaction,\n isDeleted,\n DeleteSet, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, ContentType, ContentDeleted, StructStore, ID, AbstractType, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\nimport * as binary from 'lib0/binary'\n\n/**\n * @todo This should return several items\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {{item:Item, diff:number}}\n */\nexport const followRedone = (store, id) => {\n /**\n * @type {ID|null}\n */\n let nextID = id\n let diff = 0\n let item\n do {\n if (diff > 0) {\n nextID = createID(nextID.client, nextID.clock + diff)\n }\n item = getItem(store, nextID)\n diff = nextID.clock - item.id.clock\n nextID = item.redone\n } while (nextID !== null && item instanceof Item)\n return {\n item, diff\n }\n}\n\n/**\n * Make sure that neither item nor any of its parents is ever deleted.\n *\n * This property does not persist when storing it into a database or when\n * sending it to other peers\n *\n * @param {Item|null} item\n * @param {boolean} keep\n */\nexport const keepItem = (item, keep) => {\n while (item !== null && item.keep !== keep) {\n item.keep = keep\n item = /** @type {AbstractType<any>} */ (item.parent)._item\n }\n}\n\n/**\n * Split leftItem into two items\n * @param {Transaction} transaction\n * @param {Item} leftItem\n * @param {number} diff\n * @return {Item}\n *\n * @function\n * @private\n */\nexport const splitItem = (transaction, leftItem, diff) => {\n // create rightItem\n const { client, clock } = leftItem.id\n const rightItem = new Item(\n createID(client, clock + diff),\n leftItem,\n createID(client, clock + diff - 1),\n leftItem.right,\n leftItem.rightOrigin,\n leftItem.parent,\n leftItem.parentSub,\n leftItem.content.splice(diff)\n )\n if (leftItem.deleted) {\n rightItem.markDeleted()\n }\n if (leftItem.keep) {\n rightItem.keep = true\n }\n if (leftItem.redone !== null) {\n rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff)\n }\n // update left (do not set leftItem.rightOrigin as it will lead to problems when syncing)\n leftItem.right = rightItem\n // update right\n if (rightItem.right !== null) {\n rightItem.right.left = rightItem\n }\n // right is more specific.\n transaction._mergeStructs.push(rightItem)\n // update parent._map\n if (rightItem.parentSub !== null && rightItem.right === null) {\n /** @type {AbstractType<any>} */ (rightItem.parent)._map.set(rightItem.parentSub, rightItem)\n }\n leftItem.length = diff\n return rightItem\n}\n\n/**\n * Redoes the effect of this operation.\n *\n * @param {Transaction} transaction The Yjs instance.\n * @param {Item} item\n * @param {Set<Item>} redoitems\n * @param {DeleteSet} itemsToDelete\n *\n * @return {Item|null}\n *\n * @private\n */\nexport const redoItem = (transaction, item, redoitems, itemsToDelete) => {\n const doc = transaction.doc\n const store = doc.store\n const ownClientID = doc.clientID\n const redone = item.redone\n if (redone !== null) {\n return getItemCleanStart(transaction, redone)\n }\n let parentItem = /** @type {AbstractType<any>} */ (item.parent)._item\n /**\n * @type {Item|null}\n */\n let left = null\n /**\n * @type {Item|null}\n */\n let right\n // make sure that parent is redone\n if (parentItem !== null && parentItem.deleted === true) {\n // try to undo parent if it will be undone anyway\n if (parentItem.redone === null && (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems, itemsToDelete) === null)) {\n return null\n }\n while (parentItem.redone !== null) {\n parentItem = getItemCleanStart(transaction, parentItem.redone)\n }\n }\n const parentType = parentItem === null ? /** @type {AbstractType<any>} */ (item.parent) : /** @type {ContentType} */ (parentItem.content).type\n\n if (item.parentSub === null) {\n // Is an array item. Insert at the old position\n left = item.left\n right = item\n // find next cloned_redo items\n while (left !== null) {\n /**\n * @type {Item|null}\n */\n let leftTrace = left\n // trace redone until parent matches\n while (leftTrace !== null && /** @type {AbstractType<any>} */ (leftTrace.parent)._item !== parentItem) {\n leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone)\n }\n if (leftTrace !== null && /** @type {AbstractType<any>} */ (leftTrace.parent)._item === parentItem) {\n left = leftTrace\n break\n }\n left = left.left\n }\n while (right !== null) {\n /**\n * @type {Item|null}\n */\n let rightTrace = right\n // trace redone until parent matches\n while (rightTrace !== null && /** @type {AbstractType<any>} */ (rightTrace.parent)._item !== parentItem) {\n rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone)\n }\n if (rightTrace !== null && /** @type {AbstractType<any>} */ (rightTrace.parent)._item === parentItem) {\n right = rightTrace\n break\n }\n right = right.right\n }\n } else {\n right = null\n if (item.right) {\n left = item\n // Iterate right while right is in itemsToDelete\n // If it is intended to delete right while item is redone, we can expect that item should replace right.\n while (left !== null && left.right !== null && isDeleted(itemsToDelete, left.right.id)) {\n left = left.right\n }\n // follow redone\n // trace redone until parent matches\n while (left !== null && left.redone !== null) {\n left = getItemCleanStart(transaction, left.redone)\n }\n // check wether we were allowed to follow right (indicating that originally this op was replaced by another item)\n if (left === null || /** @type {AbstractType<any>} */ (left.parent)._item !== parentItem) {\n // invalid parent; should never happen\n return null\n }\n if (left && left.right !== null) {\n // It is not possible to redo this item because it conflicts with a\n // change from another client\n return null\n }\n } else {\n left = parentType._map.get(item.parentSub) || null\n }\n }\n const nextClock = getState(store, ownClientID)\n const nextId = createID(ownClientID, nextClock)\n const redoneItem = new Item(\n nextId,\n left, left && left.lastId,\n right, right && right.id,\n parentType,\n item.parentSub,\n item.content.copy()\n )\n item.redone = nextId\n keepItem(redoneItem, true)\n redoneItem.integrate(transaction, 0)\n return redoneItem\n}\n\n/**\n * Abstract class that represents any content.\n */\nexport class Item extends AbstractStruct {\n /**\n * @param {ID} id\n * @param {Item | null} left\n * @param {ID | null} origin\n * @param {Item | null} right\n * @param {ID | null} rightOrigin\n * @param {AbstractType<any>|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it.\n * @param {string | null} parentSub\n * @param {AbstractContent} content\n */\n constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) {\n super(id, content.getLength())\n /**\n * The item that was originally to the left of this item.\n * @type {ID | null}\n */\n this.origin = origin\n /**\n * The item that is currently to the left of this item.\n * @type {Item | null}\n */\n this.left = left\n /**\n * The item that is currently to the right of this item.\n * @type {Item | null}\n */\n this.right = right\n /**\n * The item that was originally to the right of this item.\n * @type {ID | null}\n */\n this.rightOrigin = rightOrigin\n /**\n * @type {AbstractType<any>|ID|null}\n */\n this.parent = parent\n /**\n * If the parent refers to this item with some kind of key (e.g. YMap, the\n * key is specified here. The key is then used to refer to the list in which\n * to insert this item. If `parentSub = null` type._start is the list in\n * which to insert to. Otherwise it is `parent._map`.\n * @type {String | null}\n */\n this.parentSub = parentSub\n /**\n * If this type's effect is redone this type refers to the type that undid\n * this operation.\n * @type {ID | null}\n */\n this.redone = null\n /**\n * @type {AbstractContent}\n */\n this.content = content\n /**\n * bit1: keep\n * bit2: countable\n * bit3: deleted\n * bit4: mark - mark node as fast-search-marker\n * @type {number} byte\n */\n this.info = this.content.isCountable() ? binary.BIT2 : 0\n }\n\n /**\n * This is used to mark the item as an indexed fast-search marker\n *\n * @type {boolean}\n */\n set marker (isMarked) {\n if (((this.info & binary.BIT4) > 0) !== isMarked) {\n this.info ^= binary.BIT4\n }\n }\n\n get marker () {\n return (this.info & binary.BIT4) > 0\n }\n\n /**\n * If true, do not garbage collect this Item.\n */\n get keep () {\n return (this.info & binary.BIT1) > 0\n }\n\n set keep (doKeep) {\n if (this.keep !== doKeep) {\n this.info ^= binary.BIT1\n }\n }\n\n get countable () {\n return (this.info & binary.BIT2) > 0\n }\n\n /**\n * Whether this item was deleted or not.\n * @type {Boolean}\n */\n get deleted () {\n return (this.info & binary.BIT3) > 0\n }\n\n set deleted (doDelete) {\n if (this.deleted !== doDelete) {\n this.info ^= binary.BIT3\n }\n }\n\n markDeleted () {\n this.info |= binary.BIT3\n }\n\n /**\n * Return the creator clientID of the missing op or define missing items and return null.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) {\n return this.origin.client\n }\n if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) {\n return this.rightOrigin.client\n }\n if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) {\n return this.parent.client\n }\n\n // We have all missing ids, now find the items\n\n if (this.origin) {\n this.left = getItemCleanEnd(transaction, store, this.origin)\n this.origin = this.left.lastId\n }\n if (this.rightOrigin) {\n this.right = getItemCleanStart(transaction, this.rightOrigin)\n this.rightOrigin = this.right.id\n }\n if ((this.left && this.left.constructor === GC) || (this.right && this.right.constructor === GC)) {\n this.parent = null\n }\n // only set parent if this shouldn't be garbage collected\n if (!this.parent) {\n if (this.left && this.left.constructor === Item) {\n this.parent = this.left.parent\n this.parentSub = this.left.parentSub\n }\n if (this.right && this.right.constructor === Item) {\n this.parent = this.right.parent\n this.parentSub = this.right.parentSub\n }\n } else if (this.parent.constructor === ID) {\n const parentItem = getItem(store, this.parent)\n if (parentItem.constructor === GC) {\n this.parent = null\n } else {\n this.parent = /** @type {ContentType} */ (parentItem.content).type\n }\n }\n return null\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset\n this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1))\n this.origin = this.left.lastId\n this.content = this.content.splice(offset)\n this.length -= offset\n }\n\n if (this.parent) {\n if ((!this.left && (!this.right || this.right.left !== null)) || (this.left && this.left.right !== this.right)) {\n /**\n * @type {Item|null}\n */\n let left = this.left\n\n /**\n * @type {Item|null}\n */\n let o\n // set o to the first conflicting item\n if (left !== null) {\n o = left.right\n } else if (this.parentSub !== null) {\n o = /** @type {AbstractType<any>} */ (this.parent)._map.get(this.parentSub) || null\n while (o !== null && o.left !== null) {\n o = o.left\n }\n } else {\n o = /** @type {AbstractType<any>} */ (this.parent)._start\n }\n // TODO: use something like DeleteSet here (a tree implementation would be best)\n // @todo use global set definitions\n /**\n * @type {Set<Item>}\n */\n const conflictingItems = new Set()\n /**\n * @type {Set<Item>}\n */\n const itemsBeforeOrigin = new Set()\n // Let c in conflictingItems, b in itemsBeforeOrigin\n // ***{origin}bbbb{this}{c,b}{c,b}{o}***\n // Note that conflictingItems is a subset of itemsBeforeOrigin\n while (o !== null && o !== this.right) {\n itemsBeforeOrigin.add(o)\n conflictingItems.add(o)\n if (compareIDs(this.origin, o.origin)) {\n // case 1\n if (o.id.client < this.id.client) {\n left = o\n conflictingItems.clear()\n } else if (compareIDs(this.rightOrigin, o.rightOrigin)) {\n // this and o are conflicting and point to the same integration points. The id decides which item comes first.\n // Since this is to the left of o, we can break here\n break\n } // else, o might be integrated before an item that this conflicts with. If so, we will find it in the next iterations\n } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { // use getItem instead of getItemCleanEnd because we don't want / need to split items.\n // case 2\n if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) {\n left = o\n conflictingItems.clear()\n }\n } else {\n break\n }\n o = o.right\n }\n this.left = left\n }\n // reconnect left/right + update parent map/start if necessary\n if (this.left !== null) {\n const right = this.left.right\n this.right = right\n this.left.right = this\n } else {\n let r\n if (this.parentSub !== null) {\n r = /** @type {AbstractType<any>} */ (this.parent)._map.get(this.parentSub) || null\n while (r !== null && r.left !== null) {\n r = r.left\n }\n } else {\n r = /** @type {AbstractType<any>} */ (this.parent)._start\n ;/** @type {AbstractType<any>} */ (this.parent)._start = this\n }\n this.right = r\n }\n if (this.right !== null) {\n this.right.left = this\n } else if (this.parentSub !== null) {\n // set as current parent value if right === null and this is parentSub\n /** @type {AbstractType<any>} */ (this.parent)._map.set(this.parentSub, this)\n if (this.left !== null) {\n // this is the current attribute value of parent. delete right\n this.left.delete(transaction)\n }\n }\n // adjust length of parent\n if (this.parentSub === null && this.countable && !this.deleted) {\n /** @type {AbstractType<any>} */ (this.parent)._length += this.length\n }\n addStruct(transaction.doc.store, this)\n this.content.integrate(transaction, this)\n // add parent to transaction.changed\n addChangedTypeToTransaction(transaction, /** @type {AbstractType<any>} */ (this.parent), this.parentSub)\n if ((/** @type {AbstractType<any>} */ (this.parent)._item !== null && /** @type {AbstractType<any>} */ (this.parent)._item.deleted) || (this.parentSub !== null && this.right !== null)) {\n // delete if parent is deleted or if this is not the current attribute value of parent\n this.delete(transaction)\n }\n } else {\n // parent is not defined. Integrate GC struct instead\n new GC(this.id, this.length).integrate(transaction, 0)\n }\n }\n\n /**\n * Returns the next non-deleted item\n */\n get next () {\n let n = this.right\n while (n !== null && n.deleted) {\n n = n.right\n }\n return n\n }\n\n /**\n * Returns the previous non-deleted item\n */\n get prev () {\n let n = this.left\n while (n !== null && n.deleted) {\n n = n.left\n }\n return n\n }\n\n /**\n * Computes the last content address of this Item.\n */\n get lastId () {\n // allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible\n return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1)\n }\n\n /**\n * Try to merge two items\n *\n * @param {Item} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (\n this.constructor === right.constructor &&\n compareIDs(right.origin, this.lastId) &&\n this.right === right &&\n compareIDs(this.rightOrigin, right.rightOrigin) &&\n this.id.client === right.id.client &&\n this.id.clock + this.length === right.id.clock &&\n this.deleted === right.deleted &&\n this.redone === null &&\n right.redone === null &&\n this.content.constructor === right.content.constructor &&\n this.content.mergeWith(right.content)\n ) {\n const searchMarker = /** @type {AbstractType<any>} */ (this.parent)._searchMarker\n if (searchMarker) {\n searchMarker.forEach(marker => {\n if (marker.p === right) {\n // right is going to be \"forgotten\" so we need to update the marker\n marker.p = this\n // adjust marker index\n if (!this.deleted && this.countable) {\n marker.index -= this.length\n }\n }\n })\n }\n if (right.keep) {\n this.keep = true\n }\n this.right = right.right\n if (this.right !== null) {\n this.right.left = this\n }\n this.length += right.length\n return true\n }\n return false\n }\n\n /**\n * Mark this Item as deleted.\n *\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (!this.deleted) {\n const parent = /** @type {AbstractType<any>} */ (this.parent)\n // adjust the length of parent\n if (this.countable && this.parentSub === null) {\n parent._length -= this.length\n }\n this.markDeleted()\n addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length)\n addChangedTypeToTransaction(transaction, parent, this.parentSub)\n this.content.delete(transaction)\n }\n }\n\n /**\n * @param {StructStore} store\n * @param {boolean} parentGCd\n */\n gc (store, parentGCd) {\n if (!this.deleted) {\n throw error.unexpectedCase()\n }\n this.content.gc(store)\n if (parentGCd) {\n replaceStruct(store, this, new GC(this.id, this.length))\n } else {\n this.content = new ContentDeleted(this.length)\n }\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n * @param {number} offset\n */\n write (encoder, offset) {\n const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin\n const rightOrigin = this.rightOrigin\n const parentSub = this.parentSub\n const info = (this.content.getRef() & binary.BITS5) |\n (origin === null ? 0 : binary.BIT8) | // origin is defined\n (rightOrigin === null ? 0 : binary.BIT7) | // right origin is defined\n (parentSub === null ? 0 : binary.BIT6) // parentSub is non-null\n encoder.writeInfo(info)\n if (origin !== null) {\n encoder.writeLeftID(origin)\n }\n if (rightOrigin !== null) {\n encoder.writeRightID(rightOrigin)\n }\n if (origin === null && rightOrigin === null) {\n const parent = /** @type {AbstractType<any>} */ (this.parent)\n if (parent._item !== undefined) {\n const parentItem = parent._item\n if (parentItem === null) {\n // parent type on y._map\n // find the correct key\n const ykey = findRootTypeKey(parent)\n encoder.writeParentInfo(true) // write parentYKey\n encoder.writeString(ykey)\n } else {\n encoder.writeParentInfo(false) // write parent id\n encoder.writeLeftID(parentItem.id)\n }\n } else if (parent.constructor === String) { // this edge case was added by differential updates\n encoder.writeParentInfo(true) // write parentYKey\n encoder.writeString(parent)\n } else if (parent.constructor === ID) {\n encoder.writeParentInfo(false) // write parent id\n encoder.writeLeftID(parent)\n } else {\n error.unexpectedCase()\n }\n if (parentSub !== null) {\n encoder.writeString(parentSub)\n }\n }\n this.content.write(encoder, offset)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @param {number} info\n */\nexport const readItemContent = (decoder, info) => contentRefs[info & binary.BITS5](decoder)\n\n/**\n * A lookup map for reading Item content.\n *\n * @type {Array<function(UpdateDecoderV1 | UpdateDecoderV2):AbstractContent>}\n */\nexport const contentRefs = [\n () => { error.unexpectedCase() }, // GC is not ItemContent\n readContentDeleted, // 1\n readContentJSON, // 2\n readContentBinary, // 3\n readContentString, // 4\n readContentEmbed, // 5\n readContentFormat, // 6\n readContentType, // 7\n readContentAny, // 8\n readContentDoc, // 9\n () => { error.unexpectedCase() } // 10 - Skip is not ItemContent\n]\n\n/**\n * Do not implement this class!\n */\nexport class AbstractContent {\n /**\n * @return {number}\n */\n getLength () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {Array<any>}\n */\n getContent () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Should return false if this Item is some kind of meta information\n * (e.g. format information).\n *\n * * Whether this Item should be addressable via `yarray.get(i)`\n * * Whether this Item should be counted when computing yarray.length\n *\n * @return {boolean}\n */\n isCountable () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {AbstractContent}\n */\n copy () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {number} offset\n * @return {AbstractContent}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {AbstractContent} right\n * @return {boolean}\n */\n mergeWith (right) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {number}\n */\n getRef () {\n throw error.methodUnimplemented()\n }\n}\n","\nimport {\n AbstractStruct,\n UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\nimport * as error from 'lib0/error'\nimport * as encoding from 'lib0/encoding'\n\nexport const structSkipRefNumber = 10\n\n/**\n * @private\n */\nexport class Skip extends AbstractStruct {\n get deleted () {\n return true\n }\n\n delete () {}\n\n /**\n * @param {Skip} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (this.constructor !== right.constructor) {\n return false\n }\n this.length += right.length\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n // skip structs cannot be integrated\n error.unexpectedCase()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeInfo(structSkipRefNumber)\n // write as VarUint because Skips can't make use of predictable length-encoding\n encoding.writeVarUint(encoder.restEncoder, this.length - offset)\n }\n\n /**\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n return null\n }\n}\n","/** eslint-env browser */\n\nexport {\n Doc,\n Transaction,\n YArray as Array,\n YMap as Map,\n YText as Text,\n YXmlText as XmlText,\n YXmlHook as XmlHook,\n YXmlElement as XmlElement,\n YXmlFragment as XmlFragment,\n YXmlEvent,\n YMapEvent,\n YArrayEvent,\n YTextEvent,\n YEvent,\n Item,\n AbstractStruct,\n GC,\n ContentBinary,\n ContentDeleted,\n ContentEmbed,\n ContentFormat,\n ContentJSON,\n ContentAny,\n ContentString,\n ContentType,\n AbstractType,\n getTypeChildren,\n createRelativePositionFromTypeIndex,\n createRelativePositionFromJSON,\n createAbsolutePositionFromRelativePosition,\n compareRelativePositions,\n AbsolutePosition,\n RelativePosition,\n ID,\n createID,\n compareIDs,\n getState,\n Snapshot,\n createSnapshot,\n createDeleteSet,\n createDeleteSetFromStructStore,\n cleanupYTextFormatting,\n snapshot,\n emptySnapshot,\n findRootTypeKey,\n findIndexSS,\n getItem,\n typeListToArraySnapshot,\n typeMapGetSnapshot,\n createDocFromSnapshot,\n iterateDeletedStructs,\n applyUpdate,\n applyUpdateV2,\n readUpdate,\n readUpdateV2,\n encodeStateAsUpdate,\n encodeStateAsUpdateV2,\n encodeStateVector,\n UndoManager,\n decodeSnapshot,\n encodeSnapshot,\n decodeSnapshotV2,\n encodeSnapshotV2,\n decodeStateVector,\n logUpdate,\n logUpdateV2,\n decodeUpdate,\n decodeUpdateV2,\n relativePositionToJSON,\n isDeleted,\n isParentOf,\n equalSnapshots,\n PermanentUserData, // @TODO experimental\n tryGc,\n transact,\n AbstractConnector,\n logType,\n mergeUpdates,\n mergeUpdatesV2,\n parseUpdateMeta,\n parseUpdateMetaV2,\n encodeStateVectorFromUpdate,\n encodeStateVectorFromUpdateV2,\n encodeRelativePosition,\n decodeRelativePosition,\n diffUpdate,\n diffUpdateV2,\n convertUpdateFormatV1ToV2,\n convertUpdateFormatV2ToV1\n} from './internals.js'\n\nconst glo = /** @type {any} */ (typeof window !== 'undefined'\n ? window\n // @ts-ignore\n : typeof global !== 'undefined' ? global : {})\n\nconst importIdentifier = '__ $YJS$ __'\n\nif (glo[importIdentifier] === true) {\n /**\n * Dear reader of this warning message. Please take this seriously.\n *\n * If you see this message, please make sure that you only import one version of Yjs. In many cases,\n * your package manager installs two versions of Yjs that are used by different packages within your project.\n * Another reason for this message is that some parts of your project use the commonjs version of Yjs\n * and others use the EcmaScript version of Yjs.\n *\n * This often leads to issues that are hard to debug. We often need to perform constructor checks,\n * e.g. `struct instanceof GC`. If you imported different versions of Yjs, it is impossible for us to\n * do the constructor checks anymore - which might break the CRDT algorithm.\n */\n console.warn('Yjs was already imported. Importing different versions of Yjs often leads to issues.')\n}\nglo[importIdentifier] = true\n","type InspectableObject = Record<string | number | symbol, unknown>;\n\nfunction isObject(o: unknown): o is InspectableObject {\n return Object.prototype.toString.call(o) === '[object Object]';\n}\n\nexport function isPlainObject(o: unknown): o is InspectableObject {\n if (!isObject(o)) {\n return false;\n }\n\n // If has modified constructor\n const ctor = o.constructor;\n if (ctor === undefined) {\n return true;\n }\n\n // If has modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false) {\n return false;\n }\n\n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n\n // Most likely a plain Object\n return true;\n}\n\n// Slates deep equality function: https://github.com/ianstormtaylor/slate/blob/68aff89e892fe15a16314398ff052ade6068900b/packages/slate/src/utils/deep-equal.ts#L13\n// We have to match slates deepEquals behavior to merge insert deltas in the same way slate does.\nexport function deepEquals(\n node: InspectableObject,\n another: InspectableObject\n): boolean {\n // eslint-disable-next-line guard-for-in\n for (const key in node) {\n const a = node[key];\n const b = another[key];\n\n if (isPlainObject(a) && isPlainObject(b)) {\n if (!deepEquals(a, b)) {\n return false;\n }\n } else if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n } else if (a !== b) {\n return false;\n }\n }\n\n for (const key in another) {\n if (node[key] === undefined && another[key] !== undefined) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function pick<TObj, TKeys extends keyof TObj>(\n obj: TObj,\n ...keys: TKeys[]\n): Pick<TObj, TKeys> {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => keys.includes(key as TKeys))\n ) as Pick<TObj, TKeys>;\n}\n\nexport function omit<TObj, TKeys extends keyof TObj>(\n obj: TObj,\n ...keys: TKeys[]\n): Omit<TObj, TKeys> {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => !keys.includes(key as TKeys))\n ) as Omit<TObj, TKeys>;\n}\n\nexport function omitNullEntries<TObj>(obj: TObj): {\n [K in keyof TObj]: TObj[K] extends null ? never : K;\n} {\n return Object.fromEntries(\n Object.entries(obj).filter(([, value]) => value !== null)\n ) as { [K in keyof TObj]: TObj[K] extends null ? never : K };\n}\n","import * as Y from 'yjs';\nimport { DeltaInsert, InsertDelta } from '../model/types';\nimport { deepEquals } from './object';\n\nexport function normalizeInsertDelta(delta: InsertDelta): InsertDelta {\n const normalized: InsertDelta = [];\n\n for (const element of delta) {\n if (typeof element.insert === 'string' && element.insert.length === 0) {\n continue;\n }\n\n const prev = normalized[normalized.length - 1];\n if (\n !prev ||\n typeof prev.insert !== 'string' ||\n typeof element.insert !== 'string'\n ) {\n normalized.push(element);\n continue;\n }\n\n const merge =\n prev.attributes === element.attributes ||\n (!prev.attributes === !element.attributes &&\n deepEquals(prev.attributes ?? {}, element.attributes ?? {}));\n\n if (merge) {\n prev.insert += element.insert;\n continue;\n }\n\n normalized.push(element);\n }\n\n return normalized;\n}\n\nexport function yTextToInsertDelta(yText: Y.XmlText): InsertDelta {\n return normalizeInsertDelta(yText.toDelta());\n}\n\nexport function getInsertLength({ insert }: DeltaInsert): number {\n return typeof insert === 'string' ? insert.length : 1;\n}\n\nexport function getInsertDeltaLength(delta: InsertDelta): number {\n return delta.reduce((curr, element) => curr + getInsertLength(element), 0);\n}\n\nexport function sliceInsertDelta(\n delta: InsertDelta,\n start: number,\n length: number\n): InsertDelta {\n if (length < 1) {\n return [];\n }\n\n let currentOffset = 0;\n const sliced: InsertDelta = [];\n const end = start + length;\n\n for (let i = 0; i < delta.length; i++) {\n if (currentOffset >= end) {\n break;\n }\n\n const element = delta[i];\n const elementLength = getInsertLength(element);\n\n if (currentOffset + elementLength <= start) {\n currentOffset += elementLength;\n continue;\n }\n\n if (typeof element.insert !== 'string') {\n currentOffset += elementLength;\n sliced.push(element);\n continue;\n }\n\n const startOffset = Math.max(0, start - currentOffset);\n const endOffset = Math.min(\n elementLength,\n elementLength - (currentOffset + elementLength - end)\n );\n\n sliced.push({\n ...element,\n insert: element.insert.slice(startOffset, endOffset),\n });\n currentOffset += elementLength;\n }\n\n return sliced;\n}\n","import { BaseText, Descendant, Text } from 'slate';\nimport { omit } from './object';\n\nexport function getProperties<TNode extends Descendant>(\n node: TNode\n): Omit<TNode, TNode extends BaseText ? 'text' : 'children'> {\n return omit(\n node,\n (Text.isText(node) ? 'text' : 'children') as keyof TNode\n ) as Omit<TNode, TNode extends BaseText ? 'text' : 'children'>;\n}\n","import { Element, Node, Text } from 'slate';\nimport * as Y from 'yjs';\nimport { DeltaInsert, InsertDelta } from '../model/types';\nimport { yTextToInsertDelta } from './delta';\nimport { getProperties } from './slate';\n\nexport function yTextToSlateElement(yText: Y.XmlText): Element {\n const delta = yTextToInsertDelta(yText);\n\n const children =\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n delta.length > 0 ? delta.map(deltaInsertToSlateNode) : [{ text: '' }];\n\n return { ...yText.getAttributes(), children };\n}\n\nexport function deltaInsertToSlateNode(insert: DeltaInsert): Node {\n if (typeof insert.insert === 'string') {\n return { ...insert.attributes, text: insert.insert };\n }\n\n return yTextToSlateElement(insert.insert);\n}\n\nexport function slateNodesToInsertDelta(nodes: Node[]): InsertDelta {\n return nodes.map((node) => {\n if (Text.isText(node)) {\n return { insert: node.text, attributes: getProperties(node) };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return { insert: slateElementToYText(node) };\n });\n}\n\nexport function slateElementToYText({\n children,\n ...attributes\n}: Element): Y.XmlText {\n const yElement = new Y.XmlText();\n\n Object.entries(attributes).forEach(([key, value]) => {\n yElement.setAttribute(key, value);\n });\n\n yElement.applyDelta(slateNodesToInsertDelta(children), { sanitize: false });\n return yElement;\n}\n","const SYNC_SKEW_ERROR_PATTERNS = [\n 'Cannot find a descendant at path',\n 'yOffset out of bounds',\n 'Cannot descent into slate text',\n \"yText isn't a descendant of root element\",\n \"Path doesn't match yText\",\n 'Unexpected y parent type',\n 'Path has to a have a length >= 1',\n 'yTarget spans multiple nodes',\n];\n\nexport function isSyncSkewError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n\n return SYNC_SKEW_ERROR_PATTERNS.some((pattern) =>\n error.message.includes(pattern)\n );\n}\n","import { Element, Node, Path, Text } from 'slate';\nimport * as Y from 'yjs';\nimport { YTarget } from '../model/types';\nimport { sliceInsertDelta, yTextToInsertDelta } from './delta';\n\nexport function getSlateNodeYLength(node: Node | undefined): number {\n if (!node) {\n return 0;\n }\n\n return Text.isText(node) ? node.text.length : 1;\n}\n\nexport function slatePathOffsetToYOffset(element: Element, pathOffset: number) {\n return element.children\n .slice(0, pathOffset)\n .reduce((yOffset, node) => yOffset + getSlateNodeYLength(node), 0);\n}\n\nexport function getYTarget(\n yRoot: Y.XmlText,\n slateRoot: Node,\n path: Path\n): YTarget {\n if (path.length === 0) {\n throw new Error('Path has to a have a length >= 1');\n }\n\n if (Text.isText(slateRoot)) {\n throw new Error('Cannot descent into slate text');\n }\n\n const [pathOffset, ...childPath] = path;\n\n const yOffset = slatePathOffsetToYOffset(slateRoot, pathOffset);\n const targetNode = slateRoot.children[pathOffset];\n\n const delta = yTextToInsertDelta(yRoot);\n const targetLength = getSlateNodeYLength(targetNode);\n\n const targetDelta = sliceInsertDelta(delta, yOffset, targetLength);\n if (targetDelta.length > 1) {\n throw new Error(\"Path doesn't match yText, yTarget spans multiple nodes\");\n }\n\n const yTarget = targetDelta[0]?.insert;\n if (childPath.length > 0) {\n if (!(yTarget instanceof Y.XmlText)) {\n throw new Error(\n \"Path doesn't match yText, cannot descent into non-yText\"\n );\n }\n\n return getYTarget(yTarget, targetNode, childPath);\n }\n\n return {\n yParent: yRoot,\n textRange: { start: yOffset, end: yOffset + targetLength },\n yTarget: yTarget instanceof Y.XmlText ? yTarget : undefined,\n slateParent: slateRoot,\n slateTarget: targetNode,\n targetDelta,\n };\n}\n\nexport function yOffsetToSlateOffsets(\n parent: Element,\n yOffset: number,\n opts: { assoc?: number; insert?: boolean } = {}\n): [number, number] {\n const { assoc = 0, insert = false } = opts;\n\n let currentOffset = 0;\n let lastNonEmptyPathOffset = 0;\n for (let pathOffset = 0; pathOffset < parent.children.length; pathOffset++) {\n const child = parent.children[pathOffset];\n const nodeLength = Text.isText(child) ? child.text.length : 1;\n\n if (nodeLength > 0) {\n lastNonEmptyPathOffset = pathOffset;\n }\n\n const endOffset = currentOffset + nodeLength;\n if (\n nodeLength > 0 &&\n (assoc >= 0 ? endOffset > yOffset : endOffset >= yOffset)\n ) {\n return [pathOffset, yOffset - currentOffset];\n }\n\n currentOffset += nodeLength;\n }\n\n if (yOffset > currentOffset + (insert ? 1 : 0)) {\n throw new Error('yOffset out of bounds');\n }\n\n if (insert) {\n return [parent.children.length, 0];\n }\n\n const child = parent.children[lastNonEmptyPathOffset];\n const textOffset = Text.isText(child) ? child.text.length : 1;\n return [lastNonEmptyPathOffset, textOffset];\n}\n\nexport function getSlatePath(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n yText: Y.XmlText\n): Path {\n const yNodePath = [yText];\n while (yNodePath[0] !== sharedRoot) {\n const { parent: yParent } = yNodePath[0];\n\n if (!yParent) {\n throw new Error(\"yText isn't a descendant of root element\");\n }\n\n if (!(yParent instanceof Y.XmlText)) {\n throw new Error('Unexpected y parent type');\n }\n\n yNodePath.unshift(yParent);\n }\n\n if (yNodePath.length < 2) {\n return [];\n }\n\n let slateParent = slateRoot;\n return yNodePath.reduce<Path>((path, yParent, idx) => {\n const yChild = yNodePath[idx + 1];\n if (!yChild) {\n return path;\n }\n\n let yOffset = 0;\n const currentDelta = yTextToInsertDelta(yParent);\n for (const element of currentDelta) {\n if (element.insert === yChild) {\n break;\n }\n\n yOffset += typeof element.insert === 'string' ? element.insert.length : 1;\n }\n\n if (Text.isText(slateParent)) {\n throw new Error('Cannot descent into slate text');\n }\n\n const [pathOffset] = yOffsetToSlateOffsets(slateParent, yOffset);\n slateParent = slateParent.children[pathOffset];\n return path.concat(pathOffset);\n }, []);\n}\n","import * as Y from 'yjs';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function assertDocumentAttachment<T extends Y.AbstractType<any>>(\n sharedType: T\n): asserts sharedType is T & { doc: NonNullable<T['doc']> } {\n if (!sharedType.doc) {\n throw new Error(\"shared type isn't attached to a document\");\n }\n}\n","import { BasePoint, BaseRange, Node, Text } from 'slate';\nimport * as Y from 'yjs';\nimport { InsertDelta, RelativeRange, TextRange } from '../model/types';\nimport { getInsertDeltaLength, yTextToInsertDelta } from './delta';\nimport { isSyncSkewError } from './errors';\nimport { getSlatePath, getYTarget, yOffsetToSlateOffsets } from './location';\nimport { assertDocumentAttachment } from './yjs';\n\nexport const STORED_POSITION_PREFIX = '__slateYjsStoredPosition_';\n\nexport function slatePointToRelativePosition(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n point: BasePoint\n): Y.RelativePosition {\n const { yTarget, yParent, textRange } = getYTarget(\n sharedRoot,\n slateRoot,\n point.path\n );\n\n if (yTarget) {\n throw new Error(\n 'Slate point points to a non-text element inside sharedRoot'\n );\n }\n\n const index = textRange.start + point.offset;\n return Y.createRelativePositionFromTypeIndex(\n yParent,\n index,\n index === textRange.end ? -1 : 0\n );\n}\n\nexport function absolutePositionToSlatePoint(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n { type, index, assoc }: Y.AbsolutePosition\n): BasePoint | null {\n if (!(type instanceof Y.XmlText)) {\n throw new Error('Absolute position points to a non-XMLText');\n }\n\n try {\n const parentPath = getSlatePath(sharedRoot, slateRoot, type);\n const parent = Node.get(slateRoot, parentPath);\n\n if (Text.isText(parent)) {\n return null;\n }\n\n const [pathOffset, textOffset] = yOffsetToSlateOffsets(parent, index, {\n assoc,\n });\n\n const target = parent.children[pathOffset];\n if (!Text.isText(target)) {\n return null;\n }\n\n return { path: [...parentPath, pathOffset], offset: textOffset };\n } catch (error) {\n if (isSyncSkewError(error)) {\n return null;\n }\n throw error;\n }\n}\n\nexport function relativePositionToSlatePoint(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n pos: Y.RelativePosition\n): BasePoint | null {\n if (!sharedRoot.doc) {\n throw new Error(\"sharedRoot isn't attach to a yDoc\");\n }\n\n const absPos = Y.createAbsolutePositionFromRelativePosition(\n pos,\n sharedRoot.doc\n );\n\n return absPos && absolutePositionToSlatePoint(sharedRoot, slateRoot, absPos);\n}\n\nexport function getStoredPosition(\n sharedRoot: Y.XmlText,\n key: string\n): Y.RelativePosition | null {\n const rawPosition = sharedRoot.getAttribute(STORED_POSITION_PREFIX + key);\n if (!rawPosition) {\n return null;\n }\n\n return Y.decodeRelativePosition(rawPosition);\n}\n\nexport function getStoredPositions(\n sharedRoot: Y.XmlText\n): Record<string, Y.RelativePosition> {\n return Object.fromEntries(\n Object.entries(sharedRoot.getAttributes())\n .filter(([key]) => key.startsWith(STORED_POSITION_PREFIX))\n .map(([key, position]) => [\n key.slice(STORED_POSITION_PREFIX.length),\n Y.createRelativePositionFromJSON(position),\n ])\n );\n}\n\nfunction getStoredPositionsAbsolute(sharedRoot: Y.XmlText) {\n assertDocumentAttachment(sharedRoot);\n\n return Object.fromEntries(\n Object.entries(sharedRoot.getAttributes())\n .filter(([key]) => key.startsWith(STORED_POSITION_PREFIX))\n .map(\n ([key, position]) =>\n [\n key.slice(STORED_POSITION_PREFIX.length),\n Y.createAbsolutePositionFromRelativePosition(\n Y.decodeRelativePosition(position),\n sharedRoot.doc\n ),\n ] as const\n )\n .filter(([, position]) => position)\n ) as Record<string, Y.AbsolutePosition>;\n}\n\nexport function removeStoredPosition(sharedRoot: Y.XmlText, key: string) {\n sharedRoot.removeAttribute(STORED_POSITION_PREFIX + key);\n}\n\nexport function setStoredPosition(\n sharedRoot: Y.XmlText,\n key: string,\n position: Y.RelativePosition\n) {\n sharedRoot.setAttribute(\n STORED_POSITION_PREFIX + key,\n Y.encodeRelativePosition(position)\n );\n}\n\nfunction getAbsolutePositionsInTextRange(\n absolutePositions: Record<string, Y.AbsolutePosition>,\n yTarget: Y.XmlText,\n textRange?: TextRange\n) {\n return Object.fromEntries(\n Object.entries(absolutePositions).filter(([, position]) => {\n if (position.type !== yTarget) {\n return false;\n }\n\n if (!textRange) {\n return true;\n }\n\n return position.assoc >= 0\n ? position.index >= textRange.start && position.index < textRange.end\n : position.index > textRange.start && position.index >= textRange.end;\n })\n );\n}\n\nfunction getAbsolutePositionsInYText(\n absolutePositions: Record<string, Y.AbsolutePosition>,\n yText: Y.XmlText,\n parentPath = ''\n): Record<string, Record<string, Y.AbsolutePosition>> {\n const positions = {\n [parentPath]: getAbsolutePositionsInTextRange(absolutePositions, yText),\n };\n\n const insertDelta = yTextToInsertDelta(yText);\n insertDelta.forEach(({ insert }, i) => {\n if (insert instanceof Y.XmlText) {\n Object.assign(\n positions,\n getAbsolutePositionsInYText(\n absolutePositions,\n insert,\n parentPath ? `${parentPath}.${i}` : i.toString()\n )\n );\n }\n });\n\n return positions;\n}\n\nexport function getStoredPositionsInDeltaAbsolute(\n sharedRoot: Y.XmlText,\n yText: Y.XmlText,\n delta: InsertDelta,\n deltaOffset = 0\n) {\n const absolutePositions = getStoredPositionsAbsolute(sharedRoot);\n\n const positions = {\n '': getAbsolutePositionsInTextRange(absolutePositions, yText, {\n start: deltaOffset,\n end: deltaOffset + getInsertDeltaLength(delta),\n }),\n };\n\n delta.forEach(({ insert }, i) => {\n if (insert instanceof Y.XmlText) {\n Object.assign(\n positions,\n getAbsolutePositionsInYText(absolutePositions, insert, i.toString())\n );\n }\n });\n\n return positions;\n}\n\nexport function restoreStoredPositionsWithDeltaAbsolute(\n sharedRoot: Y.XmlText,\n yText: Y.XmlText,\n absolutePositions: Record<string, Record<string, Y.AbsolutePosition>>,\n delta: InsertDelta,\n newDeltaOffset = 0,\n previousDeltaOffset = 0,\n path = ''\n) {\n const toRestore = absolutePositions[path];\n\n if (toRestore) {\n Object.entries(toRestore).forEach(([key, position]) => {\n setStoredPosition(\n sharedRoot,\n key,\n Y.createRelativePositionFromTypeIndex(\n yText,\n position.index - previousDeltaOffset + newDeltaOffset,\n position.assoc\n )\n );\n });\n }\n\n delta.forEach(({ insert }, i) => {\n if (insert instanceof Y.XmlText) {\n restoreStoredPositionsWithDeltaAbsolute(\n sharedRoot,\n insert,\n absolutePositions,\n yTextToInsertDelta(insert),\n 0,\n 0,\n path ? `${path}.${i}` : i.toString()\n );\n }\n });\n}\n\nexport function slateRangeToRelativeRange(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n range: BaseRange\n): RelativeRange {\n return {\n anchor: slatePointToRelativePosition(sharedRoot, slateRoot, range.anchor),\n focus: slatePointToRelativePosition(sharedRoot, slateRoot, range.focus),\n };\n}\n\nexport function relativeRangeToSlateRange(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n range: RelativeRange\n): BaseRange | null {\n const anchor = relativePositionToSlatePoint(\n sharedRoot,\n slateRoot,\n range.anchor\n );\n\n if (!anchor) {\n return null;\n }\n\n const focus = relativePositionToSlatePoint(\n sharedRoot,\n slateRoot,\n range.focus\n );\n\n if (!focus) {\n return null;\n }\n\n return { anchor, focus };\n}\n","import { Editor, Element, Node, Operation, Path, Text } from 'slate';\nimport * as Y from 'yjs';\nimport { Delta } from '../model/types';\nimport { deltaInsertToSlateNode } from '../utils/convert';\nimport {\n getSlateNodeYLength,\n getSlatePath,\n yOffsetToSlateOffsets,\n} from '../utils/location';\nimport { deepEquals, omitNullEntries, pick } from '../utils/object';\nimport { getProperties } from '../utils/slate';\n\nfunction applyDelta(node: Element, slatePath: Path, delta: Delta): Operation[] {\n const ops: Operation[] = [];\n\n let yOffset = delta.reduce((length, change) => {\n if ('retain' in change) {\n return length + change.retain;\n }\n\n if ('delete' in change) {\n return length + change.delete;\n }\n\n return length;\n }, 0);\n\n // Apply changes in reverse order to avoid path changes.\n delta.reverse().forEach((change) => {\n if ('attributes' in change && 'retain' in change) {\n const [startPathOffset, startTextOffset] = yOffsetToSlateOffsets(\n node,\n yOffset - change.retain\n );\n const [endPathOffset, endTextOffset] = yOffsetToSlateOffsets(\n node,\n yOffset,\n { assoc: -1 }\n );\n\n for (\n let pathOffset = endPathOffset;\n pathOffset >= startPathOffset;\n pathOffset--\n ) {\n const child = node.children[pathOffset];\n const childPath = [...slatePath, pathOffset];\n\n if (!Text.isText(child)) {\n // Ignore attribute updates on non-text nodes (which are backed by Y.XmlText)\n // to be consistent with deltaInsertToSlateNode. Y.XmlText attributes don't show\n // up in deltas but in key changes (YEvent.changes.keys).\n continue;\n }\n\n const newProperties = change.attributes;\n const properties = pick(\n node,\n ...(Object.keys(change.attributes) as Array<keyof Element>)\n );\n\n if (pathOffset === startPathOffset || pathOffset === endPathOffset) {\n const start = pathOffset === startPathOffset ? startTextOffset : 0;\n const end =\n pathOffset === endPathOffset ? endTextOffset : child.text.length;\n\n if (end !== child.text.length) {\n ops.push({\n type: 'split_node',\n path: childPath,\n position: end,\n properties: getProperties(child),\n });\n }\n\n if (start !== 0) {\n ops.push({\n type: 'split_node',\n path: childPath,\n position: start,\n properties: omitNullEntries({\n ...getProperties(child),\n ...newProperties,\n }),\n });\n\n continue;\n }\n }\n\n ops.push({\n type: 'set_node',\n newProperties,\n path: childPath,\n properties,\n });\n }\n }\n\n if ('retain' in change) {\n yOffset -= change.retain;\n }\n\n if ('delete' in change) {\n const [startPathOffset, startTextOffset] = yOffsetToSlateOffsets(\n node,\n yOffset - change.delete\n );\n const [endPathOffset, endTextOffset] = yOffsetToSlateOffsets(\n node,\n yOffset,\n { assoc: -1 }\n );\n\n for (\n let pathOffset =\n endTextOffset === 0 ? endPathOffset - 1 : endPathOffset;\n pathOffset >= startPathOffset;\n pathOffset--\n ) {\n const child = node.children[pathOffset];\n const childPath = [...slatePath, pathOffset];\n\n if (\n Text.isText(child) &&\n (pathOffset === startPathOffset || pathOffset === endPathOffset)\n ) {\n const start = pathOffset === startPathOffset ? startTextOffset : 0;\n const end =\n pathOffset === endPathOffset ? endTextOffset : child.text.length;\n\n ops.push({\n type: 'remove_text',\n offset: start,\n text: child.text.slice(start, end),\n path: childPath,\n });\n\n yOffset -= end - start;\n continue;\n }\n\n ops.push({\n type: 'remove_node',\n node: child,\n path: childPath,\n });\n yOffset -= getSlateNodeYLength(child);\n }\n\n return;\n }\n\n if ('insert' in change) {\n const [pathOffset, textOffset] = yOffsetToSlateOffsets(node, yOffset, {\n insert: true,\n });\n const child = node.children[pathOffset];\n const childPath = [...slatePath, pathOffset];\n\n if (Text.isText(child)) {\n const lastOp = ops[ops.length - 1];\n\n /**\n * The props that exist at the current path\n * Since we're not actually using slate to update the node\n * this is a simulation\n */\n const currentProps =\n lastOp != null && lastOp.type === 'insert_node'\n ? lastOp.node\n : getProperties(child);\n\n let lastPath: Path = [];\n\n if (\n lastOp != null &&\n (lastOp.type === 'insert_node' ||\n lastOp.type === 'insert_text' ||\n lastOp.type === 'split_node' ||\n lastOp.type === 'set_node')\n ) {\n lastPath = lastOp.path;\n }\n\n /**\n * If the insert is a string and the attributes are the same as the\n * props at the current path, we can just insert a text node\n */\n if (\n typeof change.insert === 'string' &&\n deepEquals(change.attributes ?? {}, currentProps) &&\n Path.equals(childPath, lastPath)\n ) {\n return ops.push({\n type: 'insert_text',\n offset: textOffset,\n text: change.insert,\n path: childPath,\n });\n }\n\n const toInsert = deltaInsertToSlateNode(change);\n if (textOffset === 0) {\n return ops.push({\n type: 'insert_node',\n path: childPath,\n node: toInsert,\n });\n }\n\n if (textOffset < child.text.length) {\n ops.push({\n type: 'split_node',\n path: childPath,\n position: textOffset,\n properties: getProperties(child),\n });\n }\n\n return ops.push({\n type: 'insert_node',\n path: Path.next(childPath),\n node: toInsert,\n });\n }\n\n return ops.push({\n type: 'insert_node',\n path: childPath,\n node: deltaInsertToSlateNode(change),\n });\n }\n });\n\n return ops;\n}\n\nexport function translateYTextEvent(\n sharedRoot: Y.XmlText,\n editor: Editor,\n event: Y.YTextEvent\n): Operation[] {\n const { target, changes } = event;\n const delta = event.delta as Delta;\n\n if (!(target instanceof Y.XmlText)) {\n throw new Error('Unexpected target node type');\n }\n\n const ops: Operation[] = [];\n const slatePath = getSlatePath(sharedRoot, editor, target);\n const targetElement = Node.get(editor, slatePath);\n\n if (Text.isText(targetElement)) {\n throw new Error('Cannot apply yTextEvent to text node');\n }\n\n const keyChanges = Array.from(changes.keys.entries());\n if (slatePath.length > 0 && keyChanges.length > 0) {\n const newProperties = Object.fromEntries(\n keyChanges.map(([key, info]) => [\n key,\n info.action === 'delete' ? null : target.getAttribute(key),\n ])\n );\n\n const properties = Object.fromEntries(\n keyChanges.map(([key]) => [key, targetElement[key]])\n );\n\n ops.push({ type: 'set_node', newProperties, properties, path: slatePath });\n }\n\n if (delta.length > 0) {\n ops.push(...applyDelta(targetElement, slatePath, delta));\n }\n\n return ops;\n}\n","import { Editor, Operation, Transforms } from 'slate';\nimport * as Y from 'yjs';\nimport { RelativeRange } from '../model/types';\nimport { yTextToSlateElement } from '../utils/convert';\nimport { isSyncSkewError } from '../utils/errors';\nimport {\n relativeRangeToSlateRange,\n slateRangeToRelativeRange,\n} from '../utils/position';\nimport { translateYTextEvent } from './textEvent';\n\nlet lastResyncTime = 0;\nconst RESYNC_THROTTLE_MS = 1000;\n\n/**\n * Translate a yjs event into slate operations. The editor state has to match the\n * yText state before the event occurred.\n *\n * @param sharedType\n * @param op\n */\nexport function translateYjsEvent(\n sharedRoot: Y.XmlText,\n editor: Editor,\n event: Y.YEvent<Y.XmlText>\n): Operation[] {\n if (event instanceof Y.YTextEvent) {\n return translateYTextEvent(sharedRoot, editor, event);\n }\n\n throw new Error('Unexpected Y event type');\n}\n\n/**\n * Performs a full re-sync of the Slate editor from the Yjs shared root.\n * Preserves the user's selection if possible by converting to/from relative positions.\n */\nfunction resyncFromYjs(sharedRoot: Y.XmlText, editor: Editor): void {\n let savedSelection: RelativeRange | null = null;\n\n try {\n if (editor.selection) {\n savedSelection = slateRangeToRelativeRange(\n sharedRoot,\n editor,\n editor.selection\n );\n }\n } catch {\n // Selection conversion failed; we'll lose the selection but continue with re-sync\n }\n\n const content = yTextToSlateElement(sharedRoot);\n editor.children = content.children;\n Editor.normalize(editor, { force: true });\n\n if (savedSelection) {\n try {\n const newSelection = relativeRangeToSlateRange(\n sharedRoot,\n editor,\n savedSelection\n );\n if (newSelection) {\n Transforms.select(editor, newSelection);\n }\n } catch {\n // Selection restoration failed; cursor position is lost but document is correct\n }\n }\n}\n\n/**\n * Translates yjs events into slate operations and applies them to the editor. The\n * editor state has to match the yText state before the events occurred.\n *\n * If a sync-skew error occurs (e.g. invalid path due to Yjs/Slate mismatch),\n * the editor is re-synced from the Yjs shared root to recover gracefully.\n *\n * @param sharedRoot\n * @param editor\n * @param events\n */\nexport function applyYjsEvents(\n sharedRoot: Y.XmlText,\n editor: Editor,\n events: Y.YEvent<Y.XmlText>[]\n) {\n Editor.withoutNormalizing(editor, () => {\n for (const event of events) {\n try {\n const ops = translateYjsEvent(sharedRoot, editor, event);\n for (const op of ops) {\n editor.apply(op);\n }\n } catch (error) {\n if (isSyncSkewError(error)) {\n const now = Date.now();\n if (now - lastResyncTime >= RESYNC_THROTTLE_MS) {\n lastResyncTime = now;\n console.warn(\n '[slate-yjs] Sync skew detected, re-syncing from Yjs:',\n error instanceof Error ? error.message : error\n );\n resyncFromYjs(sharedRoot, editor);\n } else {\n console.warn(\n '[slate-yjs] Sync skew detected (throttled, skipping re-sync):',\n error instanceof Error ? error.message : error\n );\n }\n return;\n }\n throw error;\n }\n }\n });\n}\n","import { InsertNodeOperation, Node, Text } from 'slate';\nimport * as Y from 'yjs';\nimport { slateElementToYText } from '../../utils/convert';\nimport { getYTarget } from '../../utils/location';\nimport { getProperties } from '../../utils/slate';\n\nexport function insertNode(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n op: InsertNodeOperation\n): void {\n const { yParent, textRange } = getYTarget(sharedRoot, slateRoot, op.path);\n\n if (Text.isText(op.node)) {\n return yParent.insert(\n textRange.start,\n op.node.text,\n getProperties(op.node)\n );\n }\n\n yParent.insertEmbed(textRange.start, slateElementToYText(op.node));\n}\n","import * as Y from 'yjs';\nimport { InsertDelta } from '../model/types';\nimport { yTextToInsertDelta } from './delta';\n\nexport function cloneInsertDeltaDeep(delta: InsertDelta): InsertDelta {\n return delta.map((element) => {\n if (typeof element.insert === 'string') {\n return element;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return { ...element, insert: cloneDeep(element.insert) };\n });\n}\n\nexport function cloneDeep(yText: Y.XmlText): Y.XmlText {\n const clone = new Y.XmlText();\n\n const attributes = yText.getAttributes();\n Object.entries(attributes).forEach(([key, value]) => {\n clone.setAttribute(key, value);\n });\n\n clone.applyDelta(cloneInsertDeltaDeep(yTextToInsertDelta(yText)), {\n sanitize: false,\n });\n\n return clone;\n}\n","import { MergeNodeOperation, Node, Path, Text } from 'slate';\nimport * as Y from 'yjs';\nimport { Delta } from '../../model/types';\nimport { cloneInsertDeltaDeep } from '../../utils/clone';\nimport { yTextToInsertDelta } from '../../utils/delta';\nimport { getYTarget } from '../../utils/location';\nimport {\n getStoredPositionsInDeltaAbsolute,\n restoreStoredPositionsWithDeltaAbsolute,\n} from '../../utils/position';\nimport { getProperties } from '../../utils/slate';\n\nexport function mergeNode(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n op: MergeNodeOperation\n): void {\n const target = getYTarget(sharedRoot, slateRoot, op.path);\n const prev = getYTarget(\n target.yParent,\n target.slateParent,\n Path.previous(op.path.slice(-1))\n );\n\n if (!target.yTarget !== !prev.yTarget) {\n throw new Error('Cannot merge y text with y element');\n }\n\n if (!prev.yTarget || !target.yTarget) {\n const { yParent: parent, textRange, slateTarget } = target;\n if (!slateTarget) {\n throw new Error('Expected Slate target node for merge op.');\n }\n\n const prevSibling = Node.get(slateRoot, Path.previous(op.path));\n if (!Text.isText(prevSibling)) {\n throw new Error('Path points to Y.Text but not a Slate text node.');\n }\n\n const targetProps = getProperties(slateTarget);\n const prevSiblingProps = getProperties(prevSibling);\n const unsetProps = Object.keys(targetProps).reduce((acc, key) => {\n const prevSiblingHasProp = key in prevSiblingProps;\n return prevSiblingHasProp ? acc : { ...acc, [key]: null };\n }, {});\n\n return parent.format(textRange.start, textRange.end - textRange.start, {\n ...unsetProps,\n ...prevSiblingProps,\n });\n }\n\n const deltaApplyYOffset = prev.yTarget.length;\n const targetDelta = yTextToInsertDelta(target.yTarget);\n const clonedDelta = cloneInsertDeltaDeep(targetDelta);\n\n const storedPositions = getStoredPositionsInDeltaAbsolute(\n sharedRoot,\n target.yTarget,\n targetDelta,\n deltaApplyYOffset\n );\n\n const applyDelta: Delta = [{ retain: deltaApplyYOffset }, ...clonedDelta];\n\n prev.yTarget.applyDelta(applyDelta, {\n sanitize: false,\n });\n\n target.yParent.delete(\n target.textRange.start,\n target.textRange.end - target.textRange.start\n );\n\n restoreStoredPositionsWithDeltaAbsolute(\n sharedRoot,\n prev.yTarget,\n storedPositions,\n clonedDelta,\n deltaApplyYOffset\n );\n}\n","import { MoveNodeOperation, Node, Path, Text } from 'slate';\nimport * as Y from 'yjs';\nimport { Delta } from '../../model/types';\nimport { cloneInsertDeltaDeep } from '../../utils/clone';\nimport { getInsertDeltaLength, yTextToInsertDelta } from '../../utils/delta';\nimport { getYTarget } from '../../utils/location';\nimport {\n getStoredPositionsInDeltaAbsolute,\n restoreStoredPositionsWithDeltaAbsolute,\n} from '../../utils/position';\n\nexport function moveNode(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n op: MoveNodeOperation\n): void {\n const newParentPath = Path.parent(op.newPath);\n const newPathOffset = op.newPath[op.newPath.length - 1];\n const parent = Node.get(slateRoot, newParentPath);\n if (Text.isText(parent)) {\n throw new Error('Cannot move slate node into text element');\n }\n const normalizedNewPath = [\n ...newParentPath,\n Math.min(newPathOffset, parent.children.length),\n ];\n\n const origin = getYTarget(sharedRoot, slateRoot, op.path);\n const target = getYTarget(sharedRoot, slateRoot, normalizedNewPath);\n const insertDelta = cloneInsertDeltaDeep(origin.targetDelta);\n\n const storedPositions = getStoredPositionsInDeltaAbsolute(\n sharedRoot,\n origin.yParent,\n origin.targetDelta\n );\n\n origin.yParent.delete(\n origin.textRange.start,\n origin.textRange.end - origin.textRange.start\n );\n\n const targetLength = getInsertDeltaLength(yTextToInsertDelta(target.yParent));\n const deltaApplyYOffset = Math.min(target.textRange.start, targetLength);\n const applyDelta: Delta = [{ retain: deltaApplyYOffset }, ...insertDelta];\n\n target.yParent.applyDelta(applyDelta, { sanitize: false });\n\n restoreStoredPositionsWithDeltaAbsolute(\n sharedRoot,\n target.yParent,\n storedPositions,\n insertDelta,\n deltaApplyYOffset,\n origin.textRange.start\n );\n}\n","import { Node, RemoveNodeOperation } from 'slate';\nimport * as Y from 'yjs';\nimport { getYTarget } from '../../utils/location';\n\nexport function removeNode(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n op: RemoveNodeOperation\n): void {\n const { yParent: parent, textRange } = getYTarget(\n sharedRoot,\n slateRoot,\n op.path\n );\n parent.delete(textRange.start, textRange.end - textRange.start);\n}\n","import { Node, SetNodeOperation } from 'slate';\nimport * as Y from 'yjs';\nimport { getYTarget } from '../../utils/location';\n\nexport function setNode(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n op: SetNodeOperation\n): void {\n const { yTarget, textRange, yParent } = getYTarget(\n sharedRoot,\n slateRoot,\n op.path\n );\n\n if (yTarget) {\n Object.entries(op.newProperties).forEach(([key, value]) => {\n if (value === null) {\n return yTarget.removeAttribute(key);\n }\n\n yTarget.setAttribute(key, value);\n });\n\n return Object.entries(op.properties).forEach(([key]) => {\n if (!op.newProperties.hasOwnProperty(key)) {\n yTarget.removeAttribute(key);\n }\n });\n }\n\n const unset = Object.fromEntries(\n Object.keys(op.properties).map((key) => [key, null])\n );\n const newProperties = { ...unset, ...op.newProperties };\n\n yParent.format(\n textRange.start,\n textRange.end - textRange.start,\n newProperties\n );\n}\n","import { Node, SplitNodeOperation, Text } from 'slate';\nimport * as Y from 'yjs';\nimport { cloneInsertDeltaDeep } from '../../utils/clone';\nimport { sliceInsertDelta, yTextToInsertDelta } from '../../utils/delta';\nimport { getSlateNodeYLength, getYTarget } from '../../utils/location';\nimport {\n getStoredPositionsInDeltaAbsolute,\n restoreStoredPositionsWithDeltaAbsolute,\n} from '../../utils/position';\n\nexport function splitNode(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n op: SplitNodeOperation\n): void {\n const target = getYTarget(sharedRoot, slateRoot, op.path);\n\n if (!target.slateTarget) {\n throw new Error('Y target without corresponding slate node');\n }\n\n if (!target.yTarget) {\n if (!Text.isText(target.slateTarget)) {\n throw new Error('Mismatch node type between y target and slate node');\n }\n\n const unset: Record<string, null> = {};\n target.targetDelta.forEach((element) => {\n if (element.attributes) {\n Object.keys(element.attributes).forEach((key) => {\n unset[key] = null;\n });\n }\n });\n\n return target.yParent.format(\n target.textRange.start,\n target.textRange.end - target.textRange.start,\n { ...unset, ...op.properties }\n );\n }\n\n if (Text.isText(target.slateTarget)) {\n throw new Error('Mismatch node type between y target and slate node');\n }\n\n const splitTarget = getYTarget(target.yTarget, target.slateTarget, [\n op.position,\n ]);\n\n const ySplitOffset = target.slateTarget.children\n .slice(0, op.position)\n .reduce((length, child) => length + getSlateNodeYLength(child), 0);\n\n const length = target.slateTarget.children.reduce(\n (current, child) => current + getSlateNodeYLength(child),\n 0\n );\n\n const splitDelta = sliceInsertDelta(\n yTextToInsertDelta(target.yTarget),\n ySplitOffset,\n length - ySplitOffset\n );\n const clonedDelta = cloneInsertDeltaDeep(splitDelta);\n\n const storedPositions = getStoredPositionsInDeltaAbsolute(\n sharedRoot,\n target.yTarget,\n splitDelta,\n ySplitOffset\n );\n\n const toInsert = new Y.XmlText();\n toInsert.applyDelta(clonedDelta, {\n sanitize: false,\n });\n\n Object.entries(op.properties).forEach(([key, value]) => {\n toInsert.setAttribute(key, value);\n });\n\n target.yTarget.delete(\n splitTarget.textRange.start,\n target.yTarget.length - splitTarget.textRange.start\n );\n\n target.yParent.insertEmbed(target.textRange.end, toInsert);\n\n restoreStoredPositionsWithDeltaAbsolute(\n sharedRoot,\n toInsert,\n storedPositions,\n clonedDelta,\n 0,\n ySplitOffset\n );\n}\n","import { NodeOperation } from 'slate';\nimport { OpMapper } from '../types';\nimport { insertNode } from './insertNode';\nimport { mergeNode } from './mergeNode';\nimport { moveNode } from './moveNode';\nimport { removeNode } from './removeNode';\nimport { setNode } from './setNode';\nimport { splitNode } from './splitNode';\n\nexport const NODE_MAPPER: OpMapper<NodeOperation> = {\n insert_node: insertNode,\n remove_node: removeNode,\n set_node: setNode,\n merge_node: mergeNode,\n move_node: moveNode,\n split_node: splitNode,\n};\n","import { InsertTextOperation, Node, Text } from 'slate';\nimport type Y from 'yjs';\nimport { getYTarget } from '../../utils/location';\nimport { getProperties } from '../../utils/slate';\n\nexport function insertText(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n op: InsertTextOperation\n): void {\n const { yParent: target, textRange } = getYTarget(\n sharedRoot,\n slateRoot,\n op.path\n );\n\n const targetNode = Node.get(slateRoot, op.path);\n if (!Text.isText(targetNode)) {\n throw new Error('Cannot insert text into non-text node');\n }\n\n target.insert(\n textRange.start + op.offset,\n op.text,\n getProperties(targetNode)\n );\n}\n","import { Node, RemoveTextOperation } from 'slate';\nimport type Y from 'yjs';\nimport { getYTarget } from '../../utils/location';\n\nexport function removeText(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n op: RemoveTextOperation\n): void {\n const { yParent: target, textRange } = getYTarget(\n sharedRoot,\n slateRoot,\n op.path\n );\n target.delete(textRange.start + op.offset, op.text.length);\n}\n","import { TextOperation } from 'slate';\nimport { OpMapper } from '../types';\nimport { insertText } from './insertText';\nimport { removeText } from './removeText';\n\nexport const TEXT_MAPPER: OpMapper<TextOperation> = {\n insert_text: insertText,\n remove_text: removeText,\n};\n","import { Node, Operation } from 'slate';\nimport * as Y from 'yjs';\nimport { NODE_MAPPER } from './node';\nimport { TEXT_MAPPER } from './text';\nimport { ApplyFunc, OpMapper } from './types';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nconst NOOP = () => {};\n\nconst opMappers: OpMapper = {\n ...TEXT_MAPPER,\n ...NODE_MAPPER,\n\n set_selection: NOOP,\n};\n\nexport function applySlateOp(\n sharedRoot: Y.XmlText,\n slateRoot: Node,\n op: Operation\n): void {\n const apply = opMappers[op.type] as ApplyFunc<typeof op>;\n if (!apply) {\n throw new Error(`Unknown operation: ${op.type}`);\n }\n\n apply(sharedRoot, slateRoot, op);\n}\n","import { BaseEditor, Descendant, Editor, Operation, Point } from 'slate';\nimport * as Y from 'yjs';\nimport { applyYjsEvents } from '../applyToSlate';\nimport { applySlateOp } from '../applyToYjs';\nimport { yTextToSlateElement } from '../utils/convert';\nimport {\n getStoredPosition,\n getStoredPositions,\n relativePositionToSlatePoint,\n removeStoredPosition,\n setStoredPosition,\n slatePointToRelativePosition,\n} from '../utils/position';\nimport { assertDocumentAttachment } from '../utils/yjs';\n\ntype LocalChange = {\n op: Operation;\n doc: Descendant[];\n origin: unknown;\n};\n\nconst DEFAULT_LOCAL_ORIGIN = Symbol('slate-yjs-operation');\nconst DEFAULT_POSITION_STORAGE_ORIGIN = Symbol('slate-yjs-position-storage');\n\nconst ORIGIN: WeakMap<Editor, unknown> = new WeakMap();\nconst LOCAL_CHANGES: WeakMap<Editor, LocalChange[]> = new WeakMap();\nconst CONNECTED: WeakSet<Editor> = new WeakSet();\n\nexport type YjsEditor = BaseEditor & {\n sharedRoot: Y.XmlText;\n\n localOrigin: unknown;\n positionStorageOrigin: unknown;\n\n applyRemoteEvents: (events: Y.YEvent<Y.XmlText>[], origin: unknown) => void;\n\n storeLocalChange: (op: Operation) => void;\n flushLocalChanges: () => void;\n\n isLocalOrigin: (origin: unknown) => boolean;\n\n connect: () => void;\n disconnect: () => void;\n};\n\nexport const YjsEditor = {\n isYjsEditor(value: unknown): value is YjsEditor {\n return (\n Editor.isEditor(value) &&\n (value as YjsEditor).sharedRoot instanceof Y.XmlText &&\n 'localOrigin' in value &&\n 'positionStorageOrigin' in value &&\n typeof (value as YjsEditor).applyRemoteEvents === 'function' &&\n typeof (value as YjsEditor).storeLocalChange === 'function' &&\n typeof (value as YjsEditor).flushLocalChanges === 'function' &&\n typeof (value as YjsEditor).isLocalOrigin === 'function' &&\n typeof (value as YjsEditor).connect === 'function' &&\n typeof (value as YjsEditor).disconnect === 'function'\n );\n },\n\n localChanges(editor: YjsEditor): LocalChange[] {\n return LOCAL_CHANGES.get(editor) ?? [];\n },\n\n applyRemoteEvents(\n editor: YjsEditor,\n events: Y.YEvent<Y.XmlText>[],\n origin: unknown\n ): void {\n editor.applyRemoteEvents(events, origin);\n },\n\n storeLocalChange(editor: YjsEditor, op: Operation): void {\n editor.storeLocalChange(op);\n },\n\n flushLocalChanges(editor: YjsEditor): void {\n editor.flushLocalChanges();\n },\n\n connected(editor: YjsEditor): boolean {\n return CONNECTED.has(editor);\n },\n\n connect(editor: YjsEditor): void {\n editor.connect();\n },\n\n disconnect(editor: YjsEditor): void {\n editor.disconnect();\n },\n\n isLocal(editor: YjsEditor): boolean {\n return editor.isLocalOrigin(YjsEditor.origin(editor));\n },\n\n origin(editor: YjsEditor): unknown {\n const origin = ORIGIN.get(editor);\n return origin !== undefined ? origin : editor.localOrigin;\n },\n\n withOrigin(editor: YjsEditor, origin: unknown, fn: () => void): void {\n const prev = YjsEditor.origin(editor);\n ORIGIN.set(editor, origin);\n fn();\n ORIGIN.set(editor, prev);\n },\n\n storePosition(editor: YjsEditor, key: string, point: Point): void {\n const { sharedRoot, positionStorageOrigin: locationStorageOrigin } = editor;\n assertDocumentAttachment(sharedRoot);\n\n const position = slatePointToRelativePosition(sharedRoot, editor, point);\n\n sharedRoot.doc.transact(() => {\n setStoredPosition(sharedRoot, key, position);\n }, locationStorageOrigin);\n },\n\n removeStoredPosition(editor: YjsEditor, key: string): void {\n const { sharedRoot, positionStorageOrigin: locationStorageOrigin } = editor;\n assertDocumentAttachment(sharedRoot);\n\n sharedRoot.doc.transact(() => {\n removeStoredPosition(sharedRoot, key);\n }, locationStorageOrigin);\n },\n\n position(editor: YjsEditor, key: string): Point | null | undefined {\n const position = getStoredPosition(editor.sharedRoot, key);\n if (!position) {\n return undefined;\n }\n\n return relativePositionToSlatePoint(editor.sharedRoot, editor, position);\n },\n\n storedPositionsRelative(\n editor: YjsEditor\n ): Record<string, Y.RelativePosition> {\n return getStoredPositions(editor.sharedRoot);\n },\n};\n\nexport type WithYjsOptions = {\n autoConnect?: boolean;\n\n // Origin used when applying local slate operations to yjs\n localOrigin?: unknown;\n\n // Origin used when storing positions\n positionStorageOrigin?: unknown;\n};\n\nexport function withYjs<T extends Editor>(\n editor: T,\n sharedRoot: Y.XmlText,\n {\n localOrigin,\n positionStorageOrigin,\n autoConnect = false,\n }: WithYjsOptions = {}\n): T & YjsEditor {\n const e = editor as T & YjsEditor;\n\n e.sharedRoot = sharedRoot;\n\n e.localOrigin = localOrigin ?? DEFAULT_LOCAL_ORIGIN;\n e.positionStorageOrigin =\n positionStorageOrigin ?? DEFAULT_POSITION_STORAGE_ORIGIN;\n\n e.applyRemoteEvents = (events, origin) => {\n YjsEditor.flushLocalChanges(e);\n\n Editor.withoutNormalizing(e, () => {\n YjsEditor.withOrigin(e, origin, () => {\n applyYjsEvents(e.sharedRoot, e, events);\n });\n });\n };\n\n e.isLocalOrigin = (origin) => origin === e.localOrigin;\n\n const handleYEvents = (\n events: Y.YEvent<Y.XmlText>[],\n transaction: Y.Transaction\n ) => {\n if (e.isLocalOrigin(transaction.origin)) {\n return;\n }\n\n YjsEditor.applyRemoteEvents(e, events, transaction.origin);\n };\n\n let autoConnectTimeoutId: ReturnType<typeof setTimeout> | null = null;\n if (autoConnect) {\n autoConnectTimeoutId = setTimeout(() => {\n autoConnectTimeoutId = null;\n YjsEditor.connect(e);\n });\n }\n\n e.connect = () => {\n if (YjsEditor.connected(e)) {\n throw new Error('already connected');\n }\n\n e.sharedRoot.observeDeep(handleYEvents);\n const content = yTextToSlateElement(e.sharedRoot);\n e.children = content.children;\n CONNECTED.add(e);\n\n Editor.normalize(editor, { force: true });\n if (!editor.operations.length) {\n editor.onChange();\n }\n };\n\n e.disconnect = () => {\n if (autoConnectTimeoutId) {\n clearTimeout(autoConnectTimeoutId);\n }\n\n YjsEditor.flushLocalChanges(e);\n e.sharedRoot.unobserveDeep(handleYEvents);\n CONNECTED.delete(e);\n };\n\n e.storeLocalChange = (op) => {\n LOCAL_CHANGES.set(e, [\n ...YjsEditor.localChanges(e),\n { op, doc: editor.children, origin: YjsEditor.origin(e) },\n ]);\n };\n\n e.flushLocalChanges = () => {\n assertDocumentAttachment(e.sharedRoot);\n const localChanges = YjsEditor.localChanges(e);\n LOCAL_CHANGES.delete(e);\n\n // Group local changes by origin so we can apply them in the correct order\n // with the correct origin with a minimal amount of transactions.\n const txGroups: LocalChange[][] = [];\n localChanges.forEach((change) => {\n const currentGroup = txGroups[txGroups.length - 1];\n if (currentGroup && currentGroup[0].origin === change.origin) {\n return currentGroup.push(change);\n }\n\n txGroups.push([change]);\n });\n\n txGroups.forEach((txGroup) => {\n assertDocumentAttachment(e.sharedRoot);\n\n e.sharedRoot.doc.transact(() => {\n txGroup.forEach((change) => {\n assertDocumentAttachment(e.sharedRoot);\n applySlateOp(e.sharedRoot, { children: change.doc }, change.op);\n });\n }, txGroup[0].origin);\n });\n };\n\n const { apply, onChange } = e;\n e.apply = (op) => {\n if (YjsEditor.connected(e) && YjsEditor.isLocal(e)) {\n YjsEditor.storeLocalChange(e, op);\n }\n\n apply(op);\n };\n\n e.onChange = () => {\n if (YjsEditor.connected(e)) {\n YjsEditor.flushLocalChanges(e);\n }\n\n onChange();\n };\n\n return e;\n}\n","import { Editor, Transforms } from 'slate';\nimport * as Y from 'yjs';\nimport { HistoryStackItem, RelativeRange } from '../model/types';\nimport {\n relativeRangeToSlateRange,\n slateRangeToRelativeRange,\n} from '../utils/position';\nimport { YjsEditor } from './withYjs';\n\nconst LAST_SELECTION: WeakMap<Editor, RelativeRange | null> = new WeakMap();\nconst DEFAULT_WITHOUT_SAVING_ORIGIN = Symbol(\n 'slate-yjs-history-without-saving'\n);\n\nexport type YHistoryEditor = YjsEditor & {\n undoManager: Y.UndoManager;\n\n withoutSavingOrigin: unknown;\n\n undo: () => void;\n redo: () => void;\n};\n\nexport const YHistoryEditor = {\n isYHistoryEditor(value: unknown): value is YHistoryEditor {\n return (\n YjsEditor.isYjsEditor(value) &&\n (value as YHistoryEditor).undoManager instanceof Y.UndoManager &&\n typeof (value as YHistoryEditor).undo === 'function' &&\n typeof (value as YHistoryEditor).redo === 'function' &&\n 'withoutSavingOrigin' in value\n );\n },\n\n canUndo(editor: YHistoryEditor) {\n return editor.undoManager.undoStack.length > 0;\n },\n\n canRedo(editor: YHistoryEditor) {\n return editor.undoManager.redoStack.length > 0;\n },\n\n isSaving(editor: YHistoryEditor): boolean {\n return editor.undoManager.trackedOrigins.has(YjsEditor.origin(editor));\n },\n\n withoutSaving(editor: YHistoryEditor, fn: () => void) {\n YjsEditor.withOrigin(editor, editor.withoutSavingOrigin, fn);\n },\n};\n\nexport type WithYHistoryOptions = NonNullable<\n ConstructorParameters<typeof Y.UndoManager>[1]\n> & {\n withoutSavingOrigin?: unknown;\n};\n\nexport function withYHistory<T extends YjsEditor>(\n editor: T,\n {\n withoutSavingOrigin = DEFAULT_WITHOUT_SAVING_ORIGIN,\n trackedOrigins = new Set([editor.localOrigin]),\n ...options\n }: WithYHistoryOptions = {}\n): T & YHistoryEditor {\n const e = editor as T & YHistoryEditor;\n\n const undoManager = new Y.UndoManager(e.sharedRoot, {\n trackedOrigins,\n ...options,\n });\n\n e.undoManager = undoManager;\n e.withoutSavingOrigin = withoutSavingOrigin;\n\n const { onChange, isLocalOrigin } = e;\n e.onChange = () => {\n onChange();\n\n LAST_SELECTION.set(\n e,\n e.selection && slateRangeToRelativeRange(e.sharedRoot, e, e.selection)\n );\n };\n\n e.isLocalOrigin = (origin) =>\n origin === e.withoutSavingOrigin || isLocalOrigin(origin);\n\n const handleStackItemAdded = ({\n stackItem,\n }: {\n stackItem: HistoryStackItem;\n type: 'redo' | 'undo';\n }) => {\n stackItem.meta.set(\n 'selection',\n e.selection && slateRangeToRelativeRange(e.sharedRoot, e, e.selection)\n );\n stackItem.meta.set('selectionBefore', LAST_SELECTION.get(e));\n };\n\n const handleStackItemUpdated = ({\n stackItem,\n }: {\n stackItem: HistoryStackItem;\n type: 'redo' | 'undo';\n }) => {\n stackItem.meta.set(\n 'selection',\n e.selection && slateRangeToRelativeRange(e.sharedRoot, e, e.selection)\n );\n };\n\n const handleStackItemPopped = ({\n stackItem,\n type,\n }: {\n stackItem: HistoryStackItem;\n type: 'redo' | 'undo';\n }) => {\n // TODO: Change once https://github.com/yjs/yjs/issues/353 is resolved\n const inverseStack =\n type === 'undo' ? e.undoManager.redoStack : e.undoManager.undoStack;\n const inverseItem = inverseStack[inverseStack.length - 1];\n if (inverseItem) {\n inverseItem.meta.set('selection', stackItem.meta.get('selectionBefore'));\n inverseItem.meta.set('selectionBefore', stackItem.meta.get('selection'));\n }\n\n const relativeSelection = stackItem.meta.get(\n 'selectionBefore'\n ) as RelativeRange | null;\n\n if (!relativeSelection) {\n return;\n }\n\n const selection = relativeRangeToSlateRange(\n e.sharedRoot,\n e,\n relativeSelection\n );\n\n if (!selection) {\n return;\n }\n\n Transforms.select(e, selection);\n };\n\n const { connect, disconnect } = e;\n e.connect = () => {\n connect();\n\n e.undoManager.on('stack-item-added', handleStackItemAdded);\n e.undoManager.on('stack-item-popped', handleStackItemPopped);\n e.undoManager.on('stack-item-updated', handleStackItemUpdated);\n };\n\n e.disconnect = () => {\n e.undoManager.off('stack-item-added', handleStackItemAdded);\n e.undoManager.off('stack-item-popped', handleStackItemPopped);\n e.undoManager.off('stack-item-updated', handleStackItemUpdated);\n\n disconnect();\n };\n\n e.undo = () => {\n if (YjsEditor.connected(e)) {\n YjsEditor.flushLocalChanges(e);\n e.undoManager.undo();\n }\n };\n\n e.redo = () => {\n if (YjsEditor.connected(e)) {\n YjsEditor.flushLocalChanges(e);\n e.undoManager.redo();\n }\n };\n\n return e;\n}\n","import { Editor, Range } from 'slate';\nimport { Awareness } from 'y-protocols/awareness';\nimport * as Y from 'yjs';\nimport { RelativeRange } from '../model/types';\nimport { slateRangeToRelativeRange } from '../utils/position';\nimport { YjsEditor } from './withYjs';\n\nexport type CursorStateChangeEvent = {\n added: number[];\n updated: number[];\n removed: number[];\n};\n\nexport type RemoteCursorChangeEventListener = (\n event: CursorStateChangeEvent\n) => void;\n\nconst CURSOR_CHANGE_EVENT_LISTENERS: WeakMap<\n Editor,\n Set<RemoteCursorChangeEventListener>\n> = new WeakMap();\n\nexport type CursorState<\n TCursorData extends Record<string, unknown> = Record<string, unknown>\n> = {\n relativeSelection: RelativeRange | null;\n data?: TCursorData;\n clientId: number;\n};\n\nexport type CursorEditor<\n TCursorData extends Record<string, unknown> = Record<string, unknown>\n> = YjsEditor & {\n awareness: Awareness;\n\n cursorDataField: string;\n selectionStateField: string;\n\n sendCursorPosition: (range: Range | null) => void;\n sendCursorData: (data: TCursorData) => void;\n};\n\nexport const CursorEditor = {\n isCursorEditor(value: unknown): value is CursorEditor {\n return (\n YjsEditor.isYjsEditor(value) &&\n (value as CursorEditor).awareness &&\n typeof (value as CursorEditor).cursorDataField === 'string' &&\n typeof (value as CursorEditor).selectionStateField === 'string' &&\n typeof (value as CursorEditor).sendCursorPosition === 'function' &&\n typeof (value as CursorEditor).sendCursorData === 'function'\n );\n },\n\n sendCursorPosition<TCursorData extends Record<string, unknown>>(\n editor: CursorEditor<TCursorData>,\n range: Range | null = editor.selection\n ) {\n editor.sendCursorPosition(range);\n },\n\n sendCursorData<TCursorData extends Record<string, unknown>>(\n editor: CursorEditor<TCursorData>,\n data: TCursorData\n ) {\n editor.sendCursorData(data);\n },\n\n on<TCursorData extends Record<string, unknown>>(\n editor: CursorEditor<TCursorData>,\n event: 'change',\n handler: RemoteCursorChangeEventListener\n ) {\n if (event !== 'change') {\n return;\n }\n\n const listeners = CURSOR_CHANGE_EVENT_LISTENERS.get(editor) ?? new Set();\n listeners.add(handler);\n CURSOR_CHANGE_EVENT_LISTENERS.set(editor, listeners);\n },\n\n off<TCursorData extends Record<string, unknown>>(\n editor: CursorEditor<TCursorData>,\n event: 'change',\n listener: RemoteCursorChangeEventListener\n ) {\n if (event !== 'change') {\n return;\n }\n\n const listeners = CURSOR_CHANGE_EVENT_LISTENERS.get(editor);\n if (listeners) {\n listeners.delete(listener);\n }\n },\n\n cursorState<TCursorData extends Record<string, unknown>>(\n editor: CursorEditor<TCursorData>,\n clientId: number\n ): CursorState<TCursorData> | null {\n if (\n clientId === editor.awareness.clientID ||\n !YjsEditor.connected(editor)\n ) {\n return null;\n }\n\n const state = editor.awareness.getStates().get(clientId);\n if (!state) {\n return null;\n }\n\n return {\n relativeSelection: state[editor.selectionStateField] ?? null,\n data: state[editor.cursorDataField],\n clientId,\n };\n },\n\n cursorStates<TCursorData extends Record<string, unknown>>(\n editor: CursorEditor<TCursorData>\n ): Record<string, CursorState<TCursorData>> {\n if (!YjsEditor.connected(editor)) {\n return {};\n }\n\n return Object.fromEntries(\n Array.from(editor.awareness.getStates().entries(), ([id, state]) => {\n // Ignore own state\n if (id === editor.awareness.clientID || !state) {\n return null;\n }\n\n return [\n id,\n {\n relativeSelection: state[editor.selectionStateField],\n data: state[editor.cursorDataField],\n },\n ];\n }).filter(Array.isArray)\n );\n },\n};\n\nexport type WithCursorsOptions<\n TCursorData extends Record<string, unknown> = Record<string, unknown>\n> = {\n // Local state field used to store the user selection\n cursorStateField?: string;\n\n // Local state field used to store data attached to the local client\n cursorDataField?: string;\n\n data?: TCursorData;\n autoSend?: boolean;\n};\n\nexport function withCursors<\n TCursorData extends Record<string, unknown>,\n TEditor extends YjsEditor\n>(\n editor: TEditor,\n awareness: Awareness,\n {\n cursorStateField: selectionStateField = 'selection',\n cursorDataField = 'data',\n autoSend = true,\n data,\n }: WithCursorsOptions<TCursorData> = {}\n): TEditor & CursorEditor<TCursorData> {\n const e = editor as TEditor & CursorEditor<TCursorData>;\n\n e.awareness = awareness;\n e.cursorDataField = cursorDataField;\n e.selectionStateField = selectionStateField;\n\n e.sendCursorData = (cursorData: TCursorData) => {\n e.awareness.setLocalStateField(e.cursorDataField, cursorData);\n };\n\n e.sendCursorPosition = (range) => {\n const localState = e.awareness.getLocalState();\n const currentRange = localState?.[selectionStateField];\n\n if (!range) {\n if (currentRange) {\n e.awareness.setLocalStateField(e.selectionStateField, null);\n }\n\n return;\n }\n\n const { anchor, focus } = slateRangeToRelativeRange(e.sharedRoot, e, range);\n\n if (\n !currentRange ||\n !Y.compareRelativePositions(anchor, currentRange) ||\n !Y.compareRelativePositions(focus, currentRange)\n ) {\n e.awareness.setLocalStateField(e.selectionStateField, { anchor, focus });\n }\n };\n\n const awarenessChangeListener: RemoteCursorChangeEventListener = (yEvent) => {\n const listeners = CURSOR_CHANGE_EVENT_LISTENERS.get(e);\n if (!listeners) {\n return;\n }\n\n const localId = e.awareness.clientID;\n const event = {\n added: yEvent.added.filter((id) => id !== localId),\n removed: yEvent.removed.filter((id) => id !== localId),\n updated: yEvent.updated.filter((id) => id !== localId),\n };\n\n if (\n event.added.length > 0 ||\n event.removed.length > 0 ||\n event.updated.length > 0\n ) {\n listeners.forEach((listener) => listener(event));\n }\n };\n\n const { connect, disconnect } = e;\n e.connect = () => {\n connect();\n\n e.awareness.on('change', awarenessChangeListener);\n\n awarenessChangeListener({\n removed: [],\n added: Array.from(e.awareness.getStates().keys()),\n updated: [],\n });\n\n if (autoSend) {\n if (data) {\n CursorEditor.sendCursorData(e, data);\n }\n\n const { onChange } = e;\n e.onChange = () => {\n onChange();\n\n if (YjsEditor.connected(e)) {\n CursorEditor.sendCursorPosition(e);\n }\n };\n }\n };\n\n e.disconnect = () => {\n e.awareness.off('change', awarenessChangeListener);\n\n awarenessChangeListener({\n removed: Array.from(e.awareness.getStates().keys()),\n added: [],\n updated: [],\n });\n\n disconnect();\n };\n\n return e;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,AAOA,oBAAkB,IAAG;AACnB,WAAO,OAAO,UAAU,SAAS,KAAK,EAAC,MAAM;AAAA,EAC/C;AAEA,yBAAuB,IAAG;AACxB,QAAI,MAAK;AAET,QAAI,SAAS,EAAC,MAAM;AAAO,aAAO;AAGlC,WAAO,GAAE;AACT,QAAI,SAAS;AAAW,aAAO;AAG/B,WAAO,KAAK;AACZ,QAAI,SAAS,IAAI,MAAM;AAAO,aAAO;AAGrC,QAAI,KAAK,eAAe,eAAe,MAAM,OAAO;AAClD,aAAO;AAAA,IACT;AAGA,WAAO;AAAA,EACT;;;aCaoB,IAAA;AAAA,aAAA,KAAA,UAAA,QAA+B,KAAA,MAAA,KAAA,IAAA,KAAA,IAAA,CAAA,GAAA,IAAA,GAAA,IAAA,IAAA;AAAA,SAAA,IAAA,KAAA,UAAA;AAAA,QAAA,MACrC;AAAA,UACN,KAAI,EAAO,KACX,KAAO,KAEG,AAAA,OAAN,MAAM,aACb,GAAE,MAAM,MAAM,EAAA,IACd,KAHA,uBAAuB;AAAA,YAIhB,MAAA,aAAiB,EAAA;IAAA;AAAA,UAElB,MAAA,gCACqB,KAC7B,IAAK,SAAS,MAAM,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