matrix-js-sdk 41.8.0 → 41.9.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 (458) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +1 -1
  3. package/lib/@types/AESEncryptedSecretStoragePayload.js +3 -1
  4. package/lib/@types/IIdentityServerProvider.js +3 -1
  5. package/lib/@types/PushRules.js +7 -7
  6. package/lib/@types/PushRules.js.map +1 -1
  7. package/lib/@types/auth.js +4 -4
  8. package/lib/@types/auth.js.map +1 -1
  9. package/lib/@types/beacon.js +2 -2
  10. package/lib/@types/beacon.js.map +1 -1
  11. package/lib/@types/common.js +3 -1
  12. package/lib/@types/crypto.js +3 -1
  13. package/lib/@types/event.js +20 -20
  14. package/lib/@types/event.js.map +1 -1
  15. package/lib/@types/events.js +3 -1
  16. package/lib/@types/extensible_events.js +6 -6
  17. package/lib/@types/extensible_events.js.map +1 -1
  18. package/lib/@types/global.d.js.map +1 -1
  19. package/lib/@types/json.js +3 -1
  20. package/lib/@types/local_notifications.js +3 -1
  21. package/lib/@types/location.js +4 -4
  22. package/lib/@types/location.js.map +1 -1
  23. package/lib/@types/matrix-sdk-crypto-wasm.d.js +3 -1
  24. package/lib/@types/media.js +3 -1
  25. package/lib/@types/membership.js +1 -1
  26. package/lib/@types/membership.js.map +1 -1
  27. package/lib/@types/partials.js +6 -6
  28. package/lib/@types/partials.js.map +1 -1
  29. package/lib/@types/polls.js +5 -5
  30. package/lib/@types/polls.js.map +1 -1
  31. package/lib/@types/read_receipts.js +2 -2
  32. package/lib/@types/read_receipts.js.map +1 -1
  33. package/lib/@types/registration.js +3 -1
  34. package/lib/@types/requests.js +1 -1
  35. package/lib/@types/requests.js.map +1 -1
  36. package/lib/@types/retention.js +1 -1
  37. package/lib/@types/retention.js.map +1 -1
  38. package/lib/@types/search.js +1 -1
  39. package/lib/@types/search.js.map +1 -1
  40. package/lib/@types/signed.js +3 -1
  41. package/lib/@types/spaces.js +3 -1
  42. package/lib/@types/state_events.js +3 -1
  43. package/lib/@types/synapse.js +3 -1
  44. package/lib/@types/sync.js +1 -1
  45. package/lib/@types/sync.js.map +1 -1
  46. package/lib/@types/threepids.js +1 -1
  47. package/lib/@types/threepids.js.map +1 -1
  48. package/lib/@types/topic.js +1 -1
  49. package/lib/@types/topic.js.map +1 -1
  50. package/lib/@types/uia.js +3 -1
  51. package/lib/NamespacedValue.js +8 -8
  52. package/lib/NamespacedValue.js.map +1 -1
  53. package/lib/ReEmitter.js +9 -16
  54. package/lib/ReEmitter.js.map +1 -1
  55. package/lib/ToDeviceMessageQueue.js +49 -57
  56. package/lib/ToDeviceMessageQueue.js.map +1 -1
  57. package/lib/autodiscovery.js +232 -247
  58. package/lib/autodiscovery.js.map +1 -1
  59. package/lib/base64.js +1 -1
  60. package/lib/base64.js.map +1 -1
  61. package/lib/browser-index.d.ts +2 -2
  62. package/lib/browser-index.d.ts.map +1 -1
  63. package/lib/browser-index.js +5 -5
  64. package/lib/browser-index.js.map +1 -1
  65. package/lib/capabilityPoller.js +19 -22
  66. package/lib/capabilityPoller.js.map +1 -1
  67. package/lib/client.d.ts +2 -8
  68. package/lib/client.d.ts.map +1 -1
  69. package/lib/client.js +2043 -2487
  70. package/lib/client.js.map +1 -1
  71. package/lib/common-crypto/CryptoBackend.js +2 -2
  72. package/lib/common-crypto/CryptoBackend.js.map +1 -1
  73. package/lib/common-crypto/key-passphrase.js.map +1 -1
  74. package/lib/content-helpers.js +43 -48
  75. package/lib/content-helpers.js.map +1 -1
  76. package/lib/content-repo.js +14 -24
  77. package/lib/content-repo.js.map +1 -1
  78. package/lib/crypto/store/base.js +6 -6
  79. package/lib/crypto/store/base.js.map +1 -1
  80. package/lib/crypto/store/indexeddb-crypto-store-backend.js +190 -238
  81. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  82. package/lib/crypto/store/indexeddb-crypto-store.js +25 -30
  83. package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
  84. package/lib/crypto/store/localStorage-crypto-store.js +113 -145
  85. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
  86. package/lib/crypto/store/memory-crypto-store.js +74 -105
  87. package/lib/crypto/store/memory-crypto-store.js.map +1 -1
  88. package/lib/crypto-api/CryptoEvent.js +1 -1
  89. package/lib/crypto-api/CryptoEvent.js.map +1 -1
  90. package/lib/crypto-api/CryptoEventHandlerMap.js +3 -1
  91. package/lib/crypto-api/index.d.ts +15 -6
  92. package/lib/crypto-api/index.d.ts.map +1 -1
  93. package/lib/crypto-api/index.js +22 -22
  94. package/lib/crypto-api/index.js.map +1 -1
  95. package/lib/crypto-api/key-passphrase.js +15 -23
  96. package/lib/crypto-api/key-passphrase.js.map +1 -1
  97. package/lib/crypto-api/keybackup.js +3 -1
  98. package/lib/crypto-api/recovery-key.js +11 -12
  99. package/lib/crypto-api/recovery-key.js.map +1 -1
  100. package/lib/crypto-api/verification.js +3 -3
  101. package/lib/crypto-api/verification.js.map +1 -1
  102. package/lib/digest.js +7 -14
  103. package/lib/digest.js.map +1 -1
  104. package/lib/embedded.d.ts.map +1 -1
  105. package/lib/embedded.js +380 -505
  106. package/lib/embedded.js.map +1 -1
  107. package/lib/errors.js +2 -2
  108. package/lib/errors.js.map +1 -1
  109. package/lib/event-mapper.js +10 -12
  110. package/lib/event-mapper.js.map +1 -1
  111. package/lib/extensible_events_v1/ExtensibleEvent.js.map +1 -1
  112. package/lib/extensible_events_v1/InvalidEventError.js.map +1 -1
  113. package/lib/extensible_events_v1/MessageEvent.js +11 -13
  114. package/lib/extensible_events_v1/MessageEvent.js.map +1 -1
  115. package/lib/extensible_events_v1/PollEndEvent.js +3 -4
  116. package/lib/extensible_events_v1/PollEndEvent.js.map +1 -1
  117. package/lib/extensible_events_v1/PollResponseEvent.js +5 -6
  118. package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -1
  119. package/lib/extensible_events_v1/PollStartEvent.js +8 -10
  120. package/lib/extensible_events_v1/PollStartEvent.js.map +1 -1
  121. package/lib/extensible_events_v1/utilities.js.map +1 -1
  122. package/lib/feature.js +18 -31
  123. package/lib/feature.js.map +1 -1
  124. package/lib/filter-component.d.ts.map +1 -1
  125. package/lib/filter-component.js +20 -26
  126. package/lib/filter-component.js.map +1 -1
  127. package/lib/filter.js +14 -17
  128. package/lib/filter.js.map +1 -1
  129. package/lib/http-api/errors.js +28 -43
  130. package/lib/http-api/errors.js.map +1 -1
  131. package/lib/http-api/fetch.js +141 -159
  132. package/lib/http-api/fetch.js.map +1 -1
  133. package/lib/http-api/index.js +17 -20
  134. package/lib/http-api/index.js.map +1 -1
  135. package/lib/http-api/interface.js +1 -1
  136. package/lib/http-api/interface.js.map +1 -1
  137. package/lib/http-api/method.js +1 -1
  138. package/lib/http-api/method.js.map +1 -1
  139. package/lib/http-api/prefix.js +3 -3
  140. package/lib/http-api/prefix.js.map +1 -1
  141. package/lib/http-api/refresh.js +74 -94
  142. package/lib/http-api/refresh.js.map +1 -1
  143. package/lib/http-api/utils.d.ts +1 -1
  144. package/lib/http-api/utils.d.ts.map +1 -1
  145. package/lib/http-api/utils.js +34 -42
  146. package/lib/http-api/utils.js.map +1 -1
  147. package/lib/index.js.map +1 -1
  148. package/lib/indexeddb-helpers.js +3 -3
  149. package/lib/indexeddb-helpers.js.map +1 -1
  150. package/lib/indexeddb-worker.js.map +1 -1
  151. package/lib/interactive-auth.d.ts +5 -5
  152. package/lib/interactive-auth.d.ts.map +1 -1
  153. package/lib/interactive-auth.js +172 -204
  154. package/lib/interactive-auth.js.map +1 -1
  155. package/lib/logger.js +21 -57
  156. package/lib/logger.js.map +1 -1
  157. package/lib/matrix.js +7 -11
  158. package/lib/matrix.js.map +1 -1
  159. package/lib/matrixrtc/CallMembership.js +80 -74
  160. package/lib/matrixrtc/CallMembership.js.map +1 -1
  161. package/lib/matrixrtc/EncryptionManager.js +1 -1
  162. package/lib/matrixrtc/EncryptionManager.js.map +1 -1
  163. package/lib/matrixrtc/IKeyTransport.js +1 -1
  164. package/lib/matrixrtc/IKeyTransport.js.map +1 -1
  165. package/lib/matrixrtc/IMembershipManager.js +1 -1
  166. package/lib/matrixrtc/IMembershipManager.js.map +1 -1
  167. package/lib/matrixrtc/LivekitTransport.d.ts +1 -1
  168. package/lib/matrixrtc/LivekitTransport.js +4 -4
  169. package/lib/matrixrtc/LivekitTransport.js.map +1 -1
  170. package/lib/matrixrtc/MatrixRTCSession.js +137 -187
  171. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  172. package/lib/matrixrtc/MatrixRTCSessionManager.js +36 -41
  173. package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
  174. package/lib/matrixrtc/MembershipManager.js +332 -378
  175. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  176. package/lib/matrixrtc/MembershipManagerActionScheduler.js +54 -63
  177. package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
  178. package/lib/matrixrtc/RTCEncryptionManager.js +119 -143
  179. package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
  180. package/lib/matrixrtc/ToDeviceKeyTransport.js +53 -58
  181. package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
  182. package/lib/matrixrtc/index.js.map +1 -1
  183. package/lib/matrixrtc/membershipData/common.js +1 -1
  184. package/lib/matrixrtc/membershipData/common.js.map +1 -1
  185. package/lib/matrixrtc/membershipData/index.js.map +1 -1
  186. package/lib/matrixrtc/membershipData/rtc.js +15 -23
  187. package/lib/matrixrtc/membershipData/rtc.js.map +1 -1
  188. package/lib/matrixrtc/membershipData/session.js +4 -5
  189. package/lib/matrixrtc/membershipData/session.js.map +1 -1
  190. package/lib/matrixrtc/types.js +4 -6
  191. package/lib/matrixrtc/types.js.map +1 -1
  192. package/lib/matrixrtc/utils.js +4 -11
  193. package/lib/matrixrtc/utils.js.map +1 -1
  194. package/lib/models/MSC3089Branch.js +91 -116
  195. package/lib/models/MSC3089Branch.js.map +1 -1
  196. package/lib/models/MSC3089TreeSpace.js +209 -245
  197. package/lib/models/MSC3089TreeSpace.js.map +1 -1
  198. package/lib/models/ToDeviceMessage.js +3 -1
  199. package/lib/models/beacon.js +14 -13
  200. package/lib/models/beacon.js.map +1 -1
  201. package/lib/models/compare-event-ordering.js +13 -13
  202. package/lib/models/compare-event-ordering.js.map +1 -1
  203. package/lib/models/device.js +3 -3
  204. package/lib/models/device.js.map +1 -1
  205. package/lib/models/event-context.js +5 -8
  206. package/lib/models/event-context.js.map +1 -1
  207. package/lib/models/event-status.js +1 -1
  208. package/lib/models/event-status.js.map +1 -1
  209. package/lib/models/event-timeline-set.js +88 -94
  210. package/lib/models/event-timeline-set.js.map +1 -1
  211. package/lib/models/event-timeline.js +28 -30
  212. package/lib/models/event-timeline.js.map +1 -1
  213. package/lib/models/event.js +182 -226
  214. package/lib/models/event.js.map +1 -1
  215. package/lib/models/invites-ignorer-types.js +4 -4
  216. package/lib/models/invites-ignorer-types.js.map +1 -1
  217. package/lib/models/invites-ignorer.js +159 -179
  218. package/lib/models/invites-ignorer.js.map +1 -1
  219. package/lib/models/poll.js +71 -81
  220. package/lib/models/poll.js.map +1 -1
  221. package/lib/models/profile-keys.js +2 -2
  222. package/lib/models/profile-keys.js.map +1 -1
  223. package/lib/models/read-receipt.js +40 -56
  224. package/lib/models/read-receipt.js.map +1 -1
  225. package/lib/models/related-relations.js.map +1 -1
  226. package/lib/models/relations-container.js +22 -23
  227. package/lib/models/relations-container.js.map +1 -1
  228. package/lib/models/relations.js +133 -159
  229. package/lib/models/relations.js.map +1 -1
  230. package/lib/models/room-member.js +24 -29
  231. package/lib/models/room-member.js.map +1 -1
  232. package/lib/models/room-receipts.js +29 -43
  233. package/lib/models/room-receipts.js.map +1 -1
  234. package/lib/models/room-retention.js +74 -83
  235. package/lib/models/room-retention.js.map +1 -1
  236. package/lib/models/room-state.js +143 -172
  237. package/lib/models/room-state.js.map +1 -1
  238. package/lib/models/room-sticky-events.d.ts +1 -0
  239. package/lib/models/room-sticky-events.d.ts.map +1 -1
  240. package/lib/models/room-sticky-events.js +45 -65
  241. package/lib/models/room-sticky-events.js.map +1 -1
  242. package/lib/models/room-summary.js.map +1 -1
  243. package/lib/models/room.d.ts.map +1 -1
  244. package/lib/models/room.js +765 -909
  245. package/lib/models/room.js.map +1 -1
  246. package/lib/models/search-result.js +5 -5
  247. package/lib/models/search-result.js.map +1 -1
  248. package/lib/models/thread.js +225 -285
  249. package/lib/models/thread.js.map +1 -1
  250. package/lib/models/typed-event-emitter.js +7 -18
  251. package/lib/models/typed-event-emitter.js.map +1 -1
  252. package/lib/models/user.js +8 -8
  253. package/lib/models/user.js.map +1 -1
  254. package/lib/oidc/authorize.js +208 -241
  255. package/lib/oidc/authorize.js.map +1 -1
  256. package/lib/oidc/discovery.js +23 -36
  257. package/lib/oidc/discovery.js.map +1 -1
  258. package/lib/oidc/error.js +1 -1
  259. package/lib/oidc/error.js.map +1 -1
  260. package/lib/oidc/index.js +1 -0
  261. package/lib/oidc/index.js.map +1 -1
  262. package/lib/oidc/register.js +60 -66
  263. package/lib/oidc/register.js.map +1 -1
  264. package/lib/oidc/tokenRefresher.js +77 -91
  265. package/lib/oidc/tokenRefresher.js.map +1 -1
  266. package/lib/oidc/validate.js +18 -18
  267. package/lib/oidc/validate.js.map +1 -1
  268. package/lib/pushprocessor.js +71 -82
  269. package/lib/pushprocessor.js.map +1 -1
  270. package/lib/randomstring.js +9 -9
  271. package/lib/randomstring.js.map +1 -1
  272. package/lib/realtime-callbacks.js +25 -28
  273. package/lib/realtime-callbacks.js.map +1 -1
  274. package/lib/receipt-accumulator.d.ts +2 -0
  275. package/lib/receipt-accumulator.d.ts.map +1 -1
  276. package/lib/receipt-accumulator.js +14 -22
  277. package/lib/receipt-accumulator.js.map +1 -1
  278. package/lib/rendezvous/MSC4108SignInWithQR.js +271 -302
  279. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  280. package/lib/rendezvous/RendezvousChannel.js +3 -1
  281. package/lib/rendezvous/RendezvousCode.js +3 -1
  282. package/lib/rendezvous/RendezvousError.js.map +1 -1
  283. package/lib/rendezvous/RendezvousFailureReason.js +2 -2
  284. package/lib/rendezvous/RendezvousFailureReason.js.map +1 -1
  285. package/lib/rendezvous/RendezvousIntent.js +1 -1
  286. package/lib/rendezvous/RendezvousIntent.js.map +1 -1
  287. package/lib/rendezvous/RendezvousTransport.js +3 -1
  288. package/lib/rendezvous/channels/MSC4108SecureChannel.js +123 -147
  289. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
  290. package/lib/rendezvous/index.js +44 -69
  291. package/lib/rendezvous/index.js.map +1 -1
  292. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts +1 -1
  293. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +134 -152
  294. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
  295. package/lib/retentionPolicy.js +6 -9
  296. package/lib/retentionPolicy.js.map +1 -1
  297. package/lib/room-hierarchy.js +52 -60
  298. package/lib/room-hierarchy.js.map +1 -1
  299. package/lib/rust-crypto/CrossSigningIdentity.js +94 -104
  300. package/lib/rust-crypto/CrossSigningIdentity.js.map +1 -1
  301. package/lib/rust-crypto/DehydratedDeviceManager.js +157 -190
  302. package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -1
  303. package/lib/rust-crypto/KeyClaimManager.js +18 -22
  304. package/lib/rust-crypto/KeyClaimManager.js.map +1 -1
  305. package/lib/rust-crypto/OutgoingRequestProcessor.js +109 -139
  306. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
  307. package/lib/rust-crypto/OutgoingRequestsManager.js +66 -80
  308. package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -1
  309. package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts +1 -1
  310. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +196 -224
  311. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
  312. package/lib/rust-crypto/RoomEncryptor.js +127 -143
  313. package/lib/rust-crypto/RoomEncryptor.js.map +1 -1
  314. package/lib/rust-crypto/backup.js +453 -549
  315. package/lib/rust-crypto/backup.js.map +1 -1
  316. package/lib/rust-crypto/constants.js +1 -1
  317. package/lib/rust-crypto/constants.js.map +1 -1
  318. package/lib/rust-crypto/device-converter.js +15 -28
  319. package/lib/rust-crypto/device-converter.js.map +1 -1
  320. package/lib/rust-crypto/index.js +103 -116
  321. package/lib/rust-crypto/index.js.map +1 -1
  322. package/lib/rust-crypto/libolm_migration.js +303 -365
  323. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  324. package/lib/rust-crypto/rust-crypto.d.ts +5 -1
  325. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
  326. package/lib/rust-crypto/rust-crypto.js +1067 -1332
  327. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  328. package/lib/rust-crypto/secret-storage.js +12 -25
  329. package/lib/rust-crypto/secret-storage.js.map +1 -1
  330. package/lib/rust-crypto/verification.js +137 -189
  331. package/lib/rust-crypto/verification.js.map +1 -1
  332. package/lib/scheduler.js +44 -19
  333. package/lib/scheduler.js.map +1 -1
  334. package/lib/secret-storage.js +179 -213
  335. package/lib/secret-storage.js.map +1 -1
  336. package/lib/serverCapabilities.js +6 -9
  337. package/lib/serverCapabilities.js.map +1 -1
  338. package/lib/service-types.js +1 -1
  339. package/lib/service-types.js.map +1 -1
  340. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  341. package/lib/sliding-sync-sdk.js +368 -424
  342. package/lib/sliding-sync-sdk.js.map +1 -1
  343. package/lib/sliding-sync.js +135 -171
  344. package/lib/sliding-sync.js.map +1 -1
  345. package/lib/store/index.js +3 -1
  346. package/lib/store/indexeddb-backend.js +3 -1
  347. package/lib/store/indexeddb-local-backend.js +194 -253
  348. package/lib/store/indexeddb-local-backend.js.map +1 -1
  349. package/lib/store/indexeddb-remote-backend.js +33 -63
  350. package/lib/store/indexeddb-remote-backend.js.map +1 -1
  351. package/lib/store/indexeddb-store-worker.js +22 -23
  352. package/lib/store/indexeddb-store-worker.js.map +1 -1
  353. package/lib/store/indexeddb.js +44 -71
  354. package/lib/store/indexeddb.js.map +1 -1
  355. package/lib/store/local-storage-events-emitter.js +2 -2
  356. package/lib/store/local-storage-events-emitter.js.map +1 -1
  357. package/lib/store/memory.js +34 -57
  358. package/lib/store/memory.js.map +1 -1
  359. package/lib/store/stub.js +22 -35
  360. package/lib/store/stub.js.map +1 -1
  361. package/lib/sync-accumulator.js +54 -66
  362. package/lib/sync-accumulator.js.map +1 -1
  363. package/lib/sync.d.ts.map +1 -1
  364. package/lib/sync.js +905 -998
  365. package/lib/sync.js.map +1 -1
  366. package/lib/testing.js +63 -105
  367. package/lib/testing.js.map +1 -1
  368. package/lib/thread-utils.js +1 -4
  369. package/lib/thread-utils.js.map +1 -1
  370. package/lib/timeline-window.js +89 -102
  371. package/lib/timeline-window.js.map +1 -1
  372. package/lib/types.js +1 -1
  373. package/lib/types.js.map +1 -1
  374. package/lib/utils/decryptAESSecretStorageItem.js +14 -25
  375. package/lib/utils/decryptAESSecretStorageItem.js.map +1 -1
  376. package/lib/utils/encryptAESSecretStorageItem.js +27 -38
  377. package/lib/utils/encryptAESSecretStorageItem.js.map +1 -1
  378. package/lib/utils/internal/deriveKeys.js +25 -32
  379. package/lib/utils/internal/deriveKeys.js.map +1 -1
  380. package/lib/utils/roomVersion.js +1 -1
  381. package/lib/utils/roomVersion.js.map +1 -1
  382. package/lib/utils.js +83 -135
  383. package/lib/utils.js.map +1 -1
  384. package/lib/version-support.js +3 -3
  385. package/lib/version-support.js.map +1 -1
  386. package/lib/webrtc/audioContext.js +5 -6
  387. package/lib/webrtc/audioContext.js.map +1 -1
  388. package/lib/webrtc/call.js +1081 -1250
  389. package/lib/webrtc/call.js.map +1 -1
  390. package/lib/webrtc/callEventHandler.js +202 -214
  391. package/lib/webrtc/callEventHandler.js.map +1 -1
  392. package/lib/webrtc/callEventTypes.js +2 -2
  393. package/lib/webrtc/callEventTypes.js.map +1 -1
  394. package/lib/webrtc/callFeed.js +18 -20
  395. package/lib/webrtc/callFeed.js.map +1 -1
  396. package/lib/webrtc/groupCall.js +513 -602
  397. package/lib/webrtc/groupCall.js.map +1 -1
  398. package/lib/webrtc/groupCallEventHandler.js +59 -62
  399. package/lib/webrtc/groupCallEventHandler.js.map +1 -1
  400. package/lib/webrtc/mediaHandler.js +198 -232
  401. package/lib/webrtc/mediaHandler.js.map +1 -1
  402. package/lib/webrtc/stats/callFeedStatsReporter.js +16 -20
  403. package/lib/webrtc/stats/callFeedStatsReporter.js.map +1 -1
  404. package/lib/webrtc/stats/callStatsReportGatherer.js +67 -75
  405. package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
  406. package/lib/webrtc/stats/callStatsReportSummary.js +3 -1
  407. package/lib/webrtc/stats/connectionStats.js.map +1 -1
  408. package/lib/webrtc/stats/connectionStatsBuilder.js +2 -2
  409. package/lib/webrtc/stats/connectionStatsBuilder.js.map +1 -1
  410. package/lib/webrtc/stats/connectionStatsReportBuilder.js +20 -24
  411. package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +1 -1
  412. package/lib/webrtc/stats/groupCallStats.js +6 -8
  413. package/lib/webrtc/stats/groupCallStats.js.map +1 -1
  414. package/lib/webrtc/stats/media/mediaSsrcHandler.js +7 -8
  415. package/lib/webrtc/stats/media/mediaSsrcHandler.js.map +1 -1
  416. package/lib/webrtc/stats/media/mediaTrackHandler.js +7 -9
  417. package/lib/webrtc/stats/media/mediaTrackHandler.js.map +1 -1
  418. package/lib/webrtc/stats/media/mediaTrackStats.js +3 -3
  419. package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -1
  420. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +7 -7
  421. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -1
  422. package/lib/webrtc/stats/statsReport.js +1 -1
  423. package/lib/webrtc/stats/statsReport.js.map +1 -1
  424. package/lib/webrtc/stats/statsReportEmitter.js.map +1 -1
  425. package/lib/webrtc/stats/summaryStatsReportGatherer.js +14 -14
  426. package/lib/webrtc/stats/summaryStatsReportGatherer.js.map +1 -1
  427. package/lib/webrtc/stats/trackStatsBuilder.js +32 -34
  428. package/lib/webrtc/stats/trackStatsBuilder.js.map +1 -1
  429. package/lib/webrtc/stats/transportStats.js +3 -1
  430. package/lib/webrtc/stats/transportStatsBuilder.js +9 -9
  431. package/lib/webrtc/stats/transportStatsBuilder.js.map +1 -1
  432. package/lib/webrtc/stats/valueFormatter.js +1 -1
  433. package/lib/webrtc/stats/valueFormatter.js.map +1 -1
  434. package/package.json +18 -33
  435. package/src/@types/global.d.ts +2 -2
  436. package/src/ToDeviceMessageQueue.ts +2 -2
  437. package/src/browser-index.ts +4 -4
  438. package/src/client.ts +15 -20
  439. package/src/crypto-api/index.ts +17 -6
  440. package/src/embedded.ts +4 -6
  441. package/src/filter-component.ts +1 -0
  442. package/src/http-api/utils.ts +1 -1
  443. package/src/interactive-auth.ts +11 -5
  444. package/src/matrixrtc/LivekitTransport.ts +1 -1
  445. package/src/matrixrtc/MatrixRTCSession.ts +1 -1
  446. package/src/models/MSC3089Branch.ts +1 -1
  447. package/src/models/room-sticky-events.ts +1 -0
  448. package/src/models/room.ts +9 -11
  449. package/src/receipt-accumulator.ts +2 -0
  450. package/src/rendezvous/index.ts +1 -1
  451. package/src/rendezvous/transports/MSC4108RendezvousSession.ts +2 -2
  452. package/src/rust-crypto/PerSessionKeyBackupDownloader.ts +1 -1
  453. package/src/rust-crypto/index.ts +6 -6
  454. package/src/rust-crypto/rust-crypto.ts +31 -7
  455. package/src/rust-crypto/verification.ts +1 -1
  456. package/src/sliding-sync-sdk.ts +5 -7
  457. package/src/store/indexeddb-local-backend.ts +3 -3
  458. package/src/sync.ts +6 -8
@@ -1 +1 @@
1
- {"version":3,"file":"pushprocessor.js","names":["deepCompare","escapeRegExp","globToRegexp","isNullOrUndefined","ConditionKind","PushRuleActionName","PushRuleKind","RuleId","TweakName","EventType","RULEKINDS_IN_ORDER","Override","ContentSpecific","RoomSpecific","SenderSpecific","Underride","DEFAULT_OVERRIDE_RULES","rule_id","default","enabled","conditions","kind","EventPropertyIs","key","value","SenderNotificationPermission","actions","Notify","set_tweak","Highlight","EventMatch","pattern","DontNotify","RoomServerAcl","UserDefinedRules","Symbol","EXPECTED_DEFAULT_OVERRIDE_RULE_IDS","Master","SuppressNotices","InviteToSelf","MemberEvent","IsUserMention","ContainsDisplayName","IsRoomMention","AtRoomNotification","Tombstone","DEFAULT_UNDERRIDE_RULES","CallStarted","Sound","EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS","IncomingCall","EncryptedDM","DM","Message","EncryptedMessage","mergeRulesWithDefaults","logger","incomingRules","defaultRules","orderedRuleIds","incomingDefaultRules","filter","rule","incomingCustomRules","insertDefaultPushRule","ruleId","newRules","push","warn","concat","nextExpectedRuleIdIndex","ruleIndex","indexOf","defaultRuleId","slice","PushProcessor","constructor","client","_defineProperty","Map","actionListToActionsObject","actionList","actionObj","notify","tweaks","action","undefined","rewriteDefaultRules","userId","arguments","length","JSON","parse","stringify","global","override","underride","getPushRuleGlobRegex","alignToWordBoundary","flags","_ref","_ref2","_slicedToArray","prefix","suffix","cacheKey","cachedGlobToRegex","RegExp","updateCachedPushRuleKeys","room","sender","toRemoveKeys","Set","parsedKeys","keys","ruleset","condition","delete","set","partsForDottedKey","forEach","k","matchingRuleFromKindSet","ev","kindset","rawrule","templateRuleToRaw","ruleMatchesEvent","_objectSpread","tprule","eventFulfillsCondition","cond","eventFulfillsEventMatchCondition","eventFulfillsEventPropertyIsCondition","EventPropertyContains","eventFulfillsEventPropertyContains","eventFulfillsDisplayNameCondition","RoomMemberCount","eventFulfillsRoomMemberCountCondition","eventFulfillsSenderNotifPermCondition","CallStartedPrefix","eventFulfillsCallStartedCondition","notifLevelKey","getRoom","getRoomId","currentState","mayTriggerNotifOfType","getSender","is","members","memberCount","getJoinedMemberCount","m","match","ineq","rhs","parseInt","isNaN","_room$currentState","content","getContent","isEncrypted","getClearContent","body","member","getMember","credentials","displayName","name","pat","search","val","valueForDottedKey","regex","Array","isArray","includes","_cond","getPrevContent","str","result","part","escaped","c","parts","get","firstPart","currentIndex","getType","event","thisPart","matchingRuleForEventWithRulesets","rulesets","getSafeUserId","pushActionsForEventAndRulesets","highlight","_rule$conditions","supportsIntentionalMentions","ContainsUserName","some","actionsForEvent","_this$pushActionsForE","pushRules","actionsAndRuleForEvent","getPushRuleById","_result$rule","getPushRuleAndKindById","scope","_this$client$pushRule"],"sources":["../src/pushprocessor.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\nimport { deepCompare, escapeRegExp, globToRegexp, isNullOrUndefined } from \"./utils.ts\";\nimport { type Logger } from \"./logger.ts\";\nimport { type MatrixClient } from \"./client.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\nimport {\n ConditionKind,\n type IAnnotatedPushRule,\n type ICallStartedCondition,\n type ICallStartedPrefixCondition,\n type IContainsDisplayNameCondition,\n type IEventMatchCondition,\n type IEventPropertyContainsCondition,\n type IEventPropertyIsCondition,\n type IPushRule,\n type IPushRules,\n type IRoomMemberCountCondition,\n type ISenderNotificationPermissionCondition,\n type PushRuleAction,\n PushRuleActionName,\n type PushRuleCondition,\n PushRuleKind,\n type PushRuleSet,\n RuleId,\n TweakName,\n} from \"./@types/PushRules.ts\";\nimport { EventType } from \"./@types/event.ts\";\n\nconst RULEKINDS_IN_ORDER = [\n PushRuleKind.Override,\n PushRuleKind.ContentSpecific,\n PushRuleKind.RoomSpecific,\n PushRuleKind.SenderSpecific,\n PushRuleKind.Underride,\n];\n\n// The default override rules to apply to the push rules that arrive from the server.\n// We do this for two reasons:\n// 1. Synapse is unlikely to send us the push rule in an incremental sync - see\n// https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for\n// more details.\n// 2. We often want to start using push rules ahead of the server supporting them,\n// and so we can put them here.\nconst DEFAULT_OVERRIDE_RULES: Record<string, IPushRule> = {\n \".m.rule.is_room_mention\": {\n // Matrix v1.7\n rule_id: \".m.rule.is_room_mention\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventPropertyIs,\n key: \"content.m\\\\.mentions.room\",\n value: true,\n },\n {\n kind: ConditionKind.SenderNotificationPermission,\n key: \"room\",\n },\n ],\n actions: [\n PushRuleActionName.Notify,\n {\n set_tweak: TweakName.Highlight,\n },\n ],\n },\n \".m.rule.reaction\": {\n // For homeservers which don't support MSC2153 yet\n rule_id: \".m.rule.reaction\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: \"m.reaction\",\n },\n ],\n actions: [PushRuleActionName.DontNotify],\n },\n \".org.matrix.msc3786.rule.room.server_acl\": {\n // For homeservers which don't support MSC3786 yet\n rule_id: \".org.matrix.msc3786.rule.room.server_acl\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: EventType.RoomServerAcl,\n },\n {\n kind: ConditionKind.EventMatch,\n key: \"state_key\",\n pattern: \"\",\n },\n ],\n actions: [],\n },\n};\n\n// A special rule id for `EXPECTED_DEFAULT_OVERRIDE_RULE_IDS` and friends which denotes where user-defined rules live in the order.\nconst UserDefinedRules = Symbol(\"UserDefinedRules\");\n\ntype OrderedRules = Array<string | typeof UserDefinedRules>;\n\nconst EXPECTED_DEFAULT_OVERRIDE_RULE_IDS: OrderedRules = [\n RuleId.Master,\n UserDefinedRules,\n RuleId.SuppressNotices,\n RuleId.InviteToSelf,\n RuleId.MemberEvent,\n RuleId.IsUserMention,\n RuleId.ContainsDisplayName,\n RuleId.IsRoomMention,\n RuleId.AtRoomNotification,\n RuleId.Tombstone,\n \".m.rule.reaction\",\n \".m.rule.room.server_acl\",\n \".org.matrix.msc3786.rule.room.server_acl\",\n \".m.rule.suppress_edits\",\n];\n\nconst DEFAULT_UNDERRIDE_RULES: Record<string, IPushRule> = {\n \".org.matrix.msc3914.rule.room.call\": {\n // For homeservers which don't support MSC3914 yet\n rule_id: \".org.matrix.msc3914.rule.room.call\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: \"org.matrix.msc3401.call\",\n },\n {\n kind: ConditionKind.CallStarted,\n },\n ],\n actions: [PushRuleActionName.Notify, { set_tweak: TweakName.Sound, value: \"default\" }],\n },\n};\n\nconst EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS: OrderedRules = [\n UserDefinedRules,\n RuleId.IncomingCall,\n \".org.matrix.msc3914.rule.room.call\",\n RuleId.EncryptedDM,\n RuleId.DM,\n RuleId.Message,\n RuleId.EncryptedMessage,\n];\n\n/**\n * Make sure that each of the rules listed in `defaultRuleIds` is listed in the given set of push rules.\n *\n * @param logger - A `Logger` to write log messages to.\n * @param kind - the kind of push rule set being merged.\n * @param incomingRules - the existing set of known push rules for the user.\n * @param defaultRules - a lookup table for the default definitions of push rules.\n * @param orderedRuleIds - the IDs of the expected push rules, in order.\n *\n * @returns A copy of `incomingRules`, with any missing default rules inserted in the right place.\n */\nfunction mergeRulesWithDefaults(\n logger: Logger,\n kind: PushRuleKind,\n incomingRules: IPushRule[],\n defaultRules: Record<string, IPushRule>,\n orderedRuleIds: OrderedRules,\n): IPushRule[] {\n // Split the incomingRules into defaults and custom\n const incomingDefaultRules = incomingRules.filter((rule) => rule.default);\n const incomingCustomRules = incomingRules.filter((rule) => !rule.default);\n\n function insertDefaultPushRule(ruleId: OrderedRules[number]): void {\n if (ruleId === UserDefinedRules) {\n // Re-insert any user-defined rules that were in `incomingRules`\n newRules.push(...incomingCustomRules);\n } else if (ruleId in defaultRules) {\n logger.warn(`Adding default global ${kind} push rule ${ruleId}`);\n newRules.push(defaultRules[ruleId]);\n } else {\n logger.warn(`Missing default global ${kind} push rule ${ruleId}`);\n }\n }\n\n let nextExpectedRuleIdIndex = 0;\n const newRules: IPushRule[] = [];\n // Merge our expected rules (including the incoming custom rules) into the incoming default rules.\n for (const rule of incomingDefaultRules) {\n const ruleIndex = orderedRuleIds.indexOf(rule.rule_id);\n if (ruleIndex === -1) {\n // an unrecognised rule; copy it over\n newRules.push(rule);\n continue;\n }\n while (ruleIndex > nextExpectedRuleIdIndex) {\n // insert new rules\n const defaultRuleId = orderedRuleIds[nextExpectedRuleIdIndex];\n insertDefaultPushRule(defaultRuleId);\n nextExpectedRuleIdIndex += 1;\n }\n // copy over the existing rule\n newRules.push(rule);\n nextExpectedRuleIdIndex += 1;\n }\n\n // Now copy over any remaining default rules\n for (const ruleId of orderedRuleIds.slice(nextExpectedRuleIdIndex)) {\n insertDefaultPushRule(ruleId);\n }\n\n return newRules;\n}\n\nexport interface IActionsObject {\n /** Whether this event should notify the user or not. */\n notify: boolean;\n /** How this event should be notified. */\n tweaks: Partial<Record<TweakName, any>>;\n}\n\nexport class PushProcessor {\n /**\n * Construct a Push Processor.\n * @param client - The Matrix client object to use\n */\n public constructor(private readonly client: MatrixClient) {}\n\n /**\n * Maps the original key from the push rules to a list of property names\n * after unescaping.\n */\n private readonly parsedKeys = new Map<string, string[]>();\n\n /**\n * Convert a list of actions into a object with the actions as keys and their values\n * @example\n * eg. `[ 'notify', { set_tweak: 'sound', value: 'default' } ]`\n * becomes `{ notify: true, tweaks: { sound: 'default' } }`\n * @param actionList - The actions list\n *\n * @returns A object with key 'notify' (true or false) and an object of actions\n */\n public static actionListToActionsObject(actionList: PushRuleAction[]): IActionsObject {\n const actionObj: IActionsObject = { notify: false, tweaks: {} };\n for (const action of actionList) {\n if (action === PushRuleActionName.Notify) {\n actionObj.notify = true;\n } else if (typeof action === \"object\") {\n if (action.value === undefined) {\n action.value = true;\n }\n actionObj.tweaks[action.set_tweak] = action.value;\n }\n }\n return actionObj;\n }\n\n /**\n * Rewrites conditions on a client's push rules to match the defaults\n * where applicable. Useful for upgrading push rules to more strict\n * conditions when the server is falling behind on defaults.\n *\n * @param logger - A `Logger` to write log messages to.\n * @param incomingRules - The client's existing push rules\n * @param userId - The Matrix ID of the client.\n * @returns The rewritten rules\n */\n public static rewriteDefaultRules(\n logger: Logger,\n incomingRules: IPushRules,\n userId: string | undefined = undefined,\n ): IPushRules {\n let newRules: IPushRules = JSON.parse(JSON.stringify(incomingRules)); // deep clone\n\n // These lines are mostly to make the tests happy. We shouldn't run into these\n // properties missing in practice.\n if (!newRules) newRules = {} as IPushRules;\n if (!newRules.global) newRules.global = {} as PushRuleSet;\n if (!newRules.global.override) newRules.global.override = [];\n if (!newRules.global.underride) newRules.global.underride = [];\n\n // Merge the client-level defaults with the ones from the server\n newRules.global.override = mergeRulesWithDefaults(\n logger,\n PushRuleKind.Override,\n newRules.global.override,\n DEFAULT_OVERRIDE_RULES,\n EXPECTED_DEFAULT_OVERRIDE_RULE_IDS,\n );\n\n newRules.global.underride = mergeRulesWithDefaults(\n logger,\n PushRuleKind.Underride,\n newRules.global.underride,\n DEFAULT_UNDERRIDE_RULES,\n EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS,\n );\n\n return newRules;\n }\n\n /**\n * Create a RegExp object for the given glob pattern with a single capture group around the pattern itself, caching the result.\n * No cache invalidation is present currently,\n * as this will be inherently bounded to the size of the user's own push rules.\n * @param pattern - the glob pattern to convert to a RegExp\n * @param alignToWordBoundary - whether to align the pattern to word boundaries,\n * as specified for `content.body` matches, will use lookaround assertions to ensure the match only includes the pattern\n * @param flags - the flags to pass to the RegExp constructor, defaults to case-insensitive\n */\n public static getPushRuleGlobRegex(pattern: string, alignToWordBoundary = false, flags = \"i\"): RegExp {\n const [prefix, suffix] = alignToWordBoundary ? [\"(?<=^|\\\\W)\", \"(?=\\\\W|$)\"] : [\"^\", \"$\"];\n const cacheKey = `${alignToWordBoundary}-${flags}-${pattern}`;\n\n if (!PushProcessor.cachedGlobToRegex[cacheKey]) {\n PushProcessor.cachedGlobToRegex[cacheKey] = new RegExp(\n prefix + \"(\" + globToRegexp(pattern) + \")\" + suffix,\n flags,\n );\n }\n return PushProcessor.cachedGlobToRegex[cacheKey];\n }\n\n /**\n * Pre-caches the parsed keys for push rules and cleans out any obsolete cache\n * entries. Should be called after push rules are updated.\n * @param newRules - The new push rules.\n */\n public updateCachedPushRuleKeys(newRules: IPushRules): void {\n // These lines are mostly to make the tests happy. We shouldn't run into these\n // properties missing in practice.\n if (!newRules) newRules = {} as IPushRules;\n if (!newRules.global) newRules.global = {} as PushRuleSet;\n if (!newRules.global.override) newRules.global.override = [];\n if (!newRules.global.room) newRules.global.room = [];\n if (!newRules.global.sender) newRules.global.sender = [];\n if (!newRules.global.underride) newRules.global.underride = [];\n\n // Process the 'key' property on event_match conditions pre-cache the\n // values and clean-out any unused values.\n const toRemoveKeys = new Set(this.parsedKeys.keys());\n for (const ruleset of [\n newRules.global.override,\n newRules.global.room,\n newRules.global.sender,\n newRules.global.underride,\n ]) {\n for (const rule of ruleset) {\n if (!rule.conditions) {\n continue;\n }\n\n for (const condition of rule.conditions) {\n if (condition.kind !== ConditionKind.EventMatch) {\n continue;\n }\n\n // Ensure we keep this key.\n toRemoveKeys.delete(condition.key);\n\n // Pre-process the key.\n this.parsedKeys.set(condition.key, PushProcessor.partsForDottedKey(condition.key));\n }\n }\n }\n // Any keys that were previously cached, but are no longer needed should\n // be removed.\n toRemoveKeys.forEach((k) => this.parsedKeys.delete(k));\n }\n\n private static cachedGlobToRegex: Record<string, RegExp> = {}; // $glob: RegExp\n\n private matchingRuleFromKindSet(ev: MatrixEvent, kindset: PushRuleSet): IAnnotatedPushRule | null {\n for (const kind of RULEKINDS_IN_ORDER) {\n const ruleset = kindset[kind];\n if (!ruleset) {\n continue;\n }\n\n for (const rule of ruleset) {\n if (!rule.enabled) {\n continue;\n }\n\n const rawrule = this.templateRuleToRaw(kind, rule);\n if (!rawrule) {\n continue;\n }\n\n if (this.ruleMatchesEvent(rawrule, ev)) {\n return {\n ...rule,\n kind,\n };\n }\n }\n }\n return null;\n }\n\n private templateRuleToRaw(\n kind: PushRuleKind,\n tprule: IPushRule,\n ): Pick<IPushRule, \"rule_id\" | \"actions\" | \"conditions\"> | null {\n const rawrule: Pick<IPushRule, \"rule_id\" | \"actions\" | \"conditions\"> = {\n rule_id: tprule.rule_id,\n actions: tprule.actions,\n conditions: [],\n };\n switch (kind) {\n case PushRuleKind.Underride:\n case PushRuleKind.Override:\n rawrule.conditions = tprule.conditions;\n break;\n case PushRuleKind.RoomSpecific:\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"room_id\",\n value: tprule.rule_id,\n });\n break;\n case PushRuleKind.SenderSpecific:\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"user_id\",\n value: tprule.rule_id,\n });\n break;\n case PushRuleKind.ContentSpecific:\n if (!tprule.pattern) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"content.body\",\n pattern: tprule.pattern,\n });\n break;\n }\n return rawrule;\n }\n\n private eventFulfillsCondition(cond: PushRuleCondition, ev: MatrixEvent): boolean {\n switch (cond.kind) {\n case ConditionKind.EventMatch:\n return this.eventFulfillsEventMatchCondition(cond, ev);\n case ConditionKind.EventPropertyIs:\n return this.eventFulfillsEventPropertyIsCondition(cond, ev);\n case ConditionKind.EventPropertyContains:\n return this.eventFulfillsEventPropertyContains(cond, ev);\n case ConditionKind.ContainsDisplayName:\n return this.eventFulfillsDisplayNameCondition(cond, ev);\n case ConditionKind.RoomMemberCount:\n return this.eventFulfillsRoomMemberCountCondition(cond, ev);\n case ConditionKind.SenderNotificationPermission:\n return this.eventFulfillsSenderNotifPermCondition(cond, ev);\n case ConditionKind.CallStarted:\n case ConditionKind.CallStartedPrefix:\n return this.eventFulfillsCallStartedCondition(cond, ev);\n }\n\n // unknown conditions: we previously matched all unknown conditions,\n // but given that rules can be added to the base rules on a server,\n // it's probably better to not match unknown conditions.\n return false;\n }\n\n private eventFulfillsSenderNotifPermCondition(\n cond: ISenderNotificationPermissionCondition,\n ev: MatrixEvent,\n ): boolean {\n const notifLevelKey = cond[\"key\"];\n if (!notifLevelKey) {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n if (!room?.currentState) {\n return false;\n }\n\n // Note that this should not be the current state of the room but the state at\n // the point the event is in the DAG. Unfortunately the js-sdk does not store\n // this.\n return room.currentState.mayTriggerNotifOfType(notifLevelKey, ev.getSender()!);\n }\n\n private eventFulfillsRoomMemberCountCondition(cond: IRoomMemberCountCondition, ev: MatrixEvent): boolean {\n if (!cond.is) {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n if (!room || !room.currentState || !room.currentState.members) {\n return false;\n }\n\n const memberCount = room.currentState.getJoinedMemberCount();\n\n const m = cond.is.match(/^([=<>]*)(\\d*)$/);\n if (!m) {\n return false;\n }\n const ineq = m[1];\n const rhs = parseInt(m[2]);\n if (isNaN(rhs)) {\n return false;\n }\n switch (ineq) {\n case \"\":\n case \"==\":\n return memberCount == rhs;\n case \"<\":\n return memberCount < rhs;\n case \">\":\n return memberCount > rhs;\n case \"<=\":\n return memberCount <= rhs;\n case \">=\":\n return memberCount >= rhs;\n default:\n return false;\n }\n }\n\n private eventFulfillsDisplayNameCondition(cond: IContainsDisplayNameCondition, ev: MatrixEvent): boolean {\n let content = ev.getContent();\n if (ev.isEncrypted() && ev.getClearContent()) {\n content = ev.getClearContent()!;\n }\n if (!content || !content.body || typeof content.body != \"string\") {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n const member = room?.currentState?.getMember(this.client.credentials.userId!);\n if (!member) {\n return false;\n }\n\n const displayName = member.name;\n\n // N.B. we can't use \\b as it chokes on unicode. however \\W seems to be okay\n // as shorthand for [^0-9A-Za-z_].\n const pat = new RegExp(\"(^|\\\\W)\" + escapeRegExp(displayName) + \"(\\\\W|$)\", \"i\");\n return content.body.search(pat) > -1;\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing against the condition's glob-based\n * pattern.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventMatchCondition(cond: IEventMatchCondition, ev: MatrixEvent): boolean {\n if (!cond.key) {\n return false;\n }\n\n const val = this.valueForDottedKey(cond.key, ev);\n if (typeof val !== \"string\") {\n return false;\n }\n\n // XXX This does not match in a case-insensitive manner.\n //\n // See https://spec.matrix.org/v1.5/client-server-api/#conditions-1\n if (cond.value) {\n return cond.value === val;\n }\n\n if (typeof cond.pattern !== \"string\") {\n return false;\n }\n\n // Align to word boundary on `content.body` matches, whole string otherwise\n // https://spec.matrix.org/v1.13/client-server-api/#conditions-1\n const regex = PushProcessor.getPushRuleGlobRegex(cond.pattern, cond.key === \"content.body\");\n return !!val.match(regex);\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing exactly against the condition's\n * value.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventPropertyIsCondition(cond: IEventPropertyIsCondition, ev: MatrixEvent): boolean {\n if (!cond.key || cond.value === undefined) {\n return false;\n }\n return cond.value === this.valueForDottedKey(cond.key, ev);\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing exactly against the condition's\n * value.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventPropertyContains(cond: IEventPropertyContainsCondition, ev: MatrixEvent): boolean {\n if (!cond.key || cond.value === undefined) {\n return false;\n }\n const val = this.valueForDottedKey(cond.key, ev);\n if (!Array.isArray(val)) {\n return false;\n }\n return val.includes(cond.value);\n }\n\n private eventFulfillsCallStartedCondition(\n _cond: ICallStartedCondition | ICallStartedPrefixCondition,\n ev: MatrixEvent,\n ): boolean {\n // Since servers don't support properly sending push notification\n // about MSC3401 call events, we do the handling ourselves\n return (\n [\"m.ring\", \"m.prompt\"].includes(ev.getContent()[\"m.intent\"]) &&\n !(\"m.terminated\" in ev.getContent()) &&\n (ev.getPrevContent()[\"m.terminated\"] !== ev.getContent()[\"m.terminated\"] ||\n deepCompare(ev.getPrevContent(), {}))\n );\n }\n\n /**\n * Parse the key into the separate fields to search by splitting on\n * unescaped \".\", and then removing any escape characters.\n *\n * @param str - The key of the push rule condition: a dotted field.\n * @returns The unescaped parts to fetch.\n * @internal\n */\n public static partsForDottedKey(str: string): string[] {\n const result: string[] = [];\n\n // The current field and whether the previous character was the escape\n // character (a backslash).\n let part = \"\";\n let escaped = false;\n\n // Iterate over each character, and decide whether to append to the current\n // part (following the escape rules) or to start a new part (based on the\n // field separator).\n for (const c of str) {\n // If the previous character was the escape character (a backslash)\n // then decide what to append to the current part.\n if (escaped) {\n if (c === \"\\\\\" || c === \".\") {\n // An escaped backslash or dot just gets added.\n part += c;\n } else {\n // A character that shouldn't be escaped gets the backslash prepended.\n part += \"\\\\\" + c;\n }\n // This always resets being escaped.\n escaped = false;\n continue;\n }\n\n if (c == \".\") {\n // The field separator creates a new part.\n result.push(part);\n part = \"\";\n } else if (c == \"\\\\\") {\n // A backslash adds no characters, but starts an escape sequence.\n escaped = true;\n } else {\n // Otherwise, just add the current character.\n part += c;\n }\n }\n\n // Ensure the final part is included. If there's an open escape sequence\n // it should be included.\n if (escaped) {\n part += \"\\\\\";\n }\n result.push(part);\n\n return result;\n }\n\n /**\n * For a dotted field and event, fetch the value at that position, if one\n * exists.\n *\n * @param key - The key of the push rule condition: a dotted field to fetch.\n * @param ev - The matrix event to fetch the field from.\n * @returns The value at the dotted path given by key.\n */\n private valueForDottedKey(key: string, ev: MatrixEvent): any {\n // The key should already have been parsed via updateCachedPushRuleKeys,\n // but if it hasn't (maybe via an old consumer of the SDK which hasn't\n // been updated?) then lazily calculate it here.\n let parts = this.parsedKeys.get(key);\n if (parts === undefined) {\n parts = PushProcessor.partsForDottedKey(key);\n this.parsedKeys.set(key, parts);\n }\n let val: any;\n\n // special-case the first component to deal with encrypted messages\n const firstPart = parts[0];\n let currentIndex = 0;\n if (firstPart === \"content\") {\n val = ev.getContent();\n ++currentIndex;\n } else if (firstPart === \"type\") {\n val = ev.getType();\n ++currentIndex;\n } else {\n // use the raw event for any other fields\n val = ev.event;\n }\n\n for (; currentIndex < parts.length; ++currentIndex) {\n // The previous iteration resulted in null or undefined, bail (and\n // avoid the type error of attempting to retrieve a property).\n if (isNullOrUndefined(val)) {\n return undefined;\n }\n\n const thisPart = parts[currentIndex];\n val = val[thisPart];\n }\n return val;\n }\n\n private matchingRuleForEventWithRulesets(ev: MatrixEvent, rulesets?: IPushRules): IAnnotatedPushRule | null {\n if (!rulesets) {\n return null;\n }\n\n if (ev.getSender() === this.client.getSafeUserId()) {\n return null;\n }\n\n return this.matchingRuleFromKindSet(ev, rulesets.global);\n }\n\n private pushActionsForEventAndRulesets(\n ev: MatrixEvent,\n rulesets?: IPushRules,\n ): {\n actions?: IActionsObject;\n rule?: IAnnotatedPushRule;\n } {\n const rule = this.matchingRuleForEventWithRulesets(ev, rulesets);\n if (!rule) {\n return {};\n }\n\n const actionObj = PushProcessor.actionListToActionsObject(rule.actions);\n\n // Some actions are implicit in some situations: we add those here\n if (actionObj.tweaks.highlight === undefined) {\n // if it isn't specified, highlight if it's a content\n // rule but otherwise not\n actionObj.tweaks.highlight = rule.kind == PushRuleKind.ContentSpecific;\n }\n\n return { actions: actionObj, rule };\n }\n\n public ruleMatchesEvent(rule: Partial<IPushRule> & Pick<IPushRule, \"conditions\">, ev: MatrixEvent): boolean {\n // Disable the deprecated mentions push rules if the new mentions property exists.\n if (\n this.client.supportsIntentionalMentions() &&\n ev.getContent()[\"m.mentions\"] !== undefined &&\n (rule.rule_id === RuleId.ContainsUserName ||\n rule.rule_id === RuleId.ContainsDisplayName ||\n rule.rule_id === RuleId.AtRoomNotification)\n ) {\n return false;\n }\n\n return !rule.conditions?.some((cond) => !this.eventFulfillsCondition(cond, ev));\n }\n\n /**\n * Get the user's push actions for the given event\n */\n public actionsForEvent(ev: MatrixEvent): IActionsObject {\n const { actions } = this.pushActionsForEventAndRulesets(ev, this.client.pushRules);\n return actions || ({} as IActionsObject);\n }\n\n public actionsAndRuleForEvent(ev: MatrixEvent): {\n actions?: IActionsObject;\n rule?: IAnnotatedPushRule;\n } {\n return this.pushActionsForEventAndRulesets(ev, this.client.pushRules);\n }\n\n /**\n * Get one of the users push rules by its ID\n *\n * @param ruleId - The ID of the rule to search for\n * @returns The push rule, or null if no such rule was found\n */\n public getPushRuleById(ruleId: string): IPushRule | null {\n const result = this.getPushRuleAndKindById(ruleId);\n return result?.rule ?? null;\n }\n\n /**\n * Get one of the users push rules by its ID\n *\n * @param ruleId - The ID of the rule to search for\n * @returns rule The push rule, or null if no such rule was found\n * @returns kind - The PushRuleKind of the rule to search for\n */\n public getPushRuleAndKindById(ruleId: string): { rule: IPushRule; kind: PushRuleKind } | null {\n for (const scope of [\"global\"] as const) {\n if (this.client.pushRules?.[scope] === undefined) continue;\n\n for (const kind of RULEKINDS_IN_ORDER) {\n if (this.client.pushRules[scope][kind] === undefined) continue;\n\n for (const rule of this.client.pushRules[scope][kind]!) {\n if (rule.rule_id === ruleId) return { rule, kind };\n }\n }\n }\n return null;\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,WAAW,EAAEC,YAAY,EAAEC,YAAY,EAAEC,iBAAiB,QAAQ,YAAY;AAIvF,SACIC,aAAa,EAabC,kBAAkB,EAElBC,YAAY,EAEZC,MAAM,EACNC,SAAS,QACN,uBAAuB;AAC9B,SAASC,SAAS,QAAQ,mBAAmB;AAE7C,IAAMC,kBAAkB,G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C,EAAW;MAAA,IAAAC,qBAAA;MACrC,IAAI,EAAAA,qBAAA,OAAI,CAACnI,MAAM,CAAC6H,SAAS,cAAAM,qBAAA,uBAArBA,qBAAA,CAAwBD,KAAK,CAAC,MAAKzH,SAAS,EAAE;MAElD,KAAK,IAAMjE,IAAI,IAAIX,kBAAkB,EAAE;QACnC,IAAI,IAAI,CAACmE,MAAM,CAAC6H,SAAS,CAACK,KAAK,CAAC,CAAC1L,IAAI,CAAC,KAAKiE,SAAS,EAAE;QAEtD,KAAK,IAAMxB,IAAI,IAAI,IAAI,CAACe,MAAM,CAAC6H,SAAS,CAACK,KAAK,CAAC,CAAC1L,IAAI,CAAC,EAAG;UACpD,IAAIyC,IAAI,CAAC7C,OAAO,KAAKgD,MAAM,EAAE,OAAO;YAAEH,IAAI;YAAEzC;UAAK,CAAC;QACtD;MACJ;IACJ;IACA,OAAO,IAAI;EACf;AACJ;AAACyD,eAAA,CAxmBYH,aAAa,uBAsJqC,CAAC,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"pushprocessor.js","names":[],"sources":["../src/pushprocessor.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\nimport { deepCompare, escapeRegExp, globToRegexp, isNullOrUndefined } from \"./utils.ts\";\nimport { type Logger } from \"./logger.ts\";\nimport { type MatrixClient } from \"./client.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\nimport {\n ConditionKind,\n type IAnnotatedPushRule,\n type ICallStartedCondition,\n type ICallStartedPrefixCondition,\n type IContainsDisplayNameCondition,\n type IEventMatchCondition,\n type IEventPropertyContainsCondition,\n type IEventPropertyIsCondition,\n type IPushRule,\n type IPushRules,\n type IRoomMemberCountCondition,\n type ISenderNotificationPermissionCondition,\n type PushRuleAction,\n PushRuleActionName,\n type PushRuleCondition,\n PushRuleKind,\n type PushRuleSet,\n RuleId,\n TweakName,\n} from \"./@types/PushRules.ts\";\nimport { EventType } from \"./@types/event.ts\";\n\nconst RULEKINDS_IN_ORDER = [\n PushRuleKind.Override,\n PushRuleKind.ContentSpecific,\n PushRuleKind.RoomSpecific,\n PushRuleKind.SenderSpecific,\n PushRuleKind.Underride,\n];\n\n// The default override rules to apply to the push rules that arrive from the server.\n// We do this for two reasons:\n// 1. Synapse is unlikely to send us the push rule in an incremental sync - see\n// https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for\n// more details.\n// 2. We often want to start using push rules ahead of the server supporting them,\n// and so we can put them here.\nconst DEFAULT_OVERRIDE_RULES: Record<string, IPushRule> = {\n \".m.rule.is_room_mention\": {\n // Matrix v1.7\n rule_id: \".m.rule.is_room_mention\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventPropertyIs,\n key: \"content.m\\\\.mentions.room\",\n value: true,\n },\n {\n kind: ConditionKind.SenderNotificationPermission,\n key: \"room\",\n },\n ],\n actions: [\n PushRuleActionName.Notify,\n {\n set_tweak: TweakName.Highlight,\n },\n ],\n },\n \".m.rule.reaction\": {\n // For homeservers which don't support MSC2153 yet\n rule_id: \".m.rule.reaction\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: \"m.reaction\",\n },\n ],\n actions: [PushRuleActionName.DontNotify],\n },\n \".org.matrix.msc3786.rule.room.server_acl\": {\n // For homeservers which don't support MSC3786 yet\n rule_id: \".org.matrix.msc3786.rule.room.server_acl\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: EventType.RoomServerAcl,\n },\n {\n kind: ConditionKind.EventMatch,\n key: \"state_key\",\n pattern: \"\",\n },\n ],\n actions: [],\n },\n};\n\n// A special rule id for `EXPECTED_DEFAULT_OVERRIDE_RULE_IDS` and friends which denotes where user-defined rules live in the order.\nconst UserDefinedRules = Symbol(\"UserDefinedRules\");\n\ntype OrderedRules = Array<string | typeof UserDefinedRules>;\n\nconst EXPECTED_DEFAULT_OVERRIDE_RULE_IDS: OrderedRules = [\n RuleId.Master,\n UserDefinedRules,\n RuleId.SuppressNotices,\n RuleId.InviteToSelf,\n RuleId.MemberEvent,\n RuleId.IsUserMention,\n RuleId.ContainsDisplayName,\n RuleId.IsRoomMention,\n RuleId.AtRoomNotification,\n RuleId.Tombstone,\n \".m.rule.reaction\",\n \".m.rule.room.server_acl\",\n \".org.matrix.msc3786.rule.room.server_acl\",\n \".m.rule.suppress_edits\",\n];\n\nconst DEFAULT_UNDERRIDE_RULES: Record<string, IPushRule> = {\n \".org.matrix.msc3914.rule.room.call\": {\n // For homeservers which don't support MSC3914 yet\n rule_id: \".org.matrix.msc3914.rule.room.call\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: \"org.matrix.msc3401.call\",\n },\n {\n kind: ConditionKind.CallStarted,\n },\n ],\n actions: [PushRuleActionName.Notify, { set_tweak: TweakName.Sound, value: \"default\" }],\n },\n};\n\nconst EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS: OrderedRules = [\n UserDefinedRules,\n RuleId.IncomingCall,\n \".org.matrix.msc3914.rule.room.call\",\n RuleId.EncryptedDM,\n RuleId.DM,\n RuleId.Message,\n RuleId.EncryptedMessage,\n];\n\n/**\n * Make sure that each of the rules listed in `defaultRuleIds` is listed in the given set of push rules.\n *\n * @param logger - A `Logger` to write log messages to.\n * @param kind - the kind of push rule set being merged.\n * @param incomingRules - the existing set of known push rules for the user.\n * @param defaultRules - a lookup table for the default definitions of push rules.\n * @param orderedRuleIds - the IDs of the expected push rules, in order.\n *\n * @returns A copy of `incomingRules`, with any missing default rules inserted in the right place.\n */\nfunction mergeRulesWithDefaults(\n logger: Logger,\n kind: PushRuleKind,\n incomingRules: IPushRule[],\n defaultRules: Record<string, IPushRule>,\n orderedRuleIds: OrderedRules,\n): IPushRule[] {\n // Split the incomingRules into defaults and custom\n const incomingDefaultRules = incomingRules.filter((rule) => rule.default);\n const incomingCustomRules = incomingRules.filter((rule) => !rule.default);\n\n function insertDefaultPushRule(ruleId: OrderedRules[number]): void {\n if (ruleId === UserDefinedRules) {\n // Re-insert any user-defined rules that were in `incomingRules`\n newRules.push(...incomingCustomRules);\n } else if (ruleId in defaultRules) {\n logger.warn(`Adding default global ${kind} push rule ${ruleId}`);\n newRules.push(defaultRules[ruleId]);\n } else {\n logger.warn(`Missing default global ${kind} push rule ${ruleId}`);\n }\n }\n\n let nextExpectedRuleIdIndex = 0;\n const newRules: IPushRule[] = [];\n // Merge our expected rules (including the incoming custom rules) into the incoming default rules.\n for (const rule of incomingDefaultRules) {\n const ruleIndex = orderedRuleIds.indexOf(rule.rule_id);\n if (ruleIndex === -1) {\n // an unrecognised rule; copy it over\n newRules.push(rule);\n continue;\n }\n while (ruleIndex > nextExpectedRuleIdIndex) {\n // insert new rules\n const defaultRuleId = orderedRuleIds[nextExpectedRuleIdIndex];\n insertDefaultPushRule(defaultRuleId);\n nextExpectedRuleIdIndex += 1;\n }\n // copy over the existing rule\n newRules.push(rule);\n nextExpectedRuleIdIndex += 1;\n }\n\n // Now copy over any remaining default rules\n for (const ruleId of orderedRuleIds.slice(nextExpectedRuleIdIndex)) {\n insertDefaultPushRule(ruleId);\n }\n\n return newRules;\n}\n\nexport interface IActionsObject {\n /** Whether this event should notify the user or not. */\n notify: boolean;\n /** How this event should be notified. */\n tweaks: Partial<Record<TweakName, any>>;\n}\n\nexport class PushProcessor {\n /**\n * Construct a Push Processor.\n * @param client - The Matrix client object to use\n */\n public constructor(private readonly client: MatrixClient) {}\n\n /**\n * Maps the original key from the push rules to a list of property names\n * after unescaping.\n */\n private readonly parsedKeys = new Map<string, string[]>();\n\n /**\n * Convert a list of actions into a object with the actions as keys and their values\n * @example\n * eg. `[ 'notify', { set_tweak: 'sound', value: 'default' } ]`\n * becomes `{ notify: true, tweaks: { sound: 'default' } }`\n * @param actionList - The actions list\n *\n * @returns A object with key 'notify' (true or false) and an object of actions\n */\n public static actionListToActionsObject(actionList: PushRuleAction[]): IActionsObject {\n const actionObj: IActionsObject = { notify: false, tweaks: {} };\n for (const action of actionList) {\n if (action === PushRuleActionName.Notify) {\n actionObj.notify = true;\n } else if (typeof action === \"object\") {\n if (action.value === undefined) {\n action.value = true;\n }\n actionObj.tweaks[action.set_tweak] = action.value;\n }\n }\n return actionObj;\n }\n\n /**\n * Rewrites conditions on a client's push rules to match the defaults\n * where applicable. Useful for upgrading push rules to more strict\n * conditions when the server is falling behind on defaults.\n *\n * @param logger - A `Logger` to write log messages to.\n * @param incomingRules - The client's existing push rules\n * @param userId - The Matrix ID of the client.\n * @returns The rewritten rules\n */\n public static rewriteDefaultRules(\n logger: Logger,\n incomingRules: IPushRules,\n userId: string | undefined = undefined,\n ): IPushRules {\n let newRules: IPushRules = JSON.parse(JSON.stringify(incomingRules)); // deep clone\n\n // These lines are mostly to make the tests happy. We shouldn't run into these\n // properties missing in practice.\n if (!newRules) newRules = {} as IPushRules;\n if (!newRules.global) newRules.global = {} as PushRuleSet;\n if (!newRules.global.override) newRules.global.override = [];\n if (!newRules.global.underride) newRules.global.underride = [];\n\n // Merge the client-level defaults with the ones from the server\n newRules.global.override = mergeRulesWithDefaults(\n logger,\n PushRuleKind.Override,\n newRules.global.override,\n DEFAULT_OVERRIDE_RULES,\n EXPECTED_DEFAULT_OVERRIDE_RULE_IDS,\n );\n\n newRules.global.underride = mergeRulesWithDefaults(\n logger,\n PushRuleKind.Underride,\n newRules.global.underride,\n DEFAULT_UNDERRIDE_RULES,\n EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS,\n );\n\n return newRules;\n }\n\n /**\n * Create a RegExp object for the given glob pattern with a single capture group around the pattern itself, caching the result.\n * No cache invalidation is present currently,\n * as this will be inherently bounded to the size of the user's own push rules.\n * @param pattern - the glob pattern to convert to a RegExp\n * @param alignToWordBoundary - whether to align the pattern to word boundaries,\n * as specified for `content.body` matches, will use lookaround assertions to ensure the match only includes the pattern\n * @param flags - the flags to pass to the RegExp constructor, defaults to case-insensitive\n */\n public static getPushRuleGlobRegex(pattern: string, alignToWordBoundary = false, flags = \"i\"): RegExp {\n const [prefix, suffix] = alignToWordBoundary ? [\"(?<=^|\\\\W)\", \"(?=\\\\W|$)\"] : [\"^\", \"$\"];\n const cacheKey = `${alignToWordBoundary}-${flags}-${pattern}`;\n\n if (!PushProcessor.cachedGlobToRegex[cacheKey]) {\n PushProcessor.cachedGlobToRegex[cacheKey] = new RegExp(\n prefix + \"(\" + globToRegexp(pattern) + \")\" + suffix,\n flags,\n );\n }\n return PushProcessor.cachedGlobToRegex[cacheKey];\n }\n\n /**\n * Pre-caches the parsed keys for push rules and cleans out any obsolete cache\n * entries. Should be called after push rules are updated.\n * @param newRules - The new push rules.\n */\n public updateCachedPushRuleKeys(newRules: IPushRules): void {\n // These lines are mostly to make the tests happy. We shouldn't run into these\n // properties missing in practice.\n if (!newRules) newRules = {} as IPushRules;\n if (!newRules.global) newRules.global = {} as PushRuleSet;\n if (!newRules.global.override) newRules.global.override = [];\n if (!newRules.global.room) newRules.global.room = [];\n if (!newRules.global.sender) newRules.global.sender = [];\n if (!newRules.global.underride) newRules.global.underride = [];\n\n // Process the 'key' property on event_match conditions pre-cache the\n // values and clean-out any unused values.\n const toRemoveKeys = new Set(this.parsedKeys.keys());\n for (const ruleset of [\n newRules.global.override,\n newRules.global.room,\n newRules.global.sender,\n newRules.global.underride,\n ]) {\n for (const rule of ruleset) {\n if (!rule.conditions) {\n continue;\n }\n\n for (const condition of rule.conditions) {\n if (condition.kind !== ConditionKind.EventMatch) {\n continue;\n }\n\n // Ensure we keep this key.\n toRemoveKeys.delete(condition.key);\n\n // Pre-process the key.\n this.parsedKeys.set(condition.key, PushProcessor.partsForDottedKey(condition.key));\n }\n }\n }\n // Any keys that were previously cached, but are no longer needed should\n // be removed.\n toRemoveKeys.forEach((k) => this.parsedKeys.delete(k));\n }\n\n private static cachedGlobToRegex: Record<string, RegExp> = {}; // $glob: RegExp\n\n private matchingRuleFromKindSet(ev: MatrixEvent, kindset: PushRuleSet): IAnnotatedPushRule | null {\n for (const kind of RULEKINDS_IN_ORDER) {\n const ruleset = kindset[kind];\n if (!ruleset) {\n continue;\n }\n\n for (const rule of ruleset) {\n if (!rule.enabled) {\n continue;\n }\n\n const rawrule = this.templateRuleToRaw(kind, rule);\n if (!rawrule) {\n continue;\n }\n\n if (this.ruleMatchesEvent(rawrule, ev)) {\n return {\n ...rule,\n kind,\n };\n }\n }\n }\n return null;\n }\n\n private templateRuleToRaw(\n kind: PushRuleKind,\n tprule: IPushRule,\n ): Pick<IPushRule, \"rule_id\" | \"actions\" | \"conditions\"> | null {\n const rawrule: Pick<IPushRule, \"rule_id\" | \"actions\" | \"conditions\"> = {\n rule_id: tprule.rule_id,\n actions: tprule.actions,\n conditions: [],\n };\n switch (kind) {\n case PushRuleKind.Underride:\n case PushRuleKind.Override:\n rawrule.conditions = tprule.conditions;\n break;\n case PushRuleKind.RoomSpecific:\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"room_id\",\n value: tprule.rule_id,\n });\n break;\n case PushRuleKind.SenderSpecific:\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"user_id\",\n value: tprule.rule_id,\n });\n break;\n case PushRuleKind.ContentSpecific:\n if (!tprule.pattern) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"content.body\",\n pattern: tprule.pattern,\n });\n break;\n }\n return rawrule;\n }\n\n private eventFulfillsCondition(cond: PushRuleCondition, ev: MatrixEvent): boolean {\n switch (cond.kind) {\n case ConditionKind.EventMatch:\n return this.eventFulfillsEventMatchCondition(cond, ev);\n case ConditionKind.EventPropertyIs:\n return this.eventFulfillsEventPropertyIsCondition(cond, ev);\n case ConditionKind.EventPropertyContains:\n return this.eventFulfillsEventPropertyContains(cond, ev);\n case ConditionKind.ContainsDisplayName:\n return this.eventFulfillsDisplayNameCondition(cond, ev);\n case ConditionKind.RoomMemberCount:\n return this.eventFulfillsRoomMemberCountCondition(cond, ev);\n case ConditionKind.SenderNotificationPermission:\n return this.eventFulfillsSenderNotifPermCondition(cond, ev);\n case ConditionKind.CallStarted:\n case ConditionKind.CallStartedPrefix:\n return this.eventFulfillsCallStartedCondition(cond, ev);\n }\n\n // unknown conditions: we previously matched all unknown conditions,\n // but given that rules can be added to the base rules on a server,\n // it's probably better to not match unknown conditions.\n return false;\n }\n\n private eventFulfillsSenderNotifPermCondition(\n cond: ISenderNotificationPermissionCondition,\n ev: MatrixEvent,\n ): boolean {\n const notifLevelKey = cond[\"key\"];\n if (!notifLevelKey) {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n if (!room?.currentState) {\n return false;\n }\n\n // Note that this should not be the current state of the room but the state at\n // the point the event is in the DAG. Unfortunately the js-sdk does not store\n // this.\n return room.currentState.mayTriggerNotifOfType(notifLevelKey, ev.getSender()!);\n }\n\n private eventFulfillsRoomMemberCountCondition(cond: IRoomMemberCountCondition, ev: MatrixEvent): boolean {\n if (!cond.is) {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n if (!room || !room.currentState || !room.currentState.members) {\n return false;\n }\n\n const memberCount = room.currentState.getJoinedMemberCount();\n\n const m = cond.is.match(/^([=<>]*)(\\d*)$/);\n if (!m) {\n return false;\n }\n const ineq = m[1];\n const rhs = parseInt(m[2]);\n if (isNaN(rhs)) {\n return false;\n }\n switch (ineq) {\n case \"\":\n case \"==\":\n return memberCount == rhs;\n case \"<\":\n return memberCount < rhs;\n case \">\":\n return memberCount > rhs;\n case \"<=\":\n return memberCount <= rhs;\n case \">=\":\n return memberCount >= rhs;\n default:\n return false;\n }\n }\n\n private eventFulfillsDisplayNameCondition(cond: IContainsDisplayNameCondition, ev: MatrixEvent): boolean {\n let content = ev.getContent();\n if (ev.isEncrypted() && ev.getClearContent()) {\n content = ev.getClearContent()!;\n }\n if (!content || !content.body || typeof content.body != \"string\") {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n const member = room?.currentState?.getMember(this.client.credentials.userId!);\n if (!member) {\n return false;\n }\n\n const displayName = member.name;\n\n // N.B. we can't use \\b as it chokes on unicode. however \\W seems to be okay\n // as shorthand for [^0-9A-Za-z_].\n const pat = new RegExp(\"(^|\\\\W)\" + escapeRegExp(displayName) + \"(\\\\W|$)\", \"i\");\n return content.body.search(pat) > -1;\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing against the condition's glob-based\n * pattern.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventMatchCondition(cond: IEventMatchCondition, ev: MatrixEvent): boolean {\n if (!cond.key) {\n return false;\n }\n\n const val = this.valueForDottedKey(cond.key, ev);\n if (typeof val !== \"string\") {\n return false;\n }\n\n // XXX This does not match in a case-insensitive manner.\n //\n // See https://spec.matrix.org/v1.5/client-server-api/#conditions-1\n if (cond.value) {\n return cond.value === val;\n }\n\n if (typeof cond.pattern !== \"string\") {\n return false;\n }\n\n // Align to word boundary on `content.body` matches, whole string otherwise\n // https://spec.matrix.org/v1.13/client-server-api/#conditions-1\n const regex = PushProcessor.getPushRuleGlobRegex(cond.pattern, cond.key === \"content.body\");\n return !!val.match(regex);\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing exactly against the condition's\n * value.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventPropertyIsCondition(cond: IEventPropertyIsCondition, ev: MatrixEvent): boolean {\n if (!cond.key || cond.value === undefined) {\n return false;\n }\n return cond.value === this.valueForDottedKey(cond.key, ev);\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing exactly against the condition's\n * value.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventPropertyContains(cond: IEventPropertyContainsCondition, ev: MatrixEvent): boolean {\n if (!cond.key || cond.value === undefined) {\n return false;\n }\n const val = this.valueForDottedKey(cond.key, ev);\n if (!Array.isArray(val)) {\n return false;\n }\n return val.includes(cond.value);\n }\n\n private eventFulfillsCallStartedCondition(\n _cond: ICallStartedCondition | ICallStartedPrefixCondition,\n ev: MatrixEvent,\n ): boolean {\n // Since servers don't support properly sending push notification\n // about MSC3401 call events, we do the handling ourselves\n return (\n [\"m.ring\", \"m.prompt\"].includes(ev.getContent()[\"m.intent\"]) &&\n !(\"m.terminated\" in ev.getContent()) &&\n (ev.getPrevContent()[\"m.terminated\"] !== ev.getContent()[\"m.terminated\"] ||\n deepCompare(ev.getPrevContent(), {}))\n );\n }\n\n /**\n * Parse the key into the separate fields to search by splitting on\n * unescaped \".\", and then removing any escape characters.\n *\n * @param str - The key of the push rule condition: a dotted field.\n * @returns The unescaped parts to fetch.\n * @internal\n */\n public static partsForDottedKey(str: string): string[] {\n const result: string[] = [];\n\n // The current field and whether the previous character was the escape\n // character (a backslash).\n let part = \"\";\n let escaped = false;\n\n // Iterate over each character, and decide whether to append to the current\n // part (following the escape rules) or to start a new part (based on the\n // field separator).\n for (const c of str) {\n // If the previous character was the escape character (a backslash)\n // then decide what to append to the current part.\n if (escaped) {\n if (c === \"\\\\\" || c === \".\") {\n // An escaped backslash or dot just gets added.\n part += c;\n } else {\n // A character that shouldn't be escaped gets the backslash prepended.\n part += \"\\\\\" + c;\n }\n // This always resets being escaped.\n escaped = false;\n continue;\n }\n\n if (c == \".\") {\n // The field separator creates a new part.\n result.push(part);\n part = \"\";\n } else if (c == \"\\\\\") {\n // A backslash adds no characters, but starts an escape sequence.\n escaped = true;\n } else {\n // Otherwise, just add the current character.\n part += c;\n }\n }\n\n // Ensure the final part is included. If there's an open escape sequence\n // it should be included.\n if (escaped) {\n part += \"\\\\\";\n }\n result.push(part);\n\n return result;\n }\n\n /**\n * For a dotted field and event, fetch the value at that position, if one\n * exists.\n *\n * @param key - The key of the push rule condition: a dotted field to fetch.\n * @param ev - The matrix event to fetch the field from.\n * @returns The value at the dotted path given by key.\n */\n private valueForDottedKey(key: string, ev: MatrixEvent): any {\n // The key should already have been parsed via updateCachedPushRuleKeys,\n // but if it hasn't (maybe via an old consumer of the SDK which hasn't\n // been updated?) then lazily calculate it here.\n let parts = this.parsedKeys.get(key);\n if (parts === undefined) {\n parts = PushProcessor.partsForDottedKey(key);\n this.parsedKeys.set(key, parts);\n }\n let val: any;\n\n // special-case the first component to deal with encrypted messages\n const firstPart = parts[0];\n let currentIndex = 0;\n if (firstPart === \"content\") {\n val = ev.getContent();\n ++currentIndex;\n } else if (firstPart === \"type\") {\n val = ev.getType();\n ++currentIndex;\n } else {\n // use the raw event for any other fields\n val = ev.event;\n }\n\n for (; currentIndex < parts.length; ++currentIndex) {\n // The previous iteration resulted in null or undefined, bail (and\n // avoid the type error of attempting to retrieve a property).\n if (isNullOrUndefined(val)) {\n return undefined;\n }\n\n const thisPart = parts[currentIndex];\n val = val[thisPart];\n }\n return val;\n }\n\n private matchingRuleForEventWithRulesets(ev: MatrixEvent, rulesets?: IPushRules): IAnnotatedPushRule | null {\n if (!rulesets) {\n return null;\n }\n\n if (ev.getSender() === this.client.getSafeUserId()) {\n return null;\n }\n\n return this.matchingRuleFromKindSet(ev, rulesets.global);\n }\n\n private pushActionsForEventAndRulesets(\n ev: MatrixEvent,\n rulesets?: IPushRules,\n ): {\n actions?: IActionsObject;\n rule?: IAnnotatedPushRule;\n } {\n const rule = this.matchingRuleForEventWithRulesets(ev, rulesets);\n if (!rule) {\n return {};\n }\n\n const actionObj = PushProcessor.actionListToActionsObject(rule.actions);\n\n // Some actions are implicit in some situations: we add those here\n if (actionObj.tweaks.highlight === undefined) {\n // if it isn't specified, highlight if it's a content\n // rule but otherwise not\n actionObj.tweaks.highlight = rule.kind == PushRuleKind.ContentSpecific;\n }\n\n return { actions: actionObj, rule };\n }\n\n public ruleMatchesEvent(rule: Partial<IPushRule> & Pick<IPushRule, \"conditions\">, ev: MatrixEvent): boolean {\n // Disable the deprecated mentions push rules if the new mentions property exists.\n if (\n this.client.supportsIntentionalMentions() &&\n ev.getContent()[\"m.mentions\"] !== undefined &&\n (rule.rule_id === RuleId.ContainsUserName ||\n rule.rule_id === RuleId.ContainsDisplayName ||\n rule.rule_id === RuleId.AtRoomNotification)\n ) {\n return false;\n }\n\n return !rule.conditions?.some((cond) => !this.eventFulfillsCondition(cond, ev));\n }\n\n /**\n * Get the user's push actions for the given event\n */\n public actionsForEvent(ev: MatrixEvent): IActionsObject {\n const { actions } = this.pushActionsForEventAndRulesets(ev, this.client.pushRules);\n return actions || ({} as IActionsObject);\n }\n\n public actionsAndRuleForEvent(ev: MatrixEvent): {\n actions?: IActionsObject;\n rule?: IAnnotatedPushRule;\n } {\n return this.pushActionsForEventAndRulesets(ev, this.client.pushRules);\n }\n\n /**\n * Get one of the users push rules by its ID\n *\n * @param ruleId - The ID of the rule to search for\n * @returns The push rule, or null if no such rule was found\n */\n public getPushRuleById(ruleId: string): IPushRule | null {\n const result = this.getPushRuleAndKindById(ruleId);\n return result?.rule ?? null;\n }\n\n /**\n * Get one of the users push rules by its ID\n *\n * @param ruleId - The ID of the rule to search for\n * @returns rule The push rule, or null if no such rule was found\n * @returns kind - The PushRuleKind of the rule to search for\n */\n public getPushRuleAndKindById(ruleId: string): { rule: IPushRule; kind: PushRuleKind } | null {\n for (const scope of [\"global\"] as const) {\n if (this.client.pushRules?.[scope] === undefined) continue;\n\n for (const kind of RULEKINDS_IN_ORDER) {\n if (this.client.pushRules[scope][kind] === undefined) continue;\n\n for (const rule of this.client.pushRules[scope][kind]!) {\n if (rule.rule_id === ruleId) return { rule, k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BY,aAAa,uBAsJqC,CAAC,CAAC","ignoreList":[]}
@@ -21,21 +21,21 @@ import { encodeUnpaddedBase64Url } from "./base64.js";
21
21
  * String representing the lowercase latin alphabet for use in {@link secureRandomStringFrom}
22
22
  * (can be combined with other such exports or other characters by appending strings)
23
23
  */
24
- export var LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
24
+ export const LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
25
25
 
26
26
  /**
27
27
  * String representing the uppercase latin alphabet for use in secureRandomStringFrom
28
28
  * (can be combined with other such exports or other characters by appending strings)
29
29
  */
30
- export var UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
30
+ export const UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
31
31
 
32
32
  /**
33
33
  * String representing the arabic numerals for use in secureRandomStringFrom
34
34
  * (can be combined with other such exports or other characters by appending strings)
35
35
  */
36
- export var DIGITS = "0123456789";
36
+ export const DIGITS = "0123456789";
37
37
  export function secureRandomBase64Url(len) {
38
- var key = new Uint8Array(len);
38
+ const key = new Uint8Array(len);
39
39
  globalThis.crypto.getRandomValues(key);
40
40
  return encodeUnpaddedBase64Url(key);
41
41
  }
@@ -73,21 +73,21 @@ export function secureRandomStringFrom(len, chars) {
73
73
  // likely to be chosen (minus 1 to convert to indices in a string). (Essentially, we're using a d8
74
74
  // to choose between 7 possibilities and re-rolling on an 8, keeping all 7 outcomes equally likely.)
75
75
  // Our random values must be strictly less than this
76
- var randomValueCutoff = 256 - 256 % chars.length;
76
+ const randomValueCutoff = 256 - 256 % chars.length;
77
77
 
78
78
  // Grab 30% more entropy than we need. This should be enough that we can discard the values that are
79
79
  // too high without having to go back and grab more unless we're super unlucky.
80
- var entropyBuffer = new Uint8Array(Math.floor(len * 1.3));
80
+ const entropyBuffer = new Uint8Array(Math.floor(len * 1.3));
81
81
  // Mark all of this buffer as used to start with (we haven't populated it with entropy yet) so it will
82
82
  // be filled on the first iteration.
83
- var entropyBufferPos = entropyBuffer.length;
84
- var result = [];
83
+ let entropyBufferPos = entropyBuffer.length;
84
+ const result = [];
85
85
  while (result.length < len) {
86
86
  if (entropyBufferPos === entropyBuffer.length) {
87
87
  globalThis.crypto.getRandomValues(entropyBuffer);
88
88
  entropyBufferPos = 0;
89
89
  }
90
- var randomByte = entropyBuffer[entropyBufferPos++];
90
+ const randomByte = entropyBuffer[entropyBufferPos++];
91
91
  if (randomByte < randomValueCutoff) {
92
92
  result.push(chars[randomByte % chars.length]);
93
93
  }
@@ -1 +1 @@
1
- {"version":3,"file":"randomstring.js","names":["encodeUnpaddedBase64Url","LOWERCASE","UPPERCASE","DIGITS","secureRandomBase64Url","len","key","Uint8Array","globalThis","crypto","getRandomValues","secureRandomString","secureRandomStringFrom","chars","length","Error","randomValueCutoff","entropyBuffer","Math","floor","entropyBufferPos","result","randomByte","push","join"],"sources":["../src/randomstring.ts"],"sourcesContent":["/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 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 { encodeUnpaddedBase64Url } from \"./base64.ts\";\n\n/**\n * String representing the lowercase latin alphabet for use in {@link secureRandomStringFrom}\n * (can be combined with other such exports or other characters by appending strings)\n */\nexport const LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\n\n/**\n * String representing the uppercase latin alphabet for use in secureRandomStringFrom\n * (can be combined with other such exports or other characters by appending strings)\n */\nexport const UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n/**\n * String representing the arabic numerals for use in secureRandomStringFrom\n * (can be combined with other such exports or other characters by appending strings)\n */\nexport const DIGITS = \"0123456789\";\n\nexport function secureRandomBase64Url(len: number): string {\n const key = new Uint8Array(len);\n globalThis.crypto.getRandomValues(key);\n\n return encodeUnpaddedBase64Url(key);\n}\n\n/**\n * Generates a random string of uppercase and lowercase letters plus digits using a\n * cryptographically secure random number generator.\n * @param len The length of the string to generate\n * @returns Random string of uppercase and lowercase letters plus digits of length `len`\n */\nexport function secureRandomString(len: number): string {\n return secureRandomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS);\n}\n\n/**\n * Generate a cryptographically secure random string using characters given.\n *\n * @param len - The length of the string to generate (must be positive and less than 32768).\n * @param chars - The characters to use in the random string (between 2 and 256 characters long).\n * @returns Random string of characters of length `len`.\n */\nexport function secureRandomStringFrom(len: number, chars: string): string {\n // This is intended for latin strings so 256 possibilities should be more than enough and\n // means we can use random bytes, minimising the amount of entropy we need to ask for.\n if (chars.length < 2 || chars.length > 256) {\n throw new Error(\"Character set must be between 2 and 256 characters long\");\n }\n\n if (len < 1 || len > 32768) {\n throw new Error(\"Requested random string length must be between 1 and 32768\");\n }\n\n // We'll generate random unsigned bytes, so get the largest number less than 256 that is a multiple\n // of the length of the character set: We'll need to discard any random values that are larger than\n // this as we can't possibly map them onto the character set while keeping each character equally\n // likely to be chosen (minus 1 to convert to indices in a string). (Essentially, we're using a d8\n // to choose between 7 possibilities and re-rolling on an 8, keeping all 7 outcomes equally likely.)\n // Our random values must be strictly less than this\n const randomValueCutoff = 256 - (256 % chars.length);\n\n // Grab 30% more entropy than we need. This should be enough that we can discard the values that are\n // too high without having to go back and grab more unless we're super unlucky.\n const entropyBuffer = new Uint8Array(Math.floor(len * 1.3));\n // Mark all of this buffer as used to start with (we haven't populated it with entropy yet) so it will\n // be filled on the first iteration.\n let entropyBufferPos = entropyBuffer.length;\n\n const result = [];\n while (result.length < len) {\n if (entropyBufferPos === entropyBuffer.length) {\n globalThis.crypto.getRandomValues(entropyBuffer);\n entropyBufferPos = 0;\n }\n\n const randomByte = entropyBuffer[entropyBufferPos++];\n\n if (randomByte < randomValueCutoff) {\n result.push(chars[randomByte % chars.length]);\n }\n }\n\n return result.join(\"\");\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,uBAAuB,QAAQ,aAAa;;AAErD;AACA;AACA;AACA;AACA,OAAO,IAAMC,SAAS,GAAG,4BAA4B;;AAErD;AACA;AACA;AACA;AACA,OAAO,IAAMC,SAAS,GAAG,4BAA4B;;AAErD;AACA;AACA;AACA;AACA,OAAO,IAAMC,MAAM,GAAG,YAAY;AAElC,OAAO,SAASC,qBAAqBA,CAACC,GAAW,EAAU;EACvD,IAAMC,GAAG,GAAG,IAAIC,UAAU,CAACF,GAAG,CAAC;EAC/BG,UAAU,CAACC,MAAM,CAACC,eAAe,CAACJ,GAAG,CAAC;EAEtC,OAAON,uBAAuB,CAACM,GAAG,CAAC;AACvC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASK,kBAAkBA,CAACN,GAAW,EAAU;EACpD,OAAOO,sBAAsB,CAACP,GAAG,EAAEH,SAAS,GAAGD,SAAS,GAAGE,MAAM,CAAC;AACtE;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASS,sBAAsBA,CAACP,GAAW,EAAEQ,KAAa,EAAU;EACvE;EACA;EACA,IAAIA,KAAK,CAACC,MAAM,GAAG,CAAC,IAAID,KAAK,CAACC,MAAM,GAAG,GAAG,EAAE;IACxC,MAAM,IAAIC,KAAK,CAAC,yDAAyD,CAAC;EAC9E;EAEA,IAAIV,GAAG,GAAG,CAAC,IAAIA,GAAG,GAAG,KAAK,EAAE;IACxB,MAAM,IAAIU,KAAK,CAAC,4DAA4D,CAAC;EACjF;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMC,iBAAiB,GAAG,GAAG,GAAI,GAAG,GAAGH,KAAK,CAACC,MAAO;;EAEpD;EACA;EACA,IAAMG,aAAa,GAAG,IAAIV,UAAU,CAACW,IAAI,CAACC,KAAK,CAACd,GAAG,GAAG,GAAG,CAAC,CAAC;EAC3D;EACA;EACA,IAAIe,gBAAgB,GAAGH,aAAa,CAACH,MAAM;EAE3C,IAAMO,MAAM,GAAG,EAAE;EACjB,OAAOA,MAAM,CAACP,MAAM,GAAGT,GAAG,EAAE;IACxB,IAAIe,gBAAgB,KAAKH,aAAa,CAACH,MAAM,EAAE;MAC3CN,UAAU,CAACC,MAAM,CAACC,eAAe,CAACO,aAAa,CAAC;MAChDG,gBAAgB,GAAG,CAAC;IACxB;IAEA,IAAME,UAAU,GAAGL,aAAa,CAACG,gBAAgB,EAAE,CAAC;IAEpD,IAAIE,UAAU,GAAGN,iBAAiB,EAAE;MAChCK,MAAM,CAACE,IAAI,CAACV,KAAK,CAACS,UAAU,GAAGT,KAAK,CAACC,MAAM,CAAC,CAAC;IACjD;EACJ;EAEA,OAAOO,MAAM,CAACG,IAAI,CAAC,EAAE,CAAC;AAC1B","ignoreList":[]}
1
+ {"version":3,"file":"randomstring.js","names":[],"sources":["../src/randomstring.ts"],"sourcesContent":["/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 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 { encodeUnpaddedBase64Url } from \"./base64.ts\";\n\n/**\n * String representing the lowercase latin alphabet for use in {@link secureRandomStringFrom}\n * (can be combined with other such exports or other characters by appending strings)\n */\nexport const LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\n\n/**\n * String representing the uppercase latin alphabet for use in secureRandomStringFrom\n * (can be combined with other such exports or other characters by appending strings)\n */\nexport const UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n/**\n * String representing the arabic numerals for use in secureRandomStringFrom\n * (can be combined with other such exports or other characters by appending strings)\n */\nexport const DIGITS = \"0123456789\";\n\nexport function secureRandomBase64Url(len: number): string {\n const key = new Uint8Array(len);\n globalThis.crypto.getRandomValues(key);\n\n return encodeUnpaddedBase64Url(key);\n}\n\n/**\n * Generates a random string of uppercase and lowercase letters plus digits using a\n * cryptographically secure random number generator.\n * @param len The length of the string to generate\n * @returns Random string of uppercase and lowercase letters plus digits of length `len`\n */\nexport function secureRandomString(len: number): string {\n return secureRandomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS);\n}\n\n/**\n * Generate a cryptographically secure random string using characters given.\n *\n * @param len - The length of the string to generate (must be positive and less than 32768).\n * @param chars - The characters to use in the random string (between 2 and 256 characters long).\n * @returns Random string of characters of length `len`.\n */\nexport function secureRandomStringFrom(len: number, chars: string): string {\n // This is intended for latin strings so 256 possibilities should be more than enough and\n // means we can use random bytes, minimising the amount of entropy we need to ask for.\n if (chars.length < 2 || chars.length > 256) {\n throw new Error(\"Character set must be between 2 and 256 characters long\");\n }\n\n if (len < 1 || len > 32768) {\n throw new Error(\"Requested random string length must be between 1 and 32768\");\n }\n\n // We'll generate random unsigned bytes, so get the largest number less than 256 that is a multiple\n // of the length of the character set: We'll need to discard any random values that are larger than\n // this as we can't possibly map them onto the character set while keeping each character equally\n // likely to be chosen (minus 1 to convert to indices in a string). (Essentially, we're using a d8\n // to choose between 7 possibilities and re-rolling on an 8, keeping all 7 outcomes equally likely.)\n // Our random values must be strictly less than this\n const randomValueCutoff = 256 - (256 % chars.length);\n\n // Grab 30% more entropy than we need. This should be enough that we can discard the values that are\n // too high without having to go back and grab more unless we're super unlucky.\n const entropyBuffer = new Uint8Array(Math.floor(len * 1.3));\n // Mark all of this buffer as used to start with (we haven't populated it with entropy yet) so it will\n // be filled on the first iteration.\n let entropyBufferPos = entropyBuffer.length;\n\n const result = [];\n while (result.length < len) {\n if (entropyBufferPos === entropyBuffer.length) {\n globalThis.crypto.getRandomValues(entropyBuffer);\n entropyBufferPos = 0;\n }\n\n const randomByte = entropyBuffer[entropyBufferPos++];\n\n if (randomByte < randomValueCutoff) {\n result.push(chars[randomByte % chars.length]);\n }\n }\n\n return result.join(\"\");\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,uBAAuB,QAAQ,aAAa;;AAErD;AACA;AACA;AACA;AACA,OAAO,MAAM,SAAS,GAAG,4BAA4B;;AAErD;AACA;AACA;AACA;AACA,OAAO,MAAM,SAAS,GAAG,4BAA4B;;AAErD;AACA;AACA;AACA;AACA,OAAO,MAAM,MAAM,GAAG,YAAY;AAElC,OAAO,SAAS,qBAAqB,CAAC,GAAW,EAAU;EACvD,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC;EAC/B,UAAU,CAAC,MAAM,CAAC,eAAe,CAAC,GAAG,CAAC;EAEtC,OAAO,uBAAuB,CAAC,GAAG,CAAC;AACvC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,kBAAkB,CAAC,GAAW,EAAU;EACpD,OAAO,sBAAsB,CAAC,GAAG,EAAE,SAAS,GAAG,SAAS,GAAG,MAAM,CAAC;AACtE;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,sBAAsB,CAAC,GAAW,EAAE,KAAa,EAAU;EACvE;EACA;EACA,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,GAAG,EAAE;IACxC,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC;EAC9E;EAEA,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,KAAK,EAAE;IACxB,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC;EACjF;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA,MAAM,iBAAiB,GAAG,GAAG,GAAI,GAAG,GAAG,KAAK,CAAC,MAAO;;EAEpD;EACA;EACA,MAAM,aAAa,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,GAAG,CAAC,CAAC;EAC3D;EACA;EACA,IAAI,gBAAgB,GAAG,aAAa,CAAC,MAAM;EAE3C,MAAM,MAAM,GAAG,EAAE;EACjB,OAAO,MAAM,CAAC,MAAM,GAAG,GAAG,EAAE;IACxB,IAAI,gBAAgB,KAAK,aAAa,CAAC,MAAM,EAAE;MAC3C,UAAU,CAAC,MAAM,CAAC,eAAe,CAAC,aAAa,CAAC;MAChD,gBAAgB,GAAG,CAAC;IACxB;IAEA,MAAM,UAAU,GAAG,aAAa,CAAC,gBAAgB,EAAE,CAAC;IAEpD,IAAI,UAAU,GAAG,iBAAiB,EAAE;MAChC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;IACjD;EACJ;EAEA,OAAO,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC;AAC1B","ignoreList":[]}
@@ -28,20 +28,20 @@ import { logger } from "./logger.js";
28
28
 
29
29
  // we schedule a callback at least this often, to check if we've missed out on
30
30
  // some wall-clock time due to being suspended.
31
- var TIMER_CHECK_PERIOD_MS = 1000;
31
+ const TIMER_CHECK_PERIOD_MS = 1000;
32
32
 
33
33
  // counter, for making up ids to return from setTimeout
34
- var count = 0;
34
+ let count = 0;
35
35
 
36
36
  // the key for our callback with the real globalThis.setTimeout
37
- var realCallbackKey;
37
+ let realCallbackKey;
38
38
  // a sorted list of the callbacks to be run.
39
39
  // each is an object with keys [runAt, func, params, key].
40
- var callbackList = [];
40
+ const callbackList = [];
41
41
 
42
42
  // var debuglog = logger.log.bind(logger);
43
43
  /* istanbul ignore next */
44
- var debuglog = function debuglog() {};
44
+ const debuglog = function (...params) {};
45
45
 
46
46
  /**
47
47
  * reimplementation of window.setTimeout, which will call the callback if
@@ -53,18 +53,15 @@ var debuglog = function debuglog() {};
53
53
  * @returns an identifier for this callback, which may be passed into
54
54
  * clearTimeout later.
55
55
  */
56
- export function setTimeout(func, delayMs) {
57
- for (var _len = arguments.length, params = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
58
- params[_key - 2] = arguments[_key];
59
- }
56
+ export function setTimeout(func, delayMs, ...params) {
60
57
  delayMs = delayMs || 0;
61
58
  if (delayMs < 0) {
62
59
  delayMs = 0;
63
60
  }
64
- var runAt = Date.now() + delayMs;
65
- var key = count++;
61
+ const runAt = Date.now() + delayMs;
62
+ const key = count++;
66
63
  debuglog("setTimeout: scheduling cb", key, "at", runAt, "(delay", delayMs, ")");
67
- var data = {
64
+ const data = {
68
65
  runAt: runAt,
69
66
  func: func,
70
67
  params: params,
@@ -72,7 +69,7 @@ export function setTimeout(func, delayMs) {
72
69
  };
73
70
 
74
71
  // figure out where it goes in the list
75
- var idx = binarySearch(callbackList, function (el) {
72
+ const idx = binarySearch(callbackList, function (el) {
76
73
  return el.runAt - runAt;
77
74
  });
78
75
  callbackList.splice(idx, 0, data);
@@ -91,9 +88,9 @@ export function clearTimeout(key) {
91
88
  }
92
89
 
93
90
  // remove the element from the list
94
- var i;
91
+ let i;
95
92
  for (i = 0; i < callbackList.length; i++) {
96
- var cb = callbackList[i];
93
+ const cb = callbackList[i];
97
94
  if (cb.key == key) {
98
95
  callbackList.splice(i, 1);
99
96
  break;
@@ -111,29 +108,29 @@ function scheduleRealCallback() {
111
108
  if (realCallbackKey) {
112
109
  globalThis.clearTimeout(realCallbackKey);
113
110
  }
114
- var first = callbackList[0];
111
+ const first = callbackList[0];
115
112
  if (!first) {
116
113
  debuglog("scheduleRealCallback: no more callbacks, not rescheduling");
117
114
  return;
118
115
  }
119
- var timestamp = Date.now();
120
- var delayMs = Math.min(first.runAt - timestamp, TIMER_CHECK_PERIOD_MS);
116
+ const timestamp = Date.now();
117
+ const delayMs = Math.min(first.runAt - timestamp, TIMER_CHECK_PERIOD_MS);
121
118
  debuglog("scheduleRealCallback: now:", timestamp, "delay:", delayMs);
122
119
  realCallbackKey = globalThis.setTimeout(runCallbacks, delayMs);
123
120
  }
124
121
  function runCallbacks() {
125
- var timestamp = Date.now();
122
+ const timestamp = Date.now();
126
123
  debuglog("runCallbacks: now:", timestamp);
127
124
 
128
125
  // get the list of things to call
129
- var callbacksToRun = [];
126
+ const callbacksToRun = [];
130
127
  // eslint-disable-next-line
131
128
  while (true) {
132
- var first = callbackList[0];
129
+ const first = callbackList[0];
133
130
  if (!first || first.runAt > timestamp) {
134
131
  break;
135
132
  }
136
- var cb = callbackList.shift();
133
+ const cb = callbackList.shift();
137
134
  debuglog("runCallbacks: popping", cb.key);
138
135
  callbacksToRun.push(cb);
139
136
  }
@@ -142,9 +139,9 @@ function runCallbacks() {
142
139
  // keep the codepaths the same whether or not our functions
143
140
  // register their own setTimeouts.
144
141
  scheduleRealCallback();
145
- for (var _cb of callbacksToRun) {
142
+ for (const cb of callbacksToRun) {
146
143
  try {
147
- _cb.func.apply(globalThis, _cb.params);
144
+ cb.func.apply(globalThis, cb.params);
148
145
  } catch (e) {
149
146
  logger.error("Uncaught exception in callback function", e);
150
147
  }
@@ -158,11 +155,11 @@ function runCallbacks() {
158
155
  */
159
156
  function binarySearch(array, func) {
160
157
  // min is inclusive, max exclusive.
161
- var min = 0;
162
- var max = array.length;
158
+ let min = 0;
159
+ let max = array.length;
163
160
  while (min < max) {
164
- var mid = min + max >> 1;
165
- var res = func(array[mid]);
161
+ const mid = min + max >> 1;
162
+ const res = func(array[mid]);
166
163
  if (res > 0) {
167
164
  // the element at 'mid' is too big; set it as the new max.
168
165
  max = mid;
@@ -1 +1 @@
1
- {"version":3,"file":"realtime-callbacks.js","names":["logger","TIMER_CHECK_PERIOD_MS","count","realCallbackKey","callbackList","debuglog","setTimeout","func","delayMs","_len","arguments","length","params","Array","_key","runAt","Date","now","key","data","idx","binarySearch","el","splice","scheduleRealCallback","clearTimeout","i","cb","globalThis","first","timestamp","Math","min","runCallbacks","callbacksToRun","shift","push","apply","e","error","array","max","mid","res"],"sources":["../src/realtime-callbacks.ts"],"sourcesContent":["/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2019 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/* A re-implementation of the javascript callback functions (setTimeout,\n * clearTimeout; setInterval and clearInterval are not yet implemented) which\n * try to improve handling of large clock jumps (as seen when\n * suspending/resuming the system).\n *\n * In particular, if a timeout would have fired while the system was suspended,\n * it will instead fire as soon as possible after resume.\n */\n\nimport { logger } from \"./logger.ts\";\n\n// we schedule a callback at least this often, to check if we've missed out on\n// some wall-clock time due to being suspended.\nconst TIMER_CHECK_PERIOD_MS = 1000;\n\n// counter, for making up ids to return from setTimeout\nlet count = 0;\n\n// the key for our callback with the real globalThis.setTimeout\nlet realCallbackKey: NodeJS.Timeout | number;\n\ntype Callback = {\n runAt: number;\n func: (...params: any[]) => void;\n params: any[];\n key: number;\n};\n\n// a sorted list of the callbacks to be run.\n// each is an object with keys [runAt, func, params, key].\nconst callbackList: Callback[] = [];\n\n// var debuglog = logger.log.bind(logger);\n/* istanbul ignore next */\nconst debuglog = function (...params: any[]): void {};\n\n/**\n * reimplementation of window.setTimeout, which will call the callback if\n * the wallclock time goes past the deadline.\n *\n * @param func - callback to be called after a delay\n * @param delayMs - number of milliseconds to delay by\n *\n * @returns an identifier for this callback, which may be passed into\n * clearTimeout later.\n */\nexport function setTimeout(func: (...params: any[]) => void, delayMs: number, ...params: any[]): number {\n delayMs = delayMs || 0;\n if (delayMs < 0) {\n delayMs = 0;\n }\n\n const runAt = Date.now() + delayMs;\n const key = count++;\n debuglog(\"setTimeout: scheduling cb\", key, \"at\", runAt, \"(delay\", delayMs, \")\");\n const data = {\n runAt: runAt,\n func: func,\n params: params,\n key: key,\n };\n\n // figure out where it goes in the list\n const idx = binarySearch(callbackList, function (el) {\n return el.runAt - runAt;\n });\n\n callbackList.splice(idx, 0, data);\n scheduleRealCallback();\n\n return key;\n}\n\n/**\n * reimplementation of window.clearTimeout, which mirrors setTimeout\n *\n * @param key - result from an earlier setTimeout call\n */\nexport function clearTimeout(key: number): void {\n if (callbackList.length === 0) {\n return;\n }\n\n // remove the element from the list\n let i: number;\n for (i = 0; i < callbackList.length; i++) {\n const cb = callbackList[i];\n if (cb.key == key) {\n callbackList.splice(i, 1);\n break;\n }\n }\n\n // iff it was the first one in the list, reschedule our callback.\n if (i === 0) {\n scheduleRealCallback();\n }\n}\n\n// use the real globalThis.setTimeout to schedule a callback to runCallbacks.\nfunction scheduleRealCallback(): void {\n if (realCallbackKey) {\n globalThis.clearTimeout(realCallbackKey as NodeJS.Timeout);\n }\n\n const first = callbackList[0];\n\n if (!first) {\n debuglog(\"scheduleRealCallback: no more callbacks, not rescheduling\");\n return;\n }\n\n const timestamp = Date.now();\n const delayMs = Math.min(first.runAt - timestamp, TIMER_CHECK_PERIOD_MS);\n\n debuglog(\"scheduleRealCallback: now:\", timestamp, \"delay:\", delayMs);\n realCallbackKey = globalThis.setTimeout(runCallbacks, delayMs);\n}\n\nfunction runCallbacks(): void {\n const timestamp = Date.now();\n debuglog(\"runCallbacks: now:\", timestamp);\n\n // get the list of things to call\n const callbacksToRun: Callback[] = [];\n // eslint-disable-next-line\n while (true) {\n const first = callbackList[0];\n if (!first || first.runAt > timestamp) {\n break;\n }\n const cb = callbackList.shift()!;\n debuglog(\"runCallbacks: popping\", cb.key);\n callbacksToRun.push(cb);\n }\n\n // reschedule the real callback before running our functions, to\n // keep the codepaths the same whether or not our functions\n // register their own setTimeouts.\n scheduleRealCallback();\n\n for (const cb of callbacksToRun) {\n try {\n cb.func.apply(globalThis, cb.params);\n } catch (e) {\n logger.error(\"Uncaught exception in callback function\", e);\n }\n }\n}\n\n/* search in a sorted array.\n *\n * returns the index of the last element for which func returns\n * greater than zero, or array.length if no such element exists.\n */\nfunction binarySearch<T>(array: T[], func: (v: T) => number): number {\n // min is inclusive, max exclusive.\n let min = 0;\n let max = array.length;\n\n while (min < max) {\n const mid = (min + max) >> 1;\n const res = func(array[mid]);\n if (res > 0) {\n // the element at 'mid' is too big; set it as the new max.\n max = mid;\n } else {\n // the element at 'mid' is too small. 'min' is inclusive, so +1.\n min = mid + 1;\n }\n }\n // presumably, min==max now.\n return min;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,MAAM,QAAQ,aAAa;;AAEpC;AACA;AACA,IAAMC,qBAAqB,GAAG,IAAI;;AAElC;AACA,IAAIC,KAAK,GAAG,CAAC;;AAEb;AACA,IAAIC,eAAwC;AAS5C;AACA;AACA,IAAMC,YAAwB,GAAG,EAAE;;AAEnC;AACA;AACA,IAAMC,QAAQ,GAAG,SAAXA,QAAQA,CAAA,EAAqC,CAAC,CAAC;;AAErD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,UAAUA,CAACC,IAAgC,EAAEC,OAAe,EAA4B;EAAA,SAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,EAAvBC,MAAM,OAAAC,KAAA,CAAAJ,IAAA,OAAAA,IAAA,WAAAK,IAAA,MAAAA,IAAA,GAAAL,IAAA,EAAAK,IAAA;IAANF,MAAM,CAAAE,IAAA,QAAAJ,SAAA,CAAAI,IAAA;EAAA;EACnFN,OAAO,GAAGA,OAAO,IAAI,CAAC;EACtB,I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ACxC,CAAC,CAAC,OAAO0B,CAAC,EAAE;MACRtC,MAAM,CAACuC,KAAK,CAAC,yCAAyC,EAAED,CAAC,CAAC;IAC9D;EACJ;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA,SAASjB,YAAYA,CAAImB,KAAU,EAAEjC,IAAsB,EAAU;EACjE;EACA,IAAIyB,GAAG,GAAG,CAAC;EACX,IAAIS,GAAG,GAAGD,KAAK,CAAC7B,MAAM;EAEtB,OAAOqB,GAAG,GAAGS,GAAG,EAAE;IACd,IAAMC,GAAG,GAAIV,GAAG,GAAGS,GAAG,IAAK,CAAC;IAC5B,IAAME,GAAG,GAAGpC,IAAI,CAACiC,KAAK,CAACE,GAAG,CAAC,CAAC;IAC5B,IAAIC,GAAG,GAAG,CAAC,EAAE;MACT;MACAF,GAAG,GAAGC,GAAG;IACb,CAAC,MAAM;MACH;MACAV,GAAG,GAAGU,GAAG,GAAG,CAAC;IACjB;EACJ;EACA;EACA,OAAOV,GAAG;AACd","ignoreList":[]}
1
+ {"version":3,"file":"realtime-callbacks.js","names":[],"sources":["../src/realtime-callbacks.ts"],"sourcesContent":["/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2019 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/* A re-implementation of the javascript callback functions (setTimeout,\n * clearTimeout; setInterval and clearInterval are not yet implemented) which\n * try to improve handling of large clock jumps (as seen when\n * suspending/resuming the system).\n *\n * In particular, if a timeout would have fired while the system was suspended,\n * it will instead fire as soon as possible after resume.\n */\n\nimport { logger } from \"./logger.ts\";\n\n// we schedule a callback at least this often, to check if we've missed out on\n// some wall-clock time due to being suspended.\nconst TIMER_CHECK_PERIOD_MS = 1000;\n\n// counter, for making up ids to return from setTimeout\nlet count = 0;\n\n// the key for our callback with the real globalThis.setTimeout\nlet realCallbackKey: NodeJS.Timeout | number;\n\ntype Callback = {\n runAt: number;\n func: (...params: any[]) => void;\n params: any[];\n key: number;\n};\n\n// a sorted list of the callbacks to be run.\n// each is an object with keys [runAt, func, params, key].\nconst callbackList: Callback[] = [];\n\n// var debuglog = logger.log.bind(logger);\n/* istanbul ignore next */\nconst debuglog = function (...params: any[]): void {};\n\n/**\n * reimplementation of window.setTimeout, which will call the callback if\n * the wallclock time goes past the deadline.\n *\n * @param func - callback to be called after a delay\n * @param delayMs - number of milliseconds to delay by\n *\n * @returns an identifier for this callback, which may be passed into\n * clearTimeout later.\n */\nexport function setTimeout(func: (...params: any[]) => void, delayMs: number, ...params: any[]): number {\n delayMs = delayMs || 0;\n if (delayMs < 0) {\n delayMs = 0;\n }\n\n const runAt = Date.now() + delayMs;\n const key = count++;\n debuglog(\"setTimeout: scheduling cb\", key, \"at\", runAt, \"(delay\", delayMs, \")\");\n const data = {\n runAt: runAt,\n func: func,\n params: params,\n key: key,\n };\n\n // figure out where it goes in the list\n const idx = binarySearch(callbackList, function (el) {\n return el.runAt - runAt;\n });\n\n callbackList.splice(idx, 0, data);\n scheduleRealCallback();\n\n return key;\n}\n\n/**\n * reimplementation of window.clearTimeout, which mirrors setTimeout\n *\n * @param key - result from an earlier setTimeout call\n */\nexport function clearTimeout(key: number): void {\n if (callbackList.length === 0) {\n return;\n }\n\n // remove the element from the list\n let i: number;\n for (i = 0; i < callbackList.length; i++) {\n const cb = callbackList[i];\n if (cb.key == key) {\n callbackList.splice(i, 1);\n break;\n }\n }\n\n // iff it was the first one in the list, reschedule our callback.\n if (i === 0) {\n scheduleRealCallback();\n }\n}\n\n// use the real globalThis.setTimeout to schedule a callback to runCallbacks.\nfunction scheduleRealCallback(): void {\n if (realCallbackKey) {\n globalThis.clearTimeout(realCallbackKey as NodeJS.Timeout);\n }\n\n const first = callbackList[0];\n\n if (!first) {\n debuglog(\"scheduleRealCallback: no more callbacks, not rescheduling\");\n return;\n }\n\n const timestamp = Date.now();\n const delayMs = Math.min(first.runAt - timestamp, TIMER_CHECK_PERIOD_MS);\n\n debuglog(\"scheduleRealCallback: now:\", timestamp, \"delay:\", delayMs);\n realCallbackKey = globalThis.setTimeout(runCallbacks, delayMs);\n}\n\nfunction runCallbacks(): void {\n const timestamp = Date.now();\n debuglog(\"runCallbacks: now:\", timestamp);\n\n // get the list of things to call\n const callbacksToRun: Callback[] = [];\n // eslint-disable-next-line\n while (true) {\n const first = callbackList[0];\n if (!first || first.runAt > timestamp) {\n break;\n }\n const cb = callbackList.shift()!;\n debuglog(\"runCallbacks: popping\", cb.key);\n callbacksToRun.push(cb);\n }\n\n // reschedule the real callback before running our functions, to\n // keep the codepaths the same whether or not our functions\n // register their own setTimeouts.\n scheduleRealCallback();\n\n for (const cb of callbacksToRun) {\n try {\n cb.func.apply(globalThis, cb.params);\n } catch (e) {\n logger.error(\"Uncaught exception in callback function\", e);\n }\n }\n}\n\n/* search in a sorted array.\n *\n * returns the index of the last element for which func returns\n * greater than zero, or array.length if no such element exists.\n */\nfunction binarySearch<T>(array: T[], func: (v: T) => number): number {\n // min is inclusive, max exclusive.\n let min = 0;\n let max = array.length;\n\n while (min < max) {\n const mid = (min + max) >> 1;\n const res = func(array[mid]);\n if (res > 0) {\n // the element at 'mid' is too big; set it as the new max.\n max = mid;\n } else {\n // the element at 'mid' is too small. 'min' is inclusive, so +1.\n min = mid + 1;\n }\n }\n // presumably, min==max now.\n return min;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,MAAM,QAAQ,aAAa;;AAEpC;AACA;AACA,MAAM,qBAAqB,GAAG,IAAI;;AAElC;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AAC;EAC3B;;EAEA;EACA;EACA;EACA,oBAAoB,CAAC,CAAC;EAEtB,KAAK,MAAM,EAAE,IAAI,cAAc,EAAE;IAC7B,IAAI;MACA,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE,EAAE,CAAC,MAAM,CAAC;IACxC,CAAC,CAAC,OAAO,CAAC,EAAE;MACR,MAAM,CAAC,KAAK,CAAC,yCAAyC,EAAE,CAAC,CAAC;IAC9D;EACJ;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA,SAAS,YAAY,CAAI,KAAU,EAAE,IAAsB,EAAU;EACjE;EACA,IAAI,GAAG,GAAG,CAAC;EACX,IAAI,GAAG,GAAG,KAAK,CAAC,MAAM;EAEtB,OAAO,GAAG,GAAG,GAAG,EAAE;IACd,MAAM,GAAG,GAAI,GAAG,GAAG,GAAG,IAAK,CAAC;IAC5B,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC5B,IAAI,GAAG,GAAG,CAAC,EAAE;MACT;MACA,GAAG,GAAG,GAAG;IACb,CAAC,MAAM;MACH;MACA,GAAG,GAAG,GAAG,GAAG,CAAC;IACjB;EACJ;EACA;EACA,OAAO,GAAG;AACd","ignoreList":[]}
@@ -28,12 +28,14 @@ export declare class ReceiptAccumulator {
28
28
  /**
29
29
  * @returns an iterator of pairs of [userId, AccumulatedReceipt] - all the
30
30
  * most recently-received unthreaded receipts for each user.
31
+ * @yields pairs of [userId, AccumulatedReceipt]
31
32
  */
32
33
  private allUnthreaded;
33
34
  /**
34
35
  * @returns an iterator of pairs of [userId, AccumulatedReceipt] - all the
35
36
  * most recently-received threaded receipts for each user, in all
36
37
  * threads.
38
+ * @yields pairs of [userId, AccumulatedReceipt]
37
39
  */
38
40
  private allThreaded;
39
41
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"receipt-accumulator.d.ts","sourceRoot":"","sources":["../src/receipt-accumulator.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAY3D;;;;;;;;;;GAUG;AACH,qBAAa,kBAAkB;IAC3B,4DAA4D;IAC5D,OAAO,CAAC,sBAAsB,CAA8C;IAE5E,+EAA+E;IAC/E,OAAO,CAAC,oBAAoB,CAE1B;IAEF;;;OAGG;IACH,OAAO,CAAC,aAAa;IAIrB;;;OAGG;IACH,OAAO,CAAC,WAAW;IAInB;;;OAGG;IACH,OAAO,CAAC,aAAa;IAIrB;;;;OAIG;IACH,OAAO,CAAE,WAAW;IAQpB;;;OAGG;IACI,sBAAsB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,SAAS,GAAG,IAAI;IA8DxE;;;;OAIG;IACI,4BAA4B,CAAC,MAAM,EAAE,MAAM,GAAG,aAAa,GAAG,IAAI;CAgC5E"}
1
+ {"version":3,"file":"receipt-accumulator.d.ts","sourceRoot":"","sources":["../src/receipt-accumulator.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAY3D;;;;;;;;;;GAUG;AACH,qBAAa,kBAAkB;IAC3B,4DAA4D;IAC5D,OAAO,CAAC,sBAAsB,CAA8C;IAE5E,+EAA+E;IAC/E,OAAO,CAAC,oBAAoB,CAE1B;IAEF;;;OAGG;IACH,OAAO,CAAC,aAAa;IAIrB;;;OAGG;IACH,OAAO,CAAC,WAAW;IAInB;;;;OAIG;IACH,OAAO,CAAC,aAAa;IAIrB;;;;;OAKG;IACH,OAAO,CAAE,WAAW;IAQpB;;;OAGG;IACI,sBAAsB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,SAAS,GAAG,IAAI;IA8DxE;;;;OAIG;IACI,4BAA4B,CAAC,MAAM,EAAE,MAAM,GAAG,aAAa,GAAG,IAAI;CAgC5E"}