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":"interactive-auth.js","names":["logger","MatrixError","EMAIL_STAGE_TYPE","MSISDN_STAGE_TYPE","AuthType","NoAuthFlowFoundError","Error","constructor","m","required_stages","flows","_defineProperty","InteractiveAuth","opts","_this","_asyncToGenerator","requestingEmailToken","trace","emailAttempt","requestTokenResult","requestEmailTokenCallback","inputs","emailAddress","clientSecret","data","session","emailSid","sid","warn","matrixClient","authData","requestCallback","doRequest","busyChangedCallback","busyChanged","stateUpdatedCallback","stateUpdated","startAuthStage","requestEmailToken","sessionId","generateClientSecret","supportedStages","undefined","Set","attemptAuth","_this2","_this2$data","attemptAuthDeferred","Promise","withResolvers","promise","length","_this2$busyChangedCal","call","auth","finally","_this2$busyChangedCal2","startNextAuthStage","poll","_this3","submitPromise","authDict","currentStage","creds","client_secret","isUrl","getIdentityServerUrl","id_server","URL","host","type","threepid_creds","submitAuthDict","getSessionId","_this$data","getClientSecret","getStageParams","loginType","_this$data2","params","getChosenFlow","chosenFlow","_arguments","arguments","_this4","_this4$data","background","_this4$busyChangedCal","_unused","Object","assign","_this4$busyChangedCal2","getEmailSid","setEmailSid","_arguments2","_this5","result","resolve","error","_matrixError$data$flo","_matrixError$data","_this5$data","_this5$chosenFlow","matrixError","errorFlows","haveFlows","Boolean","httpStatus","_this5$attemptAuthDef","reject","log","completed","e","stages","includes","Email","_this$data3","_this$data4","nextStage","chooseStage","Dummy","errcode","_this$data5","_this$data6","chooseFlow","JSON","stringify","firstUncompletedStage","scoreFlow","flow","score","filter","stage","has","_this$data7","haveEmail","haveMsisdn","phoneCountry","phoneNumber","sort","a","b","flowHasEmail","flowHasMsisdn","requiredStages","push","_this$data8","find","stageType"],"sources":["../src/interactive-auth.ts"],"sourcesContent":["/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations 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 { logger } from \"./logger.ts\";\nimport { type MatrixClient } from \"./client.ts\";\nimport { MatrixError } from \"./http-api/index.ts\";\nimport { type UserIdentifier } from \"./@types/auth.ts\";\n\nconst EMAIL_STAGE_TYPE = \"m.login.email.identity\";\nconst MSISDN_STAGE_TYPE = \"m.login.msisdn\";\n\nexport interface UIAFlow {\n stages: Array<AuthType | string>;\n}\n\nexport interface IInputs {\n // An email address. If supplied, a flow using email verification will be chosen.\n emailAddress?: string;\n // An ISO two letter country code. Gives the country that opts.phoneNumber should be resolved relative to.\n phoneCountry?: string;\n // A phone number. If supplied, a flow using phone number validation will be chosen.\n phoneNumber?: string;\n registrationToken?: string;\n}\n\nexport interface IStageStatus {\n emailSid?: string;\n errcode?: string;\n error?: string;\n}\n\n/**\n * Data returned in the body of a 401 response from a UIA endpoint.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#user-interactive-api-in-the-rest-api\n */\nexport interface IAuthData {\n /**\n * This is a session identifier that the client must pass back to the home server,\n * if one is provided, in subsequent attempts to authenticate in the same API call.\n */\n session?: string;\n /**\n * A list of the stages the client has completed successfully\n */\n completed?: string[];\n /**\n * A list of the login flows supported by the server for this API.\n */\n flows?: UIAFlow[];\n /**\n * Contains any information that the client will need to know in order to use a given type of authentication.\n * For each login type presented, that type may be present as a key in this dictionary.\n * For example, the public part of an OAuth client ID could be given here.\n */\n params?: Record<string, Record<string, any>>;\n}\n\nexport enum AuthType {\n Password = \"m.login.password\",\n Recaptcha = \"m.login.recaptcha\",\n Terms = \"m.login.terms\",\n Email = \"m.login.email.identity\",\n Msisdn = \"m.login.msisdn\",\n Sso = \"m.login.sso\",\n SsoUnstable = \"org.matrix.login.sso\",\n Dummy = \"m.login.dummy\",\n RegistrationToken = \"m.login.registration_token\",\n // For backwards compatability with servers that have not yet updated to\n // use the stable \"m.login.registration_token\" type.\n // The authentication flow is the same in both cases.\n UnstableRegistrationToken = \"org.matrix.msc3231.login.registration_token\",\n /**\n * m.oauth stage introduced by MSC4312:\n * https://spec.matrix.org/v1.17/client-server-api/#oauth-authentication\n */\n OAuth = \"m.oauth\",\n}\n\n/**\n * https://spec.matrix.org/v1.7/client-server-api/#password-based\n */\ntype PasswordDict = {\n type: AuthType.Password;\n identifier: UserIdentifier;\n password: string;\n session: string;\n};\n\n/**\n * https://spec.matrix.org/v1.7/client-server-api/#google-recaptcha\n */\ntype RecaptchaDict = {\n type: AuthType.Recaptcha;\n response: string;\n session: string;\n};\n\ninterface ThreepidCreds {\n sid: string;\n client_secret: string;\n id_server: string;\n id_access_token: string;\n}\n\n/**\n * https://spec.matrix.org/v1.7/client-server-api/#email-based-identity--homeserver\n */\ntype EmailIdentityDict = {\n type: AuthType.Email;\n threepid_creds: ThreepidCreds;\n session: string;\n};\n\n/**\n * The parameters which are submitted as the `auth` dict in a UIA request\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#authentication-types\n */\nexport type AuthDict =\n | PasswordDict\n | RecaptchaDict\n | EmailIdentityDict\n | { type: Exclude<string, AuthType>; [key: string]: any }\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n | {};\n\nexport class NoAuthFlowFoundError extends Error {\n public name = \"NoAuthFlowFoundError\";\n\n public constructor(\n m: string,\n // eslint-disable-next-line @typescript-eslint/naming-convention, camelcase\n public readonly required_stages: string[],\n public readonly flows: UIAFlow[],\n ) {\n super(m);\n }\n}\n\n/**\n * The type of an application callback to perform the user-interactive bit of UIA.\n *\n * It is called with a single parameter, `makeRequest`, which is a function which takes the UIA parameters and\n * makes the HTTP request. The `authData` parameter in `makeRequest` can be set to null to omit the `auth` field\n * from the UIA request.\n *\n * The generic parameter `T` is the type of the response of the endpoint, once it is eventually successful.\n */\nexport type UIAuthCallback<T> = (makeRequest: (authData: AuthDict | null) => Promise<T>) => Promise<T>;\n\ninterface IOpts<T> {\n /**\n * A matrix client to use for the auth process\n */\n matrixClient: MatrixClient;\n /**\n * Error response from the last request. If null, a request will be made with no auth before starting.\n */\n authData?: IAuthData;\n /**\n * Inputs provided by the user and used by different stages of the auto process.\n * The inputs provided will affect what flow is chosen.\n */\n inputs?: IInputs;\n /**\n * If resuming an existing interactive auth session, the sessionId of that session.\n */\n sessionId?: string;\n /**\n * If resuming an existing interactive auth session, the client secret for that session\n */\n clientSecret?: string;\n /**\n * If returning from having completed m.login.email.identity auth, the sid for the email verification session.\n */\n emailSid?: string;\n\n /**\n * If specified, will prefer flows which entirely consist of listed stages.\n * These should normally be of type AuthTypes but can be string when supporting custom auth stages.\n *\n * This can be used to avoid needing the fallback mechanism.\n */\n supportedStages?: Array<AuthType | string>;\n\n /**\n * Called with the new auth dict to submit the request.\n * Also passes a second deprecated arg which is a flag set to true if this request is a background request.\n * The busyChanged callback should be used instead of the background flag.\n * Should return a promise which resolves to the successful response or rejects with a MatrixError.\n */\n doRequest(auth: AuthDict | null, background: boolean): Promise<T>;\n /**\n * Called when the status of the UI auth changes,\n * ie. when the state of an auth stage changes of when the auth flow moves to a new stage.\n * The arguments are: the login type (eg m.login.password); and an object which is either an error or an\n * informational object specific to the login type.\n * If the 'errcode' key is defined, the object is an error, and has keys:\n * errcode: string, the textual error code, eg. M_UNKNOWN\n * error: string, human readable string describing the error\n *\n * The login type specific objects are as follows:\n * m.login.email.identity:\n * * emailSid: string, the sid of the active email auth session\n */\n stateUpdated(nextStage: AuthType | string, status: IStageStatus): void;\n\n /**\n * A function that takes the email address (string), clientSecret (string), attempt number (int) and\n * sessionId (string) and calls the relevant requestToken function and returns the promise returned by that\n * function.\n * If the resulting promise rejects, the rejection will propagate through to the attemptAuth promise.\n */\n requestEmailToken(email: string, secret: string, attempt: number, session: string): Promise<{ sid: string }>;\n /**\n * Called whenever the interactive auth logic becomes busy submitting information provided by the user or finishes.\n * After this has been called with true the UI should indicate that a request is in progress\n * until it is called again with false.\n */\n busyChanged?(busy: boolean): void;\n startAuthStage?(nextStage: string): Promise<void>; // LEGACY\n}\n\n/**\n * Abstracts the logic used to drive the interactive auth process.\n *\n * <p>Components implementing an interactive auth flow should instantiate one of\n * these, passing in the necessary callbacks to the constructor. They should\n * then call attemptAuth, which will return a promise which will resolve or\n * reject when the interactive-auth process completes.\n *\n * <p>Meanwhile, calls will be made to the startAuthStage and doRequest\n * callbacks, and information gathered from the user can be submitted with\n * submitAuthDict.\n *\n * @param opts - options object\n * @typeParam T - the return type of the request when it is successful\n */\nexport class InteractiveAuth<T> {\n private readonly matrixClient: MatrixClient;\n private readonly inputs: IInputs;\n private readonly clientSecret: string;\n private readonly requestCallback: IOpts<T>[\"doRequest\"];\n private readonly busyChangedCallback?: IOpts<T>[\"busyChanged\"];\n private readonly stateUpdatedCallback: IOpts<T>[\"stateUpdated\"];\n private readonly requestEmailTokenCallback: IOpts<T>[\"requestEmailToken\"];\n private readonly supportedStages?: Set<string>;\n\n // The current latest data or error received from the server during the user interactive auth flow.\n private data: IAuthData & MatrixError[\"data\"];\n private emailSid?: string;\n private requestingEmailToken = false;\n private attemptAuthDeferred: PromiseWithResolvers<T> | null = null;\n private chosenFlow: UIAFlow | null = null;\n private currentStage: string | null = null;\n\n private emailAttempt = 1;\n\n // if we are currently trying to submit an auth dict (which includes polling)\n // the promise the will resolve/reject when it completes\n private submitPromise: Promise<void> | null = null;\n\n public constructor(opts: IOpts<T>) {\n this.matrixClient = opts.matrixClient;\n this.data = opts.authData || { flows: [] };\n this.requestCallback = opts.doRequest;\n this.busyChangedCallback = opts.busyChanged;\n // startAuthStage included for backwards compat\n this.stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;\n this.requestEmailTokenCallback = opts.requestEmailToken;\n this.inputs = opts.inputs || {};\n\n if (opts.sessionId) this.data.session = opts.sessionId;\n this.clientSecret = opts.clientSecret || this.matrixClient.generateClientSecret();\n this.emailSid = opts.emailSid;\n if (opts.supportedStages !== undefined) this.supportedStages = new Set(opts.supportedStages);\n }\n\n /**\n * begin the authentication process.\n *\n * @returns which resolves to the response on success,\n * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if\n * no suitable authentication flow can be found\n */\n public async attemptAuth(): Promise<T> {\n // This promise will be quite long-lived and will resolve when the\n // request is authenticated and completes successfully.\n this.attemptAuthDeferred = Promise.withResolvers();\n // pluck the promise out now, as doRequest may clear before we return\n const promise = this.attemptAuthDeferred.promise;\n\n // if we have no flows, try a request to acquire the flows\n if (!(this.data as IAuthData)?.flows?.length) {\n this.busyChangedCallback?.(true);\n // use the existing sessionId, if one is present.\n const auth = (this.data as IAuthData).session ? { session: (this.data as IAuthData).session } : null;\n this.doRequest(auth).finally(() => {\n this.busyChangedCallback?.(false);\n });\n } else {\n this.startNextAuthStage();\n }\n\n return promise;\n }\n\n /**\n * Poll to check if the auth session or current stage has been\n * completed out-of-band. If so, the attemptAuth promise will\n * be resolved.\n */\n public async poll(): Promise<void> {\n if (!(this.data as IAuthData).session) return;\n // likewise don't poll if there is no auth session in progress\n if (!this.attemptAuthDeferred) return;\n // if we currently have a request in flight, there's no point making\n // another just to check what the status is\n if (this.submitPromise) return;\n\n let authDict: AuthDict = {};\n if (this.currentStage == EMAIL_STAGE_TYPE) {\n // The email can be validated out-of-band, but we need to provide the\n // creds so the HS can go & check it.\n if (this.emailSid) {\n const creds: Record<string, string> = {\n sid: this.emailSid,\n client_secret: this.clientSecret,\n };\n const isUrl = this.matrixClient.getIdentityServerUrl();\n if (isUrl) {\n creds.id_server = new URL(isUrl).host;\n }\n authDict = {\n type: EMAIL_STAGE_TYPE,\n threepid_creds: creds,\n };\n }\n }\n\n this.submitAuthDict(authDict, true);\n }\n\n /**\n * get the auth session ID\n *\n * @returns session id\n */\n public getSessionId(): string | undefined {\n return (this.data as IAuthData)?.session;\n }\n\n /**\n * get the client secret used for validation sessions\n * with the identity server.\n *\n * @returns client secret\n */\n public getClientSecret(): string {\n return this.clientSecret;\n }\n\n /**\n * get the server params for a given stage\n *\n * @param loginType - login type for the stage\n * @returns any parameters from the server for this stage\n */\n public getStageParams(loginType: string): Record<string, any> | undefined {\n return (this.data as IAuthData)?.params?.[loginType];\n }\n\n public getChosenFlow(): UIAFlow | null {\n return this.chosenFlow;\n }\n\n /**\n * submit a new auth dict and fire off the request. This will either\n * make attemptAuth resolve/reject, or cause the startAuthStage callback\n * to be called for a new stage.\n *\n * @param authData - new auth dict to send to the server. Should\n * include a `type` property denoting the login type, as well as any\n * other params for that stage.\n * @param background - If true, this request failing will not result\n * in the attemptAuth promise being rejected. This can be set to true\n * for requests that just poll to see if auth has been completed elsewhere.\n */\n public async submitAuthDict(authData: AuthDict, background = false): Promise<void> {\n if (!this.attemptAuthDeferred) {\n throw new Error(\"submitAuthDict() called before attemptAuth()\");\n }\n\n if (!background) {\n this.busyChangedCallback?.(true);\n }\n\n // if we're currently trying a request, wait for it to finish\n // as otherwise we can get multiple 200 responses which can mean\n // things like multiple logins for register requests.\n // (but discard any exceptions as we only care when its done,\n // not whether it worked or not)\n while (this.submitPromise) {\n try {\n await this.submitPromise;\n } catch {}\n }\n\n // use the sessionid from the last request, if one is present.\n let auth: AuthDict;\n if ((this.data as IAuthData)?.session) {\n auth = Object.assign(\n {\n session: (this.data as IAuthData).session,\n },\n authData,\n );\n } else {\n auth = authData;\n }\n\n try {\n // NB. the 'background' flag is deprecated by the busyChanged\n // callback and is here for backwards compat\n this.submitPromise = this.doRequest(auth, background);\n await this.submitPromise;\n } finally {\n this.submitPromise = null;\n if (!background) {\n this.busyChangedCallback?.(false);\n }\n }\n }\n\n /**\n * Gets the sid for the email validation session\n * Specific to m.login.email.identity\n *\n * @returns The sid of the email auth session\n */\n public getEmailSid(): string | undefined {\n return this.emailSid;\n }\n\n /**\n * Sets the sid for the email validation session\n * This must be set in order to successfully poll for completion\n * of the email validation.\n * Specific to m.login.email.identity\n *\n * @param sid - The sid for the email validation session\n */\n public setEmailSid(sid: string): void {\n this.emailSid = sid;\n }\n\n /**\n * Requests a new email token and sets the email sid for the validation session\n */\n public requestEmailToken = async (): Promise<void> => {\n if (!this.requestingEmailToken) {\n logger.trace(\"Requesting email token. Attempt: \" + this.emailAttempt);\n // If we've picked a flow with email auth, we send the email\n // now because we want the request to fail as soon as possible\n // if the email address is not valid (ie. already taken or not\n // registered, depending on what the operation is).\n this.requestingEmailToken = true;\n try {\n const requestTokenResult = await this.requestEmailTokenCallback(\n this.inputs.emailAddress!,\n this.clientSecret,\n this.emailAttempt++,\n (this.data as IAuthData).session!,\n );\n this.emailSid = requestTokenResult.sid;\n logger.trace(\"Email token request succeeded\");\n } finally {\n this.requestingEmailToken = false;\n }\n } else {\n logger.warn(\"Could not request email token: Already requesting\");\n }\n };\n\n /**\n * Fire off a request, and either resolve the promise, or call\n * startAuthStage.\n *\n * @internal\n * @param auth - new auth dict, including session id\n * @param background - If true, this request is a background poll, so it\n * failing will not result in the attemptAuth promise being rejected.\n * This can be set to true for requests that just poll to see if auth has\n * been completed elsewhere.\n */\n private async doRequest(auth: AuthDict | null, background = false): Promise<void> {\n try {\n const result = await this.requestCallback(auth, background);\n this.attemptAuthDeferred!.resolve(result);\n this.attemptAuthDeferred = null;\n } catch (error) {\n const matrixError = error instanceof MatrixError ? error : null;\n\n // sometimes UI auth errors don't come with flows\n const errorFlows = matrixError?.data?.flows ?? null;\n const haveFlows = (this.data as IAuthData)?.flows || Boolean(errorFlows);\n if (!matrixError || matrixError.httpStatus !== 401 || !matrixError.data || !haveFlows) {\n // doesn't look like an interactive-auth failure.\n if (!background) {\n this.attemptAuthDeferred?.reject(error);\n } else {\n // We ignore all failures here (even non-UI auth related ones)\n // since we don't want to suddenly fail if the internet connection\n // had a blip whilst we were polling\n logger.log(\"Background poll request failed doing UI auth: ignoring\", error);\n }\n }\n if (matrixError && !matrixError.data) {\n matrixError.data = {};\n }\n // if the error didn't come with flows, completed flows or session ID,\n // copy over the ones we have. Synapse sometimes sends responses without\n // any UI auth data (eg. when polling for email validation, if the email\n // has not yet been validated). This appears to be a Synapse bug, which\n // we workaround here.\n if (matrixError && !matrixError.data.flows && !matrixError.data.completed && !matrixError.data.session) {\n matrixError.data.flows = (this.data as IAuthData).flows;\n matrixError.data.completed = (this.data as IAuthData).completed;\n matrixError.data.session = (this.data as IAuthData).session;\n }\n if (matrixError) {\n this.data = matrixError.data;\n }\n try {\n this.startNextAuthStage();\n } catch (e) {\n this.attemptAuthDeferred!.reject(e);\n this.attemptAuthDeferred = null;\n return;\n }\n\n if (!this.emailSid && this.chosenFlow?.stages.includes(AuthType.Email)) {\n try {\n await this.requestEmailToken();\n // NB. promise is not resolved here - at some point, doRequest\n // will be called again and if the user has jumped through all\n // the hoops correctly, auth will be complete and the request\n // will succeed.\n // Also, we should expose the fact that this request has compledted\n // so clients can know that the email has actually been sent.\n } catch (e) {\n // we failed to request an email token, so fail the request.\n // This could be due to the email already beeing registered\n // (or not being registered, depending on what we're trying\n // to do) or it could be a network failure. Either way, pass\n // the failure up as the user can't complete auth if we can't\n // send the email, for whatever reason.\n this.attemptAuthDeferred!.reject(e);\n this.attemptAuthDeferred = null;\n }\n }\n }\n }\n\n /**\n * Pick the next stage and call the callback\n *\n * @internal\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private startNextAuthStage(): void {\n const nextStage = this.chooseStage();\n if (!nextStage) {\n throw new Error(\"No incomplete flows from the server\");\n }\n this.currentStage = nextStage;\n\n if (nextStage === AuthType.Dummy) {\n this.submitAuthDict({\n type: \"m.login.dummy\",\n });\n return;\n }\n\n if (this.data?.errcode || this.data?.error) {\n this.stateUpdatedCallback(nextStage, {\n errcode: this.data?.errcode || \"\",\n error: this.data?.error || \"\",\n });\n return;\n }\n\n this.stateUpdatedCallback(nextStage, nextStage === EMAIL_STAGE_TYPE ? { emailSid: this.emailSid } : {});\n }\n\n /**\n * Pick the next auth stage\n *\n * @internal\n * @returns login type\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private chooseStage(): AuthType | string | undefined {\n if (this.chosenFlow === null) {\n this.chosenFlow = this.chooseFlow();\n }\n logger.log(\"Active flow => %s\", JSON.stringify(this.chosenFlow));\n const nextStage = this.firstUncompletedStage(this.chosenFlow);\n logger.log(\"Next stage: %s\", nextStage);\n return nextStage;\n }\n\n // Returns a low number for flows we consider best. Counts increase for longer flows and even more so\n // for flows which contain stages not listed in `supportedStages`.\n private scoreFlow(flow: UIAFlow): number {\n let score = flow.stages.length;\n if (this.supportedStages !== undefined) {\n // Add 10 points to the score for each unsupported stage in the flow.\n score += flow.stages.filter((stage) => !this.supportedStages!.has(stage)).length * 10;\n }\n return score;\n }\n\n /**\n * Pick one of the flows from the returned list\n * If a flow using all of the inputs is found, it will\n * be returned, otherwise, null will be returned.\n *\n * Only flows using all given inputs are chosen because it\n * is likely to be surprising if the user provides a\n * credential and it is not used. For example, for registration,\n * this could result in the email not being used which would leave\n * the account with no means to reset a password.\n *\n * @internal\n * @returns flow\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private chooseFlow(): UIAFlow {\n const flows = (this.data as IAuthData)?.flows || [];\n\n // we've been given an email or we've already done an email part\n const haveEmail = Boolean(this.inputs.emailAddress) || Boolean(this.emailSid);\n const haveMsisdn = Boolean(this.inputs.phoneCountry) && Boolean(this.inputs.phoneNumber);\n\n // Flows are not represented in a significant order, so we can choose any we support best\n // Sort flows based on how many unsupported stages they contain ascending\n flows.sort((a, b) => this.scoreFlow(a) - this.scoreFlow(b));\n\n for (const flow of flows) {\n let flowHasEmail = false;\n let flowHasMsisdn = false;\n for (const stage of flow.stages) {\n if (stage === EMAIL_STAGE_TYPE) {\n flowHasEmail = true;\n } else if (stage == MSISDN_STAGE_TYPE) {\n flowHasMsisdn = true;\n }\n }\n\n if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {\n return flow;\n }\n }\n\n const requiredStages: string[] = [];\n if (haveEmail) requiredStages.push(EMAIL_STAGE_TYPE);\n if (haveMsisdn) requiredStages.push(MSISDN_STAGE_TYPE);\n // Throw an error with a fairly generic description, but with more\n // information such that the app can give a better one if so desired.\n throw new NoAuthFlowFoundError(\"No appropriate authentication flow found\", requiredStages, flows);\n }\n\n /**\n * Get the first uncompleted stage in the given flow\n *\n * @internal\n * @returns login type\n */\n private firstUncompletedStage(flow: UIAFlow): AuthType | string | undefined {\n const completed = (this.data as IAuthData)?.completed || [];\n return flow.stages.find((stageType) => !completed.includes(stageType));\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,MAAM,QAAQ,aAAa;AAEpC,SAASC,WAAW,QAAQ,qBAAqB;AAGjD,IAAMC,gBAAgB,GAAG,wBAAwB;AACjD,IAAMC,iBAAiB,GAAG,gBAAgB;;AAsB1C;AACA;AACA;AACA;AACA;;AAuBA,WAAYC,QAAQ,0BAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAUhB;EACA;EACA;EAZQA,QAAQ;EAchB;AACJ;AACA;AACA;EAjBYA,QAAQ;EAAA,OAARA,QAAQ;AAAA;;AAqBpB;AACA;AACA;;AAQA;AACA;AACA;;AAcA;AACA;AACA;;AAOA;AACA;AACA;AACA;AACA;;AASA,OAAO,MAAMC,oBAAoB,SAASC,KAAK,CAAC;EAGrCC,WAAWA,CACdC,CAAS;EACT;EACgBC,eAAyB,EACzBC,KAAgB,EAClC;IACE,KAAK,CAACF,CAAC,CAAC;IAAC,KAHOC,eAAyB,GAAzBA,eAAyB;IAAA,KACzBC,KAAgB,GAAhBA,KAAgB;IAAAC,eAAA,eANtB,sBAAsB;EASpC;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AA4EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,eAAe,CAAI;EAwBrBL,WAAWA,CAACM,IAAc,EAAE;I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interactive-auth.js","names":[],"sources":["../src/interactive-auth.ts"],"sourcesContent":["/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations 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 { logger } from \"./logger.ts\";\nimport { type MatrixClient } from \"./client.ts\";\nimport { MatrixError } from \"./http-api/index.ts\";\nimport { type UserIdentifier } from \"./@types/auth.ts\";\n\nconst EMAIL_STAGE_TYPE = \"m.login.email.identity\";\nconst MSISDN_STAGE_TYPE = \"m.login.msisdn\";\n\nexport interface UIAFlow {\n stages: Array<AuthType | string>;\n}\n\nexport interface IInputs {\n // An email address. If supplied, a flow using email verification will be chosen.\n emailAddress?: string;\n // An ISO two letter country code. Gives the country that opts.phoneNumber should be resolved relative to.\n phoneCountry?: string;\n // A phone number. If supplied, a flow using phone number validation will be chosen.\n phoneNumber?: string;\n registrationToken?: string;\n}\n\nexport interface IStageStatus {\n emailSid?: string;\n errcode?: string;\n error?: string;\n}\n\n/**\n * Data returned in the body of a 401 response from a UIA endpoint.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#user-interactive-api-in-the-rest-api\n */\nexport interface IAuthData {\n /**\n * This is a session identifier that the client must pass back to the home server,\n * if one is provided, in subsequent attempts to authenticate in the same API call.\n */\n session?: string;\n /**\n * A list of the stages the client has completed successfully\n */\n completed?: string[];\n /**\n * A list of the login flows supported by the server for this API.\n */\n flows?: UIAFlow[];\n /**\n * Contains any information that the client will need to know in order to use a given type of authentication.\n * For each login type presented, that type may be present as a key in this dictionary.\n * For example, the public part of an OAuth client ID could be given here.\n */\n params?: Record<string, Record<string, any>>;\n}\n\nexport enum AuthType {\n Password = \"m.login.password\",\n Recaptcha = \"m.login.recaptcha\",\n Terms = \"m.login.terms\",\n Email = \"m.login.email.identity\",\n Msisdn = \"m.login.msisdn\",\n Sso = \"m.login.sso\",\n SsoUnstable = \"org.matrix.login.sso\",\n Dummy = \"m.login.dummy\",\n RegistrationToken = \"m.login.registration_token\",\n // For backwards compatability with servers that have not yet updated to\n // use the stable \"m.login.registration_token\" type.\n // The authentication flow is the same in both cases.\n UnstableRegistrationToken = \"org.matrix.msc3231.login.registration_token\",\n /**\n * m.oauth stage introduced by MSC4312:\n * https://spec.matrix.org/v1.17/client-server-api/#oauth-authentication\n */\n OAuth = \"m.oauth\",\n}\n\n/**\n * https://spec.matrix.org/v1.7/client-server-api/#password-based\n */\ntype PasswordDict = {\n type: AuthType.Password;\n identifier: UserIdentifier;\n password: string;\n session: string;\n};\n\n/**\n * https://spec.matrix.org/v1.7/client-server-api/#google-recaptcha\n */\ntype RecaptchaDict = {\n type: AuthType.Recaptcha;\n response: string;\n session: string;\n};\n\ninterface ThreepidCreds {\n sid: string;\n client_secret: string;\n id_server: string;\n id_access_token: string;\n}\n\n/**\n * https://spec.matrix.org/v1.7/client-server-api/#email-based-identity--homeserver\n */\ntype EmailIdentityDict = {\n type: AuthType.Email;\n threepid_creds: ThreepidCreds;\n session: string;\n};\n\n/**\n * The parameters which are submitted as the `auth` dict in a UIA request\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#authentication-types\n */\nexport type AuthDict =\n | PasswordDict\n | RecaptchaDict\n | EmailIdentityDict\n | { type: Exclude<string, AuthType>; [key: string]: any }\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n | {};\n\nexport class NoAuthFlowFoundError extends Error {\n public name = \"NoAuthFlowFoundError\";\n\n public constructor(\n m: string,\n // eslint-disable-next-line @typescript-eslint/naming-convention, camelcase\n public readonly required_stages: string[],\n public readonly flows: UIAFlow[],\n ) {\n super(m);\n }\n}\n\n/**\n * The type of an application callback to perform the user-interactive bit of UIA.\n *\n * It is called with a single parameter, `makeRequest`, which is a function which takes the UIA parameters and\n * makes the HTTP request. The `authData` parameter in `makeRequest` can be set to null to omit the `auth` field\n * from the UIA request.\n *\n * The generic parameter `T` is the type of the response of the endpoint, once it is eventually successful.\n */\nexport type UIAuthCallback<T> = (makeRequest: (authData: AuthDict | null) => Promise<T>) => Promise<T>;\n\ninterface IOpts<T> {\n /**\n * A matrix client to use for the auth process\n */\n matrixClient: MatrixClient;\n /**\n * Error response from the last request. If null, a request will be made with no auth before starting.\n */\n authData?: IAuthData;\n /**\n * Inputs provided by the user and used by different stages of the auto process.\n * The inputs provided will affect what flow is chosen.\n */\n inputs?: IInputs;\n /**\n * If resuming an existing interactive auth session, the sessionId of that session.\n */\n sessionId?: string;\n /**\n * If resuming an existing interactive auth session, the client secret for that session\n */\n clientSecret?: string;\n /**\n * If returning from having completed m.login.email.identity auth, the sid for the email verification session.\n */\n emailSid?: string;\n\n /**\n * If specified, will prefer flows which entirely consist of listed stages.\n * These should normally be of type AuthTypes but can be string when supporting custom auth stages.\n *\n * This can be used to avoid needing the fallback mechanism.\n */\n supportedStages?: Array<AuthType | string>;\n\n /**\n * Called with the new auth dict to submit the request.\n * Also passes a second deprecated arg which is a flag set to true if this request is a background request.\n * The busyChanged callback should be used instead of the background flag.\n * Should return a promise which resolves to the successful response or rejects with a MatrixError.\n */\n doRequest(this: void, auth: AuthDict | null, background: boolean): Promise<T>;\n /**\n * Called when the status of the UI auth changes,\n * ie. when the state of an auth stage changes of when the auth flow moves to a new stage.\n * The arguments are: the login type (eg m.login.password); and an object which is either an error or an\n * informational object specific to the login type.\n * If the 'errcode' key is defined, the object is an error, and has keys:\n * errcode: string, the textual error code, eg. M_UNKNOWN\n * error: string, human readable string describing the error\n *\n * The login type specific objects are as follows:\n * m.login.email.identity:\n * * emailSid: string, the sid of the active email auth session\n */\n stateUpdated(this: void, nextStage: AuthType | string, status: IStageStatus): void;\n\n /**\n * A function that takes the email address (string), clientSecret (string), attempt number (int) and\n * sessionId (string) and calls the relevant requestToken function and returns the promise returned by that\n * function.\n * If the resulting promise rejects, the rejection will propagate through to the attemptAuth promise.\n */\n requestEmailToken(\n this: void,\n email: string,\n secret: string,\n attempt: number,\n session: string,\n ): Promise<{ sid: string }>;\n /**\n * Called whenever the interactive auth logic becomes busy submitting information provided by the user or finishes.\n * After this has been called with true the UI should indicate that a request is in progress\n * until it is called again with false.\n */\n busyChanged?(this: void, busy: boolean): void;\n startAuthStage?(this: void, nextStage: string): Promise<void>; // LEGACY\n}\n\n/**\n * Abstracts the logic used to drive the interactive auth process.\n *\n * <p>Components implementing an interactive auth flow should instantiate one of\n * these, passing in the necessary callbacks to the constructor. They should\n * then call attemptAuth, which will return a promise which will resolve or\n * reject when the interactive-auth process completes.\n *\n * <p>Meanwhile, calls will be made to the startAuthStage and doRequest\n * callbacks, and information gathered from the user can be submitted with\n * submitAuthDict.\n *\n * @param opts - options object\n * @typeParam T - the return type of the request when it is successful\n */\nexport class InteractiveAuth<T> {\n private readonly matrixClient: MatrixClient;\n private readonly inputs: IInputs;\n private readonly clientSecret: string;\n private readonly requestCallback: IOpts<T>[\"doRequest\"];\n private readonly busyChangedCallback?: IOpts<T>[\"busyChanged\"];\n private readonly stateUpdatedCallback: IOpts<T>[\"stateUpdated\"];\n private readonly requestEmailTokenCallback: IOpts<T>[\"requestEmailToken\"];\n private readonly supportedStages?: Set<string>;\n\n // The current latest data or error received from the server during the user interactive auth flow.\n private data: IAuthData & MatrixError[\"data\"];\n private emailSid?: string;\n private requestingEmailToken = false;\n private attemptAuthDeferred: PromiseWithResolvers<T> | null = null;\n private chosenFlow: UIAFlow | null = null;\n private currentStage: string | null = null;\n\n private emailAttempt = 1;\n\n // if we are currently trying to submit an auth dict (which includes polling)\n // the promise the will resolve/reject when it completes\n private submitPromise: Promise<void> | null = null;\n\n public constructor(opts: IOpts<T>) {\n this.matrixClient = opts.matrixClient;\n this.data = opts.authData || { flows: [] };\n this.requestCallback = opts.doRequest;\n this.busyChangedCallback = opts.busyChanged;\n // startAuthStage included for backwards compat\n this.stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;\n this.requestEmailTokenCallback = opts.requestEmailToken;\n this.inputs = opts.inputs || {};\n\n if (opts.sessionId) this.data.session = opts.sessionId;\n this.clientSecret = opts.clientSecret || this.matrixClient.generateClientSecret();\n this.emailSid = opts.emailSid;\n if (opts.supportedStages !== undefined) this.supportedStages = new Set(opts.supportedStages);\n }\n\n /**\n * begin the authentication process.\n *\n * @returns which resolves to the response on success,\n * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if\n * no suitable authentication flow can be found\n */\n public async attemptAuth(): Promise<T> {\n // This promise will be quite long-lived and will resolve when the\n // request is authenticated and completes successfully.\n this.attemptAuthDeferred = Promise.withResolvers();\n // pluck the promise out now, as doRequest may clear before we return\n const promise = this.attemptAuthDeferred.promise;\n\n // if we have no flows, try a request to acquire the flows\n if (!(this.data as IAuthData)?.flows?.length) {\n this.busyChangedCallback?.(true);\n // use the existing sessionId, if one is present.\n const auth = (this.data as IAuthData).session ? { session: (this.data as IAuthData).session } : null;\n this.doRequest(auth).finally(() => {\n this.busyChangedCallback?.(false);\n });\n } else {\n this.startNextAuthStage();\n }\n\n return promise;\n }\n\n /**\n * Poll to check if the auth session or current stage has been\n * completed out-of-band. If so, the attemptAuth promise will\n * be resolved.\n */\n public async poll(): Promise<void> {\n if (!(this.data as IAuthData).session) return;\n // likewise don't poll if there is no auth session in progress\n if (!this.attemptAuthDeferred) return;\n // if we currently have a request in flight, there's no point making\n // another just to check what the status is\n if (this.submitPromise) return;\n\n let authDict: AuthDict = {};\n if (this.currentStage == EMAIL_STAGE_TYPE) {\n // The email can be validated out-of-band, but we need to provide the\n // creds so the HS can go & check it.\n if (this.emailSid) {\n const creds: Record<string, string> = {\n sid: this.emailSid,\n client_secret: this.clientSecret,\n };\n const isUrl = this.matrixClient.getIdentityServerUrl();\n if (isUrl) {\n creds.id_server = new URL(isUrl).host;\n }\n authDict = {\n type: EMAIL_STAGE_TYPE,\n threepid_creds: creds,\n };\n }\n }\n\n this.submitAuthDict(authDict, true);\n }\n\n /**\n * get the auth session ID\n *\n * @returns session id\n */\n public getSessionId(): string | undefined {\n return (this.data as IAuthData)?.session;\n }\n\n /**\n * get the client secret used for validation sessions\n * with the identity server.\n *\n * @returns client secret\n */\n public getClientSecret(): string {\n return this.clientSecret;\n }\n\n /**\n * get the server params for a given stage\n *\n * @param loginType - login type for the stage\n * @returns any parameters from the server for this stage\n */\n public getStageParams(loginType: string): Record<string, any> | undefined {\n return (this.data as IAuthData)?.params?.[loginType];\n }\n\n public getChosenFlow(): UIAFlow | null {\n return this.chosenFlow;\n }\n\n /**\n * submit a new auth dict and fire off the request. This will either\n * make attemptAuth resolve/reject, or cause the startAuthStage callback\n * to be called for a new stage.\n *\n * @param authData - new auth dict to send to the server. Should\n * include a `type` property denoting the login type, as well as any\n * other params for that stage.\n * @param background - If true, this request failing will not result\n * in the attemptAuth promise being rejected. This can be set to true\n * for requests that just poll to see if auth has been completed elsewhere.\n */\n public async submitAuthDict(authData: AuthDict, background = false): Promise<void> {\n if (!this.attemptAuthDeferred) {\n throw new Error(\"submitAuthDict() called before attemptAuth()\");\n }\n\n if (!background) {\n this.busyChangedCallback?.(true);\n }\n\n // if we're currently trying a request, wait for it to finish\n // as otherwise we can get multiple 200 responses which can mean\n // things like multiple logins for register requests.\n // (but discard any exceptions as we only care when its done,\n // not whether it worked or not)\n while (this.submitPromise) {\n try {\n await this.submitPromise;\n } catch {}\n }\n\n // use the sessionid from the last request, if one is present.\n let auth: AuthDict;\n if ((this.data as IAuthData)?.session) {\n auth = Object.assign(\n {\n session: (this.data as IAuthData).session,\n },\n authData,\n );\n } else {\n auth = authData;\n }\n\n try {\n // NB. the 'background' flag is deprecated by the busyChanged\n // callback and is here for backwards compat\n this.submitPromise = this.doRequest(auth, background);\n await this.submitPromise;\n } finally {\n this.submitPromise = null;\n if (!background) {\n this.busyChangedCallback?.(false);\n }\n }\n }\n\n /**\n * Gets the sid for the email validation session\n * Specific to m.login.email.identity\n *\n * @returns The sid of the email auth session\n */\n public getEmailSid(): string | undefined {\n return this.emailSid;\n }\n\n /**\n * Sets the sid for the email validation session\n * This must be set in order to successfully poll for completion\n * of the email validation.\n * Specific to m.login.email.identity\n *\n * @param sid - The sid for the email validation session\n */\n public setEmailSid(sid: string): void {\n this.emailSid = sid;\n }\n\n /**\n * Requests a new email token and sets the email sid for the validation session\n */\n public requestEmailToken = async (): Promise<void> => {\n if (!this.requestingEmailToken) {\n logger.trace(\"Requesting email token. Attempt: \" + this.emailAttempt);\n // If we've picked a flow with email auth, we send the email\n // now because we want the request to fail as soon as possible\n // if the email address is not valid (ie. already taken or not\n // registered, depending on what the operation is).\n this.requestingEmailToken = true;\n try {\n const requestTokenResult = await this.requestEmailTokenCallback(\n this.inputs.emailAddress!,\n this.clientSecret,\n this.emailAttempt++,\n (this.data as IAuthData).session!,\n );\n this.emailSid = requestTokenResult.sid;\n logger.trace(\"Email token request succeeded\");\n } finally {\n this.requestingEmailToken = false;\n }\n } else {\n logger.warn(\"Could not request email token: Already requesting\");\n }\n };\n\n /**\n * Fire off a request, and either resolve the promise, or call\n * startAuthStage.\n *\n * @internal\n * @param auth - new auth dict, including session id\n * @param background - If true, this request is a background poll, so it\n * failing will not result in the attemptAuth promise being rejected.\n * This can be set to true for requests that just poll to see if auth has\n * been completed elsewhere.\n */\n private async doRequest(auth: AuthDict | null, background = false): Promise<void> {\n try {\n const result = await this.requestCallback(auth, background);\n this.attemptAuthDeferred!.resolve(result);\n this.attemptAuthDeferred = null;\n } catch (error) {\n const matrixError = error instanceof MatrixError ? error : null;\n\n // sometimes UI auth errors don't come with flows\n const errorFlows = matrixError?.data?.flows ?? null;\n const haveFlows = (this.data as IAuthData)?.flows || Boolean(errorFlows);\n if (!matrixError || matrixError.httpStatus !== 401 || !matrixError.data || !haveFlows) {\n // doesn't look like an interactive-auth failure.\n if (!background) {\n this.attemptAuthDeferred?.reject(error);\n } else {\n // We ignore all failures here (even non-UI auth related ones)\n // since we don't want to suddenly fail if the internet connection\n // had a blip whilst we were polling\n logger.log(\"Background poll request failed doing UI auth: ignoring\", error);\n }\n }\n if (matrixError && !matrixError.data) {\n matrixError.data = {};\n }\n // if the error didn't come with flows, completed flows or session ID,\n // copy over the ones we have. Synapse sometimes sends responses without\n // any UI auth data (eg. when polling for email validation, if the email\n // has not yet been validated). This appears to be a Synapse bug, which\n // we workaround here.\n if (matrixError && !matrixError.data.flows && !matrixError.data.completed && !matrixError.data.session) {\n matrixError.data.flows = (this.data as IAuthData).flows;\n matrixError.data.completed = (this.data as IAuthData).completed;\n matrixError.data.session = (this.data as IAuthData).session;\n }\n if (matrixError) {\n this.data = matrixError.data;\n }\n try {\n this.startNextAuthStage();\n } catch (e) {\n this.attemptAuthDeferred!.reject(e);\n this.attemptAuthDeferred = null;\n return;\n }\n\n if (!this.emailSid && this.chosenFlow?.stages.includes(AuthType.Email)) {\n try {\n await this.requestEmailToken();\n // NB. promise is not resolved here - at some point, doRequest\n // will be called again and if the user has jumped through all\n // the hoops correctly, auth will be complete and the request\n // will succeed.\n // Also, we should expose the fact that this request has compledted\n // so clients can know that the email has actually been sent.\n } catch (e) {\n // we failed to request an email token, so fail the request.\n // This could be due to the email already beeing registered\n // (or not being registered, depending on what we're trying\n // to do) or it could be a network failure. Either way, pass\n // the failure up as the user can't complete auth if we can't\n // send the email, for whatever reason.\n this.attemptAuthDeferred!.reject(e);\n this.attemptAuthDeferred = null;\n }\n }\n }\n }\n\n /**\n * Pick the next stage and call the callback\n *\n * @internal\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private startNextAuthStage(): void {\n const nextStage = this.chooseStage();\n if (!nextStage) {\n throw new Error(\"No incomplete flows from the server\");\n }\n this.currentStage = nextStage;\n\n if (nextStage === AuthType.Dummy) {\n this.submitAuthDict({\n type: \"m.login.dummy\",\n });\n return;\n }\n\n if (this.data?.errcode || this.data?.error) {\n this.stateUpdatedCallback(nextStage, {\n errcode: this.data?.errcode || \"\",\n error: this.data?.error || \"\",\n });\n return;\n }\n\n this.stateUpdatedCallback(nextStage, nextStage === EMAIL_STAGE_TYPE ? { emailSid: this.emailSid } : {});\n }\n\n /**\n * Pick the next auth stage\n *\n * @internal\n * @returns login type\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private chooseStage(): AuthType | string | undefined {\n if (this.chosenFlow === null) {\n this.chosenFlow = this.chooseFlow();\n }\n logger.log(\"Active flow => %s\", JSON.stringify(this.chosenFlow));\n const nextStage = this.firstUncompletedStage(this.chosenFlow);\n logger.log(\"Next stage: %s\", nextStage);\n return nextStage;\n }\n\n // Returns a low number for flows we consider best. Counts increase for longer flows and even more so\n // for flows which contain stages not listed in `supportedStages`.\n private scoreFlow(flow: UIAFlow): number {\n let score = flow.stages.length;\n if (this.supportedStages !== undefined) {\n // Add 10 points to the score for each unsupported stage in the flow.\n score += flow.stages.filter((stage) => !this.supportedStages!.has(stage)).length * 10;\n }\n return score;\n }\n\n /**\n * Pick one of the flows from the returned list\n * If a flow using all of the inputs is found, it will\n * be returned, otherwise, null will be returned.\n *\n * Only flows using all given inputs are chosen because it\n * is likely to be surprising if the user provides a\n * credential and it is not used. For example, for registration,\n * this could result in the email not being used which would leave\n * the account with no means to reset a password.\n *\n * @internal\n * @returns flow\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private chooseFlow(): UIAFlow {\n const flows = (this.data as IAuthData)?.flows || [];\n\n // we've been given an email or we've already done an email part\n const haveEmail = Boolean(this.inputs.emailAddress) || Boolean(this.emailSid);\n const haveMsisdn = Boolean(this.inputs.phoneCountry) && Boolean(this.inputs.phoneNumber);\n\n // Flows are not represented in a significant order, so we can choose any we support best\n // Sort flows based on how many unsupported stages they contain ascending\n flows.sort((a, b) => this.scoreFlow(a) - this.scoreFlow(b));\n\n for (const flow of flows) {\n let flowHasEmail = false;\n let flowHasMsisdn = false;\n for (const stage of flow.stages) {\n if (stage === EMAIL_STAGE_TYPE) {\n flowHasEmail = true;\n } else if (stage == MSISDN_STAGE_TYPE) {\n flowHasMsisdn = true;\n }\n }\n\n if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {\n return flow;\n }\n }\n\n const requiredStages: string[] = [];\n if (haveEmail) requiredStages.push(EMAIL_STAGE_TYPE);\n if (haveMsisdn) requiredStages.push(MSISDN_STAGE_TYPE);\n // Throw an error with a fairly generic description, but with more\n // information such that the app can give a better one if so desired.\n throw new NoAuthFlowFoundError(\"No appropriate authentication flow found\", requiredStages, flows);\n }\n\n /**\n * Get the first uncompleted stage in the given flow\n *\n * @internal\n * @returns login type\n */\n private firstUncompletedStage(flow: UIAFlow): AuthType | string | undefined {\n const completed = (this.data as IAuthData)?.completed || [];\n return flow.stages.find((stageType) => !completed.includes(stageType));\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,MAAM,QAAQ,aAAa;AAEpC,SAAS,WAAW,QAAQ,qBAAqB;AAGjD,MAAM,gBAAgB,GAAG,wBAAwB;AACjD,MAAM,iBAAiB,GAAG,gBAAgB;;AAsB1C;AACA;AACA;AACA;AACA;;AAuBA,WAAY,QAAQ,0BAAR,QAAQ;EAAR,QAAQ;EAAR,QAAQ;EAAR,QAAQ;EAAR,QAAQ;EAAR,QAAQ;EAAR,QAAQ;EAAR,QAAQ;EAAR,QAAQ;EAAR,QAAQ;EAUhB;EACA;EACA;EAZQ,QAAQ;EAchB;AACJ;AACA;AACA;EAjBY,QAAQ;EAAA,OAAR,QAAQ;AAAA;;AAqBpB;AACA;AACA;;AAQA;AACA;AACA;;AAcA;AACA;AACA;;AAOA;AACA;AACA;AACA;AACA;;AASA,OAAO,MAAM,oBAAoB,SAAS,KAAK,CAAC;EAGrC,WAAW,CACd,CAAS;EACT;EAC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,CAAC,IAAI,CAAE,SAAS,IAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;EAC1E;AACJ","ignoreList":[]}
package/lib/logger.js CHANGED
@@ -30,7 +30,7 @@ import loglevel from "loglevel";
30
30
  // An idea would be to control this via an environment variable (on Node.js).
31
31
  // See https://www.npmjs.com/package/debug to see how this could be implemented
32
32
  // Part of #332 is introducing a logging library in the first place.
33
- var DEFAULT_NAMESPACE = "matrix";
33
+ const DEFAULT_NAMESPACE = "matrix";
34
34
 
35
35
  // because rageshakes in react-sdk hijack the console log, also at module load time,
36
36
  // initializing the logger here races with the initialization of rageshakes.
@@ -38,16 +38,13 @@ var DEFAULT_NAMESPACE = "matrix";
38
38
  // console methods at initialization time by a factory that looks up the console methods
39
39
  // when logging so we always get the current value of console methods.
40
40
  loglevel.methodFactory = function (methodName, logLevel, loggerName) {
41
- return function () {
42
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
43
- args[_key] = arguments[_key];
44
- }
41
+ return function (...args) {
45
42
  /* eslint-disable @typescript-eslint/no-invalid-this */
46
43
  if (this.prefix) {
47
44
  args.unshift(this.prefix);
48
45
  }
49
46
  /* eslint-enable @typescript-eslint/no-invalid-this */
50
- var supportedByConsole = methodName === "error" || methodName === "warn" || methodName === "trace" || methodName === "info" || methodName === "debug";
47
+ const supportedByConsole = methodName === "error" || methodName === "warn" || methodName === "trace" || methodName === "info" || methodName === "debug";
51
48
  /* eslint-disable no-console */
52
49
  if (supportedByConsole) {
53
50
  return console[methodName](...args);
@@ -70,14 +67,14 @@ loglevel.methodFactory = function (methodName, logLevel, loggerName) {
70
67
  * @param prefix Prefix to add to each logged line. If undefined, no prefix will be added.
71
68
  */
72
69
  function getPrefixedLogger(prefix) {
73
- var loggerName = DEFAULT_NAMESPACE + (prefix === undefined ? "" : "-".concat(prefix));
74
- var prefixLogger = loglevel.getLogger(loggerName);
70
+ const loggerName = DEFAULT_NAMESPACE + (prefix === undefined ? "" : `-${prefix}`);
71
+ const prefixLogger = loglevel.getLogger(loggerName);
75
72
  if (prefixLogger.getChild === undefined) {
76
73
  // This is a new loglevel Logger which has not been turned into a PrefixedLogger yet.
77
74
  prefixLogger.prefix = prefix;
78
75
  prefixLogger.getChild = childPrefix => {
79
76
  // create the new child logger
80
- var childLogger = getPrefixedLogger((prefix !== null && prefix !== void 0 ? prefix : "") + childPrefix);
77
+ const childLogger = getPrefixedLogger((prefix ?? "") + childPrefix);
81
78
  // Assign the methodFactory from the parent logger.
82
79
  // This is useful if we add extensions to the parent logger that modifies
83
80
  // its methodFactory. (An example extension is: storing each log to a rageshake db)
@@ -98,7 +95,7 @@ function getPrefixedLogger(prefix) {
98
95
  * @deprecated avoid the use of this unless you are the constructor of `MatrixClient`: you should be using the logger
99
96
  * associated with `MatrixClient`.
100
97
  */
101
- export var logger = getPrefixedLogger();
98
+ export const logger = getPrefixedLogger();
102
99
 
103
100
  /**
104
101
  * A "span" for grouping related log lines together.
@@ -112,38 +109,23 @@ export var logger = getPrefixedLogger();
112
109
  */
113
110
  export class LogSpan {
114
111
  constructor(parent, name) {
115
- this.parent = parent;
116
112
  _defineProperty(this, "name", void 0);
113
+ this.parent = parent;
117
114
  this.name = name + ":";
118
115
  }
119
- trace() {
120
- for (var _len2 = arguments.length, msg = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
121
- msg[_key2] = arguments[_key2];
122
- }
116
+ trace(...msg) {
123
117
  this.parent.trace(this.name, ...msg);
124
118
  }
125
- debug() {
126
- for (var _len3 = arguments.length, msg = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
127
- msg[_key3] = arguments[_key3];
128
- }
119
+ debug(...msg) {
129
120
  this.parent.debug(this.name, ...msg);
130
121
  }
131
- info() {
132
- for (var _len4 = arguments.length, msg = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
133
- msg[_key4] = arguments[_key4];
134
- }
122
+ info(...msg) {
135
123
  this.parent.info(this.name, ...msg);
136
124
  }
137
- warn() {
138
- for (var _len5 = arguments.length, msg = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
139
- msg[_key5] = arguments[_key5];
140
- }
125
+ warn(...msg) {
141
126
  this.parent.warn(this.name, ...msg);
142
127
  }
143
- error() {
144
- for (var _len6 = arguments.length, msg = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
145
- msg[_key6] = arguments[_key6];
146
- }
128
+ error(...msg) {
147
129
  this.parent.error(this.name, ...msg);
148
130
  }
149
131
  }
@@ -173,51 +155,33 @@ export class DebugLogger {
173
155
  constructor(debugInstance) {
174
156
  this.debugInstance = debugInstance;
175
157
  }
176
- trace() {
177
- for (var _len7 = arguments.length, msg = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
178
- msg[_key7] = arguments[_key7];
179
- }
158
+ trace(...msg) {
180
159
  this.debugWithPrefix("[TRACE]", ...msg);
181
160
  }
182
- debug() {
183
- for (var _len8 = arguments.length, msg = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
184
- msg[_key8] = arguments[_key8];
185
- }
161
+ debug(...msg) {
186
162
  this.debugWithPrefix("[DEBUG]", ...msg);
187
163
  }
188
- info() {
189
- for (var _len9 = arguments.length, msg = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
190
- msg[_key9] = arguments[_key9];
191
- }
164
+ info(...msg) {
192
165
  this.debugWithPrefix("[INFO]", ...msg);
193
166
  }
194
- warn() {
195
- for (var _len0 = arguments.length, msg = new Array(_len0), _key0 = 0; _key0 < _len0; _key0++) {
196
- msg[_key0] = arguments[_key0];
197
- }
167
+ warn(...msg) {
198
168
  this.debugWithPrefix("[WARN]", ...msg);
199
169
  }
200
- error() {
201
- for (var _len1 = arguments.length, msg = new Array(_len1), _key1 = 0; _key1 < _len1; _key1++) {
202
- msg[_key1] = arguments[_key1];
203
- }
170
+ error(...msg) {
204
171
  this.debugWithPrefix("[ERROR]", ...msg);
205
172
  }
206
173
  getChild(namespace) {
207
174
  return new DebugLogger(this.debugInstance.extend(namespace));
208
175
  }
209
- debugWithPrefix(prefix) {
210
- var formatter;
176
+ debugWithPrefix(prefix, ...msg) {
177
+ let formatter;
211
178
 
212
179
  // Convert the first argument to a string, so that we can safely add a prefix. This is much the same logic that
213
180
  // `debug()` uses.
214
- for (var _len10 = arguments.length, msg = new Array(_len10 > 1 ? _len10 - 1 : 0), _key10 = 1; _key10 < _len10; _key10++) {
215
- msg[_key10 - 1] = arguments[_key10];
216
- }
217
181
  if (msg.length === 0) {
218
182
  formatter = "";
219
183
  } else if (msg[0] instanceof Error) {
220
- var err = msg.shift();
184
+ const err = msg.shift();
221
185
  formatter = err.stack || err.message;
222
186
  } else if (typeof msg[0] == "string") {
223
187
  formatter = msg.shift();
package/lib/logger.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"logger.js","names":["loglevel","DEFAULT_NAMESPACE","methodFactory","methodName","logLevel","loggerName","_len","arguments","length","args","Array","_key","prefix","unshift","supportedByConsole","console","log","getPrefixedLogger","undefined","concat","prefixLogger","getLogger","getChild","childPrefix","childLogger","rebuild","setLevel","levels","DEBUG","logger","LogSpan","constructor","parent","name","_defineProperty","trace","_len2","msg","_key2","debug","_len3","_key3","info","_len4","_key4","warn","_len5","_key5","error","_len6","_key6","DebugLogger","debugInstance","_len7","_key7","debugWithPrefix","_len8","_key8","_len9","_key9","_len0","_key0","_len1","_key1","namespace","extend","formatter","_len10","_key10","Error","err","shift","stack","message"],"sources":["../src/logger.ts"],"sourcesContent":["/*\nCopyright 2018 André Jaenisch\nCopyright 2019-2025 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 loglevel from \"loglevel\";\n\n/** Backwards-compatibility hack to expose `log` to applications that might still be relying on it. */\ninterface LoggerWithLogMethod extends Logger {\n /**\n * Output debug message to the logger.\n *\n * @param msg - Data to log.\n *\n * @deprecated prefer {@link Logger.debug}.\n */\n log(...msg: any[]): void;\n}\n\n/** Logger interface used within the js-sdk codebase */\nexport interface Logger extends BaseLogger {\n /**\n * Create a child logger.\n *\n * This child will use the `methodFactory` of the parent, so any log extensions applied to the parent\n * at the time of calling `getChild` will be applied to the child as well.\n * It will NOT apply changes to the parent's `methodFactory` after the child was created.\n * Those changes need to be applied to the child manually.\n *\n * @param namespace - name to add to the current logger to generate the child. Some implementations of `Logger`\n * use this as a prefix; others use a different mechanism.\n */\n getChild(namespace: string): Logger;\n}\n\n/** The basic interface for a logger which doesn't support children */\nexport interface BaseLogger {\n /**\n * Output trace message to the logger, with stack trace.\n *\n * @param msg - Data to log.\n */\n trace(this: void, ...msg: any[]): void;\n\n /**\n * Output debug message to the logger.\n *\n * @param msg - Data to log.\n */\n debug(this: void, ...msg: any[]): void;\n\n /**\n * Output info message to the logger.\n *\n * @param msg - Data to log.\n */\n info(this: void, ...msg: any[]): void;\n\n /**\n * Output warn message to the logger.\n *\n * @param msg - Data to log.\n */\n warn(this: void, ...msg: any[]): void;\n\n /**\n * Output error message to the logger.\n *\n * @param msg - Data to log.\n */\n error(this: void, ...msg: any[]): void;\n}\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nconst DEFAULT_NAMESPACE = \"matrix\";\n\n// because rageshakes in react-sdk hijack the console log, also at module load time,\n// initializing the logger here races with the initialization of rageshakes.\n// to avoid the issue, we override the methodFactory of loglevel that binds to the\n// console methods at initialization time by a factory that looks up the console methods\n// when logging so we always get the current value of console methods.\nloglevel.methodFactory = function (methodName, logLevel, loggerName) {\n return function (this: PrefixedLogger, ...args): void {\n /* eslint-disable @typescript-eslint/no-invalid-this */\n if (this.prefix) {\n args.unshift(this.prefix);\n }\n /* eslint-enable @typescript-eslint/no-invalid-this */\n const supportedByConsole =\n methodName === \"error\" ||\n methodName === \"warn\" ||\n methodName === \"trace\" ||\n methodName === \"info\" ||\n methodName === \"debug\";\n /* eslint-disable no-console */\n if (supportedByConsole) {\n return console[methodName](...args);\n } else {\n return console.log(...args);\n }\n /* eslint-enable no-console */\n };\n};\n\n/**\n * Implementation of {@link Logger} based on `loglevel`.\n */\ninterface PrefixedLogger extends loglevel.Logger, LoggerWithLogMethod {\n prefix?: string;\n}\n\n/**\n * Internal utility function: gets a {@link Logger} based on `loglevel`.\n *\n * Child loggers produced by {@link Logger.getChild} add the name of the child logger as a prefix on each log line.\n *\n * @param prefix Prefix to add to each logged line. If undefined, no prefix will be added.\n */\nfunction getPrefixedLogger(prefix?: string): PrefixedLogger {\n const loggerName = DEFAULT_NAMESPACE + (prefix === undefined ? \"\" : `-${prefix}`);\n const prefixLogger = loglevel.getLogger(loggerName) as PrefixedLogger;\n\n if (prefixLogger.getChild === undefined) {\n // This is a new loglevel Logger which has not been turned into a PrefixedLogger yet.\n prefixLogger.prefix = prefix;\n prefixLogger.getChild = (childPrefix): Logger => {\n // create the new child logger\n const childLogger = getPrefixedLogger((prefix ?? \"\") + childPrefix);\n // Assign the methodFactory from the parent logger.\n // This is useful if we add extensions to the parent logger that modifies\n // its methodFactory. (An example extension is: storing each log to a rageshake db)\n childLogger.methodFactory = prefixLogger.methodFactory;\n // Rebuild the child logger with the new methodFactory.\n childLogger.rebuild();\n return childLogger;\n };\n prefixLogger.setLevel(loglevel.levels.DEBUG, false);\n }\n\n return prefixLogger;\n}\n\n/**\n * Drop-in replacement for `console` using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n *\n * @deprecated avoid the use of this unless you are the constructor of `MatrixClient`: you should be using the logger\n * associated with `MatrixClient`.\n */\nexport const logger = getPrefixedLogger() as LoggerWithLogMethod;\n\n/**\n * A \"span\" for grouping related log lines together.\n *\n * The current implementation just adds the name at the start of each log line.\n *\n * This offers a lighter-weight alternative to 'child' loggers returned by {@link Logger#getChild}. In particular,\n * it's not possible to apply individual filters to the LogSpan such as setting the verbosity level. On the other hand,\n * no reference to the LogSpan is retained in the logging framework, so it is safe to make lots of them over the course\n * of an application's life and just drop references to them when the job is done.\n */\nexport class LogSpan implements BaseLogger {\n private readonly name;\n\n public constructor(\n private readonly parent: BaseLogger,\n name: string,\n ) {\n this.name = name + \":\";\n }\n\n public trace(...msg: any[]): void {\n this.parent.trace(this.name, ...msg);\n }\n\n public debug(...msg: any[]): void {\n this.parent.debug(this.name, ...msg);\n }\n\n public info(...msg: any[]): void {\n this.parent.info(this.name, ...msg);\n }\n\n public warn(...msg: any[]): void {\n this.parent.warn(this.name, ...msg);\n }\n\n public error(...msg: any[]): void {\n this.parent.error(this.name, ...msg);\n }\n}\n\n/**\n * A simplification of the `Debugger` type exposed by the `debug` library. We reimplement the bits we need here\n * to avoid a dependency on `debug`.\n */\ninterface Debugger {\n (formatter: any, ...args: any[]): void;\n extend: (namespace: string, delimiter?: string) => Debugger;\n}\n\n/**\n * A `Logger` instance, suitable for use in {@link ICreateClientOpts.logger}, which will write to the `debug` library.\n *\n * @example\n * ```js\n * import debug from \"debug\";\n *\n * const client = createClient({\n * baseUrl: homeserverUrl,\n * userId: userId,\n * accessToken: \"akjgkrgjs\",\n * deviceId: \"xzcvb\",\n * logger: new DebugLogger(debug(`matrix-js-sdk:${userId}`)),\n * });\n * ```\n */\nexport class DebugLogger implements Logger {\n public constructor(private debugInstance: Debugger) {}\n\n public trace(...msg: any[]): void {\n this.debugWithPrefix(\"[TRACE]\", ...msg);\n }\n\n public debug(...msg: any[]): void {\n this.debugWithPrefix(\"[DEBUG]\", ...msg);\n }\n\n public info(...msg: any[]): void {\n this.debugWithPrefix(\"[INFO]\", ...msg);\n }\n\n public warn(...msg: any[]): void {\n this.debugWithPrefix(\"[WARN]\", ...msg);\n }\n\n public error(...msg: any[]): void {\n this.debugWithPrefix(\"[ERROR]\", ...msg);\n }\n\n public getChild(namespace: string): DebugLogger {\n return new DebugLogger(this.debugInstance.extend(namespace));\n }\n\n private debugWithPrefix(prefix: string, ...msg: any[]): void {\n let formatter: string;\n\n // Convert the first argument to a string, so that we can safely add a prefix. This is much the same logic that\n // `debug()` uses.\n if (msg.length === 0) {\n formatter = \"\";\n } else if (msg[0] instanceof Error) {\n const err = msg.shift();\n formatter = err.stack || err.message;\n } else if (typeof msg[0] == \"string\") {\n formatter = msg.shift();\n } else {\n formatter = \"%O\";\n }\n this.debugInstance(prefix + \" \" + formatter, ...msg);\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAOA,QAAQ,MAAM,UAAU;;AAE/B;;AAYA;;AAgBA;;AAsCA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,iBAAiB,GAAG,QAAQ;;AAElC;AACA;AACA;AACA;AACA;AACAD,QAAQ,CAACE,aAAa,GAAG,UAAUC,UAAU,EAAEC,QAAQ,EAAEC,UAAU,EAAE;EACjE,OAAO,YAA+C;IAAA,SAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,EAAZC,IAAI,OAAAC,KAAA,CAAAJ,IAAA,GAAAK,IAAA,MAAAA,IAAA,GAAAL,IAAA,EAAAK,IAAA;MAAJF,IAAI,CAAAE,IAAA,IAAAJ,SAAA,CAAAI,IAAA;IAAA;IAC1C;IACA,IAAI,IAAI,CAACC,MAAM,EAAE;MACbH,IAAI,CAACI,OAAO,CAAC,IAAI,CAACD,MAAM,CAAC;IAC7B;IACA;IACA,IAAME,kBAAkB,GACpBX,UAAU,KAAK,OAAO,IACtBA,UAAU,KAAK,MAAM,IACrBA,UAAU,KAAK,OAAO,IACtBA,UAAU,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ErB;IACA;IAAA,SAAAC,MAAA,GAAA5D,SAAA,CAAAC,MAAA,EAJuC6B,GAAG,OAAA3B,KAAA,CAAAyD,MAAA,OAAAA,MAAA,WAAAC,MAAA,MAAAA,MAAA,GAAAD,MAAA,EAAAC,MAAA;MAAH/B,GAAG,CAAA+B,MAAA,QAAA7D,SAAA,CAAA6D,MAAA;IAAA;IAK1C,IAAI/B,GAAG,CAAC7B,MAAM,KAAK,CAAC,EAAE;MAClB0D,SAAS,GAAG,EAAE;IAClB,CAAC,MAAM,IAAI7B,GAAG,CAAC,CAAC,CAAC,YAAYgC,KAAK,EAAE;MAChC,IAAMC,GAAG,GAAGjC,GAAG,CAACkC,KAAK,CAAC,CAAC;MACvBL,SAAS,GAAGI,GAAG,CAACE,KAAK,IAAIF,GAAG,CAACG,OAAO;IACxC,CAAC,MAAM,IAAI,OAAOpC,GAAG,CAAC,CAAC,CAAC,IAAI,QAAQ,EAAE;MAClC6B,SAAS,GAAG7B,GAAG,CAACkC,KAAK,CAAC,CAAC;IAC3B,CAAC,MAAM;MACHL,SAAS,GAAG,IAAI;IACpB;IACA,IAAI,CAACd,aAAa,CAACxC,MAAM,GAAG,GAAG,GAAGsD,SAAS,EAAE,GAAG7B,GAAG,CAAC;EACxD;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"logger.js","names":[],"sources":["../src/logger.ts"],"sourcesContent":["/*\nCopyright 2018 André Jaenisch\nCopyright 2019-2025 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 loglevel from \"loglevel\";\n\n/** Backwards-compatibility hack to expose `log` to applications that might still be relying on it. */\ninterface LoggerWithLogMethod extends Logger {\n /**\n * Output debug message to the logger.\n *\n * @param msg - Data to log.\n *\n * @deprecated prefer {@link Logger.debug}.\n */\n log(...msg: any[]): void;\n}\n\n/** Logger interface used within the js-sdk codebase */\nexport interface Logger extends BaseLogger {\n /**\n * Create a child logger.\n *\n * This child will use the `methodFactory` of the parent, so any log extensions applied to the parent\n * at the time of calling `getChild` will be applied to the child as well.\n * It will NOT apply changes to the parent's `methodFactory` after the child was created.\n * Those changes need to be applied to the child manually.\n *\n * @param namespace - name to add to the current logger to generate the child. Some implementations of `Logger`\n * use this as a prefix; others use a different mechanism.\n */\n getChild(namespace: string): Logger;\n}\n\n/** The basic interface for a logger which doesn't support children */\nexport interface BaseLogger {\n /**\n * Output trace message to the logger, with stack trace.\n *\n * @param msg - Data to log.\n */\n trace(this: void, ...msg: any[]): void;\n\n /**\n * Output debug message to the logger.\n *\n * @param msg - Data to log.\n */\n debug(this: void, ...msg: any[]): void;\n\n /**\n * Output info message to the logger.\n *\n * @param msg - Data to log.\n */\n info(this: void, ...msg: any[]): void;\n\n /**\n * Output warn message to the logger.\n *\n * @param msg - Data to log.\n */\n warn(this: void, ...msg: any[]): void;\n\n /**\n * Output error message to the logger.\n *\n * @param msg - Data to log.\n */\n error(this: void, ...msg: any[]): void;\n}\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nconst DEFAULT_NAMESPACE = \"matrix\";\n\n// because rageshakes in react-sdk hijack the console log, also at module load time,\n// initializing the logger here races with the initialization of rageshakes.\n// to avoid the issue, we override the methodFactory of loglevel that binds to the\n// console methods at initialization time by a factory that looks up the console methods\n// when logging so we always get the current value of console methods.\nloglevel.methodFactory = function (methodName, logLevel, loggerName) {\n return function (this: PrefixedLogger, ...args): void {\n /* eslint-disable @typescript-eslint/no-invalid-this */\n if (this.prefix) {\n args.unshift(this.prefix);\n }\n /* eslint-enable @typescript-eslint/no-invalid-this */\n const supportedByConsole =\n methodName === \"error\" ||\n methodName === \"warn\" ||\n methodName === \"trace\" ||\n methodName === \"info\" ||\n methodName === \"debug\";\n /* eslint-disable no-console */\n if (supportedByConsole) {\n return console[methodName](...args);\n } else {\n return console.log(...args);\n }\n /* eslint-enable no-console */\n };\n};\n\n/**\n * Implementation of {@link Logger} based on `loglevel`.\n */\ninterface PrefixedLogger extends loglevel.Logger, LoggerWithLogMethod {\n prefix?: string;\n}\n\n/**\n * Internal utility function: gets a {@link Logger} based on `loglevel`.\n *\n * Child loggers produced by {@link Logger.getChild} add the name of the child logger as a prefix on each log line.\n *\n * @param prefix Prefix to add to each logged line. If undefined, no prefix will be added.\n */\nfunction getPrefixedLogger(prefix?: string): PrefixedLogger {\n const loggerName = DEFAULT_NAMESPACE + (prefix === undefined ? \"\" : `-${prefix}`);\n const prefixLogger = loglevel.getLogger(loggerName) as PrefixedLogger;\n\n if (prefixLogger.getChild === undefined) {\n // This is a new loglevel Logger which has not been turned into a PrefixedLogger yet.\n prefixLogger.prefix = prefix;\n prefixLogger.getChild = (childPrefix): Logger => {\n // create the new child logger\n const childLogger = getPrefixedLogger((prefix ?? \"\") + childPrefix);\n // Assign the methodFactory from the parent logger.\n // This is useful if we add extensions to the parent logger that modifies\n // its methodFactory. (An example extension is: storing each log to a rageshake db)\n childLogger.methodFactory = prefixLogger.methodFactory;\n // Rebuild the child logger with the new methodFactory.\n childLogger.rebuild();\n return childLogger;\n };\n prefixLogger.setLevel(loglevel.levels.DEBUG, false);\n }\n\n return prefixLogger;\n}\n\n/**\n * Drop-in replacement for `console` using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n *\n * @deprecated avoid the use of this unless you are the constructor of `MatrixClient`: you should be using the logger\n * associated with `MatrixClient`.\n */\nexport const logger = getPrefixedLogger() as LoggerWithLogMethod;\n\n/**\n * A \"span\" for grouping related log lines together.\n *\n * The current implementation just adds the name at the start of each log line.\n *\n * This offers a lighter-weight alternative to 'child' loggers returned by {@link Logger#getChild}. In particular,\n * it's not possible to apply individual filters to the LogSpan such as setting the verbosity level. On the other hand,\n * no reference to the LogSpan is retained in the logging framework, so it is safe to make lots of them over the course\n * of an application's life and just drop references to them when the job is done.\n */\nexport class LogSpan implements BaseLogger {\n private readonly name;\n\n public constructor(\n private readonly parent: BaseLogger,\n name: string,\n ) {\n this.name = name + \":\";\n }\n\n public trace(...msg: any[]): void {\n this.parent.trace(this.name, ...msg);\n }\n\n public debug(...msg: any[]): void {\n this.parent.debug(this.name, ...msg);\n }\n\n public info(...msg: any[]): void {\n this.parent.info(this.name, ...msg);\n }\n\n public warn(...msg: any[]): void {\n this.parent.warn(this.name, ...msg);\n }\n\n public error(...msg: any[]): void {\n this.parent.error(this.name, ...msg);\n }\n}\n\n/**\n * A simplification of the `Debugger` type exposed by the `debug` library. We reimplement the bits we need here\n * to avoid a dependency on `debug`.\n */\ninterface Debugger {\n (formatter: any, ...args: any[]): void;\n extend: (namespace: string, delimiter?: string) => Debugger;\n}\n\n/**\n * A `Logger` instance, suitable for use in {@link ICreateClientOpts.logger}, which will write to the `debug` library.\n *\n * @example\n * ```js\n * import debug from \"debug\";\n *\n * const client = createClient({\n * baseUrl: homeserverUrl,\n * userId: userId,\n * accessToken: \"akjgkrgjs\",\n * deviceId: \"xzcvb\",\n * logger: new DebugLogger(debug(`matrix-js-sdk:${userId}`)),\n * });\n * ```\n */\nexport class DebugLogger implements Logger {\n public constructor(private debugInstance: Debugger) {}\n\n public trace(...msg: any[]): void {\n this.debugWithPrefix(\"[TRACE]\", ...msg);\n }\n\n public debug(...msg: any[]): void {\n this.debugWithPrefix(\"[DEBUG]\", ...msg);\n }\n\n public info(...msg: any[]): void {\n this.debugWithPrefix(\"[INFO]\", ...msg);\n }\n\n public warn(...msg: any[]): void {\n this.debugWithPrefix(\"[WARN]\", ...msg);\n }\n\n public error(...msg: any[]): void {\n this.debugWithPrefix(\"[ERROR]\", ...msg);\n }\n\n public getChild(namespace: string): DebugLogger {\n return new DebugLogger(this.debugInstance.extend(namespace));\n }\n\n private debugWithPrefix(prefix: string, ...msg: any[]): void {\n let formatter: string;\n\n // Convert the first argument to a string, so that we can safely add a prefix. This is much the same logic that\n // `debug()` uses.\n if (msg.length === 0) {\n formatter = \"\";\n } else if (msg[0] instanceof Error) {\n const err = msg.shift();\n formatter = err.stack || err.message;\n } else if (typeof msg[0] == \"string\") {\n formatter = msg.shift();\n } else {\n formatter = \"%O\";\n }\n this.debugInstance(prefix + \" \" + formatter, ...msg);\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAO,QAAQ,MAAM,UAAU;;AAE/B;;AAYA;;AAgBA;;AAsCA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,iBAAiB,GAAG,QAAQ;;AAElC;AACA;AACA;AACA;AACA;AACA,QAAQ,CAAC,aAAa,GAAG,UAAU,UAAU,EAAE,QAAQ,EAAE,UAAU,EAAE;EACjE,OAAO,UAAgC,GAAG,IAAI,EAAQ;IAClD;IACA,IAAI,IAAI,CAAC,MAAM,EAAE;MACb,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;IAC7B;IACA;IACA,MAAM,kBAAkB,GACpB,UAAU,KAAK,OAAO,IACtB,UAAU,KAAK,MAAM,IACrB,UAAU,KAAK,OAAO,IACtB,UAAU,KAAK,MAAM,IACrB,UAAU,KAAK,OAAO;IAC1B;IACA,IAAI,kBAAkB,EAAE;MACpB,OAAO,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,IAAI,CAAC;IACvC,CAAC,MAAM;MACH,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;IAC/B;IACA;EACJ,CAAC;AACL,CAAC;;AAED;AACA;AACA;;AAKA;AACA;AACA;AAC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AAM,CAAC,SAAS,CAAC,CAAC;EAChE;EAEQ,eAAe,CAAC,MAAc,EAAE,GAAG,GAAU,EAAQ;IACzD,IAAI,SAAiB;;IAErB;IACA;IACA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE;MAClB,SAAS,GAAG,EAAE;IAClB,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,YAAY,KAAK,EAAE;MAChC,MAAM,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC;MACvB,SAAS,GAAG,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,OAAO;IACxC,CAAC,MAAM,IAAI,OAAO,GAAG,CAAC,CAAC,CAAC,IAAI,QAAQ,EAAE;MAClC,SAAS,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC,MAAM;MACH,SAAS,GAAG,IAAI;IACpB;IACA,IAAI,CAAC,aAAa,CAAC,MAAM,GAAG,GAAG,GAAG,SAAS,EAAE,GAAG,GAAG,CAAC;EACxD;AACJ","ignoreList":[]}
package/lib/matrix.js CHANGED
@@ -73,10 +73,8 @@ export * from "./models/event-status.js";
73
73
  export * from "./models/profile-keys.js";
74
74
  export * from "./models/related-relations.js";
75
75
  export { RoomStickyEventsEvent } from "./models/room-sticky-events.js";
76
- import * as _ContentHelpers from "./content-helpers.js";
77
- export { _ContentHelpers as ContentHelpers };
78
- import * as _SecretStorage from "./secret-storage.js";
79
- export { _SecretStorage as SecretStorage };
76
+ export * as ContentHelpers from "./content-helpers.js";
77
+ export * as SecretStorage from "./secret-storage.js";
80
78
  export { createNewMatrixCall, CallEvent } from "./webrtc/call.js";
81
79
  export { GroupCall, GroupCallEvent, GroupCallIntent, GroupCallState, GroupCallType, GroupCallStatsReportEvent } from "./webrtc/groupCall.js";
82
80
  export { SyncState, SetPresence } from "./sync.js";
@@ -90,7 +88,7 @@ export { LocalStorageErrors, localStorageErrorsEventsEmitter } from "./store/loc
90
88
  export { IdentityProviderBrand, SSOAction } from "./@types/auth.js";
91
89
  export { LocationAssetType } from "./@types/location.js";
92
90
  export { DebugLogger } from "./logger.js";
93
- var cryptoStoreFactory = () => new MemoryCryptoStore();
91
+ let cryptoStoreFactory = () => new MemoryCryptoStore();
94
92
 
95
93
  /**
96
94
  * Configure a different factory to be used for creating crypto stores
@@ -101,12 +99,11 @@ export function setCryptoStoreFactory(fac) {
101
99
  cryptoStoreFactory = fac;
102
100
  }
103
101
  function amendClientOpts(opts) {
104
- var _opts$store, _opts$scheduler, _opts$cryptoStore;
105
- opts.store = (_opts$store = opts.store) !== null && _opts$store !== void 0 ? _opts$store : new MemoryStore({
102
+ opts.store = opts.store ?? new MemoryStore({
106
103
  localStorage: globalThis.localStorage
107
104
  });
108
- opts.scheduler = (_opts$scheduler = opts.scheduler) !== null && _opts$scheduler !== void 0 ? _opts$scheduler : new MatrixScheduler();
109
- opts.cryptoStore = (_opts$cryptoStore = opts.cryptoStore) !== null && _opts$cryptoStore !== void 0 ? _opts$cryptoStore : cryptoStoreFactory();
105
+ opts.scheduler = opts.scheduler ?? new MatrixScheduler();
106
+ opts.cryptoStore = opts.cryptoStore ?? cryptoStoreFactory();
110
107
  return opts;
111
108
  }
112
109
 
@@ -138,8 +135,7 @@ export function createClient(opts) {
138
135
  * Set to `false` if the widget uses `waitForIFrameLoad=true` (in this case the client does not expect a content loaded action at all),
139
136
  * or if the the widget wants to send the `ContentLoaded` action at a later point in time after the initial setup.
140
137
  */
141
- export function createRoomWidgetClient(widgetApi, capabilities, roomId, opts) {
142
- var sendContentLoaded = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
138
+ export function createRoomWidgetClient(widgetApi, capabilities, roomId, opts, sendContentLoaded = true) {
143
139
  return new RoomWidgetClient(widgetApi, capabilities, roomId, amendClientOpts(opts), sendContentLoaded);
144
140
  }
145
141
  //# sourceMappingURL=matrix.js.map
package/lib/matrix.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"matrix.js","names":["MemoryCryptoStore","MemoryStore","MatrixScheduler","MatrixClient","RoomWidgetClient","RoomStickyEventsEvent","_ContentHelpers","ContentHelpers","_SecretStorage","SecretStorage","createNewMatrixCall","CallEvent","GroupCall","GroupCallEvent","GroupCallIntent","GroupCallState","GroupCallType","GroupCallStatsReportEvent","SyncState","SetPresence","SlidingSyncEvent","MediaHandlerEvent","CallFeedEvent","StatsReport","Relations","RelationsEvent","TypedEventEmitter","LocalStorageErrors","localStorageErrorsEventsEmitter","IdentityProviderBrand","SSOAction","LocationAssetType","DebugLogger","cryptoStoreFactory","setCryptoStoreFactory","fac","amendClientOpts","opts","_opts$store","_opts$scheduler","_opts$cryptoStore","store","localStorage","globalThis","scheduler","cryptoStore","createClient","createRoomWidgetClient","widgetApi","capabilities","roomId","sendContentLoaded","arguments","length","undefined"],"sources":["../src/matrix.ts"],"sourcesContent":["/*\nCopyright 2015-2022 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 { type WidgetApi } from \"matrix-widget-api\";\n\nimport { MemoryCryptoStore } from \"./crypto/store/memory-crypto-store.ts\";\nimport { MemoryStore } from \"./store/memory.ts\";\nimport { MatrixScheduler } from \"./scheduler.ts\";\nimport { MatrixClient, type ICreateClientOpts } from \"./client.ts\";\nimport { RoomWidgetClient, type ICapabilities } from \"./embedded.ts\";\nimport { type CryptoStore } from \"./crypto/store/base.ts\";\n\nexport * from \"./client.ts\";\nexport * from \"./serverCapabilities.ts\";\nexport * from \"./embedded.ts\";\nexport * from \"./http-api/index.ts\";\nexport * from \"./autodiscovery.ts\";\nexport * from \"./sync-accumulator.ts\";\nexport * from \"./errors.ts\";\nexport * from \"./base64.ts\";\nexport * from \"./models/beacon.ts\";\nexport * from \"./models/event.ts\";\nexport * from \"./models/room.ts\";\nexport * from \"./models/event-timeline.ts\";\nexport * from \"./models/event-timeline-set.ts\";\nexport * from \"./models/poll.ts\";\nexport * from \"./models/room-member.ts\";\nexport * from \"./models/room-state.ts\";\nexport * from \"./models/thread.ts\";\nexport * from \"./models/typed-event-emitter.ts\";\nexport * from \"./models/user.ts\";\nexport * from \"./models/device.ts\";\nexport * from \"./models/search-result.ts\";\nexport * from \"./oidc/index.ts\";\nexport * from \"./scheduler.ts\";\nexport * from \"./filter.ts\";\nexport * from \"./timeline-window.ts\";\nexport * from \"./interactive-auth.ts\";\nexport * from \"./version-support.ts\";\nexport * from \"./service-types.ts\";\nexport * from \"./store/memory.ts\";\nexport * from \"./store/indexeddb.ts\";\nexport * from \"./crypto/store/memory-crypto-store.ts\";\nexport * from \"./crypto/store/localStorage-crypto-store.ts\";\nexport * from \"./crypto/store/indexeddb-crypto-store.ts\";\nexport type { OutgoingRoomKeyRequest } from \"./crypto/store/base.ts\";\nexport * from \"./content-repo.ts\";\nexport type * from \"./@types/common.ts\";\nexport type * from \"./@types/uia.ts\";\nexport * from \"./@types/event.ts\";\nexport * from \"./@types/PushRules.ts\";\nexport * from \"./@types/partials.ts\";\nexport * from \"./@types/requests.ts\";\nexport * from \"./@types/search.ts\";\nexport * from \"./@types/beacon.ts\";\nexport * from \"./@types/topic.ts\";\nexport * from \"./@types/location.ts\";\nexport * from \"./@types/threepids.ts\";\nexport * from \"./@types/auth.ts\";\nexport * from \"./@types/polls.ts\";\nexport * from \"./@types/retention.ts\";\nexport type * from \"./@types/local_notifications.ts\";\nexport type * from \"./@types/registration.ts\";\nexport * from \"./@types/read_receipts.ts\";\nexport type * from \"./@types/crypto.ts\";\nexport * from \"./@types/extensible_events.ts\";\nexport type * from \"./@types/IIdentityServerProvider.ts\";\nexport * from \"./@types/membership.ts\";\nexport * from \"./models/room-summary.ts\";\nexport * from \"./models/event-status.ts\";\nexport * from \"./models/profile-keys.ts\";\nexport * from \"./models/related-relations.ts\";\nexport { type StickyMatrixEvent, RoomStickyEventsEvent } from \"./models/room-sticky-events.ts\";\nexport type { RoomSummary } from \"./client.ts\";\nexport * as ContentHelpers from \"./content-helpers.ts\";\nexport * as SecretStorage from \"./secret-storage.ts\";\nexport { createNewMatrixCall, CallEvent } from \"./webrtc/call.ts\";\nexport type { MatrixCall } from \"./webrtc/call.ts\";\nexport {\n GroupCall,\n GroupCallEvent,\n GroupCallIntent,\n GroupCallState,\n GroupCallType,\n GroupCallStatsReportEvent,\n} from \"./webrtc/groupCall.ts\";\n\nexport { SyncState, SetPresence } from \"./sync.ts\";\nexport type { ISyncStateData as SyncStateData } from \"./sync.ts\";\nexport { SlidingSyncEvent } from \"./sliding-sync.ts\";\nexport { MediaHandlerEvent } from \"./webrtc/mediaHandler.ts\";\nexport { CallFeedEvent } from \"./webrtc/callFeed.ts\";\nexport { StatsReport } from \"./webrtc/stats/statsReport.ts\";\nexport { Relations, RelationsEvent } from \"./models/relations.ts\";\nexport { TypedEventEmitter } from \"./models/typed-event-emitter.ts\";\nexport { LocalStorageErrors, localStorageErrorsEventsEmitter } from \"./store/local-storage-events-emitter.ts\";\nexport { IdentityProviderBrand, SSOAction } from \"./@types/auth.ts\";\nexport type { ISSOFlow as SSOFlow, LoginFlow } from \"./@types/auth.ts\";\nexport type { IHierarchyRelation as HierarchyRelation, IHierarchyRoom as HierarchyRoom } from \"./@types/spaces.ts\";\nexport { LocationAssetType } from \"./@types/location.ts\";\nexport { DebugLogger } from \"./logger.ts\";\n\nlet cryptoStoreFactory = (): CryptoStore => new MemoryCryptoStore();\n\n/**\n * Configure a different factory to be used for creating crypto stores\n *\n * @param fac - a function which will return a new `CryptoStore`\n */\nexport function setCryptoStoreFactory(fac: () => CryptoStore): void {\n cryptoStoreFactory = fac;\n}\n\nfunction amendClientOpts(opts: ICreateClientOpts): ICreateClientOpts {\n opts.store =\n opts.store ??\n new MemoryStore({\n localStorage: globalThis.localStorage,\n });\n opts.scheduler = opts.scheduler ?? new MatrixScheduler();\n opts.cryptoStore = opts.cryptoStore ?? cryptoStoreFactory();\n\n return opts;\n}\n\n/**\n * Construct a Matrix Client. Similar to {@link MatrixClient}\n * except that the 'request', 'store' and 'scheduler' dependencies are satisfied.\n * @param opts - The configuration options for this client. These configuration\n * options will be passed directly to {@link MatrixClient}.\n *\n * @returns A new matrix client.\n * @see {@link MatrixClient} for the full list of options for\n * `opts`.\n */\nexport function createClient(opts: ICreateClientOpts): MatrixClient {\n return new MatrixClient(amendClientOpts(opts));\n}\n\n/**\n * Construct a Matrix Client that works in a widget.\n * This client has a subset of features compared to a full client.\n * It uses the widget-api to communicate with matrix. (widget \\<-\\> client \\<-\\> homeserver)\n * @returns A new matrix client with a subset of features.\n * @param opts - The configuration options for this client. These configuration\n * options will be passed directly to {@link MatrixClient}.\n * @param widgetApi - The widget api to use for communication.\n * @param capabilities - The capabilities the widget client will request.\n * @param roomId - The room id the widget is associated with.\n * @param sendContentLoaded - Whether to send a content loaded widget action immediately after initial setup.\n * Set to `false` if the widget uses `waitForIFrameLoad=true` (in this case the client does not expect a content loaded action at all),\n * or if the the widget wants to send the `ContentLoaded` action at a later point in time after the initial setup.\n */\nexport function createRoomWidgetClient(\n widgetApi: WidgetApi,\n capabilities: ICapabilities,\n roomId: string,\n opts: ICreateClientOpts,\n sendContentLoaded = true,\n): MatrixClient {\n return new RoomWidgetClient(widgetApi, capabilities, roomId, amendClientOpts(opts), sendContentLoaded);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA,SAASA,iBAAiB,QAAQ,uCAAuC;AACzE,SAASC,WAAW,QAAQ,mBAAmB;AAC/C,SAASC,eAAe,QAAQ,gBAAgB;AAChD,SAASC,YAAY,QAAgC,aAAa;AAClE,SAASC,gBAAgB,QAA4B,eAAe;AAGpE,cAAc,aAAa;AAC3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AAA,cAAAA,iBAAA,GAAIP,kBAAkB,CAAC,CAAC;EAE3D,OAAOI,IAAI;AACf;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASS,YAAYA,CAACT,IAAuB,EAAgB;EAChE,OAAO,IAAIlC,YAAY,CAACiC,eAAe,CAACC,IAAI,CAAC,CAAC;AAClD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASU,sBAAsBA,CAClCC,SAAoB,EACpBC,YAA2B,EAC3BC,MAAc,EACdb,IAAuB,EAEX;EAAA,IADZc,iBAAiB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAExB,OAAO,IAAIhD,gBAAgB,CAAC4C,SAAS,EAAEC,YAAY,EAAEC,MAAM,EAAEd,eAAe,CAACC,IAAI,CAAC,EAAEc,iBAAiB,CAAC;AAC1G","ignoreList":[]}
1
+ {"version":3,"file":"matrix.js","names":[],"sources":["../src/matrix.ts"],"sourcesContent":["/*\nCopyright 2015-2022 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 { type WidgetApi } from \"matrix-widget-api\";\n\nimport { MemoryCryptoStore } from \"./crypto/store/memory-crypto-store.ts\";\nimport { MemoryStore } from \"./store/memory.ts\";\nimport { MatrixScheduler } from \"./scheduler.ts\";\nimport { MatrixClient, type ICreateClientOpts } from \"./client.ts\";\nimport { RoomWidgetClient, type ICapabilities } from \"./embedded.ts\";\nimport { type CryptoStore } from \"./crypto/store/base.ts\";\n\nexport * from \"./client.ts\";\nexport * from \"./serverCapabilities.ts\";\nexport * from \"./embedded.ts\";\nexport * from \"./http-api/index.ts\";\nexport * from \"./autodiscovery.ts\";\nexport * from \"./sync-accumulator.ts\";\nexport * from \"./errors.ts\";\nexport * from \"./base64.ts\";\nexport * from \"./models/beacon.ts\";\nexport * from \"./models/event.ts\";\nexport * from \"./models/room.ts\";\nexport * from \"./models/event-timeline.ts\";\nexport * from \"./models/event-timeline-set.ts\";\nexport * from \"./models/poll.ts\";\nexport * from \"./models/room-member.ts\";\nexport * from \"./models/room-state.ts\";\nexport * from \"./models/thread.ts\";\nexport * from \"./models/typed-event-emitter.ts\";\nexport * from \"./models/user.ts\";\nexport * from \"./models/device.ts\";\nexport * from \"./models/search-result.ts\";\nexport * from \"./oidc/index.ts\";\nexport * from \"./scheduler.ts\";\nexport * from \"./filter.ts\";\nexport * from \"./timeline-window.ts\";\nexport * from \"./interactive-auth.ts\";\nexport * from \"./version-support.ts\";\nexport * from \"./service-types.ts\";\nexport * from \"./store/memory.ts\";\nexport * from \"./store/indexeddb.ts\";\nexport * from \"./crypto/store/memory-crypto-store.ts\";\nexport * from \"./crypto/store/localStorage-crypto-store.ts\";\nexport * from \"./crypto/store/indexeddb-crypto-store.ts\";\nexport type { OutgoingRoomKeyRequest } from \"./crypto/store/base.ts\";\nexport * from \"./content-repo.ts\";\nexport type * from \"./@types/common.ts\";\nexport type * from \"./@types/uia.ts\";\nexport * from \"./@types/event.ts\";\nexport * from \"./@types/PushRules.ts\";\nexport * from \"./@types/partials.ts\";\nexport * from \"./@types/requests.ts\";\nexport * from \"./@types/search.ts\";\nexport * from \"./@types/beacon.ts\";\nexport * from \"./@types/topic.ts\";\nexport * from \"./@types/location.ts\";\nexport * from \"./@types/threepids.ts\";\nexport * from \"./@types/auth.ts\";\nexport * from \"./@types/polls.ts\";\nexport * from \"./@types/retention.ts\";\nexport type * from \"./@types/local_notifications.ts\";\nexport type * from \"./@types/registration.ts\";\nexport * from \"./@types/read_receipts.ts\";\nexport type * from \"./@types/crypto.ts\";\nexport * from \"./@types/extensible_events.ts\";\nexport type * from \"./@types/IIdentityServerProvider.ts\";\nexport * from \"./@types/membership.ts\";\nexport * from \"./models/room-summary.ts\";\nexport * from \"./models/event-status.ts\";\nexport * from \"./models/profile-keys.ts\";\nexport * from \"./models/related-relations.ts\";\nexport { type StickyMatrixEvent, RoomStickyEventsEvent } from \"./models/room-sticky-events.ts\";\nexport type { RoomSummary } from \"./client.ts\";\nexport * as ContentHelpers from \"./content-helpers.ts\";\nexport * as SecretStorage from \"./secret-storage.ts\";\nexport { createNewMatrixCall, CallEvent } from \"./webrtc/call.ts\";\nexport type { MatrixCall } from \"./webrtc/call.ts\";\nexport {\n GroupCall,\n GroupCallEvent,\n GroupCallIntent,\n GroupCallState,\n GroupCallType,\n GroupCallStatsReportEvent,\n} from \"./webrtc/groupCall.ts\";\n\nexport { SyncState, SetPresence } from \"./sync.ts\";\nexport type { ISyncStateData as SyncStateData } from \"./sync.ts\";\nexport { SlidingSyncEvent } from \"./sliding-sync.ts\";\nexport { MediaHandlerEvent } from \"./webrtc/mediaHandler.ts\";\nexport { CallFeedEvent } from \"./webrtc/callFeed.ts\";\nexport { StatsReport } from \"./webrtc/stats/statsReport.ts\";\nexport { Relations, RelationsEvent } from \"./models/relations.ts\";\nexport { TypedEventEmitter } from \"./models/typed-event-emitter.ts\";\nexport { LocalStorageErrors, localStorageErrorsEventsEmitter } from \"./store/local-storage-events-emitter.ts\";\nexport { IdentityProviderBrand, SSOAction } from \"./@types/auth.ts\";\nexport type { ISSOFlow as SSOFlow, LoginFlow } from \"./@types/auth.ts\";\nexport type { IHierarchyRelation as HierarchyRelation, IHierarchyRoom as HierarchyRoom } from \"./@types/spaces.ts\";\nexport { LocationAssetType } from \"./@types/location.ts\";\nexport { DebugLogger } from \"./logger.ts\";\n\nlet cryptoStoreFactory = (): CryptoStore => new MemoryCryptoStore();\n\n/**\n * Configure a different factory to be used for creating crypto stores\n *\n * @param fac - a function which will return a new `CryptoStore`\n */\nexport function setCryptoStoreFactory(fac: () => CryptoStore): void {\n cryptoStoreFactory = fac;\n}\n\nfunction amendClientOpts(opts: ICreateClientOpts): ICreateClientOpts {\n opts.store =\n opts.store ??\n new MemoryStore({\n localStorage: globalThis.localStorage,\n });\n opts.scheduler = opts.scheduler ?? new MatrixScheduler();\n opts.cryptoStore = opts.cryptoStore ?? cryptoStoreFactory();\n\n return opts;\n}\n\n/**\n * Construct a Matrix Client. Similar to {@link MatrixClient}\n * except that the 'request', 'store' and 'scheduler' dependencies are satisfied.\n * @param opts - The configuration options for this client. These configuration\n * options will be passed directly to {@link MatrixClient}.\n *\n * @returns A new matrix client.\n * @see {@link MatrixClient} for the full list of options for\n * `opts`.\n */\nexport function createClient(opts: ICreateClientOpts): MatrixClient {\n return new MatrixClient(amendClientOpts(opts));\n}\n\n/**\n * Construct a Matrix Client that works in a widget.\n * This client has a subset of features compared to a full client.\n * It uses the widget-api to communicate with matrix. (widget \\<-\\> client \\<-\\> homeserver)\n * @returns A new matrix client with a subset of features.\n * @param opts - The configuration options for this client. These configuration\n * options will be passed directly to {@link MatrixClient}.\n * @param widgetApi - The widget api to use for communication.\n * @param capabilities - The capabilities the widget client will request.\n * @param roomId - The room id the widget is associated with.\n * @param sendContentLoaded - Whether to send a content loaded widget action immediately after initial setup.\n * Set to `false` if the widget uses `waitForIFrameLoad=true` (in this case the client does not expect a content loaded action at all),\n * or if the the widget wants to send the `ContentLoaded` action at a later point in time after the initial setup.\n */\nexport function createRoomWidgetClient(\n widgetApi: WidgetApi,\n capabilities: ICapabilities,\n roomId: string,\n opts: ICreateClientOpts,\n sendContentLoaded = true,\n): MatrixClient {\n return new RoomWidgetClient(widgetApi, capabilities, roomId, amendClientOpts(opts), sendContentLoaded);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA,SAAS,iBAA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