matrix-js-sdk 42.0.0 → 42.1.0

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 (226) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/lib/@types/PushRules.d.ts.map +1 -1
  3. package/lib/@types/PushRules.js +0 -5
  4. package/lib/@types/PushRules.js.map +1 -1
  5. package/lib/@types/auth.d.ts.map +1 -1
  6. package/lib/@types/auth.js +0 -5
  7. package/lib/@types/auth.js.map +1 -1
  8. package/lib/@types/crypto.d.ts.map +1 -1
  9. package/lib/@types/crypto.js.map +1 -1
  10. package/lib/@types/event.d.ts +3 -1
  11. package/lib/@types/event.d.ts.map +1 -1
  12. package/lib/@types/event.js +1 -0
  13. package/lib/@types/event.js.map +1 -1
  14. package/lib/@types/extensible_events.js.map +1 -1
  15. package/lib/@types/matrix-sdk-crypto-wasm.d.js.map +1 -1
  16. package/lib/@types/media.js.map +1 -1
  17. package/lib/@types/partials.d.ts.map +1 -1
  18. package/lib/@types/partials.js.map +1 -1
  19. package/lib/@types/requests.d.ts.map +1 -1
  20. package/lib/@types/requests.js +0 -5
  21. package/lib/@types/requests.js.map +1 -1
  22. package/lib/@types/search.d.ts.map +1 -1
  23. package/lib/@types/search.js +0 -3
  24. package/lib/@types/search.js.map +1 -1
  25. package/lib/@types/spaces.d.ts.map +1 -1
  26. package/lib/@types/spaces.js.map +1 -1
  27. package/lib/@types/synapse.d.ts.map +1 -1
  28. package/lib/@types/synapse.js.map +1 -1
  29. package/lib/@types/threepids.js.map +1 -1
  30. package/lib/ToDeviceMessageQueue.d.ts.map +1 -1
  31. package/lib/ToDeviceMessageQueue.js +0 -2
  32. package/lib/ToDeviceMessageQueue.js.map +1 -1
  33. package/lib/browser-index.d.ts.map +1 -1
  34. package/lib/browser-index.js +3 -1
  35. package/lib/browser-index.js.map +1 -1
  36. package/lib/client.d.ts +5 -8
  37. package/lib/client.d.ts.map +1 -1
  38. package/lib/client.js +5 -46
  39. package/lib/client.js.map +1 -1
  40. package/lib/common-crypto/key-passphrase.d.ts.map +1 -1
  41. package/lib/common-crypto/key-passphrase.js +0 -3
  42. package/lib/common-crypto/key-passphrase.js.map +1 -1
  43. package/lib/crypto/store/base.d.ts.map +1 -1
  44. package/lib/crypto/store/base.js +0 -9
  45. package/lib/crypto/store/base.js.map +1 -1
  46. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  47. package/lib/crypto/store/localStorage-crypto-store.d.ts.map +1 -1
  48. package/lib/crypto/store/localStorage-crypto-store.js +0 -2
  49. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
  50. package/lib/crypto-api/keybackup.d.ts +13 -6
  51. package/lib/crypto-api/keybackup.d.ts.map +1 -1
  52. package/lib/crypto-api/keybackup.js.map +1 -1
  53. package/lib/embedded.d.ts.map +1 -1
  54. package/lib/embedded.js +0 -5
  55. package/lib/embedded.js.map +1 -1
  56. package/lib/feature.d.ts.map +1 -1
  57. package/lib/feature.js +0 -3
  58. package/lib/feature.js.map +1 -1
  59. package/lib/filter-component.d.ts.map +1 -1
  60. package/lib/filter-component.js +2 -5
  61. package/lib/filter-component.js.map +1 -1
  62. package/lib/filter.d.ts.map +1 -1
  63. package/lib/filter.js +0 -4
  64. package/lib/filter.js.map +1 -1
  65. package/lib/http-api/interface.d.ts.map +1 -1
  66. package/lib/http-api/interface.js.map +1 -1
  67. package/lib/http-api/refresh.d.ts.map +1 -1
  68. package/lib/http-api/refresh.js +0 -3
  69. package/lib/http-api/refresh.js.map +1 -1
  70. package/lib/interactive-auth.d.ts.map +1 -1
  71. package/lib/interactive-auth.js +5 -6
  72. package/lib/interactive-auth.js.map +1 -1
  73. package/lib/logger.d.ts.map +1 -1
  74. package/lib/logger.js +0 -2
  75. package/lib/logger.js.map +1 -1
  76. package/lib/matrixrtc/CallMembership.d.ts +3 -3
  77. package/lib/matrixrtc/CallMembership.js +5 -5
  78. package/lib/matrixrtc/CallMembership.js.map +1 -1
  79. package/lib/matrixrtc/MatrixRTCSession.d.ts +18 -1
  80. package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
  81. package/lib/matrixrtc/MatrixRTCSession.js +56 -4
  82. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  83. package/lib/matrixrtc/MatrixRTCSessionManager.d.ts +14 -1
  84. package/lib/matrixrtc/MatrixRTCSessionManager.d.ts.map +1 -1
  85. package/lib/matrixrtc/MatrixRTCSessionManager.js +20 -1
  86. package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
  87. package/lib/matrixrtc/MembershipManager.d.ts.map +1 -1
  88. package/lib/matrixrtc/MembershipManager.js +9 -6
  89. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  90. package/lib/matrixrtc/index.d.ts +1 -1
  91. package/lib/matrixrtc/index.d.ts.map +1 -1
  92. package/lib/matrixrtc/index.js +1 -1
  93. package/lib/matrixrtc/index.js.map +1 -1
  94. package/lib/matrixrtc/membershipData/rtc.d.ts +6 -3
  95. package/lib/matrixrtc/membershipData/rtc.d.ts.map +1 -1
  96. package/lib/matrixrtc/membershipData/rtc.js +7 -4
  97. package/lib/matrixrtc/membershipData/rtc.js.map +1 -1
  98. package/lib/matrixrtc/types.d.ts +19 -6
  99. package/lib/matrixrtc/types.d.ts.map +1 -1
  100. package/lib/matrixrtc/types.js +11 -1
  101. package/lib/matrixrtc/types.js.map +1 -1
  102. package/lib/models/event.d.ts.map +1 -1
  103. package/lib/models/event.js +0 -6
  104. package/lib/models/event.js.map +1 -1
  105. package/lib/models/room-state.d.ts.map +1 -1
  106. package/lib/models/room-state.js.map +1 -1
  107. package/lib/models/room.d.ts.map +1 -1
  108. package/lib/models/room.js +6 -6
  109. package/lib/models/room.js.map +1 -1
  110. package/lib/models/thread.d.ts +2 -2
  111. package/lib/models/thread.d.ts.map +1 -1
  112. package/lib/models/thread.js.map +1 -1
  113. package/lib/realtime-callbacks.js +0 -1
  114. package/lib/realtime-callbacks.js.map +1 -1
  115. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts.map +1 -1
  116. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +0 -1
  117. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
  118. package/lib/rust-crypto/OutgoingRequestProcessor.d.ts.map +1 -1
  119. package/lib/rust-crypto/OutgoingRequestProcessor.js +0 -2
  120. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
  121. package/lib/rust-crypto/backup.d.ts +21 -1
  122. package/lib/rust-crypto/backup.d.ts.map +1 -1
  123. package/lib/rust-crypto/backup.js +62 -21
  124. package/lib/rust-crypto/backup.js.map +1 -1
  125. package/lib/rust-crypto/device-converter.d.ts.map +1 -1
  126. package/lib/rust-crypto/device-converter.js +1 -0
  127. package/lib/rust-crypto/device-converter.js.map +1 -1
  128. package/lib/rust-crypto/index.d.ts +7 -0
  129. package/lib/rust-crypto/index.d.ts.map +1 -1
  130. package/lib/rust-crypto/index.js +3 -3
  131. package/lib/rust-crypto/index.js.map +1 -1
  132. package/lib/rust-crypto/libolm_migration.d.ts.map +1 -1
  133. package/lib/rust-crypto/libolm_migration.js +0 -2
  134. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  135. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
  136. package/lib/rust-crypto/rust-crypto.js +0 -3
  137. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  138. package/lib/scheduler.d.ts.map +1 -1
  139. package/lib/scheduler.js +0 -3
  140. package/lib/scheduler.js.map +1 -1
  141. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  142. package/lib/sliding-sync-sdk.js +6 -0
  143. package/lib/sliding-sync-sdk.js.map +1 -1
  144. package/lib/sliding-sync.d.ts.map +1 -1
  145. package/lib/sliding-sync.js +3 -0
  146. package/lib/sliding-sync.js.map +1 -1
  147. package/lib/store/indexeddb.d.ts.map +1 -1
  148. package/lib/store/indexeddb.js +0 -2
  149. package/lib/store/indexeddb.js.map +1 -1
  150. package/lib/store/memory.d.ts.map +1 -1
  151. package/lib/store/memory.js +7 -9
  152. package/lib/store/memory.js.map +1 -1
  153. package/lib/sync-accumulator.d.ts.map +1 -1
  154. package/lib/sync-accumulator.js +1 -5
  155. package/lib/sync-accumulator.js.map +1 -1
  156. package/lib/sync.d.ts.map +1 -1
  157. package/lib/sync.js +1 -1
  158. package/lib/sync.js.map +1 -1
  159. package/lib/timeline-window.d.ts.map +1 -1
  160. package/lib/timeline-window.js +0 -1
  161. package/lib/timeline-window.js.map +1 -1
  162. package/lib/utils/internal/deriveKeys.d.ts.map +1 -1
  163. package/lib/utils/internal/deriveKeys.js +0 -1
  164. package/lib/utils/internal/deriveKeys.js.map +1 -1
  165. package/lib/webrtc/callEventTypes.d.ts.map +1 -1
  166. package/lib/webrtc/callEventTypes.js +0 -5
  167. package/lib/webrtc/callEventTypes.js.map +1 -1
  168. package/package.json +5 -5
  169. package/src/@types/PushRules.ts +0 -5
  170. package/src/@types/auth.ts +0 -6
  171. package/src/@types/crypto.ts +2 -6
  172. package/src/@types/event.ts +3 -0
  173. package/src/@types/extensible_events.ts +4 -4
  174. package/src/@types/matrix-sdk-crypto-wasm.d.ts +0 -1
  175. package/src/@types/media.ts +1 -1
  176. package/src/@types/partials.ts +0 -2
  177. package/src/@types/requests.ts +0 -5
  178. package/src/@types/search.ts +0 -2
  179. package/src/@types/spaces.ts +0 -2
  180. package/src/@types/synapse.ts +0 -2
  181. package/src/@types/threepids.ts +2 -2
  182. package/src/ToDeviceMessageQueue.ts +0 -2
  183. package/src/browser-index.ts +3 -3
  184. package/src/client.ts +18 -61
  185. package/src/common-crypto/key-passphrase.ts +0 -1
  186. package/src/crypto/store/base.ts +1 -8
  187. package/src/crypto/store/indexeddb-crypto-store-backend.ts +1 -1
  188. package/src/crypto/store/localStorage-crypto-store.ts +0 -1
  189. package/src/crypto-api/keybackup.ts +14 -7
  190. package/src/embedded.ts +0 -5
  191. package/src/feature.ts +0 -3
  192. package/src/filter-component.ts +1 -2
  193. package/src/filter.ts +0 -3
  194. package/src/http-api/interface.ts +0 -1
  195. package/src/http-api/refresh.ts +0 -1
  196. package/src/interactive-auth.ts +4 -4
  197. package/src/logger.ts +0 -2
  198. package/src/matrixrtc/CallMembership.ts +5 -5
  199. package/src/matrixrtc/MatrixRTCSession.ts +70 -3
  200. package/src/matrixrtc/MatrixRTCSessionManager.ts +21 -2
  201. package/src/matrixrtc/MembershipManager.ts +8 -5
  202. package/src/matrixrtc/index.ts +1 -1
  203. package/src/matrixrtc/membershipData/rtc.ts +18 -7
  204. package/src/matrixrtc/types.ts +24 -7
  205. package/src/models/event.ts +0 -3
  206. package/src/models/room-state.ts +0 -3
  207. package/src/models/room.ts +6 -6
  208. package/src/models/thread.ts +2 -2
  209. package/src/realtime-callbacks.ts +0 -1
  210. package/src/rendezvous/transports/MSC4108RendezvousSession.ts +0 -1
  211. package/src/rust-crypto/OutgoingRequestProcessor.ts +0 -1
  212. package/src/rust-crypto/backup.ts +66 -28
  213. package/src/rust-crypto/device-converter.ts +1 -0
  214. package/src/rust-crypto/index.ts +11 -0
  215. package/src/rust-crypto/libolm_migration.ts +0 -2
  216. package/src/rust-crypto/rust-crypto.ts +0 -3
  217. package/src/scheduler.ts +0 -3
  218. package/src/sliding-sync-sdk.ts +3 -0
  219. package/src/sliding-sync.ts +2 -0
  220. package/src/store/indexeddb.ts +0 -2
  221. package/src/store/memory.ts +7 -9
  222. package/src/sync-accumulator.ts +1 -3
  223. package/src/sync.ts +1 -3
  224. package/src/timeline-window.ts +0 -1
  225. package/src/utils/internal/deriveKeys.ts +0 -1
  226. package/src/webrtc/callEventTypes.ts +0 -5
@@ -1 +1 @@
1
- {"version":3,"file":"sliding-sync.js","names":[],"sources":["../src/sliding-sync.ts"],"sourcesContent":["/*\nCopyright 2022-2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"./logger.ts\";\nimport { type MatrixClient } from \"./client.ts\";\nimport { type IRoomEvent, type IStateEvent } from \"./sync-accumulator.ts\";\nimport { TypedEventEmitter } from \"./models/typed-event-emitter.ts\";\nimport { sleep } from \"./utils.ts\";\nimport { type HTTPError } from \"./http-api/index.ts\";\n\n// /sync requests allow you to set a timeout= but the request may continue\n// beyond that and wedge forever, so we need to track how long we are willing\n// to keep open the connection. This constant is *ADDED* to the timeout= value\n// to determine the max time we're willing to wait.\nconst BUFFER_PERIOD_MS = 10 * 1000;\n\nexport const MSC3575_WILDCARD = \"*\";\nexport const MSC3575_STATE_KEY_ME = \"$ME\";\nexport const MSC3575_STATE_KEY_LAZY = \"$LAZY\";\n\n/**\n * Represents a subscription to a room or set of rooms. Controls which events are returned.\n */\nexport interface MSC3575RoomSubscription {\n required_state?: string[][];\n timeline_limit?: number;\n include_old_rooms?: MSC3575RoomSubscription;\n}\n\n/**\n * Controls which rooms are returned in a given list.\n */\nexport interface MSC3575Filter {\n is_dm?: boolean;\n is_encrypted?: boolean;\n is_invite?: boolean;\n room_name_like?: string;\n room_types?: string[];\n not_room_types?: string[];\n spaces?: string[];\n tags?: string[];\n not_tags?: string[];\n}\n\n/**\n * Represents a list subscription.\n */\nexport interface MSC3575List extends MSC3575RoomSubscription {\n ranges: number[][];\n sort?: string[];\n filters?: MSC3575Filter;\n slow_get_all_rooms?: boolean;\n}\n\n/**\n * A complete Sliding Sync request.\n */\nexport interface MSC3575SlidingSyncRequest {\n // json body params\n lists?: Record<string, MSC3575List>;\n unsubscribe_rooms?: string[];\n room_subscriptions?: Record<string, MSC3575RoomSubscription>;\n extensions?: object;\n txn_id?: string;\n\n // query params\n pos?: string;\n timeout?: number;\n clientTimeout?: number;\n}\n\n/**\n * New format of hero introduced in MSC4186 with display name and avatar URL\n * in addition to just user_id (as it is on the wire, with underscores)\n * as opposed to Hero in room-summary.ts which has fields in camelCase\n * (and also a flag to note what format the hero came from).\n */\nexport interface MSC4186Hero {\n user_id: string;\n displayname?: string;\n avatar_url?: string;\n}\n\nexport interface MSC3575RoomData {\n name: string;\n required_state: IStateEvent[];\n timeline: (IRoomEvent | IStateEvent)[];\n heroes?: MSC4186Hero[];\n notification_count?: number;\n highlight_count?: number;\n joined_count?: number;\n invited_count?: number;\n invite_state?: IStateEvent[];\n initial?: boolean;\n limited?: boolean;\n is_dm?: boolean;\n prev_batch?: string;\n num_live?: number;\n bump_stamp?: number;\n}\n\ninterface ListResponse {\n count: number;\n}\n\n/**\n * A complete Sliding Sync response\n */\nexport interface MSC3575SlidingSyncResponse {\n pos: string;\n txn_id?: string;\n lists: Record<string, ListResponse>;\n rooms: Record<string, MSC3575RoomData>;\n extensions: Record<string, object>;\n}\n\nexport enum SlidingSyncState {\n /**\n * Fired by SlidingSyncEvent.Lifecycle event immediately before processing the response.\n */\n RequestFinished = \"FINISHED\",\n /**\n * Fired by SlidingSyncEvent.Lifecycle event immediately after all room data listeners have been\n * invoked, but before list listeners.\n */\n Complete = \"COMPLETE\",\n}\n\n/**\n * Internal Class. SlidingList represents a single list in sliding sync. The list can have filters,\n * multiple sliding windows, and maintains the index-\\>room_id mapping.\n */\nclass SlidingList {\n private list!: MSC3575List;\n private isModified?: boolean;\n\n // returned data\n public joinedCount = 0;\n\n /**\n * Construct a new sliding list.\n * @param list - The range, sort and filter values to use for this list.\n */\n public constructor(list: MSC3575List) {\n this.replaceList(list);\n }\n\n /**\n * Mark this list as modified or not. Modified lists will return sticky params with calls to getList.\n * This is useful for the first time the list is sent, or if the list has changed in some way.\n * @param modified - True to mark this list as modified so all sticky parameters will be re-sent.\n */\n public setModified(modified: boolean): void {\n this.isModified = modified;\n }\n\n /**\n * Update the list range for this list. Does not affect modified status as list ranges are non-sticky.\n * @param newRanges - The new ranges for the list\n */\n public updateListRange(newRanges: number[][]): void {\n this.list.ranges = JSON.parse(JSON.stringify(newRanges));\n }\n\n /**\n * Replace list parameters. All fields will be replaced with the new list parameters.\n * @param list - The new list parameters\n */\n public replaceList(list: MSC3575List): void {\n list.filters = list.filters ?? {};\n list.ranges = list.ranges ?? [];\n this.list = JSON.parse(JSON.stringify(list));\n this.isModified = true;\n\n // reset values as the join count may be very different (if filters changed) including the rooms\n // (e.g. sort orders or sliding window ranges changed)\n\n // the total number of joined rooms according to the server, always >= len(roomIndexToRoomId)\n this.joinedCount = 0;\n }\n\n /**\n * Return a copy of the list suitable for a request body.\n * @param forceIncludeAllParams - True to forcibly include all params even if the list\n * hasn't been modified. Callers may want to do this if they are modifying the list prior to calling\n * updateList.\n */\n public getList(forceIncludeAllParams: boolean): MSC3575List {\n let list = {\n ranges: JSON.parse(JSON.stringify(this.list.ranges)),\n };\n if (this.isModified || forceIncludeAllParams) {\n list = JSON.parse(JSON.stringify(this.list));\n }\n return list;\n }\n}\n\n/**\n * When onResponse extensions should be invoked: before or after processing the main response.\n */\nexport enum ExtensionState {\n // Call onResponse before processing the response body. This is useful when your extension is\n // preparing the ground for the response body e.g. processing to-device messages before the\n // encrypted event arrives.\n PreProcess = \"ExtState.PreProcess\",\n // Call onResponse after processing the response body. This is useful when your extension is\n // decorating data from the client, and you rely on MatrixClient.getRoom returning the Room object\n // e.g. room account data.\n PostProcess = \"ExtState.PostProcess\",\n}\n\n/**\n * An interface that must be satisfied to register extensions\n */\nexport interface Extension<Req extends object, Res extends object> {\n /**\n * The extension name to go under 'extensions' in the request body.\n * @returns The JSON key.\n */\n name(): string;\n /**\n * A function which is called when the request JSON is being formed.\n * Returns the data to insert under this key.\n * @param isInitial - True when this is part of the initial request.\n * @returns The request JSON to send.\n */\n onRequest(isInitial: boolean): Promise<Req>;\n /**\n * A function which is called when there is response JSON under this extension.\n * @param data - The response JSON under the extension name.\n */\n onResponse(data: Res): Promise<void>;\n /**\n * Controls when onResponse should be called.\n * @returns The state when it should be called.\n */\n when(): ExtensionState;\n}\n\n/**\n * Events which can be fired by the SlidingSync class. These are designed to provide different levels\n * of information when processing sync responses.\n * - RoomData: concerns rooms, useful for SlidingSyncSdk to update its knowledge of rooms.\n * - Lifecycle: concerns callbacks at various well-defined points in the sync process.\n * Specifically, the order of event invocation is:\n * - Lifecycle (state=RequestFinished)\n * - RoomData (N times)\n * - Lifecycle (state=Complete)\n */\nexport enum SlidingSyncEvent {\n /**\n * This event fires when there are updates for a room. Fired as and when rooms are encountered\n * in the response.\n */\n RoomData = \"SlidingSync.RoomData\",\n /**\n * This event fires at various points in the /sync loop lifecycle.\n * - SlidingSyncState.RequestFinished: Fires after we receive a valid response but before the\n * response has been processed. Perform any pre-process steps here. If there was a problem syncing,\n * `err` will be set (e.g network errors).\n * - SlidingSyncState.Complete: Fires after the response has been processed.\n */\n Lifecycle = \"SlidingSync.Lifecycle\",\n}\n\nexport type SlidingSyncEventHandlerMap = {\n [SlidingSyncEvent.RoomData]: (roomId: string, roomData: MSC3575RoomData) => Promise<void> | void;\n [SlidingSyncEvent.Lifecycle]: (\n state: SlidingSyncState,\n resp: MSC3575SlidingSyncResponse | null,\n err?: Error,\n ) => void;\n};\n\n/**\n * SlidingSync is a high-level data structure which controls the majority of sliding sync.\n * It has no hooks into JS SDK except for needing a MatrixClient to perform the HTTP request.\n * This means this class (and everything it uses) can be used in isolation from JS SDK if needed.\n * To hook this up with the JS SDK, you need to use SlidingSyncSdk.\n */\nexport class SlidingSync extends TypedEventEmitter<SlidingSyncEvent, SlidingSyncEventHandlerMap> {\n private lists: Map<string, SlidingList>;\n private listModifiedCount = 0;\n private terminated = false;\n // flag set when resend() is called because we cannot rely on detecting AbortError in JS SDK :(\n private needsResend = false;\n // map of extension name to req/resp handler\n private extensions: Record<string, Extension<any, any>> = {};\n\n private desiredRoomSubscriptions = new Set<string>(); // the *desired* room subscriptions\n private confirmedRoomSubscriptions = new Set<string>();\n\n // map of custom subscription name to the subscription\n private customSubscriptions: Map<string, MSC3575RoomSubscription> = new Map();\n // map of room ID to custom subscription name\n private roomIdToCustomSubscription: Map<string, string> = new Map();\n\n private pendingReq?: Promise<MSC3575SlidingSyncResponse>;\n private abortController?: AbortController;\n\n /**\n * Create a new sliding sync instance\n * @param proxyBaseUrl - The base URL of the sliding sync proxy\n * @param lists - The lists to use for sliding sync.\n * @param roomSubscriptionInfo - The params to use for room subscriptions.\n * @param client - The client to use for /sync calls.\n * @param timeoutMS - The number of milliseconds to wait for a response.\n */\n public constructor(\n private readonly proxyBaseUrl: string,\n lists: Map<string, MSC3575List>,\n private roomSubscriptionInfo: MSC3575RoomSubscription,\n private readonly client: MatrixClient,\n private readonly timeoutMS: number,\n ) {\n super();\n this.lists = new Map<string, SlidingList>();\n lists.forEach((list, key) => {\n this.lists.set(key, new SlidingList(list));\n });\n }\n\n /**\n * Add a custom room subscription, referred to by an arbitrary name. If a subscription with this\n * name already exists, it is replaced. No requests are sent by calling this method.\n * @param name - The name of the subscription. Only used to reference this subscription in\n * useCustomSubscription.\n * @param sub - The subscription information.\n */\n public addCustomSubscription(name: string, sub: MSC3575RoomSubscription): void {\n if (this.customSubscriptions.has(name)) {\n logger.warn(`addCustomSubscription: ${name} already exists as a custom subscription, ignoring.`);\n return;\n }\n this.customSubscriptions.set(name, sub);\n }\n\n /**\n * Use a custom subscription previously added via addCustomSubscription. No requests are sent\n * by calling this method. Use modifyRoomSubscriptions to resend subscription information.\n * @param roomId - The room to use the subscription in.\n * @param name - The name of the subscription. If this name is unknown, the default subscription\n * will be used.\n */\n public useCustomSubscription(roomId: string, name: string): void {\n // We already know about this custom subscription, as it is immutable,\n // we don't need to unconfirm the subscription.\n if (this.roomIdToCustomSubscription.get(roomId) === name) {\n return;\n }\n this.roomIdToCustomSubscription.set(roomId, name);\n // unconfirm this subscription so a resend() will send it up afresh.\n this.confirmedRoomSubscriptions.delete(roomId);\n }\n\n /**\n * Get the room index data for a list.\n * @param key - The list key\n * @returns The list data which contains the rooms in this list\n */\n public getListData(key: string): { joinedCount: number } | null {\n const data = this.lists.get(key);\n if (!data) {\n return null;\n }\n return {\n joinedCount: data.joinedCount,\n };\n }\n\n /**\n * Get the full request list parameters for a list index. This function is provided for callers to use\n * in conjunction with setList to update fields on an existing list.\n * @param key - The list key to get the params for.\n * @returns A copy of the list params or undefined.\n */\n public getListParams(key: string): MSC3575List | null {\n const params = this.lists.get(key);\n if (!params) {\n return null;\n }\n return params.getList(true);\n }\n\n /**\n * Set new ranges for an existing list. Calling this function when _only_ the ranges have changed\n * is more efficient than calling setList(index,list) as this function won't resend sticky params,\n * whereas setList always will.\n * @param key - The list key to modify\n * @param ranges - The new ranges to apply.\n * @returns A promise which resolves to the transaction ID when it has been received down sync\n * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled\n * immediately after sending, in which case the action will be applied in the subsequent request)\n */\n public setListRanges(key: string, ranges: number[][]): void {\n const list = this.lists.get(key);\n if (!list) {\n throw new Error(\"no list with key \" + key);\n }\n list.updateListRange(ranges);\n this.resend();\n }\n\n /**\n * Add or replace a list. Calling this function will interrupt the /sync request to resend new\n * lists.\n * @param key - The key to modify\n * @param list - The new list parameters.\n * @returns A promise which resolves to the transaction ID when it has been received down sync\n * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled\n * immediately after sending, in which case the action will be applied in the subsequent request)\n */\n public setList(key: string, list: MSC3575List): void {\n const existingList = this.lists.get(key);\n if (existingList) {\n existingList.replaceList(list);\n this.lists.set(key, existingList);\n } else {\n this.lists.set(key, new SlidingList(list));\n }\n this.listModifiedCount += 1;\n this.resend();\n }\n\n /**\n * Get the room subscriptions for the sync API.\n * @returns A copy of the desired room subscriptions.\n */\n public getRoomSubscriptions(): Set<string> {\n return new Set(Array.from(this.desiredRoomSubscriptions));\n }\n\n /**\n * Modify the room subscriptions for the sync API. Calling this function will interrupt the\n * /sync request to resend new subscriptions. If the /sync stream has not started, this will\n * prepare the room subscriptions for when start() is called.\n * @param s - The new desired room subscriptions.\n */\n public modifyRoomSubscriptions(s: Set<string>): void {\n this.desiredRoomSubscriptions = s;\n this.resend();\n }\n\n /**\n * Modify which events to retrieve for room subscriptions. Invalidates all room subscriptions\n * such that they will be sent up afresh.\n * @param rs - The new room subscription fields to fetch.\n */\n public modifyRoomSubscriptionInfo(rs: MSC3575RoomSubscription): void {\n this.roomSubscriptionInfo = rs;\n this.confirmedRoomSubscriptions = new Set<string>();\n this.resend();\n }\n\n /**\n * Register an extension to send with the /sync request.\n * @param ext - The extension to register.\n */\n public registerExtension(ext: Extension<any, any>): void {\n if (this.extensions[ext.name()]) {\n throw new Error(`registerExtension: ${ext.name()} already exists as an extension`);\n }\n this.extensions[ext.name()] = ext;\n }\n\n private async getExtensionRequest(isInitial: boolean): Promise<Record<string, object | undefined>> {\n const ext: Record<string, object | undefined> = {};\n for (const extName in this.extensions) {\n ext[extName] = await this.extensions[extName].onRequest(isInitial);\n }\n return ext;\n }\n\n private async onPreExtensionsResponse(ext: Record<string, object>): Promise<void> {\n await Promise.all(\n Object.keys(ext).map(async (extName) => {\n if (this.extensions[extName].when() == ExtensionState.PreProcess) {\n await this.extensions[extName].onResponse(ext[extName]);\n }\n }),\n );\n }\n\n private async onPostExtensionsResponse(ext: Record<string, object>): Promise<void> {\n await Promise.all(\n Object.keys(ext).map(async (extName) => {\n if (this.extensions[extName].when() == ExtensionState.PostProcess) {\n await this.extensions[extName].onResponse(ext[extName]);\n }\n }),\n );\n }\n\n /**\n * Invoke all attached room data listeners.\n * @param roomId - The room which received some data.\n * @param roomData - The raw sliding sync response JSON.\n */\n private async invokeRoomDataListeners(roomId: string, roomData: MSC3575RoomData): Promise<void> {\n if (!roomData.required_state) {\n roomData.required_state = [];\n }\n if (!roomData.timeline) {\n roomData.timeline = [];\n }\n await this.emitPromised(SlidingSyncEvent.RoomData, roomId, roomData);\n }\n\n /**\n * Invoke all attached lifecycle listeners.\n * @param state - The Lifecycle state\n * @param resp - The raw sync response JSON\n * @param err - Any error that occurred when making the request e.g. network errors.\n */\n private invokeLifecycleListeners(\n state: SlidingSyncState,\n resp: MSC3575SlidingSyncResponse | null,\n err?: Error,\n ): void {\n this.emit(SlidingSyncEvent.Lifecycle, state, resp, err);\n }\n\n /**\n * Resend a Sliding Sync request. Used when something has changed in the request.\n */\n public resend(): void {\n this.needsResend = true;\n this.abortController?.abort();\n this.abortController = new AbortController();\n }\n\n /**\n * Stop syncing with the server.\n */\n public stop(): void {\n this.terminated = true;\n this.abortController?.abort();\n // remove all listeners so things can be GC'd\n this.removeAllListeners(SlidingSyncEvent.Lifecycle);\n this.removeAllListeners(SlidingSyncEvent.RoomData);\n }\n\n /**\n * Re-setup this connection e.g in the event of an expired session.\n */\n private resetup(): void {\n logger.warn(\"SlidingSync: resetting connection info\");\n // resend sticky params and de-confirm all subscriptions\n this.lists.forEach((l) => {\n l.setModified(true);\n });\n this.confirmedRoomSubscriptions = new Set<string>(); // leave desired ones alone though!\n // reset the connection as we might be wedged\n this.resend();\n }\n\n /**\n * Start syncing with the server. Blocks until stopped.\n */\n public async start(): Promise<void> {\n this.abortController = new AbortController();\n\n let currentPos: string | undefined;\n while (!this.terminated) {\n this.needsResend = false;\n let resp: MSC3575SlidingSyncResponse | undefined;\n try {\n const reqLists: Record<string, MSC3575List> = {};\n this.lists.forEach((l: SlidingList, key: string) => {\n reqLists[key] = l.getList(true);\n });\n const reqBody: MSC3575SlidingSyncRequest = {\n lists: reqLists,\n pos: currentPos,\n timeout: this.timeoutMS,\n clientTimeout: this.timeoutMS + BUFFER_PERIOD_MS,\n extensions: await this.getExtensionRequest(currentPos === undefined),\n };\n // check if we are (un)subscribing to a room and modify request this one time for it\n const newSubscriptions = difference(this.desiredRoomSubscriptions, this.confirmedRoomSubscriptions);\n const unsubscriptions = difference(this.confirmedRoomSubscriptions, this.desiredRoomSubscriptions);\n if (unsubscriptions.size > 0) {\n reqBody.unsubscribe_rooms = Array.from(unsubscriptions);\n }\n if (newSubscriptions.size > 0) {\n reqBody.room_subscriptions = {};\n for (const roomId of newSubscriptions) {\n const customSubName = this.roomIdToCustomSubscription.get(roomId);\n let sub = this.roomSubscriptionInfo;\n if (customSubName && this.customSubscriptions.has(customSubName)) {\n sub = this.customSubscriptions.get(customSubName)!;\n }\n reqBody.room_subscriptions[roomId] = sub;\n }\n }\n this.pendingReq = this.client.slidingSync(reqBody, this.proxyBaseUrl, this.abortController.signal);\n resp = await this.pendingReq;\n currentPos = resp.pos;\n // update what we think we're subscribed to.\n for (const roomId of newSubscriptions) {\n this.confirmedRoomSubscriptions.add(roomId);\n }\n for (const roomId of unsubscriptions) {\n this.confirmedRoomSubscriptions.delete(roomId);\n }\n // mark all these lists as having been sent as sticky so we don't keep sending sticky params\n this.lists.forEach((l) => {\n l.setModified(false);\n });\n // set default empty values so we don't need to null check\n resp.lists = resp.lists ?? {};\n resp.rooms = resp.rooms ?? {};\n resp.extensions = resp.extensions ?? {};\n Object.keys(resp.lists).forEach((key: string) => {\n const list = this.lists.get(key);\n if (!list || !resp) {\n return;\n }\n list.joinedCount = resp.lists[key].count;\n });\n this.invokeLifecycleListeners(SlidingSyncState.RequestFinished, resp);\n } catch (err) {\n if ((<HTTPError>err).httpStatus) {\n this.invokeLifecycleListeners(SlidingSyncState.RequestFinished, null, <Error>err);\n if ((<HTTPError>err).httpStatus === 400) {\n // session probably expired TODO: assign an errcode\n // so drop state and re-request\n this.resetup();\n currentPos = undefined;\n await sleep(50); // in case the 400 was for something else; don't tightloop\n continue;\n } // else fallthrough to generic error handling\n } else if (this.needsResend || (<Error>err).name === \"AbortError\") {\n continue; // don't sleep as we caused this error by abort()ing the request.\n }\n logger.error(err);\n await sleep(5000);\n }\n if (!resp) {\n continue;\n }\n await this.onPreExtensionsResponse(resp.extensions);\n\n for (const roomId in resp.rooms) {\n await this.invokeRoomDataListeners(roomId, resp!.rooms[roomId]);\n }\n\n this.invokeLifecycleListeners(SlidingSyncState.Complete, resp);\n await this.onPostExtensionsResponse(resp.extensions);\n }\n }\n}\n\nconst difference = (setA: Set<string>, setB: Set<string>): Set<string> => {\n const diff = new Set(setA);\n for (const elem of setB) {\n diff.delete(elem);\n }\n return diff;\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,MAAM,QAAQ,aAAa;AAGpC,SAAS,iBAAiB,QAAQ,iCAAiC;AACnE,SAAS,KAAK,QAAQ,YAAY;AAGlC;AACA;AACA;AACA;AACA,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI;AAElC,OAAO,MAAM,gBAAgB,GAAG,GAAG;AACnC,OAAO,MAAM,oBAAoB,GAAG,KAAK;AACzC,OAAO,MAAM,sBAAsB,GAAG,OAAO;;AAE7C;AACA;AACA;;AAOA;AACA;AACA;;AAaA;AACA;AACA;;AAQA;AACA;AACA;;AAeA;AACA;AACA;AACA;AACA;AACA;;AA6BA;AACA;AACA;;AASA,WAAY,gBAAgB,0BAAhB,gBAAgB;EACxB;AACJ;AACA;EAHY,gBAAgB;EAKxB;AACJ;AACA;AACA;EARY,gBAAgB;EAAA,OAAhB,gBAAgB;AAAA;;AAY5B;AACA;AACA;AACA;AACA,MAAM,WAAW,CAAC;EAOd;AACJ;AACA;AACA;EACW,WAAW,CAAC,IAAiB,EAAE;IAAA;IAAA;IAPtC;IAAA,qCACqB,CAAC;IAOlB,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;EAC1B;;EAEA;AACJ;AACA;AACA;AACA;EACW,WAAW,CAAC,QAAiB,EAAQ;IACxC,IAAI,CAAC,UAAU,GAAG,QAAQ;EAC9B;;EAEA;AACJ;AACA;AACA;EACW,eAAe,CAAC,SAAqB,EAAQ;IAChD,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;EAC5D;;EAEA;AACJ;AACA;AACA;EACW,WAAW,CAAC,IAAiB,EAAQ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S;YACtB,MAAM,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;YACjB;UACJ,CAAC,CAAC;QACN,CAAC,MAAM,IAAI,IAAI,CAAC,WAAW,IAAY,GAAG,CAAE,IAAI,KAAK,YAAY,EAAE;UAC/D,SAAS,CAAC;QACd;QACA,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC;QACjB,MAAM,KAAK,CAAC,IAAI,CAAC;MACrB;MACA,IAAI,CAAC,IAAI,EAAE;QACP;MACJ;MACA,MAAM,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,UAAU,CAAC;MAEnD,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,KAAK,EAAE;QAC7B,MAAM,IAAI,CAAC,uBAAuB,CAAC,MAAM,EAAE,IAAI,CAAE,KAAK,CAAC,MAAM,CAAC,CAAC;MACnE;MAEA,IAAI,CAAC,wBAAwB,CAAC,gBAAgB,CAAC,QAAQ,EAAE,IAAI,CAAC;MAC9D,MAAM,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,UAAU,CAAC;IACxD;EACJ;AACJ;AAEA,MAAM,UAAU,GAAG,CAAC,IAAiB,EAAE,IAAiB,KAAkB;EACtE,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC;EAC1B,KAAK,MAAM,IAAI,IAAI,IAAI,EAAE;IACrB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;EACrB;EACA,OAAO,IAAI;AACf,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"sliding-sync.js","names":[],"sources":["../src/sliding-sync.ts"],"sourcesContent":["/*\nCopyright 2022-2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"./logger.ts\";\nimport { type MatrixClient } from \"./client.ts\";\nimport { type IRoomEvent, type IStateEvent } from \"./sync-accumulator.ts\";\nimport { TypedEventEmitter } from \"./models/typed-event-emitter.ts\";\nimport { sleep } from \"./utils.ts\";\nimport { type HTTPError } from \"./http-api/index.ts\";\n\n// /sync requests allow you to set a timeout= but the request may continue\n// beyond that and wedge forever, so we need to track how long we are willing\n// to keep open the connection. This constant is *ADDED* to the timeout= value\n// to determine the max time we're willing to wait.\nconst BUFFER_PERIOD_MS = 10 * 1000;\n\nexport const MSC3575_WILDCARD = \"*\";\nexport const MSC3575_STATE_KEY_ME = \"$ME\";\nexport const MSC3575_STATE_KEY_LAZY = \"$LAZY\";\n\n/**\n * Represents a subscription to a room or set of rooms. Controls which events are returned.\n */\nexport interface MSC3575RoomSubscription {\n required_state?: string[][];\n timeline_limit?: number;\n include_old_rooms?: MSC3575RoomSubscription;\n}\n\n/**\n * Controls which rooms are returned in a given list.\n */\nexport interface MSC3575Filter {\n is_dm?: boolean;\n is_encrypted?: boolean;\n is_invite?: boolean;\n room_name_like?: string;\n room_types?: string[];\n not_room_types?: string[];\n spaces?: string[];\n tags?: string[];\n not_tags?: string[];\n}\n\n/**\n * Represents a list subscription.\n */\nexport interface MSC3575List extends MSC3575RoomSubscription {\n ranges: number[][];\n sort?: string[];\n filters?: MSC3575Filter;\n slow_get_all_rooms?: boolean;\n}\n\n/**\n * A complete Sliding Sync request.\n */\nexport interface MSC3575SlidingSyncRequest {\n // json body params\n lists?: Record<string, MSC3575List>;\n unsubscribe_rooms?: string[];\n room_subscriptions?: Record<string, MSC3575RoomSubscription>;\n extensions?: object;\n txn_id?: string;\n\n // query params\n pos?: string;\n timeout?: number;\n clientTimeout?: number;\n}\n\n/**\n * New format of hero introduced in MSC4186 with display name and avatar URL\n * in addition to just user_id (as it is on the wire, with underscores)\n * as opposed to Hero in room-summary.ts which has fields in camelCase\n * (and also a flag to note what format the hero came from).\n */\nexport interface MSC4186Hero {\n user_id: string;\n displayname?: string;\n avatar_url?: string;\n}\n\nexport interface MSC3575RoomData {\n name: string;\n required_state: IStateEvent[];\n timeline: (IRoomEvent | IStateEvent)[];\n heroes?: MSC4186Hero[];\n notification_count?: number;\n highlight_count?: number;\n joined_count?: number;\n invited_count?: number;\n invite_state?: IStateEvent[];\n initial?: boolean;\n limited?: boolean;\n is_dm?: boolean;\n prev_batch?: string;\n num_live?: number;\n bump_stamp?: number;\n}\n\ninterface ListResponse {\n count: number;\n}\n\n/**\n * A complete Sliding Sync response\n */\nexport interface MSC3575SlidingSyncResponse {\n pos: string;\n txn_id?: string;\n lists: Record<string, ListResponse>;\n rooms: Record<string, MSC3575RoomData>;\n extensions: Record<string, object>;\n}\n\nexport enum SlidingSyncState {\n /**\n * Fired by SlidingSyncEvent.Lifecycle event immediately before processing the response.\n */\n RequestFinished = \"FINISHED\",\n /**\n * Fired by SlidingSyncEvent.Lifecycle event immediately after all room data listeners have been\n * invoked, but before list listeners.\n */\n Complete = \"COMPLETE\",\n}\n\n/**\n * Internal Class. SlidingList represents a single list in sliding sync. The list can have filters,\n * multiple sliding windows, and maintains the index-\\>room_id mapping.\n */\nclass SlidingList {\n private list!: MSC3575List;\n private isModified?: boolean;\n\n // returned data\n public joinedCount = 0;\n\n /**\n * Construct a new sliding list.\n * @param list - The range, sort and filter values to use for this list.\n */\n public constructor(list: MSC3575List) {\n this.replaceList(list);\n }\n\n /**\n * Mark this list as modified or not. Modified lists will return sticky params with calls to getList.\n * This is useful for the first time the list is sent, or if the list has changed in some way.\n * @param modified - True to mark this list as modified so all sticky parameters will be re-sent.\n */\n public setModified(modified: boolean): void {\n this.isModified = modified;\n }\n\n /**\n * Update the list range for this list. Does not affect modified status as list ranges are non-sticky.\n * @param newRanges - The new ranges for the list\n */\n public updateListRange(newRanges: number[][]): void {\n this.list.ranges = JSON.parse(JSON.stringify(newRanges));\n }\n\n /**\n * Replace list parameters. All fields will be replaced with the new list parameters.\n * @param list - The new list parameters\n */\n public replaceList(list: MSC3575List): void {\n list.filters = list.filters ?? {};\n list.ranges = list.ranges ?? [];\n this.list = JSON.parse(JSON.stringify(list));\n this.isModified = true;\n\n // reset values as the join count may be very different (if filters changed) including the rooms\n // (e.g. sort orders or sliding window ranges changed)\n\n // the total number of joined rooms according to the server, always >= len(roomIndexToRoomId)\n this.joinedCount = 0;\n }\n\n /**\n * Return a copy of the list suitable for a request body.\n * @param forceIncludeAllParams - True to forcibly include all params even if the list\n * hasn't been modified. Callers may want to do this if they are modifying the list prior to calling\n * updateList.\n */\n public getList(forceIncludeAllParams: boolean): MSC3575List {\n let list = {\n ranges: JSON.parse(JSON.stringify(this.list.ranges)),\n };\n if (this.isModified || forceIncludeAllParams) {\n list = JSON.parse(JSON.stringify(this.list));\n }\n return list;\n }\n}\n\n/**\n * When onResponse extensions should be invoked: before or after processing the main response.\n */\nexport enum ExtensionState {\n // Call onResponse before processing the response body. This is useful when your extension is\n // preparing the ground for the response body e.g. processing to-device messages before the\n // encrypted event arrives.\n PreProcess = \"ExtState.PreProcess\",\n // Call onResponse after processing the response body. This is useful when your extension is\n // decorating data from the client, and you rely on MatrixClient.getRoom returning the Room object\n // e.g. room account data.\n PostProcess = \"ExtState.PostProcess\",\n}\n\n/**\n * An interface that must be satisfied to register extensions\n */\nexport interface Extension<Req extends object, Res extends object> {\n /**\n * The extension name to go under 'extensions' in the request body.\n * @returns The JSON key.\n */\n name(): string;\n /**\n * A function which is called when the request JSON is being formed.\n * Returns the data to insert under this key.\n * @param isInitial - True when this is part of the initial request.\n * @returns The request JSON to send.\n */\n onRequest(isInitial: boolean): Promise<Req>;\n /**\n * A function which is called when there is response JSON under this extension.\n * @param data - The response JSON under the extension name.\n */\n onResponse(data: Res): Promise<void>;\n /**\n * Controls when onResponse should be called.\n * @returns The state when it should be called.\n */\n when(): ExtensionState;\n}\n\n/**\n * Events which can be fired by the SlidingSync class. These are designed to provide different levels\n * of information when processing sync responses.\n * - RoomData: concerns rooms, useful for SlidingSyncSdk to update its knowledge of rooms.\n * - Lifecycle: concerns callbacks at various well-defined points in the sync process.\n * Specifically, the order of event invocation is:\n * - Lifecycle (state=RequestFinished)\n * - RoomData (N times)\n * - Lifecycle (state=Complete)\n */\nexport enum SlidingSyncEvent {\n /**\n * This event fires when there are updates for a room. Fired as and when rooms are encountered\n * in the response.\n */\n RoomData = \"SlidingSync.RoomData\",\n /**\n * This event fires at various points in the /sync loop lifecycle.\n * - SlidingSyncState.RequestFinished: Fires after we receive a valid response but before the\n * response has been processed. Perform any pre-process steps here. If there was a problem syncing,\n * `err` will be set (e.g network errors).\n * - SlidingSyncState.Complete: Fires after the response has been processed.\n */\n Lifecycle = \"SlidingSync.Lifecycle\",\n}\n\nexport type SlidingSyncEventHandlerMap = {\n [SlidingSyncEvent.RoomData]: (roomId: string, roomData: MSC3575RoomData) => Promise<void> | void;\n [SlidingSyncEvent.Lifecycle]: (\n state: SlidingSyncState,\n resp: MSC3575SlidingSyncResponse | null,\n err?: Error,\n ) => void;\n};\n\n/**\n * SlidingSync is a high-level data structure which controls the majority of sliding sync.\n * It has no hooks into JS SDK except for needing a MatrixClient to perform the HTTP request.\n * This means this class (and everything it uses) can be used in isolation from JS SDK if needed.\n * To hook this up with the JS SDK, you need to use SlidingSyncSdk.\n */\nexport class SlidingSync extends TypedEventEmitter<SlidingSyncEvent, SlidingSyncEventHandlerMap> {\n private lists: Map<string, SlidingList>;\n private listModifiedCount = 0;\n private terminated = false;\n // flag set when resend() is called because we cannot rely on detecting AbortError in JS SDK :(\n private needsResend = false;\n // map of extension name to req/resp handler\n private extensions: Record<string, Extension<any, any>> = {};\n\n private desiredRoomSubscriptions = new Set<string>(); // the *desired* room subscriptions\n private confirmedRoomSubscriptions = new Set<string>();\n\n // map of custom subscription name to the subscription\n private customSubscriptions: Map<string, MSC3575RoomSubscription> = new Map();\n // map of room ID to custom subscription name\n private roomIdToCustomSubscription: Map<string, string> = new Map();\n\n private pendingReq?: Promise<MSC3575SlidingSyncResponse>;\n private abortController?: AbortController;\n\n /**\n * Create a new sliding sync instance\n * @param proxyBaseUrl - The base URL of the sliding sync proxy\n * @param lists - The lists to use for sliding sync.\n * @param roomSubscriptionInfo - The params to use for room subscriptions.\n * @param client - The client to use for /sync calls.\n * @param timeoutMS - The number of milliseconds to wait for a response.\n */\n public constructor(\n private readonly proxyBaseUrl: string,\n lists: Map<string, MSC3575List>,\n private roomSubscriptionInfo: MSC3575RoomSubscription,\n private readonly client: MatrixClient,\n private readonly timeoutMS: number,\n ) {\n super();\n this.lists = new Map<string, SlidingList>();\n lists.forEach((list, key) => {\n this.lists.set(key, new SlidingList(list));\n });\n }\n\n /**\n * Add a custom room subscription, referred to by an arbitrary name. If a subscription with this\n * name already exists, it is replaced. No requests are sent by calling this method.\n * @param name - The name of the subscription. Only used to reference this subscription in\n * useCustomSubscription.\n * @param sub - The subscription information.\n */\n public addCustomSubscription(name: string, sub: MSC3575RoomSubscription): void {\n if (this.customSubscriptions.has(name)) {\n logger.warn(`addCustomSubscription: ${name} already exists as a custom subscription, ignoring.`);\n return;\n }\n this.customSubscriptions.set(name, sub);\n }\n\n /**\n * Use a custom subscription previously added via addCustomSubscription. No requests are sent\n * by calling this method. Use modifyRoomSubscriptions to resend subscription information.\n * @param roomId - The room to use the subscription in.\n * @param name - The name of the subscription. If this name is unknown, the default subscription\n * will be used.\n */\n public useCustomSubscription(roomId: string, name: string): void {\n // We already know about this custom subscription, as it is immutable,\n // we don't need to unconfirm the subscription.\n if (this.roomIdToCustomSubscription.get(roomId) === name) {\n return;\n }\n this.roomIdToCustomSubscription.set(roomId, name);\n // unconfirm this subscription so a resend() will send it up afresh.\n this.confirmedRoomSubscriptions.delete(roomId);\n }\n\n /**\n * Get the room index data for a list.\n * @param key - The list key\n * @returns The list data which contains the rooms in this list\n */\n public getListData(key: string): { joinedCount: number } | null {\n const data = this.lists.get(key);\n if (!data) {\n return null;\n }\n return {\n joinedCount: data.joinedCount,\n };\n }\n\n /**\n * Get the full request list parameters for a list index. This function is provided for callers to use\n * in conjunction with setList to update fields on an existing list.\n * @param key - The list key to get the params for.\n * @returns A copy of the list params or undefined.\n */\n public getListParams(key: string): MSC3575List | null {\n const params = this.lists.get(key);\n if (!params) {\n return null;\n }\n return params.getList(true);\n }\n\n /**\n * Set new ranges for an existing list. Calling this function when _only_ the ranges have changed\n * is more efficient than calling setList(index,list) as this function won't resend sticky params,\n * whereas setList always will.\n * @param key - The list key to modify\n * @param ranges - The new ranges to apply.\n * @returns A promise which resolves to the transaction ID when it has been received down sync\n * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled\n * immediately after sending, in which case the action will be applied in the subsequent request)\n */\n public setListRanges(key: string, ranges: number[][]): void {\n const list = this.lists.get(key);\n if (!list) {\n throw new Error(\"no list with key \" + key);\n }\n list.updateListRange(ranges);\n this.resend();\n }\n\n /**\n * Add or replace a list. Calling this function will interrupt the /sync request to resend new\n * lists.\n * @param key - The key to modify\n * @param list - The new list parameters.\n * @returns A promise which resolves to the transaction ID when it has been received down sync\n * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled\n * immediately after sending, in which case the action will be applied in the subsequent request)\n */\n public setList(key: string, list: MSC3575List): void {\n const existingList = this.lists.get(key);\n if (existingList) {\n existingList.replaceList(list);\n this.lists.set(key, existingList);\n } else {\n this.lists.set(key, new SlidingList(list));\n }\n this.listModifiedCount += 1;\n this.resend();\n }\n\n /**\n * Get the room subscriptions for the sync API.\n * @returns A copy of the desired room subscriptions.\n */\n public getRoomSubscriptions(): Set<string> {\n return new Set(Array.from(this.desiredRoomSubscriptions));\n }\n\n /**\n * Modify the room subscriptions for the sync API. Calling this function will interrupt the\n * /sync request to resend new subscriptions. If the /sync stream has not started, this will\n * prepare the room subscriptions for when start() is called.\n * @param s - The new desired room subscriptions.\n */\n public modifyRoomSubscriptions(s: Set<string>): void {\n this.desiredRoomSubscriptions = s;\n this.resend();\n }\n\n /**\n * Modify which events to retrieve for room subscriptions. Invalidates all room subscriptions\n * such that they will be sent up afresh.\n * @param rs - The new room subscription fields to fetch.\n */\n public modifyRoomSubscriptionInfo(rs: MSC3575RoomSubscription): void {\n this.roomSubscriptionInfo = rs;\n this.confirmedRoomSubscriptions = new Set<string>();\n this.resend();\n }\n\n /**\n * Register an extension to send with the /sync request.\n * @param ext - The extension to register.\n */\n public registerExtension(ext: Extension<any, any>): void {\n if (this.extensions[ext.name()]) {\n throw new Error(`registerExtension: ${ext.name()} already exists as an extension`);\n }\n this.extensions[ext.name()] = ext;\n }\n\n private async getExtensionRequest(isInitial: boolean): Promise<Record<string, object | undefined>> {\n const ext: Record<string, object | undefined> = {};\n // oxlint-disable-next-line guard-for-in\n for (const extName in this.extensions) {\n ext[extName] = await this.extensions[extName].onRequest(isInitial);\n }\n return ext;\n }\n\n private async onPreExtensionsResponse(ext: Record<string, object>): Promise<void> {\n await Promise.all(\n Object.keys(ext).map(async (extName) => {\n if (this.extensions[extName].when() == ExtensionState.PreProcess) {\n await this.extensions[extName].onResponse(ext[extName]);\n }\n }),\n );\n }\n\n private async onPostExtensionsResponse(ext: Record<string, object>): Promise<void> {\n await Promise.all(\n Object.keys(ext).map(async (extName) => {\n if (this.extensions[extName].when() == ExtensionState.PostProcess) {\n await this.extensions[extName].onResponse(ext[extName]);\n }\n }),\n );\n }\n\n /**\n * Invoke all attached room data listeners.\n * @param roomId - The room which received some data.\n * @param roomData - The raw sliding sync response JSON.\n */\n private async invokeRoomDataListeners(roomId: string, roomData: MSC3575RoomData): Promise<void> {\n if (!roomData.required_state) {\n roomData.required_state = [];\n }\n if (!roomData.timeline) {\n roomData.timeline = [];\n }\n await this.emitPromised(SlidingSyncEvent.RoomData, roomId, roomData);\n }\n\n /**\n * Invoke all attached lifecycle listeners.\n * @param state - The Lifecycle state\n * @param resp - The raw sync response JSON\n * @param err - Any error that occurred when making the request e.g. network errors.\n */\n private invokeLifecycleListeners(\n state: SlidingSyncState,\n resp: MSC3575SlidingSyncResponse | null,\n err?: Error,\n ): void {\n this.emit(SlidingSyncEvent.Lifecycle, state, resp, err);\n }\n\n /**\n * Resend a Sliding Sync request. Used when something has changed in the request.\n */\n public resend(): void {\n this.needsResend = true;\n this.abortController?.abort();\n this.abortController = new AbortController();\n }\n\n /**\n * Stop syncing with the server.\n */\n public stop(): void {\n this.terminated = true;\n this.abortController?.abort();\n // remove all listeners so things can be GC'd\n this.removeAllListeners(SlidingSyncEvent.Lifecycle);\n this.removeAllListeners(SlidingSyncEvent.RoomData);\n }\n\n /**\n * Re-setup this connection e.g in the event of an expired session.\n */\n private resetup(): void {\n logger.warn(\"SlidingSync: resetting connection info\");\n // resend sticky params and de-confirm all subscriptions\n this.lists.forEach((l) => {\n l.setModified(true);\n });\n this.confirmedRoomSubscriptions = new Set<string>(); // leave desired ones alone though!\n // reset the connection as we might be wedged\n this.resend();\n }\n\n /**\n * Start syncing with the server. Blocks until stopped.\n */\n public async start(): Promise<void> {\n this.abortController = new AbortController();\n\n let currentPos: string | undefined;\n while (!this.terminated) {\n this.needsResend = false;\n let resp: MSC3575SlidingSyncResponse | undefined;\n try {\n const reqLists: Record<string, MSC3575List> = {};\n this.lists.forEach((l: SlidingList, key: string) => {\n reqLists[key] = l.getList(true);\n });\n const reqBody: MSC3575SlidingSyncRequest = {\n lists: reqLists,\n pos: currentPos,\n timeout: this.timeoutMS,\n clientTimeout: this.timeoutMS + BUFFER_PERIOD_MS,\n extensions: await this.getExtensionRequest(currentPos === undefined),\n };\n // check if we are (un)subscribing to a room and modify request this one time for it\n const newSubscriptions = difference(this.desiredRoomSubscriptions, this.confirmedRoomSubscriptions);\n const unsubscriptions = difference(this.confirmedRoomSubscriptions, this.desiredRoomSubscriptions);\n if (unsubscriptions.size > 0) {\n reqBody.unsubscribe_rooms = Array.from(unsubscriptions);\n }\n if (newSubscriptions.size > 0) {\n reqBody.room_subscriptions = {};\n for (const roomId of newSubscriptions) {\n const customSubName = this.roomIdToCustomSubscription.get(roomId);\n let sub = this.roomSubscriptionInfo;\n if (customSubName && this.customSubscriptions.has(customSubName)) {\n sub = this.customSubscriptions.get(customSubName)!;\n }\n reqBody.room_subscriptions[roomId] = sub;\n }\n }\n this.pendingReq = this.client.slidingSync(reqBody, this.proxyBaseUrl, this.abortController.signal);\n resp = await this.pendingReq;\n currentPos = resp.pos;\n // update what we think we're subscribed to.\n for (const roomId of newSubscriptions) {\n this.confirmedRoomSubscriptions.add(roomId);\n }\n for (const roomId of unsubscriptions) {\n this.confirmedRoomSubscriptions.delete(roomId);\n }\n // mark all these lists as having been sent as sticky so we don't keep sending sticky params\n this.lists.forEach((l) => {\n l.setModified(false);\n });\n // set default empty values so we don't need to null check\n resp.lists = resp.lists ?? {};\n resp.rooms = resp.rooms ?? {};\n resp.extensions = resp.extensions ?? {};\n Object.keys(resp.lists).forEach((key: string) => {\n const list = this.lists.get(key);\n if (!list || !resp) {\n return;\n }\n list.joinedCount = resp.lists[key].count;\n });\n this.invokeLifecycleListeners(SlidingSyncState.RequestFinished, resp);\n } catch (err) {\n if ((<HTTPError>err).httpStatus) {\n this.invokeLifecycleListeners(SlidingSyncState.RequestFinished, null, <Error>err);\n if ((<HTTPError>err).httpStatus === 400) {\n // session probably expired TODO: assign an errcode\n // so drop state and re-request\n this.resetup();\n currentPos = undefined;\n await sleep(50); // in case the 400 was for something else; don't tightloop\n continue;\n } // else fallthrough to generic error handling\n } else if (this.needsResend || (<Error>err).name === \"AbortError\") {\n continue; // don't sleep as we caused this error by abort()ing the request.\n }\n logger.error(err);\n await sleep(5000);\n }\n if (!resp) {\n continue;\n }\n await this.onPreExtensionsResponse(resp.extensions);\n\n // oxlint-disable-next-line guard-for-in\n for (const roomId in resp.rooms) {\n await this.invokeRoomDataListeners(roomId, resp!.rooms[roomId]);\n }\n\n this.invokeLifecycleListeners(SlidingSyncState.Complete, resp);\n await this.onPostExtensionsResponse(resp.extensions);\n }\n }\n}\n\nconst difference = (setA: Set<string>, setB: Set<string>): Set<string> => {\n const diff = new Set(setA);\n for (const elem of setB) {\n diff.delete(elem);\n }\n return diff;\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,MAAM,QAAQ,aAAa;AAGpC,SAAS,iBAAiB,QAAQ,iCAAiC;AACnE,SAAS,KAAK,QAAQ,YAAY;AAGlC;AACA;AACA;AACA;AACA,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI;AAElC,OAAO,MAAM,gBAAgB,GAAG,GAAG;AACnC,OAAO,MAAM,oBAAoB,GAAG,KAAK;AACzC,OAAO,MAAM,sBAAsB,GAAG,OAAO;;AAE7C;AACA;AACA;;AAOA;AACA;AACA;;AAaA;AACA;AACA;;AAQA;AACA;AACA;;AAeA;AACA;AACA;AACA;AACA;AACA;;AA6BA;AACA;AACA;;AASA,WAAY,gBAAgB,0BAAhB,gBAAgB;EACxB;AACJ;AACA;EAHY,gBAAgB;EAKxB;AACJ;AACA;AACA;EARY,gBAAgB;EAAA,OAAhB,gBAAgB;AAAA;;AAY5B;AACA;AACA;AACA;AACA,MAAM,WAAW,CAAC;EAOd;AACJ;AACA;AACA;EACW,WAAW,CAAC,IAAiB,EAAE;IAAA;IAAA;IAPtC;IAAA,qCACqB,CAAC;IAOlB,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;EAC1B;;EAEA;AACJ;AACA;AACA;AACA;EACW,WAAW,CAAC,QAAiB,EAAQ;IACxC,IAAI,CAAC,UAAU,GAAG,QAAQ;EAC9B;;EAEA;AACJ;AACA;AACA;EACW,eAAe,CAAC,SAAqB,EAAQ;IAChD,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;EAC5D;;EAEA;AACJ;AACA;AACA;EACW,WAAW,CAAC,IAAiB,EAAQ;IACxC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,CAAC,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G,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC,CAYxE;IAEY,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAQtF;IAEM,mBAAmB,CAAC,OAAO,EAAE,sBAAsB,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAE3E;IAEM,sBAAsB,IAAI,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAEpE;IAEM,mBAAmB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEpD;IAEY,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAEhF;IAEY,iBAAiB,CAAC,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAExF;IAEY,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhE;CACJ;AAUD,KAAK,YAAY,CAAC,CAAC,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC"}
@@ -15,8 +15,6 @@ See the License for the specific language governing permissions and
15
15
  limitations under the License.
16
16
  */
17
17
 
18
- /* eslint-disable @babel/no-invalid-this */
19
-
20
18
  import { MemoryStore } from "./memory.js";
21
19
  import { LocalIndexedDBStoreBackend } from "./indexeddb-local-backend.js";
22
20
  import { RemoteIndexedDBStoreBackend } from "./indexeddb-remote-backend.js";
@@ -1 +1 @@
1
- {"version":3,"file":"indexeddb.js","names":[],"sources":["../../src/store/indexeddb.ts"],"sourcesContent":["/*\nCopyright 2017 - 2021 Vector Creations Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/* eslint-disable @babel/no-invalid-this */\n\nimport { MemoryStore, type IOpts as IBaseOpts } from \"./memory.ts\";\nimport { LocalIndexedDBStoreBackend } from \"./indexeddb-local-backend.ts\";\nimport { RemoteIndexedDBStoreBackend } from \"./indexeddb-remote-backend.ts\";\nimport { type IEvent, MatrixEvent } from \"../models/event.ts\";\nimport { logger } from \"../logger.ts\";\nimport { type ISavedSync } from \"./index.ts\";\nimport { type IIndexedDBBackend } from \"./indexeddb-backend.ts\";\nimport { type ISyncResponse } from \"../sync-accumulator.ts\";\nimport { type EventEmitterEvents, TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\nimport { type IStateEventWithRoomId } from \"../@types/search.ts\";\nimport { type IndexedToDeviceBatch, type ToDeviceBatchWithTxnId } from \"../models/ToDeviceMessage.ts\";\nimport { type IStoredClientOpts } from \"../client.ts\";\nimport { type SyncUserProfile } from \"../models/user.ts\";\n\n/**\n * This is an internal module. See {@link IndexedDBStore} for the public class.\n */\n\n// If this value is too small we'll be writing very often which will cause\n// noticeable stop-the-world pauses. If this value is too big we'll be writing\n// so infrequently that the /sync size gets bigger on reload. Writing more\n// often does not affect the length of the pause since the entire /sync\n// response is persisted each time.\nconst WRITE_DELAY_MS = 1000 * 60 * 5; // once every 5 minutes\n\ninterface IOpts extends IBaseOpts {\n /** The Indexed DB interface e.g. `window.indexedDB` */\n indexedDB?: IDBFactory;\n /** Optional database name. The same name must be used to open the same database. */\n dbName?: string;\n /** Optional factory to spin up a Worker to execute the IDB transactions within. */\n workerFactory?: () => Worker;\n}\n\ntype EventHandlerMap = {\n // Fired when an IDB command fails on a degradable path, and the store falls back to MemoryStore\n // This signals the potential for data volatility.\n degraded: (e: Error) => void;\n // Fired when the IndexedDB gets closed unexpectedly, for example, if the underlying storage is removed or\n // if the user clears the database in the browser's history preferences.\n closed: () => void;\n};\n\nexport class IndexedDBStore extends MemoryStore {\n public static exists(indexedDB: IDBFactory, dbName: string): Promise<boolean> {\n return LocalIndexedDBStoreBackend.exists(indexedDB, dbName);\n }\n\n public _backend: IIndexedDBBackend;\n\n private startedUp = false;\n private syncTs = 0;\n // Records the last-modified-time of each user at the last point we saved\n // the database, such that we can derive the set if users that have been\n // modified since we last saved.\n private userModifiedMap: Record<string, number> = {}; // user_id : timestamp\n private emitter = new TypedEventEmitter<keyof EventHandlerMap, EventHandlerMap>();\n\n /**\n * Construct a new Indexed Database store, which extends MemoryStore.\n *\n * This store functions like a MemoryStore except it periodically persists\n * the contents of the store to an IndexedDB backend.\n *\n * All data is still kept in-memory but can be loaded from disk by calling\n * `startup()`. This can make startup times quicker as a complete\n * sync from the server is not required. This does not reduce memory usage as all\n * the data is eagerly fetched when `startup()` is called.\n * ```\n * let opts = { indexedDB: window.indexedDB, localStorage: window.localStorage };\n * let store = new IndexedDBStore(opts);\n * let client = sdk.createClient({\n * store: store,\n * });\n * await store.startup(); // load from indexed db, must be called after createClient\n * client.startClient();\n * client.on(\"sync\", function(state, prevState, data) {\n * if (state === \"PREPARED\") {\n * console.log(\"Started up, now with go faster stripes!\");\n * }\n * });\n * ```\n *\n * @param opts - Options object.\n */\n public constructor(private readonly opts: IOpts) {\n super(opts);\n\n if (!opts.indexedDB) {\n throw new Error(\"Missing required option: indexedDB\");\n }\n\n if (opts.workerFactory) {\n this._backend = new RemoteIndexedDBStoreBackend(opts.workerFactory, opts.dbName);\n } else {\n this._backend = new LocalIndexedDBStoreBackend(opts.indexedDB, opts.dbName);\n }\n }\n\n /**\n * The backend instance.\n * Call through to this API if you need to perform specific indexeddb actions like deleting the database.\n */\n public get backend(): IIndexedDBBackend {\n return this._backend;\n }\n\n /** Re-exports `TypedEventEmitter.on` */\n public on(event: EventEmitterEvents | \"degraded\" | \"closed\", handler: (...args: any[]) => void): void {\n this.emitter.on(event, handler);\n }\n\n /**\n * @returns Resolved when loaded from indexed db.\n */\n public startup(): Promise<void> {\n if (this.startedUp) {\n logger.log(`IndexedDBStore.startup: already started`);\n return Promise.resolve();\n }\n\n logger.log(`IndexedDBStore.startup: connecting to backend`);\n return this.backend\n .connect(this.onClose)\n .catch((e) => {\n if (this.opts.workerFactory) {\n logger.log(\"Falling back to local indexeddb backend\");\n this._backend = new LocalIndexedDBStoreBackend(this.opts.indexedDB!, this.opts.dbName);\n return this.backend.connect(this.onClose);\n }\n throw e;\n })\n .then(() => {\n logger.log(`IndexedDBStore.startup: loading presence events`);\n return this.backend.getUserPresenceEvents();\n })\n .then((userPresenceEvents) => {\n logger.log(`IndexedDBStore.startup: processing presence events`);\n userPresenceEvents.forEach(([userId, rawEvent]) => {\n if (!this.createUser) {\n throw new Error(\n \"`IndexedDBStore.startup` must be called after assigning it to the client, not before!\",\n );\n }\n const u = this.createUser(userId);\n if (rawEvent) {\n u.setPresenceEvent(new MatrixEvent(rawEvent));\n }\n this.userModifiedMap[u.userId] = u.getLastModifiedTime();\n this.storeUser(u);\n });\n this.startedUp = true;\n });\n }\n\n /*\n * Close the database and destroy any associated workers\n */\n public destroy(): Promise<void> {\n return this.backend.destroy();\n }\n\n private onClose = (): void => {\n this.emitter.emit(\"closed\");\n };\n\n /**\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync = this.degradable((): Promise<ISavedSync | null> => {\n return this.backend.getSavedSync();\n }, \"getSavedSync\");\n\n /** @returns whether or not the database was newly created in this session. */\n public isNewlyCreated = this.degradable((): Promise<boolean> => {\n return this.backend.isNewlyCreated();\n }, \"isNewlyCreated\");\n\n /**\n * @returns If there is a saved sync, the nextBatch token\n * for this sync, otherwise null.\n */\n public getSavedSyncToken = this.degradable((): Promise<string | null> => {\n return this.backend.getNextBatchToken();\n }, \"getSavedSyncToken\");\n\n /**\n * Delete all data from this store.\n * @returns Promise which resolves if the data was deleted from the database.\n */\n public deleteAllData = this.degradable((): Promise<void> => {\n super.deleteAllData();\n return this.backend.clearDatabase().then(\n () => {\n logger.log(\"Deleted indexeddb data.\");\n },\n (err) => {\n logger.error(`Failed to delete indexeddb data: ${err}`);\n throw err;\n },\n );\n }, null);\n\n /**\n * Whether this store would like to save its data\n * Note that obviously whether the store wants to save or\n * not could change between calling this function and calling\n * save().\n *\n * @returns True if calling save() will actually save\n * (at the time this function is called).\n */\n public wantsSave(): boolean {\n const now = Date.now();\n return now - this.syncTs > WRITE_DELAY_MS;\n }\n\n /**\n * Possibly write data to the database.\n *\n * @param force - True to force a save to happen\n * @returns Promise resolves after the write completes\n * (or immediately if no write is performed)\n */\n public save(force = false): Promise<void> {\n if (force || this.wantsSave()) {\n return this.reallySave();\n }\n return Promise.resolve();\n }\n\n private reallySave = this.degradable((): Promise<void> => {\n this.syncTs = Date.now(); // set now to guard against multi-writes\n\n // work out changed users (this doesn't handle deletions but you\n // can't 'delete' users as they are just presence events).\n const userTuples: [userId: string, presenceEvent: Partial<IEvent>][] = [];\n for (const u of this.getUsers()) {\n if (this.userModifiedMap[u.userId] === u.getLastModifiedTime()) continue;\n if (!u.events.presence) continue;\n\n userTuples.push([u.userId, u.events.presence.event]);\n\n // note that we've saved this version of the user\n this.userModifiedMap[u.userId] = u.getLastModifiedTime();\n }\n\n return this.backend.syncToDatabase(userTuples);\n }, null);\n\n public setSyncData = this.degradable((syncData: ISyncResponse): Promise<void> => {\n return this.backend.setSyncData(syncData);\n }, \"setSyncData\");\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers = this.degradable((roomId: string): Promise<IStateEventWithRoomId[] | null> => {\n return this.backend.getOutOfBandMembers(roomId);\n }, \"getOutOfBandMembers\");\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param membershipEvents - the membership events to store\n * @returns when all members have been stored\n */\n public setOutOfBandMembers = this.degradable(\n (roomId: string, membershipEvents: IStateEventWithRoomId[]): Promise<void> => {\n super.setOutOfBandMembers(roomId, membershipEvents);\n return this.backend.setOutOfBandMembers(roomId, membershipEvents);\n },\n \"setOutOfBandMembers\",\n );\n\n public clearOutOfBandMembers = this.degradable((roomId: string) => {\n super.clearOutOfBandMembers(roomId);\n return this.backend.clearOutOfBandMembers(roomId);\n }, \"clearOutOfBandMembers\");\n\n public getClientOptions = this.degradable((): Promise<IStoredClientOpts | undefined> => {\n return this.backend.getClientOptions();\n }, \"getClientOptions\");\n\n public storeClientOptions = this.degradable((options: IStoredClientOpts): Promise<void> => {\n super.storeClientOptions(options);\n return this.backend.storeClientOptions(options);\n }, \"storeClientOptions\");\n\n /**\n * All member functions of `IndexedDBStore` that access the backend use this wrapper to\n * watch for failures after initial store startup, including `QuotaExceededError` as\n * free disk space changes, etc.\n *\n * When IndexedDB fails via any of these paths, we degrade this back to a `MemoryStore`\n * in place so that the current operation and all future ones are in-memory only.\n *\n * @param func - The degradable work to do.\n * @param fallback - The method name for fallback.\n * @returns A wrapped member function.\n */\n private degradable<A extends Array<any>, F extends keyof MemoryStore | null, R = void>(\n func: DegradableFn<A, R>,\n fallback: F,\n ): DegradableFn<A, F extends string ? R : void> {\n const fallbackFn = fallback ? (super[fallback] as (...args: A) => Promise<R>) : null;\n\n return (async (...args) => {\n try {\n return await func.call(this, ...args);\n } catch (e) {\n logger.error(\"IndexedDBStore failure, degrading to MemoryStore\", e);\n this.emitter.emit(\"degraded\", e as Error);\n try {\n // We try to delete IndexedDB after degrading since this store is only a\n // cache (the app will still function correctly without the data).\n // It's possible that deleting repair IndexedDB for the next app load,\n // potentially by making a little more space available.\n logger.log(\"IndexedDBStore trying to delete degraded data\");\n await this.backend.clearDatabase();\n logger.log(\"IndexedDBStore delete after degrading succeeded\");\n } catch (e) {\n logger.warn(\"IndexedDBStore delete after degrading failed\", e);\n }\n // Degrade the store from being an instance of `IndexedDBStore` to instead be\n // an instance of `MemoryStore` so that future API calls use the memory path\n // directly and skip IndexedDB entirely. This should be safe as\n // `IndexedDBStore` already extends from `MemoryStore`, so we are making the\n // store become its parent type in a way. The mutator methods of\n // `IndexedDBStore` also maintain the state that `MemoryStore` uses (many are\n // not overridden at all).\n if (fallbackFn) {\n return fallbackFn.call(this, ...args);\n }\n }\n }) as DegradableFn<A, F extends string ? R : void>;\n }\n\n // XXX: ideally these would be stored in indexeddb as part of the room but,\n // we don't store rooms as such and instead accumulate entire sync responses atm.\n public async getPendingEvents(roomId: string): Promise<Partial<IEvent>[]> {\n if (!this.localStorage) return super.getPendingEvents(roomId);\n\n const serialized = this.localStorage.getItem(pendingEventsKey(roomId));\n if (serialized) {\n try {\n return JSON.parse(serialized);\n } catch (e) {\n logger.error(\"Could not parse persisted pending events\", e);\n }\n }\n return [];\n }\n\n public async setPendingEvents(roomId: string, events: Partial<IEvent>[]): Promise<void> {\n if (!this.localStorage) return super.setPendingEvents(roomId, events);\n\n if (events.length > 0) {\n this.localStorage.setItem(pendingEventsKey(roomId), JSON.stringify(events));\n } else {\n this.localStorage.removeItem(pendingEventsKey(roomId));\n }\n }\n\n public saveToDeviceBatches(batches: ToDeviceBatchWithTxnId[]): Promise<void> {\n return this.backend.saveToDeviceBatches(batches);\n }\n\n public getOldestToDeviceBatch(): Promise<IndexedToDeviceBatch | null> {\n return this.backend.getOldestToDeviceBatch();\n }\n\n public removeToDeviceBatch(id: number): Promise<void> {\n return this.backend.removeToDeviceBatch(id);\n }\n\n public async getUserProfile(userId: string): Promise<SyncUserProfile | undefined> {\n return this.backend.getUserProfile(userId);\n }\n\n public async storeUserProfiles(userProfiles: Map<string, SyncUserProfile>): Promise<void> {\n return this.backend.storeUserProfiles(userProfiles);\n }\n\n public async removeUserProfiles(userIds: string[]): Promise<void> {\n return this.backend.removeUserProfiles(userIds);\n }\n}\n\n/**\n * @param roomId - ID of the current room\n * @returns Storage key to retrieve pending events\n */\nfunction pendingEventsKey(roomId: string): string {\n return `mx_pending_events_${roomId}`;\n}\n\ntype DegradableFn<A extends Array<any>, T> = (...args: A) => Promise<T>;\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,SAAS,WAAW,QAAiC,aAAa;AAClE,SAAS,0BAA0B,QAAQ,8BAA8B;AACzE,SAAS,2BAA2B,QAAQ,+BAA+B;AAC3E,SAAsB,WAAW,QAAQ,oBAAoB;AAC7D,SAAS,MAAM,QAAQ,cAAc;AAIrC,SAAkC,iBAAiB,QAAQ,kCAAkC;AAM7F;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM,cAAc,GAAG,IAAI,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;;AAoBtC,OAAO,MAAM,cAAc,SAAS,WAAW,CAAC;EAC5C,OAAc,MAAM,CAAC,SAAqB,EAAE,MAAc,EAAoB;IAC1E,OAAO,0BAA0B,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC;EAC/D;EAYA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACW,WAAW,CAAkB,IAAW,EAAE;IAC7C,KAAK,CAAC,IAAI,CAAC;IAAC;IAAA,mCApCI,KAAK;IAAA,gCACR,CAAC;IAClB;IACA;IACA;IAAA,yCACkD,CAAC,CAAC;IAAE;IAAA,iCACpC,IAAI,iBAAiB,CAAyC,CAAC;IAAA,iCA0G/D,MAAY;MAC1B,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC;IAC/B,CAAC;IAED;AACJ;AACA;AACA;AACA;IAJI,sCAKsB,IAAI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AiB,EAAiB;IAC9D,OAAO,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,OAAO,CAAC;EACnD;AACJ;;AAEA;AACA;AACA;AACA;AACA,SAAS,gBAAgB,CAAC,MAAc,EAAU;EAC9C,OAAO,qBAAqB,MAAM,EAAE;AACxC","ignoreList":[]}
1
+ {"version":3,"file":"indexeddb.js","names":[],"sources":["../../src/store/indexeddb.ts"],"sourcesContent":["/*\nCopyright 2017 - 2021 Vector Creations Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MemoryStore, type IOpts as IBaseOpts } from \"./memory.ts\";\nimport { LocalIndexedDBStoreBackend } from \"./indexeddb-local-backend.ts\";\nimport { RemoteIndexedDBStoreBackend } from \"./indexeddb-remote-backend.ts\";\nimport { type IEvent, MatrixEvent } from \"../models/event.ts\";\nimport { logger } from \"../logger.ts\";\nimport { type ISavedSync } from \"./index.ts\";\nimport { type IIndexedDBBackend } from \"./indexeddb-backend.ts\";\nimport { type ISyncResponse } from \"../sync-accumulator.ts\";\nimport { type EventEmitterEvents, TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\nimport { type IStateEventWithRoomId } from \"../@types/search.ts\";\nimport { type IndexedToDeviceBatch, type ToDeviceBatchWithTxnId } from \"../models/ToDeviceMessage.ts\";\nimport { type IStoredClientOpts } from \"../client.ts\";\nimport { type SyncUserProfile } from \"../models/user.ts\";\n\n/**\n * This is an internal module. See {@link IndexedDBStore} for the public class.\n */\n\n// If this value is too small we'll be writing very often which will cause\n// noticeable stop-the-world pauses. If this value is too big we'll be writing\n// so infrequently that the /sync size gets bigger on reload. Writing more\n// often does not affect the length of the pause since the entire /sync\n// response is persisted each time.\nconst WRITE_DELAY_MS = 1000 * 60 * 5; // once every 5 minutes\n\ninterface IOpts extends IBaseOpts {\n /** The Indexed DB interface e.g. `window.indexedDB` */\n indexedDB?: IDBFactory;\n /** Optional database name. The same name must be used to open the same database. */\n dbName?: string;\n /** Optional factory to spin up a Worker to execute the IDB transactions within. */\n workerFactory?: () => Worker;\n}\n\ntype EventHandlerMap = {\n // Fired when an IDB command fails on a degradable path, and the store falls back to MemoryStore\n // This signals the potential for data volatility.\n degraded: (e: Error) => void;\n // Fired when the IndexedDB gets closed unexpectedly, for example, if the underlying storage is removed or\n // if the user clears the database in the browser's history preferences.\n closed: () => void;\n};\n\nexport class IndexedDBStore extends MemoryStore {\n public static exists(indexedDB: IDBFactory, dbName: string): Promise<boolean> {\n return LocalIndexedDBStoreBackend.exists(indexedDB, dbName);\n }\n\n public _backend: IIndexedDBBackend;\n\n private startedUp = false;\n private syncTs = 0;\n // Records the last-modified-time of each user at the last point we saved\n // the database, such that we can derive the set if users that have been\n // modified since we last saved.\n private userModifiedMap: Record<string, number> = {}; // user_id : timestamp\n private emitter = new TypedEventEmitter<keyof EventHandlerMap, EventHandlerMap>();\n\n /**\n * Construct a new Indexed Database store, which extends MemoryStore.\n *\n * This store functions like a MemoryStore except it periodically persists\n * the contents of the store to an IndexedDB backend.\n *\n * All data is still kept in-memory but can be loaded from disk by calling\n * `startup()`. This can make startup times quicker as a complete\n * sync from the server is not required. This does not reduce memory usage as all\n * the data is eagerly fetched when `startup()` is called.\n * ```\n * let opts = { indexedDB: window.indexedDB, localStorage: window.localStorage };\n * let store = new IndexedDBStore(opts);\n * let client = sdk.createClient({\n * store: store,\n * });\n * await store.startup(); // load from indexed db, must be called after createClient\n * client.startClient();\n * client.on(\"sync\", function(state, prevState, data) {\n * if (state === \"PREPARED\") {\n * console.log(\"Started up, now with go faster stripes!\");\n * }\n * });\n * ```\n *\n * @param opts - Options object.\n */\n public constructor(private readonly opts: IOpts) {\n super(opts);\n\n if (!opts.indexedDB) {\n throw new Error(\"Missing required option: indexedDB\");\n }\n\n if (opts.workerFactory) {\n this._backend = new RemoteIndexedDBStoreBackend(opts.workerFactory, opts.dbName);\n } else {\n this._backend = new LocalIndexedDBStoreBackend(opts.indexedDB, opts.dbName);\n }\n }\n\n /**\n * The backend instance.\n * Call through to this API if you need to perform specific indexeddb actions like deleting the database.\n */\n public get backend(): IIndexedDBBackend {\n return this._backend;\n }\n\n /** Re-exports `TypedEventEmitter.on` */\n public on(event: EventEmitterEvents | \"degraded\" | \"closed\", handler: (...args: any[]) => void): void {\n this.emitter.on(event, handler);\n }\n\n /**\n * @returns Resolved when loaded from indexed db.\n */\n public startup(): Promise<void> {\n if (this.startedUp) {\n logger.log(`IndexedDBStore.startup: already started`);\n return Promise.resolve();\n }\n\n logger.log(`IndexedDBStore.startup: connecting to backend`);\n return this.backend\n .connect(this.onClose)\n .catch((e) => {\n if (this.opts.workerFactory) {\n logger.log(\"Falling back to local indexeddb backend\");\n this._backend = new LocalIndexedDBStoreBackend(this.opts.indexedDB!, this.opts.dbName);\n return this.backend.connect(this.onClose);\n }\n throw e;\n })\n .then(() => {\n logger.log(`IndexedDBStore.startup: loading presence events`);\n return this.backend.getUserPresenceEvents();\n })\n .then((userPresenceEvents) => {\n logger.log(`IndexedDBStore.startup: processing presence events`);\n userPresenceEvents.forEach(([userId, rawEvent]) => {\n if (!this.createUser) {\n throw new Error(\n \"`IndexedDBStore.startup` must be called after assigning it to the client, not before!\",\n );\n }\n const u = this.createUser(userId);\n if (rawEvent) {\n u.setPresenceEvent(new MatrixEvent(rawEvent));\n }\n this.userModifiedMap[u.userId] = u.getLastModifiedTime();\n this.storeUser(u);\n });\n this.startedUp = true;\n });\n }\n\n /*\n * Close the database and destroy any associated workers\n */\n public destroy(): Promise<void> {\n return this.backend.destroy();\n }\n\n private onClose = (): void => {\n this.emitter.emit(\"closed\");\n };\n\n /**\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync = this.degradable((): Promise<ISavedSync | null> => {\n return this.backend.getSavedSync();\n }, \"getSavedSync\");\n\n /** @returns whether or not the database was newly created in this session. */\n public isNewlyCreated = this.degradable((): Promise<boolean> => {\n return this.backend.isNewlyCreated();\n }, \"isNewlyCreated\");\n\n /**\n * @returns If there is a saved sync, the nextBatch token\n * for this sync, otherwise null.\n */\n public getSavedSyncToken = this.degradable((): Promise<string | null> => {\n return this.backend.getNextBatchToken();\n }, \"getSavedSyncToken\");\n\n /**\n * Delete all data from this store.\n * @returns Promise which resolves if the data was deleted from the database.\n */\n public deleteAllData = this.degradable((): Promise<void> => {\n super.deleteAllData();\n return this.backend.clearDatabase().then(\n () => {\n logger.log(\"Deleted indexeddb data.\");\n },\n (err) => {\n logger.error(`Failed to delete indexeddb data: ${err}`);\n throw err;\n },\n );\n }, null);\n\n /**\n * Whether this store would like to save its data\n * Note that obviously whether the store wants to save or\n * not could change between calling this function and calling\n * save().\n *\n * @returns True if calling save() will actually save\n * (at the time this function is called).\n */\n public wantsSave(): boolean {\n const now = Date.now();\n return now - this.syncTs > WRITE_DELAY_MS;\n }\n\n /**\n * Possibly write data to the database.\n *\n * @param force - True to force a save to happen\n * @returns Promise resolves after the write completes\n * (or immediately if no write is performed)\n */\n public save(force = false): Promise<void> {\n if (force || this.wantsSave()) {\n return this.reallySave();\n }\n return Promise.resolve();\n }\n\n private reallySave = this.degradable((): Promise<void> => {\n this.syncTs = Date.now(); // set now to guard against multi-writes\n\n // work out changed users (this doesn't handle deletions but you\n // can't 'delete' users as they are just presence events).\n const userTuples: [userId: string, presenceEvent: Partial<IEvent>][] = [];\n for (const u of this.getUsers()) {\n if (this.userModifiedMap[u.userId] === u.getLastModifiedTime()) continue;\n if (!u.events.presence) continue;\n\n userTuples.push([u.userId, u.events.presence.event]);\n\n // note that we've saved this version of the user\n this.userModifiedMap[u.userId] = u.getLastModifiedTime();\n }\n\n return this.backend.syncToDatabase(userTuples);\n }, null);\n\n public setSyncData = this.degradable((syncData: ISyncResponse): Promise<void> => {\n return this.backend.setSyncData(syncData);\n }, \"setSyncData\");\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers = this.degradable((roomId: string): Promise<IStateEventWithRoomId[] | null> => {\n return this.backend.getOutOfBandMembers(roomId);\n }, \"getOutOfBandMembers\");\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param membershipEvents - the membership events to store\n * @returns when all members have been stored\n */\n public setOutOfBandMembers = this.degradable(\n (roomId: string, membershipEvents: IStateEventWithRoomId[]): Promise<void> => {\n super.setOutOfBandMembers(roomId, membershipEvents);\n return this.backend.setOutOfBandMembers(roomId, membershipEvents);\n },\n \"setOutOfBandMembers\",\n );\n\n public clearOutOfBandMembers = this.degradable((roomId: string) => {\n super.clearOutOfBandMembers(roomId);\n return this.backend.clearOutOfBandMembers(roomId);\n }, \"clearOutOfBandMembers\");\n\n public getClientOptions = this.degradable((): Promise<IStoredClientOpts | undefined> => {\n return this.backend.getClientOptions();\n }, \"getClientOptions\");\n\n public storeClientOptions = this.degradable((options: IStoredClientOpts): Promise<void> => {\n super.storeClientOptions(options);\n return this.backend.storeClientOptions(options);\n }, \"storeClientOptions\");\n\n /**\n * All member functions of `IndexedDBStore` that access the backend use this wrapper to\n * watch for failures after initial store startup, including `QuotaExceededError` as\n * free disk space changes, etc.\n *\n * When IndexedDB fails via any of these paths, we degrade this back to a `MemoryStore`\n * in place so that the current operation and all future ones are in-memory only.\n *\n * @param func - The degradable work to do.\n * @param fallback - The method name for fallback.\n * @returns A wrapped member function.\n */\n private degradable<A extends Array<any>, F extends keyof MemoryStore | null, R = void>(\n func: DegradableFn<A, R>,\n fallback: F,\n ): DegradableFn<A, F extends string ? R : void> {\n const fallbackFn = fallback ? (super[fallback] as (...args: A) => Promise<R>) : null;\n\n return (async (...args) => {\n try {\n return await func.call(this, ...args);\n } catch (e) {\n logger.error(\"IndexedDBStore failure, degrading to MemoryStore\", e);\n this.emitter.emit(\"degraded\", e as Error);\n try {\n // We try to delete IndexedDB after degrading since this store is only a\n // cache (the app will still function correctly without the data).\n // It's possible that deleting repair IndexedDB for the next app load,\n // potentially by making a little more space available.\n logger.log(\"IndexedDBStore trying to delete degraded data\");\n await this.backend.clearDatabase();\n logger.log(\"IndexedDBStore delete after degrading succeeded\");\n } catch (e) {\n logger.warn(\"IndexedDBStore delete after degrading failed\", e);\n }\n // Degrade the store from being an instance of `IndexedDBStore` to instead be\n // an instance of `MemoryStore` so that future API calls use the memory path\n // directly and skip IndexedDB entirely. This should be safe as\n // `IndexedDBStore` already extends from `MemoryStore`, so we are making the\n // store become its parent type in a way. The mutator methods of\n // `IndexedDBStore` also maintain the state that `MemoryStore` uses (many are\n // not overridden at all).\n if (fallbackFn) {\n return fallbackFn.call(this, ...args);\n }\n }\n }) as DegradableFn<A, F extends string ? R : void>;\n }\n\n // XXX: ideally these would be stored in indexeddb as part of the room but,\n // we don't store rooms as such and instead accumulate entire sync responses atm.\n public async getPendingEvents(roomId: string): Promise<Partial<IEvent>[]> {\n if (!this.localStorage) return super.getPendingEvents(roomId);\n\n const serialized = this.localStorage.getItem(pendingEventsKey(roomId));\n if (serialized) {\n try {\n return JSON.parse(serialized);\n } catch (e) {\n logger.error(\"Could not parse persisted pending events\", e);\n }\n }\n return [];\n }\n\n public async setPendingEvents(roomId: string, events: Partial<IEvent>[]): Promise<void> {\n if (!this.localStorage) return super.setPendingEvents(roomId, events);\n\n if (events.length > 0) {\n this.localStorage.setItem(pendingEventsKey(roomId), JSON.stringify(events));\n } else {\n this.localStorage.removeItem(pendingEventsKey(roomId));\n }\n }\n\n public saveToDeviceBatches(batches: ToDeviceBatchWithTxnId[]): Promise<void> {\n return this.backend.saveToDeviceBatches(batches);\n }\n\n public getOldestToDeviceBatch(): Promise<IndexedToDeviceBatch | null> {\n return this.backend.getOldestToDeviceBatch();\n }\n\n public removeToDeviceBatch(id: number): Promise<void> {\n return this.backend.removeToDeviceBatch(id);\n }\n\n public async getUserProfile(userId: string): Promise<SyncUserProfile | undefined> {\n return this.backend.getUserProfile(userId);\n }\n\n public async storeUserProfiles(userProfiles: Map<string, SyncUserProfile>): Promise<void> {\n return this.backend.storeUserProfiles(userProfiles);\n }\n\n public async removeUserProfiles(userIds: string[]): Promise<void> {\n return this.backend.removeUserProfiles(userIds);\n }\n}\n\n/**\n * @param roomId - ID of the current room\n * @returns Storage key to retrieve pending events\n */\nfunction pendingEventsKey(roomId: string): string {\n return `mx_pending_events_${roomId}`;\n}\n\ntype DegradableFn<A extends Array<any>, T> = (...args: A) => Promise<T>;\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,WAAW,QAAiC,aAAa;AAClE,SAAS,0BAA0B,QAAQ,8BAA8B;AACzE,SAAS,2BAA2B,QAAQ,+BAA+B;AAC3E,SAAsB,WAAW,QAAQ,oBAAoB;AAC7D,SAAS,MAAM,QAAQ,cAAc;AAIrC,SAAkC,iBAAiB,QAAQ,kCAAkC;AAM7F;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM,cAAc,GAAG,IAAI,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;;AAoBtC,OAAO,MAAM,cAAc,SAAS,WAAW,CAAC;EAC5C,OAAc,MAAM,CAAC,SAAqB,EAAE,MAAc,EAAoB;IAC1E,OAAO,0BAA0B,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC;EAC/D;EAYA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACW,WAA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;IAEY,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAEhF;IAEY,iBAAiB,CAAC,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAExF;IAEY,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhE;IAEY,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAEnF;IAEY,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAEpC;CACJ"}
@@ -237,7 +237,9 @@ export class MemoryStore {
237
237
  if (isValidFilterId(value)) {
238
238
  return value;
239
239
  }
240
- } catch {}
240
+ } catch {
241
+ // Do nothing
242
+ }
241
243
  return null;
242
244
  }
243
245
 
@@ -255,7 +257,9 @@ export class MemoryStore {
255
257
  } else {
256
258
  this.localStorage.removeItem(key);
257
259
  }
258
- } catch {}
260
+ } catch {
261
+ // Do nothing
262
+ }
259
263
  }
260
264
 
261
265
  /**
@@ -266,13 +270,7 @@ export class MemoryStore {
266
270
  */
267
271
  storeAccountDataEvents(events) {
268
272
  events.forEach(event => {
269
- // MSC3391: an event with content of {} should be interpreted as deleted
270
- const isDeleted = !Object.keys(event.getContent()).length;
271
- if (isDeleted) {
272
- this.accountData.delete(event.getType());
273
- } else {
274
- this.accountData.set(event.getType(), event);
275
- }
273
+ this.accountData.set(event.getType(), event);
276
274
  });
277
275
  }
278
276
 
@@ -1 +1 @@
1
- {"version":3,"file":"memory.js","names":[],"sources":["../../src/store/memory.ts"],"sourcesContent":["/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MemoryStore} for the public class.\n */\n\nimport { type EventType } from \"../@types/event.ts\";\nimport { type Room } from \"../models/room.ts\";\nimport { type SyncUserProfile, type User } from \"../models/user.ts\";\nimport { type IEvent, type MatrixEvent } from \"../models/event.ts\";\nimport { type RoomState, RoomStateEvent } from \"../models/room-state.ts\";\nimport { type RoomMember } from \"../models/room-member.ts\";\nimport { type Filter } from \"../filter.ts\";\nimport { type ISavedSync, type IStore, type UserCreator } from \"./index.ts\";\nimport { type RoomSummary } from \"../models/room-summary.ts\";\nimport { type ISyncResponse } from \"../sync-accumulator.ts\";\nimport { type IStateEventWithRoomId } from \"../@types/search.ts\";\nimport { type IndexedToDeviceBatch, type ToDeviceBatchWithTxnId } from \"../models/ToDeviceMessage.ts\";\nimport { type IStoredClientOpts } from \"../client.ts\";\nimport { MapWithDefault } from \"../utils.ts\";\nimport { KnownMembership } from \"../@types/membership.ts\";\n\nfunction isValidFilterId(filterId?: string | number | null): boolean {\n const isValidStr =\n typeof filterId === \"string\" &&\n !!filterId &&\n filterId !== \"undefined\" && // exclude these as we've serialized undefined in localStorage before\n filterId !== \"null\";\n\n return isValidStr || typeof filterId === \"number\";\n}\n\nexport interface IOpts {\n /** The local storage instance to persist some forms of data such as tokens. Rooms will NOT be stored. */\n localStorage?: Storage;\n}\n\nexport class MemoryStore implements IStore {\n private rooms: Record<string, Room> = {}; // roomId: Room\n private users: Record<string, User> = {}; // userId: User\n private syncToken: string | null = null;\n // userId: {\n // filterId: Filter\n // }\n private filters: MapWithDefault<string, Map<string, Filter>> = new MapWithDefault(() => new Map());\n public accountData: Map<string, MatrixEvent> = new Map(); // type: content\n protected readonly localStorage?: Storage;\n private oobMembers: Map<string, IStateEventWithRoomId[]> = new Map(); // roomId: [member events]\n private pendingEvents: { [roomId: string]: Partial<IEvent>[] } = {};\n private clientOptions?: IStoredClientOpts;\n private pendingToDeviceBatches: IndexedToDeviceBatch[] = [];\n private nextToDeviceBatchId = 0;\n protected createUser?: UserCreator;\n public readonly userProfiles = new Map<string, SyncUserProfile>();\n\n /**\n * Construct a new in-memory data store for the Matrix Client.\n * @param opts - Config options\n */\n public constructor(opts: IOpts = {}) {\n this.localStorage = opts.localStorage;\n }\n\n /**\n * Retrieve the token to stream from.\n * @returns The token or null.\n */\n public getSyncToken(): string | null {\n return this.syncToken;\n }\n\n /** @returns whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n /**\n * Set the token to stream from.\n * @param token - The token to stream from.\n */\n public setSyncToken(token: string): void {\n this.syncToken = token;\n }\n\n /**\n * Store the given room.\n * @param room - The room to be stored. All properties must be stored.\n */\n public storeRoom(room: Room): void {\n this.rooms[room.roomId] = room;\n // add listeners for room member changes so we can keep the room member\n // map up-to-date.\n room.currentState.on(RoomStateEvent.Members, this.onRoomMember);\n // add existing members\n room.currentState.getMembers().forEach((m) => {\n this.onRoomMember(null, room.currentState, m);\n });\n }\n\n public setUserCreator(creator: UserCreator): void {\n this.createUser = creator;\n }\n\n /**\n * Called when a room member in a room being tracked by this store has been\n * updated.\n */\n private onRoomMember = (event: MatrixEvent | null, state: RoomState, member: RoomMember): void => {\n if (member.membership === KnownMembership.Invite) {\n // We do NOT add invited members because people love to typo user IDs\n // which would then show up in these lists (!)\n return;\n }\n\n const user = this.users[member.userId] || this.createUser?.(member.userId);\n if (member.name) {\n user.setDisplayName(member.name);\n if (member.events.member) {\n user.setRawDisplayName(member.events.member.getDirectionalContent().displayname);\n }\n }\n if (member.events.member && member.events.member.getContent().avatar_url) {\n user.setAvatarUrl(member.events.member.getContent().avatar_url);\n }\n this.users[user.userId] = user;\n };\n\n /**\n * Retrieve a room by its' room ID.\n * @param roomId - The room ID.\n * @returns The room or null.\n */\n public getRoom(roomId: string): Room | null {\n return this.rooms[roomId] || null;\n }\n\n /**\n * Retrieve all known rooms.\n * @returns A list of rooms, which may be empty.\n */\n public getRooms(): Room[] {\n return Object.values(this.rooms);\n }\n\n /**\n * Permanently delete a room.\n */\n public removeRoom(roomId: string): void {\n if (this.rooms[roomId]) {\n this.rooms[roomId].currentState.removeListener(RoomStateEvent.Members, this.onRoomMember);\n }\n delete this.rooms[roomId];\n }\n\n /**\n * Retrieve a summary of all the rooms.\n * @returns A summary of each room.\n */\n public getRoomSummaries(): RoomSummary[] {\n return Object.values(this.rooms).map(function (room) {\n return room.summary!;\n });\n }\n\n /**\n * Store a User.\n * @param user - The user to store.\n */\n public storeUser(user: User): void {\n this.users[user.userId] = user;\n }\n\n /**\n * Retrieve a User by its' user ID.\n * @param userId - The user ID.\n * @returns The user or null.\n */\n public getUser(userId: string): User | null {\n return this.users[userId] || null;\n }\n\n /**\n * Retrieve all known users.\n * @returns A list of users, which may be empty.\n */\n public getUsers(): User[] {\n return Object.values(this.users);\n }\n\n /**\n * Retrieve scrollback for this room.\n * @param room - The matrix room\n * @param limit - The max number of old events to retrieve.\n * @returns An array of objects which will be at most 'limit'\n * length and at least 0. The objects are the raw event JSON.\n */\n public scrollback(room: Room, limit: number): MatrixEvent[] {\n return [];\n }\n\n /**\n * Store events for a room. The events have already been added to the timeline\n * @param room - The room to store events for.\n * @param events - The events to store.\n * @param token - The token associated with these events.\n * @param toStart - True if these are paginated results.\n */\n public storeEvents(room: Room, events: MatrixEvent[], token: string | null, toStart: boolean): void {\n // no-op because they've already been added to the room instance.\n }\n\n /**\n * Store a filter.\n */\n public storeFilter(filter: Filter): void {\n if (!filter?.userId || !filter?.filterId) return;\n this.filters.getOrCreate(filter.userId).set(filter.filterId, filter);\n }\n\n /**\n * Retrieve a filter.\n * @returns A filter or null.\n */\n public getFilter(userId: string, filterId: string): Filter | null {\n return this.filters.get(userId)?.get(filterId) || null;\n }\n\n /**\n * Retrieve a filter ID with the given name.\n * @param filterName - The filter name.\n * @returns The filter ID or null.\n */\n public getFilterIdByName(filterName: string): string | null {\n if (!this.localStorage) {\n return null;\n }\n const key = \"mxjssdk_memory_filter_\" + filterName;\n // XXX Storage.getItem doesn't throw ...\n // or are we using something different\n // than window.localStorage in some cases\n // that does throw?\n // that would be very naughty\n try {\n const value = this.localStorage.getItem(key);\n if (isValidFilterId(value)) {\n return value;\n }\n } catch {}\n return null;\n }\n\n /**\n * Set a filter name to ID mapping.\n */\n public setFilterIdByName(filterName: string, filterId?: string): void {\n if (!this.localStorage) {\n return;\n }\n const key = \"mxjssdk_memory_filter_\" + filterName;\n try {\n if (isValidFilterId(filterId)) {\n this.localStorage.setItem(key, filterId!);\n } else {\n this.localStorage.removeItem(key);\n }\n } catch {}\n }\n\n /**\n * Store user-scoped account data events.\n * N.B. that account data only allows a single event per type, so multiple\n * events with the same type will replace each other.\n * @param events - The events to store.\n */\n public storeAccountDataEvents(events: MatrixEvent[]): void {\n events.forEach((event) => {\n // MSC3391: an event with content of {} should be interpreted as deleted\n const isDeleted = !Object.keys(event.getContent()).length;\n if (isDeleted) {\n this.accountData.delete(event.getType());\n } else {\n this.accountData.set(event.getType(), event);\n }\n });\n }\n\n /**\n * Get account data event by event type\n * @param eventType - The event type being queried\n * @returns the user account_data event of given type, if any\n */\n public getAccountData(eventType: EventType | string): MatrixEvent | undefined {\n return this.accountData.get(eventType);\n }\n\n /**\n * setSyncData does nothing as there is no backing data store.\n *\n * @param syncData - The sync data\n * @returns An immediately resolved promise.\n */\n public setSyncData(syncData: ISyncResponse): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * We never want to save becase we have nothing to save to.\n *\n * @returns If the store wants to save\n */\n public wantsSave(): boolean {\n return false;\n }\n\n /**\n * Save does nothing as there is no backing data store.\n * @param force - True to force a save (but the memory\n * store still can't save anything)\n */\n public save(force: boolean): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Startup does nothing as this store doesn't require starting up.\n * @returns An immediately resolved promise.\n */\n public startup(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync(): Promise<ISavedSync | null> {\n return Promise.resolve(null);\n }\n\n /**\n * @returns If there is a saved sync, the nextBatch token\n * for this sync, otherwise null.\n */\n public getSavedSyncToken(): Promise<string | null> {\n return Promise.resolve(null);\n }\n\n /**\n * Delete all data from this store.\n * @returns An immediately resolved promise.\n */\n public deleteAllData(): Promise<void> {\n this.rooms = {\n // roomId: Room\n };\n this.users = {\n // userId: User\n };\n this.syncToken = null;\n this.filters = new MapWithDefault(() => new Map());\n this.accountData = new Map(); // type : content\n return Promise.resolve();\n }\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers(roomId: string): Promise<IStateEventWithRoomId[] | null> {\n return Promise.resolve(this.oobMembers.get(roomId) || null);\n }\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param membershipEvents - the membership events to store\n * @returns when all members have been stored\n */\n public setOutOfBandMembers(roomId: string, membershipEvents: IStateEventWithRoomId[]): Promise<void> {\n this.oobMembers.set(roomId, membershipEvents);\n return Promise.resolve();\n }\n\n public clearOutOfBandMembers(roomId: string): Promise<void> {\n this.oobMembers.delete(roomId);\n return Promise.resolve();\n }\n\n public getClientOptions(): Promise<IStoredClientOpts | undefined> {\n return Promise.resolve(this.clientOptions);\n }\n\n public storeClientOptions(options: IStoredClientOpts): Promise<void> {\n this.clientOptions = Object.assign({}, options);\n return Promise.resolve();\n }\n\n public async getPendingEvents(roomId: string): Promise<Partial<IEvent>[]> {\n return this.pendingEvents[roomId] ?? [];\n }\n\n public async setPendingEvents(roomId: string, events: Partial<IEvent>[]): Promise<void> {\n this.pendingEvents[roomId] = events;\n }\n\n public saveToDeviceBatches(batches: ToDeviceBatchWithTxnId[]): Promise<void> {\n for (const batch of batches) {\n this.pendingToDeviceBatches.push({\n id: this.nextToDeviceBatchId++,\n eventType: batch.eventType,\n txnId: batch.txnId,\n batch: batch.batch,\n });\n }\n return Promise.resolve();\n }\n\n public async getOldestToDeviceBatch(): Promise<IndexedToDeviceBatch | null> {\n if (this.pendingToDeviceBatches.length === 0) return null;\n return this.pendingToDeviceBatches[0];\n }\n\n public removeToDeviceBatch(id: number): Promise<void> {\n this.pendingToDeviceBatches = this.pendingToDeviceBatches.filter((batch) => batch.id !== id);\n return Promise.resolve();\n }\n\n public async getUserProfile(userId: string): Promise<SyncUserProfile | undefined> {\n return this.userProfiles.get(userId);\n }\n\n public async storeUserProfiles(userProfiles: Map<string, SyncUserProfile>): Promise<void> {\n userProfiles.forEach((profile, userId) => this.userProfiles.set(userId, profile));\n }\n\n public async removeUserProfiles(userIds: string[]): Promise<void> {\n userIds.forEach((userId) => this.userProfiles.delete(userId));\n }\n\n public async removeEventsFromRoom(roomId: string, eventIds: string[]): Promise<void> {\n // Can ignore as there is no backing store.\n }\n\n public async destroy(): Promise<void> {\n // Nothing to do\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAMA,SAAyB,cAAc,QAAQ,yBAAyB;AASxE,SAAS,cAAc,QAAQ,aAAa;AAC5C,SAAS,eAAe,QAAQ,yBAAyB;AAEzD,SAAS,eAAe,CAAC,QAAiC,EAAW;EACjE,MAAM,UAAU,GACZ,OAAO,QAAQ,KAAK,QAAQ,IAC5B,CAAC,CAAC,QAAQ,IACV,QAAQ,KAAK,WAAW;EAAI;EAC5B,QAAQ,KAAK,MAAM;EAEvB,OAAO,UAAU,IAAI,OAAO,QAAQ,KAAK,QAAQ;AACrD;AAOA,OAAO,MAAM,WAAW,CAAmB;EAkBvC;AACJ;AACA;A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IACN;IACA,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC;EAC5B;EAEA,MAAa,sBAAsB,GAAyC;IACxE,IAAI,IAAI,CAAC,sBAAsB,CAAC,MAAM,KAAK,CAAC,EAAE,OAAO,IAAI;IACzD,OAAO,IAAI,CAAC,sBAAsB,CAAC,CAAC,CAAC;EACzC;EAEO,mBAAmB,CAAC,EAAU,EAAiB;IAClD,IAAI,CAAC,sBAAsB,GAAG,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAE,KAAK,IAAK,KAAK,CAAC,EAAE,KAAK,EAAE,CAAC;IAC5F,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC;EAC5B;EAEA,MAAa,cAAc,CAAC,MAAc,EAAwC;IAC9E,OAAO,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC;EACxC;EAEA,MAAa,iBAAiB,CAAC,YAA0C,EAAiB;IACtF,YAAY,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;EACrF;EAEA,MAAa,kBAAkB,CAAC,OAAiB,EAAiB;IAC9D,OAAO,CAAC,OAAO,CAAE,MAAM,IAAK,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;EACjE;EAEA,MAAa,oBAAoB,CAAC,MAAc,EAAE,QAAkB,EAAiB;IACjF;EAAA;EAGJ,MAAa,OAAO,GAAkB;IAClC;EAAA;AAER","ignoreList":[]}
1
+ {"version":3,"file":"memory.js","names":[],"sources":["../../src/store/memory.ts"],"sourcesContent":["/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MemoryStore} for the public class.\n */\n\nimport { type EventType } from \"../@types/event.ts\";\nimport { type Room } from \"../models/room.ts\";\nimport { type SyncUserProfile, type User } from \"../models/user.ts\";\nimport { type IEvent, type MatrixEvent } from \"../models/event.ts\";\nimport { type RoomState, RoomStateEvent } from \"../models/room-state.ts\";\nimport { type RoomMember } from \"../models/room-member.ts\";\nimport { type Filter } from \"../filter.ts\";\nimport { type ISavedSync, type IStore, type UserCreator } from \"./index.ts\";\nimport { type RoomSummary } from \"../models/room-summary.ts\";\nimport { type ISyncResponse } from \"../sync-accumulator.ts\";\nimport { type IStateEventWithRoomId } from \"../@types/search.ts\";\nimport { type IndexedToDeviceBatch, type ToDeviceBatchWithTxnId } from \"../models/ToDeviceMessage.ts\";\nimport { type IStoredClientOpts } from \"../client.ts\";\nimport { MapWithDefault } from \"../utils.ts\";\nimport { KnownMembership } from \"../@types/membership.ts\";\n\nfunction isValidFilterId(filterId?: string | number | null): boolean {\n const isValidStr =\n typeof filterId === \"string\" &&\n !!filterId &&\n filterId !== \"undefined\" && // exclude these as we've serialized undefined in localStorage before\n filterId !== \"null\";\n\n return isValidStr || typeof filterId === \"number\";\n}\n\nexport interface IOpts {\n /** The local storage instance to persist some forms of data such as tokens. Rooms will NOT be stored. */\n localStorage?: Storage;\n}\n\nexport class MemoryStore implements IStore {\n private rooms: Record<string, Room> = {}; // roomId: Room\n private users: Record<string, User> = {}; // userId: User\n private syncToken: string | null = null;\n // userId: {\n // filterId: Filter\n // }\n private filters: MapWithDefault<string, Map<string, Filter>> = new MapWithDefault(() => new Map());\n public accountData: Map<string, MatrixEvent> = new Map(); // type: content\n protected readonly localStorage?: Storage;\n private oobMembers: Map<string, IStateEventWithRoomId[]> = new Map(); // roomId: [member events]\n private pendingEvents: { [roomId: string]: Partial<IEvent>[] } = {};\n private clientOptions?: IStoredClientOpts;\n private pendingToDeviceBatches: IndexedToDeviceBatch[] = [];\n private nextToDeviceBatchId = 0;\n protected createUser?: UserCreator;\n public readonly userProfiles = new Map<string, SyncUserProfile>();\n\n /**\n * Construct a new in-memory data store for the Matrix Client.\n * @param opts - Config options\n */\n public constructor(opts: IOpts = {}) {\n this.localStorage = opts.localStorage;\n }\n\n /**\n * Retrieve the token to stream from.\n * @returns The token or null.\n */\n public getSyncToken(): string | null {\n return this.syncToken;\n }\n\n /** @returns whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n /**\n * Set the token to stream from.\n * @param token - The token to stream from.\n */\n public setSyncToken(token: string): void {\n this.syncToken = token;\n }\n\n /**\n * Store the given room.\n * @param room - The room to be stored. All properties must be stored.\n */\n public storeRoom(room: Room): void {\n this.rooms[room.roomId] = room;\n // add listeners for room member changes so we can keep the room member\n // map up-to-date.\n room.currentState.on(RoomStateEvent.Members, this.onRoomMember);\n // add existing members\n room.currentState.getMembers().forEach((m) => {\n this.onRoomMember(null, room.currentState, m);\n });\n }\n\n public setUserCreator(creator: UserCreator): void {\n this.createUser = creator;\n }\n\n /**\n * Called when a room member in a room being tracked by this store has been\n * updated.\n */\n private onRoomMember = (event: MatrixEvent | null, state: RoomState, member: RoomMember): void => {\n if (member.membership === KnownMembership.Invite) {\n // We do NOT add invited members because people love to typo user IDs\n // which would then show up in these lists (!)\n return;\n }\n\n const user = this.users[member.userId] || this.createUser?.(member.userId);\n if (member.name) {\n user.setDisplayName(member.name);\n if (member.events.member) {\n user.setRawDisplayName(member.events.member.getDirectionalContent().displayname);\n }\n }\n if (member.events.member && member.events.member.getContent().avatar_url) {\n user.setAvatarUrl(member.events.member.getContent().avatar_url);\n }\n this.users[user.userId] = user;\n };\n\n /**\n * Retrieve a room by its' room ID.\n * @param roomId - The room ID.\n * @returns The room or null.\n */\n public getRoom(roomId: string): Room | null {\n return this.rooms[roomId] || null;\n }\n\n /**\n * Retrieve all known rooms.\n * @returns A list of rooms, which may be empty.\n */\n public getRooms(): Room[] {\n return Object.values(this.rooms);\n }\n\n /**\n * Permanently delete a room.\n */\n public removeRoom(roomId: string): void {\n if (this.rooms[roomId]) {\n this.rooms[roomId].currentState.removeListener(RoomStateEvent.Members, this.onRoomMember);\n }\n delete this.rooms[roomId];\n }\n\n /**\n * Retrieve a summary of all the rooms.\n * @returns A summary of each room.\n */\n public getRoomSummaries(): RoomSummary[] {\n return Object.values(this.rooms).map(function (room) {\n return room.summary!;\n });\n }\n\n /**\n * Store a User.\n * @param user - The user to store.\n */\n public storeUser(user: User): void {\n this.users[user.userId] = user;\n }\n\n /**\n * Retrieve a User by its' user ID.\n * @param userId - The user ID.\n * @returns The user or null.\n */\n public getUser(userId: string): User | null {\n return this.users[userId] || null;\n }\n\n /**\n * Retrieve all known users.\n * @returns A list of users, which may be empty.\n */\n public getUsers(): User[] {\n return Object.values(this.users);\n }\n\n /**\n * Retrieve scrollback for this room.\n * @param room - The matrix room\n * @param limit - The max number of old events to retrieve.\n * @returns An array of objects which will be at most 'limit'\n * length and at least 0. The objects are the raw event JSON.\n */\n public scrollback(room: Room, limit: number): MatrixEvent[] {\n return [];\n }\n\n /**\n * Store events for a room. The events have already been added to the timeline\n * @param room - The room to store events for.\n * @param events - The events to store.\n * @param token - The token associated with these events.\n * @param toStart - True if these are paginated results.\n */\n public storeEvents(room: Room, events: MatrixEvent[], token: string | null, toStart: boolean): void {\n // no-op because they've already been added to the room instance.\n }\n\n /**\n * Store a filter.\n */\n public storeFilter(filter: Filter): void {\n if (!filter?.userId || !filter?.filterId) return;\n this.filters.getOrCreate(filter.userId).set(filter.filterId, filter);\n }\n\n /**\n * Retrieve a filter.\n * @returns A filter or null.\n */\n public getFilter(userId: string, filterId: string): Filter | null {\n return this.filters.get(userId)?.get(filterId) || null;\n }\n\n /**\n * Retrieve a filter ID with the given name.\n * @param filterName - The filter name.\n * @returns The filter ID or null.\n */\n public getFilterIdByName(filterName: string): string | null {\n if (!this.localStorage) {\n return null;\n }\n const key = \"mxjssdk_memory_filter_\" + filterName;\n // XXX Storage.getItem doesn't throw ...\n // or are we using something different\n // than window.localStorage in some cases\n // that does throw?\n // that would be very naughty\n try {\n const value = this.localStorage.getItem(key);\n if (isValidFilterId(value)) {\n return value;\n }\n } catch {\n // Do nothing\n }\n return null;\n }\n\n /**\n * Set a filter name to ID mapping.\n */\n public setFilterIdByName(filterName: string, filterId?: string): void {\n if (!this.localStorage) {\n return;\n }\n const key = \"mxjssdk_memory_filter_\" + filterName;\n try {\n if (isValidFilterId(filterId)) {\n this.localStorage.setItem(key, filterId!);\n } else {\n this.localStorage.removeItem(key);\n }\n } catch {\n // Do nothing\n }\n }\n\n /**\n * Store user-scoped account data events.\n * N.B. that account data only allows a single event per type, so multiple\n * events with the same type will replace each other.\n * @param events - The events to store.\n */\n public storeAccountDataEvents(events: MatrixEvent[]): void {\n events.forEach((event) => {\n this.accountData.set(event.getType(), event);\n });\n }\n\n /**\n * Get account data event by event type\n * @param eventType - The event type being queried\n * @returns the user account_data event of given type, if any\n */\n public getAccountData(eventType: EventType | string): MatrixEvent | undefined {\n return this.accountData.get(eventType);\n }\n\n /**\n * setSyncData does nothing as there is no backing data store.\n *\n * @param syncData - The sync data\n * @returns An immediately resolved promise.\n */\n public setSyncData(syncData: ISyncResponse): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * We never want to save becase we have nothing to save to.\n *\n * @returns If the store wants to save\n */\n public wantsSave(): boolean {\n return false;\n }\n\n /**\n * Save does nothing as there is no backing data store.\n * @param force - True to force a save (but the memory\n * store still can't save anything)\n */\n public save(force: boolean): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Startup does nothing as this store doesn't require starting up.\n * @returns An immediately resolved promise.\n */\n public startup(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync(): Promise<ISavedSync | null> {\n return Promise.resolve(null);\n }\n\n /**\n * @returns If there is a saved sync, the nextBatch token\n * for this sync, otherwise null.\n */\n public getSavedSyncToken(): Promise<string | null> {\n return Promise.resolve(null);\n }\n\n /**\n * Delete all data from this store.\n * @returns An immediately resolved promise.\n */\n public deleteAllData(): Promise<void> {\n this.rooms = {\n // roomId: Room\n };\n this.users = {\n // userId: User\n };\n this.syncToken = null;\n this.filters = new MapWithDefault(() => new Map());\n this.accountData = new Map(); // type : content\n return Promise.resolve();\n }\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers(roomId: string): Promise<IStateEventWithRoomId[] | null> {\n return Promise.resolve(this.oobMembers.get(roomId) || null);\n }\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param membershipEvents - the membership events to store\n * @returns when all members have been stored\n */\n public setOutOfBandMembers(roomId: string, membershipEvents: IStateEventWithRoomId[]): Promise<void> {\n this.oobMembers.set(roomId, membershipEvents);\n return Promise.resolve();\n }\n\n public clearOutOfBandMembers(roomId: string): Promise<void> {\n this.oobMembers.delete(roomId);\n return Promise.resolve();\n }\n\n public getClientOptions(): Promise<IStoredClientOpts | undefined> {\n return Promise.resolve(this.clientOptions);\n }\n\n public storeClientOptions(options: IStoredClientOpts): Promise<void> {\n this.clientOptions = Object.assign({}, options);\n return Promise.resolve();\n }\n\n public async getPendingEvents(roomId: string): Promise<Partial<IEvent>[]> {\n return this.pendingEvents[roomId] ?? [];\n }\n\n public async setPendingEvents(roomId: string, events: Partial<IEvent>[]): Promise<void> {\n this.pendingEvents[roomId] = events;\n }\n\n public saveToDeviceBatches(batches: ToDeviceBatchWithTxnId[]): Promise<void> {\n for (const batch of batches) {\n this.pendingToDeviceBatches.push({\n id: this.nextToDeviceBatchId++,\n eventType: batch.eventType,\n txnId: batch.txnId,\n batch: batch.batch,\n });\n }\n return Promise.resolve();\n }\n\n public async getOldestToDeviceBatch(): Promise<IndexedToDeviceBatch | null> {\n if (this.pendingToDeviceBatches.length === 0) return null;\n return this.pendingToDeviceBatches[0];\n }\n\n public removeToDeviceBatch(id: number): Promise<void> {\n this.pendingToDeviceBatches = this.pendingToDeviceBatches.filter((batch) => batch.id !== id);\n return Promise.resolve();\n }\n\n public async getUserProfile(userId: string): Promise<SyncUserProfile | undefined> {\n return this.userProfiles.get(userId);\n }\n\n public async storeUserProfiles(userProfiles: Map<string, SyncUserProfile>): Promise<void> {\n userProfiles.forEach((profile, userId) => this.userProfiles.set(userId, profile));\n }\n\n public async removeUserProfiles(userIds: string[]): Promise<void> {\n userIds.forEach((userId) => this.userProfiles.delete(userId));\n }\n\n public async removeEventsFromRoom(roomId: string, eventIds: string[]): Promise<void> {\n // Can ignore as there is no backing store.\n }\n\n public async destroy(): Promise<void> {\n // Nothing to do\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAMA,SAAyB,cAAc,QAAQ,yBAAyB;AASxE,SAAS,cAAc,QAAQ,aAAa;AAC5C,SAAS,eAAe,QAAQ,yBAAyB;AAEzD,SAAS,eAAe,CAAC,QAAiC,EAAW;EACjE,MAAM,UAAU,GACZ,OAAO,QAAQ,KAAK,QAAQ,IAC5B,CAAC,CAAC,QAAQ,IACV,QAAQ,KAAK,WAAW;EAAI;EAC5B,QAAQ,KAAK,MAAM;EAEvB,OAAO,UAAU,IAAI,OAAO,QAAQ,KAAK,QAAQ;AACrD;AAOA,OAAO,MAAM,WAAW,CAAmB;EAkBvC;AACJ;AACA;AACA;EACW,WAAW,CAAC,IAAW,GAAG,CAAC,CAAC,EAAE;IAAA,+BArBC,CAAC,CAAC;IAAE;IAAA,+BACJ,CAAC,CAAC;IAAE;IAAA,mCACP,IAAI;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,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAOpE;CACJ"}
@@ -25,8 +25,6 @@ import { MAX_STICKY_DURATION_MS } from "./models/event.js";
25
25
  import { UNREAD_THREAD_NOTIFICATIONS } from "./@types/sync.js";
26
26
  import { ReceiptAccumulator } from "./receipt-accumulator.js";
27
27
 
28
- /* eslint-disable camelcase */
29
-
30
28
  /** A to-device message as received from the sync. */
31
29
 
32
30
  /**
@@ -42,8 +40,6 @@ import { ReceiptAccumulator } from "./receipt-accumulator.js";
42
40
  * The "users" section of the sync update which contains extended profile updates.
43
41
  */
44
42
 
45
- /* eslint-enable camelcase */
46
-
47
43
  export let Category = /*#__PURE__*/function (Category) {
48
44
  Category["Invite"] = "invite";
49
45
  Category["Leave"] = "leave";
@@ -396,7 +392,7 @@ export class SyncAccumulator {
396
392
  for (let i = startIndex; i < currentData._timeline.length; i++) {
397
393
  if (currentData._timeline[i].token) {
398
394
  // keep all events after this, including this one
399
- currentData._timeline = currentData._timeline.slice(i, currentData._timeline.length);
395
+ currentData._timeline = currentData._timeline.slice(i);
400
396
  break;
401
397
  }
402
398
  }