oysterun 1.6.0-beta.2 → 1.6.0-beta.21

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 (242) hide show
  1. package/bin/oysterun.mjs +64 -17
  2. package/dev/client/connectivity/completed-message-neighbor-click.mjs +78 -0
  3. package/dev/client/connectivity/completed-message-neighbor-contract.mjs +205 -0
  4. package/dev/client/connectivity/completed-message-visibility.d.mts +4 -4
  5. package/dev/client/connectivity/completed-message-visibility.mjs +14 -11
  6. package/dev/client/connectivity/desktop-chat-sidebar-preference.mjs +57 -0
  7. package/dev/client/connectivity/host-connection-feedback.mjs +12 -1
  8. package/dev/client/connectivity/managed-host-browser.mjs +10 -0
  9. package/dev/client/connectivity/session-navigation-intent.mjs +189 -0
  10. package/dev/client/connectivity/session-transition-state.mjs +18 -6
  11. package/dev/client/connectivity/test-completed-message-neighbor-click.mjs +180 -0
  12. package/dev/client/web/index.html +5367 -609
  13. package/dev/client/web-chat/dist/assets/{ReactPrism-BwJhidYf.js → ReactPrism-C6YiTZTC.js} +1 -1
  14. package/dev/client/web-chat/dist/assets/{ReactPrism-BwJhidYf.js.map → ReactPrism-C6YiTZTC.js.map} +1 -1
  15. package/dev/client/web-chat/dist/assets/SessionsSetupApp-CKJOSPFP.js +6442 -0
  16. package/dev/client/web-chat/dist/assets/SessionsSetupApp-CKJOSPFP.js.map +1 -0
  17. package/dev/client/web-chat/dist/assets/SessionsSetupApp-Dx09Uz-6.css +1 -0
  18. package/dev/client/web-chat/dist/assets/index-Ae5I4LHp.js +9 -0
  19. package/dev/client/web-chat/dist/assets/index-Ae5I4LHp.js.map +1 -0
  20. package/dev/client/web-chat/dist/assets/index-CN_FoTB1.js +2 -0
  21. package/dev/client/web-chat/dist/assets/index-CN_FoTB1.js.map +1 -0
  22. package/dev/client/web-chat/dist/assets/{index--1xmQ99x.js → index-DCQFwgGf.js} +2 -2
  23. package/dev/client/web-chat/dist/assets/{index--1xmQ99x.js.map → index-DCQFwgGf.js.map} +1 -1
  24. package/dev/client/web-chat/dist/assets/matrix-entry-BV7G38kH.css +10 -0
  25. package/dev/client/web-chat/dist/assets/matrix-entry-abAy3aOo.js +594 -0
  26. package/dev/client/web-chat/dist/assets/matrix-entry-abAy3aOo.js.map +1 -0
  27. package/dev/client/web-chat/dist/assets/{pdf-ZjtalfgI.js → pdf-DN7oVvM6.js} +5 -5
  28. package/dev/client/web-chat/dist/assets/pdf-DN7oVvM6.js.map +1 -0
  29. package/dev/client/web-chat/dist/assets/session-notice-DlyODy1z.css +1 -0
  30. package/dev/client/web-chat/dist/assets/web-BlYuDlOV.js +1 -0
  31. package/dev/client/web-chat/dist/assets/{web-c70YaskK.js.map → web-BlYuDlOV.js.map} +1 -1
  32. package/dev/client/web-chat/dist/assets/web-Dabw6cJi.js +1 -0
  33. package/dev/client/web-chat/dist/assets/{web-BzHcZK2M.js.map → web-Dabw6cJi.js.map} +1 -1
  34. package/dev/client/web-chat/dist/index.html +1 -2
  35. package/docs/routec/dev/cloud_deplyments.md +5 -0
  36. package/docs/routec/dev/npm_native_dependency_install.md +6 -2
  37. package/docs/routec/dev/npmjs_publish.md +55 -19
  38. package/docs/routec/dev/p262_setup_input_file.md +117 -0
  39. package/docs/routec/host2_turn_started_idempotency_diagnostics.md +8 -7
  40. package/docs/routec/host_setup.md +39 -10
  41. package/docs/routec/oysterun_operation_interface_spec.md +78 -2
  42. package/docs/routec/provider_contract.md +35 -5
  43. package/host-service/README.md +36 -0
  44. package/host-service/adapters/claude-code-adapter.mjs +48 -5
  45. package/host-service/adapters/codex-app-server-adapter.mjs +320 -18
  46. package/host-service/adapters/debug-fixture-provider-adapter.mjs +102 -1
  47. package/host-service/adapters/debug-large-tool-spillover-provider-adapter.mjs +2 -0
  48. package/host-service/adapters/debug-p135-codex-replay-provider-adapter.mjs +2 -0
  49. package/host-service/adapters/debug-routec-structural-replay-provider-adapter.mjs +2 -0
  50. package/host-service/agent-config.mjs +16 -5
  51. package/host-service/agent-folder-availability.mjs +41 -0
  52. package/host-service/apns-complete-message-dispatcher.mjs +1 -0
  53. package/host-service/assets/product-skills/Oysterun/modules/oysterun-find-context/SKILL.md +24 -0
  54. package/host-service/assets/product-skills/Oysterun/modules/oysterun-session-chat/SKILL.md +94 -5
  55. package/host-service/assets/product-skills/Oysterun/modules/oysterun-sessions/SKILL.md +103 -0
  56. package/host-service/assets/product-skills/Oysterun/modules/oysterun-website/SKILL.md +7 -0
  57. package/host-service/assets/product-skills/oysterun-find-context/SKILL.md +24 -0
  58. package/host-service/assets/product-skills/oysterun-session-chat/SKILL.md +94 -5
  59. package/host-service/assets/product-skills/oysterun-sessions/SKILL.md +103 -0
  60. package/host-service/assets/product-skills/oysterun-website/SKILL.md +7 -0
  61. package/host-service/callback-durable-store.mjs +354 -47
  62. package/host-service/callback-foundation.mjs +21 -1
  63. package/host-service/callback-host-integration.mjs +345 -30
  64. package/host-service/claude-acp-model-discovery.mjs +23 -18
  65. package/host-service/cli/assert-installer-reinstall-target.mjs +9 -0
  66. package/host-service/cli/installer-recovery-guidance.mjs +20 -0
  67. package/host-service/cli/prepare-restart-restore.mjs +2 -0
  68. package/host-service/cli/product-cli.mjs +34 -33
  69. package/host-service/cli/reconcile-initial-preflight.mjs +19 -0
  70. package/host-service/cli/recover-installer-lifecycle.mjs +24 -0
  71. package/host-service/cli/run-host-lifecycle.mjs +2 -0
  72. package/host-service/cli/run-staged-lifecycle-recovery.mjs +161 -0
  73. package/host-service/codex-model-discovery.mjs +23 -18
  74. package/host-service/complete-cli-uninstall.mjs +176 -0
  75. package/host-service/complete-message-notification-predicate.mjs +8 -6
  76. package/host-service/complete-message-notification-title.mjs +4 -0
  77. package/host-service/completed-session-unread.mjs +425 -42
  78. package/host-service/completed-turn-navigation.mjs +444 -144
  79. package/host-service/completed-turn-notification-observer.mjs +116 -0
  80. package/host-service/completed-turn-service.mjs +445 -0
  81. package/host-service/config.mjs +115 -9
  82. package/host-service/desired-open-session-state.mjs +331 -0
  83. package/host-service/fixtures/p218-completed-turn-notification.json +11 -0
  84. package/host-service/frp-agent.mjs +9 -9
  85. package/host-service/grok-acp-model-discovery.mjs +31 -33
  86. package/host-service/host-lifecycle-recovery.mjs +37 -0
  87. package/host-service/host-port-resolution.mjs +98 -0
  88. package/host-service/host-runtime-diagnostics.mjs +18 -1
  89. package/host-service/initial-preflight-recovery.mjs +71 -0
  90. package/host-service/installer-recovery-guidance.mjs +85 -0
  91. package/host-service/installer-reinstall-bindings.mjs +49 -0
  92. package/host-service/installer-reinstall-target.mjs +49 -0
  93. package/host-service/legacy-continuity-observation.mjs +33 -0
  94. package/host-service/lifecycle-compat-cli.mjs +13 -0
  95. package/host-service/lifecycle-compat-preload.mjs +89 -0
  96. package/host-service/lifecycle-compatibility.mjs +164 -0
  97. package/host-service/lifecycle-continuity-assets.mjs +222 -0
  98. package/host-service/lifecycle-continuity-probe.mjs +97 -0
  99. package/host-service/lifecycle-continuity-projection.mjs +29 -0
  100. package/host-service/lifecycle-continuity-runner.mjs +192 -0
  101. package/host-service/lifecycle-continuity.mjs +493 -0
  102. package/host-service/lifecycle-service-render-bundle.mjs +120 -0
  103. package/host-service/lifecycle-user-path.mjs +34 -0
  104. package/host-service/link-annotations.mjs +10 -0
  105. package/host-service/matrix-credential-issuer.mjs +32 -1
  106. package/host-service/matrix-event-correlator.mjs +166 -27
  107. package/host-service/matrix-facade.mjs +96 -19
  108. package/host-service/matrix-room-binding.mjs +24 -0
  109. package/host-service/matrix-transcript-read-adapter.mjs +17 -3
  110. package/host-service/model-discovery-guardian.mjs +40 -0
  111. package/host-service/model-discovery-process.mjs +141 -0
  112. package/host-service/onboard-lifecycle-status.mjs +28 -0
  113. package/host-service/onboard.mjs +479 -0
  114. package/host-service/package.json +2 -1
  115. package/host-service/portable-scheduler-definitions.mjs +28 -0
  116. package/host-service/product-runtime-host-origin.mjs +22 -0
  117. package/host-service/provider-model-params.mjs +14 -17
  118. package/host-service/provider-model-refresh-runner.mjs +124 -169
  119. package/host-service/provider-model-refresh-schedule.mjs +11 -0
  120. package/host-service/provider-resume-contract.mjs +9 -3
  121. package/host-service/restart-restore-state.mjs +25 -0
  122. package/host-service/retained-host-state-holder.mjs +57 -0
  123. package/host-service/routec-matrix-sqlite-store.mjs +155 -10
  124. package/host-service/routec-matrix-storage-adapter.mjs +208 -25
  125. package/host-service/routec-matrix-storage-paths.mjs +12 -0
  126. package/host-service/routec-request-delay-window.mjs +55 -0
  127. package/host-service/scheduler-acp-provider-runner.mjs +2 -1
  128. package/host-service/scheduler-direct-provider-runner.mjs +71 -9
  129. package/host-service/scheduler-run-timeout-policy.mjs +85 -0
  130. package/host-service/scheduler-service.mjs +96 -9
  131. package/host-service/scheduler-store.mjs +9 -2
  132. package/host-service/server.mjs +2202 -552
  133. package/host-service/service-definition-migration.mjs +10 -3
  134. package/host-service/session-collection-service.mjs +320 -0
  135. package/host-service/session-history.mjs +99 -15
  136. package/host-service/session-list-preview-service.mjs +87 -12
  137. package/host-service/session-list-projection-service.mjs +182 -0
  138. package/host-service/session-loop-definitions.mjs +702 -75
  139. package/host-service/session-manager.mjs +473 -38
  140. package/host-service/session-switcher-projection.mjs +11 -3
  141. package/host-service/session-tags.mjs +451 -0
  142. package/host-service/session-transcript-target.mjs +103 -0
  143. package/host-service/setup-input-file.mjs +91 -0
  144. package/host-service/setup-provider-model-defaults.mjs +53 -0
  145. package/host-service/setup.mjs +133 -101
  146. package/host-service/stopped-user-host-package.mjs +60 -0
  147. package/host-service/test-fixtures/p236-navigation-original.mjs +500 -0
  148. package/host-service/update-reminder-state.mjs +7 -0
  149. package/host-service/voice-input-receipt-store.mjs +60 -0
  150. package/package.json +1 -1
  151. package/static/oysterun-social-preview.png +0 -0
  152. package/static/site/assets/oysterun-social-preview.png +0 -0
  153. package/static/site/blog/en/index.html +17 -0
  154. package/static/site/blog/generated_manifest.json +9 -9
  155. package/static/site/blog/index.html +18 -0
  156. package/static/site/blog/voice-input-model-experiment/en/index.html +17 -0
  157. package/static/site/blog/voice-input-model-experiment/zh/index.html +17 -0
  158. package/static/site/blog/zh/index.html +17 -0
  159. package/static/site/docs/choose-and-recover-a-provider/en/index.html +17 -0
  160. package/static/site/docs/choose-and-recover-a-provider/zh/index.html +17 -0
  161. package/static/site/docs/configure-session-files-and-settings/en/index.html +17 -0
  162. package/static/site/docs/configure-session-files-and-settings/zh/index.html +17 -0
  163. package/static/site/docs/en/index.html +17 -0
  164. package/static/site/docs/generated_manifest.json +60 -60
  165. package/static/site/docs/host-authentication-and-connection/en/index.html +17 -0
  166. package/static/site/docs/host-authentication-and-connection/zh/index.html +17 -0
  167. package/static/site/docs/index.html +18 -0
  168. package/static/site/docs/install-and-use-a-skill/en/index.html +17 -0
  169. package/static/site/docs/install-and-use-a-skill/zh/index.html +17 -0
  170. package/static/site/docs/read-large-tool-results/en/index.html +17 -0
  171. package/static/site/docs/read-large-tool-results/zh/index.html +17 -0
  172. package/static/site/docs/recover-from-a-host-runtime-error/en/index.html +17 -0
  173. package/static/site/docs/recover-from-a-host-runtime-error/zh/index.html +17 -0
  174. package/static/site/docs/restore-work-after-a-host-restart/en/index.html +17 -0
  175. package/static/site/docs/restore-work-after-a-host-restart/zh/index.html +17 -0
  176. package/static/site/docs/send-images-and-media/en/index.html +17 -0
  177. package/static/site/docs/send-images-and-media/zh/index.html +17 -0
  178. package/static/site/docs/set-up-and-understand-a-host/en/index.html +17 -0
  179. package/static/site/docs/set-up-and-understand-a-host/zh/index.html +17 -0
  180. package/static/site/docs/understand-agent-activity/en/index.html +19 -2
  181. package/static/site/docs/understand-agent-activity/en/index.md +2 -2
  182. package/static/site/docs/understand-agent-activity/zh/index.html +19 -2
  183. package/static/site/docs/understand-agent-activity/zh/index.md +2 -2
  184. package/static/site/docs/use-the-oysterun-cli-safely/en/index.html +17 -0
  185. package/static/site/docs/use-the-oysterun-cli-safely/zh/index.html +17 -0
  186. package/static/site/docs/zh/index.html +17 -0
  187. package/static/site/en/index.html +18 -1
  188. package/static/site/en/index.md +1 -1
  189. package/static/site/faq/en/index.html +17 -0
  190. package/static/site/faq/index.html +18 -0
  191. package/static/site/faq/zh/index.html +17 -0
  192. package/static/site/getting-started/en/index.html +23 -1
  193. package/static/site/getting-started/en/index.md +7 -1
  194. package/static/site/getting-started/index.html +18 -0
  195. package/static/site/getting-started/zh/index.html +23 -1
  196. package/static/site/getting-started/zh/index.md +7 -1
  197. package/static/site/index.html +18 -0
  198. package/static/site/install.sh +676 -127
  199. package/static/site/overview/en/index.html +18 -1
  200. package/static/site/overview/en/index.md +2 -2
  201. package/static/site/overview/index.html +18 -0
  202. package/static/site/overview/zh/index.html +18 -1
  203. package/static/site/overview/zh/index.md +2 -2
  204. package/static/site/privacy/en/index.html +17 -0
  205. package/static/site/privacy/index.html +18 -0
  206. package/static/site/privacy/zh/index.html +17 -0
  207. package/static/site/zh/index.html +18 -1
  208. package/static/site/zh/index.md +1 -1
  209. package/static/site_source/content/tutorials/published/understand-agent-activity/en/article.html +2 -2
  210. package/static/site_source/content/tutorials/published/understand-agent-activity/zh/article.html +2 -2
  211. package/static/site_source/downloads/install.sh +676 -127
  212. package/static/site_source/manifests/host_install.json +2 -10
  213. package/static/site_source/pages/getting-started/en.html +6 -1
  214. package/static/site_source/pages/getting-started/zh.html +6 -1
  215. package/static/site_source/pages/home/en.html +1 -1
  216. package/static/site_source/pages/home/zh.html +1 -1
  217. package/static/site_source/pages/home_main.html +3 -2
  218. package/static/site_source/pages/overview/en.html +1 -1
  219. package/static/site_source/pages/overview/zh.html +1 -1
  220. package/tool_scripts/install_oysterun_update.mjs +78 -13
  221. package/tool_scripts/oysterun_continuity_transaction.mjs +438 -0
  222. package/tool_scripts/oysterun_npm_package_manifest.mjs +32 -0
  223. package/tool_scripts/oysterun_release_service.sh +5 -0
  224. package/tool_scripts/oysterun_service_common.sh +59 -24
  225. package/tool_scripts/oysterun_setup_input.sh +97 -0
  226. package/tool_scripts/oysterun_update_restart_runner.mjs +19 -3
  227. package/tool_scripts/p233_legacy_bootstrap.mjs +254 -0
  228. package/tool_scripts/resolve_user_host_port.mjs +15 -0
  229. package/tool_scripts/restart_oysterun.sh +8 -2
  230. package/tool_scripts/stack_dashboard_credentials.mjs +2 -1
  231. package/tool_scripts/status_oysterun_launch_agents.sh +13 -1
  232. package/tool_scripts/sync_host_stack_config.mjs +9 -6
  233. package/tool_scripts/test_environment_remote_cloud_deprovision.mjs +419 -0
  234. package/tool_scripts/uninstall_oysterun_launch_agents.sh +3 -5
  235. package/dev/client/web-chat/dist/assets/index-Ce9NZBZf.js +0 -129
  236. package/dev/client/web-chat/dist/assets/index-Ce9NZBZf.js.map +0 -1
  237. package/dev/client/web-chat/dist/assets/index-DzIClZ3T.js +0 -2
  238. package/dev/client/web-chat/dist/assets/index-DzIClZ3T.js.map +0 -1
  239. package/dev/client/web-chat/dist/assets/index-NYnaSGBb.css +0 -1
  240. package/dev/client/web-chat/dist/assets/pdf-ZjtalfgI.js.map +0 -1
  241. package/dev/client/web-chat/dist/assets/web-BzHcZK2M.js +0 -1
  242. package/dev/client/web-chat/dist/assets/web-c70YaskK.js +0 -1
@@ -1,3 +1,3 @@
1
- import{g as ss,_ as k,K as nt,a as g,L as it,l as W,D as st,E as P,H as _t,T as me,C as I,M as D,d as _r,e as ot,b as _s,f as os,s as re,h as at,i as cn,V as N,k as gn,m as ke,n as q,o as un,p as dn,q as ln,t as Se,I as Re,u as pn,A as as,v as cs,w as or,x as gs,y as us,U as wn,z as ct,S as yn,B as bn,F as hn,G as ar,J as fn,N as z,O as T,P as gt,Q as Y,R as Ke,X as A,Y as ds}from"./index-Ce9NZBZf.js";let n;function cr(i){n=i}let ut=null;function ae(){return(ut===null||ut.byteLength===0)&&(ut=new Uint8Array(n.memory.buffer)),ut}const vn=typeof TextDecoder>"u"?(0,module.require)("util").TextDecoder:TextDecoder;let dt=new vn("utf-8",{ignoreBOM:!0,fatal:!0});dt.decode();const ls=2146435072;let gr=0;function ps(i,e){return gr+=e,gr>=ls&&(dt=new vn("utf-8",{ignoreBOM:!0,fatal:!0}),dt.decode(),gr=e),dt.decode(ae().subarray(i,i+e))}function y(i,e){return i=i>>>0,ps(i,e)}let u=0;const ws=typeof TextEncoder>"u"?(0,module.require)("util").TextEncoder:TextEncoder,lt=new ws("utf-8"),ys=typeof lt.encodeInto=="function"?function(i,e){return lt.encodeInto(i,e)}:function(i,e){const t=lt.encode(i);return e.set(t),{read:i.length,written:t.length}};function p(i,e,t){if(t===void 0){const a=lt.encode(i),c=e(a.length,1)>>>0;return ae().subarray(c,c+a.length).set(a),u=a.length,c}let r=i.length,s=e(r,1)>>>0;const _=ae();let o=0;for(;o<r;o++){const a=i.charCodeAt(o);if(a>127)break;_[s+o]=a}if(o!==r){o!==0&&(i=i.slice(o)),s=t(s,r,r=o+i.length*3,1)>>>0;const a=ae().subarray(s+o,s+r),c=ys(i,a);o+=c.written,s=t(s,r,o,1)>>>0}return u=o,s}let ce=null;function O(){return(ce===null||ce.buffer.detached===!0||ce.buffer.detached===void 0&&ce.buffer!==n.memory.buffer)&&(ce=new DataView(n.memory.buffer)),ce}function E(i){const e=n.__externref_table_alloc();return n.__wbindgen_export_4.set(e,i),e}function S(i,e){try{return i.apply(this,e)}catch(t){const r=E(t);n.__wbindgen_exn_store(r)}}function v(i){return i==null}function L(i,e){return i=i>>>0,ae().subarray(i/1,i/1+e)}const pt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>{n.__wbindgen_export_6.get(i.dtor)(i.a,i.b)});function ur(i,e,t,r){const s={a:i,b:e,cnt:1,dtor:t},_=(...o)=>{s.cnt++;const a=s.a;s.a=0;try{return r(a,s.b,...o)}finally{--s.cnt===0?(n.__wbindgen_export_6.get(s.dtor)(a,s.b),pt.unregister(s)):s.a=a}};return _.original=s,pt.register(_,s,s),_}function mn(i,e,t,r){const s={a:i,b:e,cnt:1,dtor:t},_=(...o)=>{s.cnt++;try{return r(s.a,s.b,...o)}finally{--s.cnt===0&&(n.__wbindgen_export_6.get(s.dtor)(s.a,s.b),s.a=0,pt.unregister(s))}};return _.original=s,pt.register(_,s,s),_}function dr(i){const e=typeof i;if(e=="number"||e=="boolean"||i==null)return`${i}`;if(e=="string")return`"${i}"`;if(e=="symbol"){const s=i.description;return s==null?"Symbol":`Symbol(${s})`}if(e=="function"){const s=i.name;return typeof s=="string"&&s.length>0?`Function(${s})`:"Function"}if(Array.isArray(i)){const s=i.length;let _="[";s>0&&(_+=dr(i[0]));for(let o=1;o<s;o++)_+=", "+dr(i[o]);return _+="]",_}const t=/\[object ([^\]]+)\]/.exec(toString.call(i));let r;if(t&&t.length>1)r=t[1];else return toString.call(i);if(r=="Object")try{return"Object("+JSON.stringify(i)+")"}catch{return"Object"}return i instanceof Error?`${i.name}: ${i.message}
1
+ import{_ as k,K as nt,a as g,L as it,l as W,D as st,E as P,H as _t,T as me,C as I,M as D,d as _r,e as ot,b as ss,c as _s,s as re,f as at,g as cn,V as N,h as gn,i as ke,j as q,k as un,m as dn,n as ln,o as Se,I as Re,p as pn,A as os,q as as,r as or,t as cs,u as gs,U as wn,v as ct,S as yn,w as bn,x as hn,y as ar,z as fn,B as z,F as T,G as gt,J as Y,N as Ke,O as A,P as us}from"./matrix-entry-abAy3aOo.js";import{g as ds}from"./index-Ae5I4LHp.js";let n;function cr(i){n=i}let ut=null;function ae(){return(ut===null||ut.byteLength===0)&&(ut=new Uint8Array(n.memory.buffer)),ut}const vn=typeof TextDecoder>"u"?(0,module.require)("util").TextDecoder:TextDecoder;let dt=new vn("utf-8",{ignoreBOM:!0,fatal:!0});dt.decode();const ls=2146435072;let gr=0;function ps(i,e){return gr+=e,gr>=ls&&(dt=new vn("utf-8",{ignoreBOM:!0,fatal:!0}),dt.decode(),gr=e),dt.decode(ae().subarray(i,i+e))}function y(i,e){return i=i>>>0,ps(i,e)}let u=0;const ws=typeof TextEncoder>"u"?(0,module.require)("util").TextEncoder:TextEncoder,lt=new ws("utf-8"),ys=typeof lt.encodeInto=="function"?function(i,e){return lt.encodeInto(i,e)}:function(i,e){const t=lt.encode(i);return e.set(t),{read:i.length,written:t.length}};function p(i,e,t){if(t===void 0){const a=lt.encode(i),c=e(a.length,1)>>>0;return ae().subarray(c,c+a.length).set(a),u=a.length,c}let r=i.length,s=e(r,1)>>>0;const _=ae();let o=0;for(;o<r;o++){const a=i.charCodeAt(o);if(a>127)break;_[s+o]=a}if(o!==r){o!==0&&(i=i.slice(o)),s=t(s,r,r=o+i.length*3,1)>>>0;const a=ae().subarray(s+o,s+r),c=ys(i,a);o+=c.written,s=t(s,r,o,1)>>>0}return u=o,s}let ce=null;function O(){return(ce===null||ce.buffer.detached===!0||ce.buffer.detached===void 0&&ce.buffer!==n.memory.buffer)&&(ce=new DataView(n.memory.buffer)),ce}function E(i){const e=n.__externref_table_alloc();return n.__wbindgen_export_4.set(e,i),e}function S(i,e){try{return i.apply(this,e)}catch(t){const r=E(t);n.__wbindgen_exn_store(r)}}function v(i){return i==null}function L(i,e){return i=i>>>0,ae().subarray(i/1,i/1+e)}const pt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>{n.__wbindgen_export_6.get(i.dtor)(i.a,i.b)});function ur(i,e,t,r){const s={a:i,b:e,cnt:1,dtor:t},_=(...o)=>{s.cnt++;const a=s.a;s.a=0;try{return r(a,s.b,...o)}finally{--s.cnt===0?(n.__wbindgen_export_6.get(s.dtor)(a,s.b),pt.unregister(s)):s.a=a}};return _.original=s,pt.register(_,s,s),_}function mn(i,e,t,r){const s={a:i,b:e,cnt:1,dtor:t},_=(...o)=>{s.cnt++;try{return r(s.a,s.b,...o)}finally{--s.cnt===0&&(n.__wbindgen_export_6.get(s.dtor)(s.a,s.b),s.a=0,pt.unregister(s))}};return _.original=s,pt.register(_,s,s),_}function dr(i){const e=typeof i;if(e=="number"||e=="boolean"||i==null)return`${i}`;if(e=="string")return`"${i}"`;if(e=="symbol"){const s=i.description;return s==null?"Symbol":`Symbol(${s})`}if(e=="function"){const s=i.name;return typeof s=="string"&&s.length>0?`Function(${s})`:"Function"}if(Array.isArray(i)){const s=i.length;let _="[";s>0&&(_+=dr(i[0]));for(let o=1;o<s;o++)_+=", "+dr(i[o]);return _+="]",_}const t=/\[object ([^\]]+)\]/.exec(toString.call(i));let r;if(t&&t.length>1)r=t[1];else return toString.call(i);if(r=="Object")try{return"Object("+JSON.stringify(i)+")"}catch{return"Object"}return i instanceof Error?`${i.name}: ${i.message}
2
2
  ${i.stack}`:r}function G(i,e){const t=e(i.length*1,1)>>>0;return ae().set(i,t/1),u=i.length,t}function l(i){const e=n.__wbindgen_export_4.get(i);return n.__externref_table_dealloc(i),e}function b(i,e){if(!(i instanceof e))throw new Error(`expected instance of ${e.name}`)}function F(i,e){const t=e(i.length*4,4)>>>0;for(let r=0;r<i.length;r++){const s=E(i[r]);O().setUint32(t+4*r,s,!0)}return u=i.length,t}function Ie(i,e){i=i>>>0;const t=O(),r=[];for(let s=i;s<i+4*e;s+=4)r.push(n.__wbindgen_export_4.get(t.getUint32(s,!0)));return n.__externref_drop_slice(i,e),r}let wt=null;function bs(){return(wt===null||wt.byteLength===0)&&(wt=new Uint16Array(n.memory.buffer)),wt}function hs(i,e){return i=i>>>0,bs().subarray(i/2,i/2+e)}function kn(){const i=n.getVersions();return rr.__wrap(i)}function fs(){n.start()}function vs(i,e,t){const r=n.closure41_externref_shim_multivalue_shim(i,e,t);if(r[1])throw l(r[0])}function ms(i,e){n.wasm_bindgen__convert__closures_____invoke__h8861d869601ff522(i,e)}function ks(i,e,t){n.closure756_externref_shim(i,e,t)}function Ss(i,e,t){n.closure438_externref_shim(i,e,t)}function Rs(i,e){n.wasm_bindgen__convert__closures_____invoke__hce61fd14ea1a6ce1(i,e)}function Ks(i,e,t,r){n.closure451_externref_shim(i,e,t,r)}const $=Object.freeze({MissingRoomKey:0,0:"MissingRoomKey",UnknownMessageIndex:1,1:"UnknownMessageIndex",MismatchedIdentityKeys:2,2:"MismatchedIdentityKeys",UnknownSenderDevice:3,3:"UnknownSenderDevice",UnsignedSenderDevice:4,4:"UnsignedSenderDevice",SenderIdentityVerificationViolation:5,5:"SenderIdentityVerificationViolation",UnableToDecrypt:6,6:"UnableToDecrypt",MismatchedSender:7,7:"MismatchedSender"}),Is=Object.freeze({Ed25519:0,0:"Ed25519",Curve25519:1,1:"Curve25519",Unknown:3,3:"Unknown"}),Cs=Object.freeze({Curve25519:0,0:"Curve25519",Ed25519:1,1:"Ed25519",Unknown:2,2:"Unknown"}),ge=Object.freeze({OlmV1Curve25519AesSha2:0,0:"OlmV1Curve25519AesSha2",MegolmV1AesSha2:1,1:"MegolmV1AesSha2",Unknown:2,2:"Unknown"}),Ce=Object.freeze({Invited:0,0:"Invited",Joined:1,1:"Joined",Shared:2,2:"Shared",WorldReadable:3,3:"WorldReadable"}),lr=Object.freeze({Verified:0,0:"Verified",BlackListed:1,1:"BlackListed",Ignored:2,2:"Ignored",Unset:3,3:"Unset"}),Ds=Object.freeze({Trace:0,0:"Trace",Debug:1,1:"Debug",Info:2,2:"Info",Warn:3,3:"Warn",Error:4,4:"Error"}),De=Object.freeze({Decrypted:0,0:"Decrypted",UnableToDecrypt:1,1:"UnableToDecrypt",PlainText:2,2:"PlainText",Invalid:3,3:"Invalid"}),Es=Object.freeze({Login:0,0:"Login",Reciprocate:1,1:"Reciprocate"}),ne=Object.freeze({Created:0,0:"Created",Scanned:1,1:"Scanned",Confirmed:2,2:"Confirmed",Reciprocated:3,3:"Reciprocated",Done:4,4:"Done",Cancelled:5,5:"Cancelled"}),Os=Object.freeze({KeysUpload:0,0:"KeysUpload",KeysQuery:1,1:"KeysQuery",KeysClaim:2,2:"KeysClaim",ToDevice:3,3:"ToDevice",SignatureUpload:4,4:"SignatureUpload",RoomMessage:5,5:"RoomMessage",KeysBackup:6,6:"KeysBackup"}),pr=Object.freeze({Red:0,0:"Red",Grey:1,1:"Grey",None:2,2:"None"}),Z=Object.freeze({AuthenticityNotGuaranteed:0,0:"AuthenticityNotGuaranteed",UnknownDevice:1,1:"UnknownDevice",UnsignedDevice:2,2:"UnsignedDevice",UnverifiedIdentity:3,3:"UnverifiedIdentity",SentInClear:4,4:"SentInClear",VerificationViolation:5,5:"VerificationViolation",MismatchedSender:6,6:"MismatchedSender"}),Ms=Object.freeze({Missing:0,0:"Missing",Invalid:1,1:"Invalid",ValidButNotTrusted:2,2:"ValidButNotTrusted",ValidAndTrusted:3,3:"ValidAndTrusted"}),qs=Object.freeze({DecryptionFailure:0,0:"DecryptionFailure",UnverifiedSenderDevice:1,1:"UnverifiedSenderDevice",NoOlmMachine:2,2:"NoOlmMachine",EncryptionIsDisabled:3,3:"EncryptionIsDisabled"}),wr=Object.freeze({Untrusted:0,0:"Untrusted",CrossSignedOrLegacy:1,1:"CrossSignedOrLegacy",CrossSigned:2,2:"CrossSigned"}),Ee=Object.freeze({SasV1:0,0:"SasV1",QrCodeScanV1:1,1:"QrCodeScanV1",QrCodeShowV1:2,2:"QrCodeShowV1",ReciprocateV1:3,3:"ReciprocateV1"}),X=Object.freeze({Created:0,0:"Created",Requested:1,1:"Requested",Ready:2,2:"Ready",Transitioned:3,3:"Transitioned",Done:4,4:"Done",Cancelled:5,5:"Cancelled"}),Bs=["pending","done"],Sn=["readonly","readwrite","versionchange","readwriteflush","cleanup"],Us=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_attachment_free(i>>>0,1));class Fs{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Us.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_attachment_free(e,0)}static encrypt(e){const t=G(e,n.__wbindgen_malloc),r=u,s=n.attachment_encrypt(t,r);if(s[2])throw l(s[1]);return pe.__wrap(s[0])}static decrypt(e){b(e,pe);const t=n.attachment_decrypt(e.__wbg_ptr);if(t[3])throw l(t[2]);var r=L(t[0],t[1]).slice();return n.__wbindgen_free(t[0],t[1]*1,1),r}}const Rn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_backupdecryptionkey_free(i>>>0,1));class V{static __wrap(e){e=e>>>0;const t=Object.create(V.prototype);return t.__wbg_ptr=e,Rn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Rn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_backupdecryptionkey_free(e,0)}static createRandomKey(){const e=n.backupdecryptionkey_createRandomKey();return V.__wrap(e)}static fromBase64(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.backupdecryptionkey_fromBase64(t,r);if(s[2])throw l(s[1]);return V.__wrap(s[0])}toBase64(){return n.backupdecryptionkey_toBase64(this.__wbg_ptr)}get megolmV1PublicKey(){const e=n.backupdecryptionkey_megolmV1PublicKey(this.__wbg_ptr);return zt.__wrap(e)}decryptV1(e,t,r){let s,_;try{const c=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),d=u,w=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),f=u,m=p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),K=u,U=n.backupdecryptionkey_decryptV1(this.__wbg_ptr,c,d,w,f,m,K);var o=U[0],a=U[1];if(U[3])throw o=0,a=0,l(U[2]);return s=o,_=a,y(o,a)}finally{n.__wbindgen_free(s,_,1)}}}const Kn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_backupkeys_free(i>>>0,1));class kt{static __wrap(e){e=e>>>0;const t=Object.create(kt.prototype);return t.__wbg_ptr=e,Kn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Kn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_backupkeys_free(e,0)}get decryptionKey(){const e=n.__wbg_get_backupkeys_decryptionKey(this.__wbg_ptr);return e===0?void 0:V.__wrap(e)}set decryptionKey(e){let t=0;v(e)||(b(e,V),t=e.__destroy_into_raw()),n.__wbg_set_backupkeys_decryptionKey(this.__wbg_ptr,t)}get backupVersion(){const e=n.__wbg_get_backupkeys_backupVersion(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}set backupVersion(e){var t=v(e)?0:p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupkeys_backupVersion(this.__wbg_ptr,t,r)}get decryptionKeyBase64(){return n.backupkeys_decryptionKeyBase64(this.__wbg_ptr)}}const In=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_backupsecretsbundle_free(i>>>0,1));class St{static __wrap(e){e=e>>>0;const t=Object.create(St.prototype);return t.__wbg_ptr=e,In.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,In.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_backupsecretsbundle_free(e,0)}get key(){let e,t;try{const r=n.__wbg_get_backupsecretsbundle_key(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set key(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_key(this.__wbg_ptr,t,r)}get backup_version(){let e,t;try{const r=n.__wbg_get_backupsecretsbundle_backup_version(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set backup_version(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_backup_version(this.__wbg_ptr,t,r)}}const yr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_base64encodedpkmessage_free(i>>>0,1));class Be{static __wrap(e){e=e>>>0;const t=Object.create(Be.prototype);return t.__wbg_ptr=e,yr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,yr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_base64encodedpkmessage_free(e,0)}get ciphertext(){let e,t;try{const r=n.__wbg_get_base64encodedpkmessage_ciphertext(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set ciphertext(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_key(this.__wbg_ptr,t,r)}get mac(){let e,t;try{const r=n.__wbg_get_base64encodedpkmessage_mac(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set mac(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_backup_version(this.__wbg_ptr,t,r)}get ephemeralKey(){let e,t;try{const r=n.__wbg_get_base64encodedpkmessage_ephemeralKey(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set ephemeralKey(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_base64encodedpkmessage_ephemeralKey(this.__wbg_ptr,t,r)}constructor(e,t,r){const s=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u,o=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),a=u,c=p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),d=u,w=n.base64encodedpkmessage_new(s,_,o,a,c,d);return this.__wbg_ptr=w>>>0,yr.register(this,this.__wbg_ptr,this),this}}const Cn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_basemigrationdata_free(i>>>0,1));class br{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Cn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_basemigrationdata_free(e,0)}get userId(){const e=n.__wbg_get_basemigrationdata_userId(this.__wbg_ptr);return e===0?void 0:h.__wrap(e)}set userId(e){let t=0;v(e)||(b(e,h),t=e.__destroy_into_raw()),n.__wbg_set_basemigrationdata_userId(this.__wbg_ptr,t)}get deviceId(){const e=n.__wbg_get_basemigrationdata_deviceId(this.__wbg_ptr);return e===0?void 0:C.__wrap(e)}set deviceId(e){let t=0;v(e)||(b(e,C),t=e.__destroy_into_raw()),n.__wbg_set_basemigrationdata_deviceId(this.__wbg_ptr,t)}get pickledAccount(){let e,t;try{const r=n.__wbg_get_basemigrationdata_pickledAccount(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set pickledAccount(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_key(this.__wbg_ptr,t,r)}get backupVersion(){const e=n.__wbg_get_basemigrationdata_backupVersion(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}set backupVersion(e){var t=v(e)?0:p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_basemigrationdata_backupVersion(this.__wbg_ptr,t,r)}get backupRecoveryKey(){const e=n.__wbg_get_basemigrationdata_backupRecoveryKey(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}set backupRecoveryKey(e){var t=v(e)?0:p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_basemigrationdata_backupRecoveryKey(this.__wbg_ptr,t,r)}get privateCrossSigningMasterKey(){const e=n.__wbg_get_basemigrationdata_privateCrossSigningMasterKey(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}set privateCrossSigningMasterKey(e){var t=v(e)?0:p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_basemigrationdata_privateCrossSigningMasterKey(this.__wbg_ptr,t,r)}get privateCrossSigningSelfSigningKey(){const e=n.__wbg_get_basemigrationdata_privateCrossSigningSelfSigningKey(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}set privateCrossSigningSelfSigningKey(e){var t=v(e)?0:p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_basemigrationdata_privateCrossSigningSelfSigningKey(this.__wbg_ptr,t,r)}get privateCrossSigningUserSigningKey(){const e=n.__wbg_get_basemigrationdata_privateCrossSigningUserSigningKey(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}set privateCrossSigningUserSigningKey(e){var t=v(e)?0:p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_basemigrationdata_privateCrossSigningUserSigningKey(this.__wbg_ptr,t,r)}constructor(){const e=n.basemigrationdata_new();return this.__wbg_ptr=e>>>0,Cn.register(this,this.__wbg_ptr,this),this}}const Dn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_cancelinfo_free(i>>>0,1));class ue{static __wrap(e){e=e>>>0;const t=Object.create(ue.prototype);return t.__wbg_ptr=e,Dn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Dn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_cancelinfo_free(e,0)}reason(){return n.cancelinfo_reason(this.__wbg_ptr)}cancelCode(){let e,t;try{const r=n.cancelinfo_cancelCode(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}cancelledbyUs(){return n.cancelinfo_cancelledbyUs(this.__wbg_ptr)!==0}}const En=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_checkcode_free(i>>>0,1));class Rt{static __wrap(e){e=e>>>0;const t=Object.create(Rt.prototype);return t.__wbg_ptr=e,En.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,En.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_checkcode_free(e,0)}as_bytes(){const e=n.checkcode_as_bytes(this.__wbg_ptr);var t=L(e[0],e[1]).slice();return n.__wbindgen_free(e[0],e[1]*1,1),t}to_digit(){return n.checkcode_to_digit(this.__wbg_ptr)}}const On=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_collectstrategy_free(i>>>0,1));class B{static __wrap(e){e=e>>>0;const t=Object.create(B.prototype);return t.__wbg_ptr=e,On.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,On.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_collectstrategy_free(e,0)}eq(e){return b(e,B),n.collectstrategy_eq(this.__wbg_ptr,e.__wbg_ptr)!==0}static deviceBasedStrategy(e,t){const r=n.collectstrategy_deviceBasedStrategy(e,t);return B.__wrap(r)}static allDevices(){const e=n.collectstrategy_allDevices();return B.__wrap(e)}static errorOnUnverifiedUserProblem(){const e=n.collectstrategy_errorOnUnverifiedUserProblem();return B.__wrap(e)}static identityBasedStrategy(){const e=n.collectstrategy_identityBasedStrategy();return B.__wrap(e)}static onlyTrustedDevices(){const e=n.collectstrategy_onlyTrustedDevices();return B.__wrap(e)}}const Mn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_crosssigningbootstraprequests_free(i>>>0,1));class Kt{static __wrap(e){e=e>>>0;const t=Object.create(Kt.prototype);return t.__wbg_ptr=e,Mn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Mn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_crosssigningbootstraprequests_free(e,0)}get uploadKeysRequest(){return n.__wbg_get_crosssigningbootstraprequests_uploadKeysRequest(this.__wbg_ptr)}get uploadSigningKeysRequest(){const e=n.__wbg_get_crosssigningbootstraprequests_uploadSigningKeysRequest(this.__wbg_ptr);return et.__wrap(e)}get uploadSignaturesRequest(){const e=n.__wbg_get_crosssigningbootstraprequests_uploadSignaturesRequest(this.__wbg_ptr);return he.__wrap(e)}}const qn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_crosssigningkeyexport_free(i>>>0,1));class It{static __wrap(e){e=e>>>0;const t=Object.create(It.prototype);return t.__wbg_ptr=e,qn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,qn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_crosssigningkeyexport_free(e,0)}get masterKey(){const e=n.crosssigningkeyexport_masterKey(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}get self_signing_key(){const e=n.crosssigningkeyexport_self_signing_key(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}get userSigningKey(){const e=n.crosssigningkeyexport_userSigningKey(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}}const Bn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_crosssigningstatus_free(i>>>0,1));class Ct{static __wrap(e){e=e>>>0;const t=Object.create(Ct.prototype);return t.__wbg_ptr=e,Bn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Bn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_crosssigningstatus_free(e,0)}get hasMaster(){return n.crosssigningstatus_hasMaster(this.__wbg_ptr)!==0}get hasSelfSigning(){return n.crosssigningstatus_hasSelfSigning(this.__wbg_ptr)!==0}get hasUserSigning(){return n.crosssigningstatus_hasUserSigning(this.__wbg_ptr)!==0}}const hr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_curve25519publickey_free(i>>>0,1));class M{static __wrap(e){e=e>>>0;const t=Object.create(M.prototype);return t.__wbg_ptr=e,hr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,hr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_curve25519publickey_free(e,0)}constructor(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.curve25519publickey_new(t,r);if(s[2])throw l(s[1]);return this.__wbg_ptr=s[0]>>>0,hr.register(this,this.__wbg_ptr,this),this}get length(){return n.curve25519publickey_length(this.__wbg_ptr)>>>0}toBase64(){let e,t;try{const r=n.curve25519publickey_toBase64(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const Un=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_curve25519secretkey_free(i>>>0,1));class te{static __wrap(e){e=e>>>0;const t=Object.create(te.prototype);return t.__wbg_ptr=e,Un.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Un.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_curve25519secretkey_free(e,0)}static new(){const e=n.curve25519secretkey_new();return te.__wrap(e)}static fromBase64(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.curve25519secretkey_fromBase64(t,r);if(s[2])throw l(s[1]);return te.__wrap(s[0])}toBase64(){let e,t;try{const r=n.curve25519secretkey_toBase64(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}toUint8Array(){const e=n.curve25519secretkey_toUint8Array(this.__wbg_ptr);var t=L(e[0],e[1]).slice();return n.__wbindgen_free(e[0],e[1]*1,1),t}static fromUint8Array(e){const t=G(e,n.__wbindgen_malloc),r=u,s=n.curve25519secretkey_fromUint8Array(t,r);if(s[2])throw l(s[1]);return te.__wrap(s[0])}}const Fn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_decryptedroomevent_free(i>>>0,1));class Dt{static __wrap(e){e=e>>>0;const t=Object.create(Dt.prototype);return t.__wbg_ptr=e,Fn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Fn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_decryptedroomevent_free(e,0)}get event(){return n.__wbg_get_decryptedroomevent_event(this.__wbg_ptr)}get sender(){const e=n.decryptedroomevent_sender(this.__wbg_ptr);return h.__wrap(e)}get senderDevice(){const e=n.decryptedroomevent_senderDevice(this.__wbg_ptr);return e===0?void 0:C.__wrap(e)}get senderCurve25519Key(){let e,t;try{const r=n.decryptedroomevent_senderCurve25519Key(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get senderClaimedEd25519Key(){return n.decryptedroomevent_senderClaimedEd25519Key(this.__wbg_ptr)}get forwardingCurve25519KeyChain(){return n.decryptedroomevent_forwardingCurve25519KeyChain(this.__wbg_ptr)}shieldState(e){const t=n.decryptedroomevent_shieldState(this.__wbg_ptr,e);return Ye.__wrap(t)}}const Vn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_decryptedtodeviceevent_free(i>>>0,1));class Et{static __wrap(e){e=e>>>0;const t=Object.create(Et.prototype);return t.__wbg_ptr=e,Vn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Vn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_decryptedtodeviceevent_free(e,0)}get rawEvent(){return n.__wbg_get_decryptedtodeviceevent_rawEvent(this.__wbg_ptr)}get encryptionInfo(){const e=n.__wbg_get_decryptedtodeviceevent_encryptionInfo(this.__wbg_ptr);return Zt.__wrap(e)}get type(){return n.decryptedtodeviceevent_type(this.__wbg_ptr)}}const Tn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_decryptionsettings_free(i>>>0,1));class Oe{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Tn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_decryptionsettings_free(e,0)}get sender_device_trust_requirement(){return n.__wbg_get_decryptionsettings_sender_device_trust_requirement(this.__wbg_ptr)}set sender_device_trust_requirement(e){n.__wbg_set_decryptionsettings_sender_device_trust_requirement(this.__wbg_ptr,e)}constructor(e){const t=n.decryptionsettings_new(e);return this.__wbg_ptr=t>>>0,Tn.register(this,this.__wbg_ptr,this),this}}const Pn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_dehydrateddevice_free(i>>>0,1));class Ot{static __wrap(e){e=e>>>0;const t=Object.create(Ot.prototype);return t.__wbg_ptr=e,Pn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Pn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_dehydrateddevice_free(e,0)}keysForUpload(e,t){return b(t,x),n.dehydrateddevice_keysForUpload(this.__wbg_ptr,e,t.__wbg_ptr)}}const zn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_dehydrateddevicekey_free(i>>>0,1));class x{static __wrap(e){e=e>>>0;const t=Object.create(x.prototype);return t.__wbg_ptr=e,zn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,zn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_dehydrateddevicekey_free(e,0)}static createRandomKey(){const e=n.dehydrateddevicekey_createRandomKey();if(e[2])throw l(e[1]);return x.__wrap(e[0])}static createKeyFromArray(e){const t=n.dehydrateddevicekey_createKeyFromArray(e);if(t[2])throw l(t[1]);return x.__wrap(t[0])}toBase64(){return n.dehydrateddevicekey_toBase64(this.__wbg_ptr)}}const Nn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_dehydrateddevices_free(i>>>0,1));class Mt{static __wrap(e){e=e>>>0;const t=Object.create(Mt.prototype);return t.__wbg_ptr=e,Nn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Nn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_dehydrateddevices_free(e,0)}create(){return n.dehydrateddevices_create(this.__wbg_ptr)}rehydrate(e,t,r){b(e,x),b(t,C);const s=p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u;return n.dehydrateddevices_rehydrate(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,s,_)}getDehydratedDeviceKey(){return n.dehydrateddevices_getDehydratedDeviceKey(this.__wbg_ptr)}saveDehydratedDeviceKey(e){return b(e,x),n.dehydrateddevices_saveDehydratedDeviceKey(this.__wbg_ptr,e.__wbg_ptr)}deleteDehydratedDeviceKey(){return n.dehydrateddevices_deleteDehydratedDeviceKey(this.__wbg_ptr)}}const An=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_device_free(i>>>0,1));class Ue{static __wrap(e){e=e>>>0;const t=Object.create(Ue.prototype);return t.__wbg_ptr=e,An.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,An.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_device_free(e,0)}requestVerification(e){var t=v(e)?0:F(e,n.__wbindgen_malloc),r=u;const s=n.device_requestVerification(this.__wbg_ptr,t,r);if(s[2])throw l(s[1]);return l(s[0])}encryptToDeviceEvent(e,t,r){const s=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u;let o=0;return v(r)||(b(r,B),o=r.__destroy_into_raw()),n.device_encryptToDeviceEvent(this.__wbg_ptr,s,_,t,o)}isVerified(){return n.device_isVerified(this.__wbg_ptr)!==0}isCrossSigningTrusted(){return n.device_isCrossSigningTrusted(this.__wbg_ptr)!==0}isCrossSignedByOwner(){return n.device_isCrossSignedByOwner(this.__wbg_ptr)!==0}setLocalTrust(e){return n.device_setLocalTrust(this.__wbg_ptr,e)}get userId(){const e=n.device_userId(this.__wbg_ptr);return h.__wrap(e)}get deviceId(){const e=n.device_deviceId(this.__wbg_ptr);return C.__wrap(e)}get displayName(){const e=n.device_displayName(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}getKey(e){const t=n.device_getKey(this.__wbg_ptr,e);if(t[2])throw l(t[1]);return t[0]===0?void 0:Fe.__wrap(t[0])}get curve25519Key(){const e=n.device_curve25519Key(this.__wbg_ptr);return e===0?void 0:M.__wrap(e)}get ed25519Key(){const e=n.device_ed25519Key(this.__wbg_ptr);return e===0?void 0:ie.__wrap(e)}get keys(){return n.device_keys(this.__wbg_ptr)}get algorithms(){return n.device_algorithms(this.__wbg_ptr)}get signatures(){const e=n.device_signatures(this.__wbg_ptr);return $e.__wrap(e)}get localTrustState(){return n.device_localTrustState(this.__wbg_ptr)}isLocallyTrusted(){return n.device_isLocallyTrusted(this.__wbg_ptr)!==0}isBlacklisted(){return n.device_isBlacklisted(this.__wbg_ptr)!==0}isDeleted(){return n.device_isDeleted(this.__wbg_ptr)!==0}firstTimeSeen(){const e=n.device_firstTimeSeen(this.__wbg_ptr);return BigInt.asUintN(64,e)}verify(){return n.device_verify(this.__wbg_ptr)}get isDehydrated(){return n.device_isDehydrated(this.__wbg_ptr)!==0}}const fr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_deviceid_free(i>>>0,1));class C{static __wrap(e){e=e>>>0;const t=Object.create(C.prototype);return t.__wbg_ptr=e,fr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,fr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_deviceid_free(e,0)}constructor(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.deviceid_new(t,r);return this.__wbg_ptr=s>>>0,fr.register(this,this.__wbg_ptr,this),this}toString(){let e,t;try{const r=n.deviceid_toString(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const jn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_devicekey_free(i>>>0,1));class Fe{static __wrap(e){e=e>>>0;const t=Object.create(Fe.prototype);return t.__wbg_ptr=e,jn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,jn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_devicekey_free(e,0)}get name(){return n.devicekey_name(this.__wbg_ptr)}get curve25519(){const e=n.devicekey_curve25519(this.__wbg_ptr);return e===0?void 0:M.__wrap(e)}get ed25519(){const e=n.devicekey_ed25519(this.__wbg_ptr);return e===0?void 0:ie.__wrap(e)}get unknown(){const e=n.devicekey_unknown(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}toBase64(){let e,t;try{const r=n.devicekey_toBase64(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const xn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_devicekeyalgorithm_free(i>>>0,1));class qt{static __wrap(e){e=e>>>0;const t=Object.create(qt.prototype);return t.__wbg_ptr=e,xn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,xn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_devicekeyalgorithm_free(e,0)}get name(){return n.devicekeyalgorithm_name(this.__wbg_ptr)}toString(){let e,t;try{const r=n.devicekeyalgorithm_toString(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const vr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_devicekeyid_free(i>>>0,1));class de{static __wrap(e){e=e>>>0;const t=Object.create(de.prototype);return t.__wbg_ptr=e,vr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,vr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_devicekeyid_free(e,0)}constructor(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.devicekeyid_new(t,r);if(s[2])throw l(s[1]);return this.__wbg_ptr=s[0]>>>0,vr.register(this,this.__wbg_ptr,this),this}get algorithm(){const e=n.devicekeyid_algorithm(this.__wbg_ptr);return qt.__wrap(e)}get deviceId(){const e=n.devicekeyid_deviceId(this.__wbg_ptr);return C.__wrap(e)}toString(){let e,t;try{const r=n.devicekeyid_toString(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const Ln=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_devicelists_free(i>>>0,1));class yt{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ln.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_devicelists_free(e,0)}constructor(e,t){var r=v(e)?0:F(e,n.__wbindgen_malloc),s=u,_=v(t)?0:F(t,n.__wbindgen_malloc),o=u;const a=n.devicelists_new(r,s,_,o);if(a[2])throw l(a[1]);return this.__wbg_ptr=a[0]>>>0,Ln.register(this,this.__wbg_ptr,this),this}isEmpty(){return n.devicelists_isEmpty(this.__wbg_ptr)!==0}get changed(){const e=n.devicelists_changed(this.__wbg_ptr);var t=Ie(e[0],e[1]).slice();return n.__wbindgen_free(e[0],e[1]*4,4),t}get left(){const e=n.devicelists_left(this.__wbg_ptr);var t=Ie(e[0],e[1]).slice();return n.__wbindgen_free(e[0],e[1]*4,4),t}}const Wn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_ecies_free(i>>>0,1));class Vs{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Wn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_ecies_free(e,0)}constructor(){const e=n.ecies_new();return this.__wbg_ptr=e>>>0,Wn.register(this,this.__wbg_ptr,this),this}public_key(){const e=n.ecies_public_key(this.__wbg_ptr);return M.__wrap(e)}establish_inbound_channel(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.ecies_establish_inbound_channel(this.__wbg_ptr,t,r);if(s[2])throw l(s[1]);return Vt.__wrap(s[0])}establish_outbound_channel(e,t){b(e,M);const r=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u,_=n.ecies_establish_outbound_channel(this.__wbg_ptr,e.__wbg_ptr,r,s);if(_[2])throw l(_[1]);return Nt.__wrap(_[0])}}const Gn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_ed25519publickey_free(i>>>0,1));class ie{static __wrap(e){e=e>>>0;const t=Object.create(ie.prototype);return t.__wbg_ptr=e,Gn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Gn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_ed25519publickey_free(e,0)}get length(){return n.ed25519publickey_length(this.__wbg_ptr)>>>0}toBase64(){let e,t;try{const r=n.ed25519publickey_toBase64(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const mr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_ed25519signature_free(i>>>0,1));class le{static __wrap(e){e=e>>>0;const t=Object.create(le.prototype);return t.__wbg_ptr=e,mr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,mr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_ed25519signature_free(e,0)}constructor(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.ed25519signature_new(t,r);if(s[2])throw l(s[1]);return this.__wbg_ptr=s[0]>>>0,mr.register(this,this.__wbg_ptr,this),this}toBase64(){let e,t;try{const r=n.ed25519signature_toBase64(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const Jn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_emoji_free(i>>>0,1));class Bt{static __wrap(e){e=e>>>0;const t=Object.create(Bt.prototype);return t.__wbg_ptr=e,Jn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Jn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_emoji_free(e,0)}get symbol(){return n.emoji_symbol(this.__wbg_ptr)}get description(){return n.emoji_description(this.__wbg_ptr)}}const kr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_encryptedattachment_free(i>>>0,1));class pe{static __wrap(e){e=e>>>0;const t=Object.create(pe.prototype);return t.__wbg_ptr=e,kr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,kr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_encryptedattachment_free(e,0)}constructor(e,t){const r=G(e,n.__wbindgen_malloc),s=u,_=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),o=u,a=n.encryptedattachment_new(r,s,_,o);if(a[2])throw l(a[1]);return this.__wbg_ptr=a[0]>>>0,kr.register(this,this.__wbg_ptr,this),this}get encryptedData(){const e=n.encryptedattachment_encryptedData(this.__wbg_ptr);var t=L(e[0],e[1]).slice();return n.__wbindgen_free(e[0],e[1]*1,1),t}get mediaEncryptionInfo(){const e=n.encryptedattachment_mediaEncryptionInfo(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}get hasMediaEncryptionInfoBeenConsumed(){return n.encryptedattachment_hasMediaEncryptionInfoBeenConsumed(this.__wbg_ptr)!==0}}const Qn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_encryptioninfo_free(i>>>0,1));class Ut{static __wrap(e){e=e>>>0;const t=Object.create(Ut.prototype);return t.__wbg_ptr=e,Qn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Qn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_encryptioninfo_free(e,0)}get sender(){const e=n.__wbg_get_encryptioninfo_sender(this.__wbg_ptr);return h.__wrap(e)}set sender(e){b(e,h);var t=e.__destroy_into_raw();n.__wbg_set_encryptioninfo_sender(this.__wbg_ptr,t)}get senderDevice(){const e=n.__wbg_get_encryptioninfo_senderDevice(this.__wbg_ptr);return e===0?void 0:C.__wrap(e)}set senderDevice(e){let t=0;v(e)||(b(e,C),t=e.__destroy_into_raw()),n.__wbg_set_encryptioninfo_senderDevice(this.__wbg_ptr,t)}get senderCurve25519Key(){let e,t;try{const r=n.__wbg_get_encryptioninfo_senderCurve25519Key(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set senderCurve25519Key(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_key(this.__wbg_ptr,t,r)}get senderClaimedEd25519Key(){const e=n.__wbg_get_encryptioninfo_senderClaimedEd25519Key(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}set senderClaimedEd25519Key(e){var t=v(e)?0:p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_basemigrationdata_backupVersion(this.__wbg_ptr,t,r)}shieldState(e){const t=n.encryptioninfo_shieldState(this.__wbg_ptr,e);return Ye.__wrap(t)}}const Hn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_encryptionsettings_free(i>>>0,1));class Sr{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Hn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_encryptionsettings_free(e,0)}get algorithm(){return n.__wbg_get_encryptionsettings_algorithm(this.__wbg_ptr)}set algorithm(e){n.__wbg_set_encryptionsettings_algorithm(this.__wbg_ptr,e)}get encryptStateEvents(){return n.__wbg_get_encryptionsettings_encryptStateEvents(this.__wbg_ptr)!==0}set encryptStateEvents(e){n.__wbg_set_encryptionsettings_encryptStateEvents(this.__wbg_ptr,e)}get rotationPeriod(){const e=n.__wbg_get_encryptionsettings_rotationPeriod(this.__wbg_ptr);return BigInt.asUintN(64,e)}set rotationPeriod(e){n.__wbg_set_encryptionsettings_rotationPeriod(this.__wbg_ptr,e)}get rotationPeriodMessages(){const e=n.__wbg_get_encryptionsettings_rotationPeriodMessages(this.__wbg_ptr);return BigInt.asUintN(64,e)}set rotationPeriodMessages(e){n.__wbg_set_encryptionsettings_rotationPeriodMessages(this.__wbg_ptr,e)}get historyVisibility(){return n.__wbg_get_encryptionsettings_historyVisibility(this.__wbg_ptr)}set historyVisibility(e){n.__wbg_set_encryptionsettings_historyVisibility(this.__wbg_ptr,e)}get sharingStrategy(){const e=n.__wbg_get_encryptionsettings_sharingStrategy(this.__wbg_ptr);return B.__wrap(e)}set sharingStrategy(e){b(e,B);var t=e.__destroy_into_raw();n.__wbg_set_encryptionsettings_sharingStrategy(this.__wbg_ptr,t)}constructor(){const e=n.encryptionsettings_new();return this.__wbg_ptr=e>>>0,Hn.register(this,this.__wbg_ptr,this),this}}const Yn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_establishedecies_free(i>>>0,1));class se{static __wrap(e){e=e>>>0;const t=Object.create(se.prototype);return t.__wbg_ptr=e,Yn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Yn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_establishedecies_free(e,0)}public_key(){const e=n.establishedecies_public_key(this.__wbg_ptr);return M.__wrap(e)}encrypt(e){let t,r;try{const s=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u,o=n.establishedecies_encrypt(this.__wbg_ptr,s,_);return t=o[0],r=o[1],y(o[0],o[1])}finally{n.__wbindgen_free(t,r,1)}}decrypt(e){let t,r;try{const o=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),a=u,c=n.establishedecies_decrypt(this.__wbg_ptr,o,a);var s=c[0],_=c[1];if(c[3])throw s=0,_=0,l(c[2]);return t=s,r=_,y(s,_)}finally{n.__wbindgen_free(t,r,1)}}check_code(){const e=n.establishedecies_check_code(this.__wbg_ptr);return Rt.__wrap(e)}}const $n=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_eventid_free(i>>>0,1));class Rr{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,$n.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_eventid_free(e,0)}constructor(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.eventid_new(t,r);if(s[2])throw l(s[1]);return this.__wbg_ptr=s[0]>>>0,$n.register(this,this.__wbg_ptr,this),this}get localpart(){let e,t;try{const r=n.eventid_localpart(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get serverName(){const e=n.eventid_serverName(this.__wbg_ptr);return e===0?void 0:He.__wrap(e)}toString(){let e,t;try{const r=n.eventid_toString(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const Zn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_identitykeys_free(i>>>0,1));class Ft{static __wrap(e){e=e>>>0;const t=Object.create(Ft.prototype);return t.__wbg_ptr=e,Zn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Zn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_identitykeys_free(e,0)}get ed25519(){const e=n.__wbg_get_identitykeys_ed25519(this.__wbg_ptr);return ie.__wrap(e)}set ed25519(e){b(e,ie);var t=e.__destroy_into_raw();n.__wbg_set_identitykeys_ed25519(this.__wbg_ptr,t)}get curve25519(){const e=n.__wbg_get_identitykeys_curve25519(this.__wbg_ptr);return M.__wrap(e)}set curve25519(e){b(e,M);var t=e.__destroy_into_raw();n.__wbg_set_identitykeys_curve25519(this.__wbg_ptr,t)}}const Xn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_inboundcreationresult_free(i>>>0,1));class Vt{static __wrap(e){e=e>>>0;const t=Object.create(Vt.prototype);return t.__wbg_ptr=e,Xn.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Xn.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_inboundcreationresult_free(e,0)}get channel(){const e=n.__wbg_get_inboundcreationresult_channel(this.__wbg_ptr);return se.__wrap(e)}set channel(e){b(e,se);var t=e.__destroy_into_raw();n.__wbg_set_inboundcreationresult_channel(this.__wbg_ptr,t)}get message(){let e,t;try{const r=n.__wbg_get_inboundcreationresult_message(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set message(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_key(this.__wbg_ptr,t,r)}}const ei=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_inboundgroupsession_free(i>>>0,1));class Tt{static __wrap(e){e=e>>>0;const t=Object.create(Tt.prototype);return t.__wbg_ptr=e,ei.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ei.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_inboundgroupsession_free(e,0)}get roomId(){const e=n.inboundgroupsession_roomId(this.__wbg_ptr);return R.__wrap(e)}get senderKey(){const e=n.inboundgroupsession_senderKey(this.__wbg_ptr);return M.__wrap(e)}get sessionId(){let e,t;try{const r=n.inboundgroupsession_sessionId(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}hasBeenImported(){return n.inboundgroupsession_hasBeenImported(this.__wbg_ptr)!==0}}const ti=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_invalidtodeviceevent_free(i>>>0,1));class Pt{static __wrap(e){e=e>>>0;const t=Object.create(Pt.prototype);return t.__wbg_ptr=e,ti.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ti.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_invalidtodeviceevent_free(e,0)}get rawEvent(){return n.__wbg_get_invalidtodeviceevent_rawEvent(this.__wbg_ptr)}get type(){return n.invalidtodeviceevent_type(this.__wbg_ptr)}}const Kr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_keysbackuprequest_free(i>>>0,1));class Ve{static __wrap(e){e=e>>>0;const t=Object.create(Ve.prototype);return t.__wbg_ptr=e,Kr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Kr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_keysbackuprequest_free(e,0)}get id(){return n.__wbg_get_keysbackuprequest_id(this.__wbg_ptr)}get body(){return n.__wbg_get_keysbackuprequest_body(this.__wbg_ptr)}get version(){return n.__wbg_get_keysbackuprequest_version(this.__wbg_ptr)}constructor(e,t,r){const s=n.keysbackuprequest_new(e,t,r);return this.__wbg_ptr=s>>>0,Kr.register(this,this.__wbg_ptr,this),this}get type(){return n.keysbackuprequest_type(this.__wbg_ptr)}}const Ir=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_keysclaimrequest_free(i>>>0,1));class Te{static __wrap(e){e=e>>>0;const t=Object.create(Te.prototype);return t.__wbg_ptr=e,Ir.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ir.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_keysclaimrequest_free(e,0)}get id(){return n.__wbg_get_keysclaimrequest_id(this.__wbg_ptr)}get body(){return n.__wbg_get_keysclaimrequest_body(this.__wbg_ptr)}constructor(e,t){const r=n.keysclaimrequest_new(e,t);return this.__wbg_ptr=r>>>0,Ir.register(this,this.__wbg_ptr,this),this}get type(){return n.keysclaimrequest_type(this.__wbg_ptr)}}const Cr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_keysqueryrequest_free(i>>>0,1));class we{static __wrap(e){e=e>>>0;const t=Object.create(we.prototype);return t.__wbg_ptr=e,Cr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Cr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_keysqueryrequest_free(e,0)}get id(){return n.__wbg_get_keysqueryrequest_id(this.__wbg_ptr)}get body(){return n.__wbg_get_keysqueryrequest_body(this.__wbg_ptr)}constructor(e,t){const r=n.keysqueryrequest_new(e,t);return this.__wbg_ptr=r>>>0,Cr.register(this,this.__wbg_ptr,this),this}get type(){return n.keysqueryrequest_type(this.__wbg_ptr)}}const Dr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_keysuploadrequest_free(i>>>0,1));class Pe{static __wrap(e){e=e>>>0;const t=Object.create(Pe.prototype);return t.__wbg_ptr=e,Dr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Dr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_keysuploadrequest_free(e,0)}get id(){return n.__wbg_get_keysuploadrequest_id(this.__wbg_ptr)}get body(){return n.__wbg_get_keysuploadrequest_body(this.__wbg_ptr)}constructor(e,t){const r=n.keysuploadrequest_new(e,t);return this.__wbg_ptr=r>>>0,Dr.register(this,this.__wbg_ptr,this),this}get type(){return n.keysuploadrequest_type(this.__wbg_ptr)}}const ri=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_maybesignature_free(i>>>0,1));class ze{static __wrap(e){e=e>>>0;const t=Object.create(ze.prototype);return t.__wbg_ptr=e,ri.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ri.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_maybesignature_free(e,0)}isValid(){return n.maybesignature_isValid(this.__wbg_ptr)!==0}isInvalid(){return n.maybesignature_isInvalid(this.__wbg_ptr)!==0}get signature(){const e=n.maybesignature_signature(this.__wbg_ptr);return e===0?void 0:Yt.__wrap(e)}get invalidSignatureSource(){const e=n.maybesignature_invalidSignatureSource(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}}const ni=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_megolmdecryptionerror_free(i>>>0,1));class Ne{static __wrap(e){e=e>>>0;const t=Object.create(Ne.prototype);return t.__wbg_ptr=e,ni.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ni.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_megolmdecryptionerror_free(e,0)}get code(){return n.__wbg_get_megolmdecryptionerror_code(this.__wbg_ptr)}get description(){return n.__wbg_get_megolmdecryptionerror_description(this.__wbg_ptr)}get maybe_withheld(){return n.__wbg_get_megolmdecryptionerror_maybe_withheld(this.__wbg_ptr)}}const ii=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_megolmv1backupkey_free(i>>>0,1));class zt{static __wrap(e){e=e>>>0;const t=Object.create(zt.prototype);return t.__wbg_ptr=e,ii.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ii.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_megolmv1backupkey_free(e,0)}get publicKeyBase64(){return n.megolmv1backupkey_publicKeyBase64(this.__wbg_ptr)}get algorithm(){return n.megolmv1backupkey_algorithm(this.__wbg_ptr)}}const Ts=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_migration_free(i>>>0,1));class bt{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ts.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_migration_free(e,0)}static migrateBaseData(e,t,r,s){return b(e,br),b(r,j),n.migration_migrateBaseData(e.__wbg_ptr,t,r.__wbg_ptr,v(s)?0:E(s))}static migrateOlmSessions(e,t,r,s){const _=F(e,n.__wbindgen_malloc),o=u;b(r,j);const a=n.migration_migrateOlmSessions(_,o,t,r.__wbg_ptr,v(s)?0:E(s));if(a[2])throw l(a[1]);return l(a[0])}static migrateMegolmSessions(e,t,r,s){const _=F(e,n.__wbindgen_malloc),o=u;b(r,j);const a=n.migration_migrateMegolmSessions(_,o,t,r.__wbg_ptr,v(s)?0:E(s));if(a[2])throw l(a[1]);return l(a[0])}}const Er=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_olmmachine_free(i>>>0,1));class Ae{static __wrap(e){e=e>>>0;const t=Object.create(Ae.prototype);return t.__wbg_ptr=e,Er.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Er.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_olmmachine_free(e,0)}constructor(){const e=n.olmmachine_new();if(e[2])throw l(e[1]);return this.__wbg_ptr=e[0]>>>0,Er.register(this,this.__wbg_ptr,this),this}static initialize(e,t,r,s,_){b(e,h),b(t,C);var o=v(r)?0:p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),a=u,c=v(s)?0:p(s,n.__wbindgen_malloc,n.__wbindgen_realloc),d=u;return n.olmmachine_initialize(e.__wbg_ptr,t.__wbg_ptr,o,a,c,d,v(_)?0:E(_))}static initFromStore(e,t,r,s){return b(e,h),b(t,C),b(r,j),n.olmmachine_initFromStore(e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,v(s)?0:E(s))}get userId(){const e=n.olmmachine_userId(this.__wbg_ptr);return h.__wrap(e)}get deviceId(){const e=n.olmmachine_deviceId(this.__wbg_ptr);return C.__wrap(e)}get deviceCreationTimeMs(){return n.olmmachine_deviceCreationTimeMs(this.__wbg_ptr)}get identityKeys(){const e=n.olmmachine_identityKeys(this.__wbg_ptr);return Ft.__wrap(e)}get displayName(){return n.olmmachine_displayName(this.__wbg_ptr)}get roomKeyRequestsEnabled(){return n.olmmachine_roomKeyRequestsEnabled(this.__wbg_ptr)!==0}set roomKeyRequestsEnabled(e){n.olmmachine_set_roomKeyRequestsEnabled(this.__wbg_ptr,e)}get roomKeyForwardingEnabled(){return n.olmmachine_roomKeyForwardingEnabled(this.__wbg_ptr)!==0}set roomKeyForwardingEnabled(e){n.olmmachine_set_roomKeyForwardingEnabled(this.__wbg_ptr,e)}trackedUsers(){const e=n.olmmachine_trackedUsers(this.__wbg_ptr);if(e[2])throw l(e[1]);return l(e[0])}updateTrackedUsers(e){const t=F(e,n.__wbindgen_malloc),r=u;return n.olmmachine_updateTrackedUsers(this.__wbg_ptr,t,r)}markAllTrackedUsersAsDirty(){return n.olmmachine_markAllTrackedUsersAsDirty(this.__wbg_ptr)}receiveSyncChanges(e,t,r,s,_){const o=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),a=u;b(t,yt);let c=0;v(_)||(b(_,Oe),c=_.__destroy_into_raw());const d=n.olmmachine_receiveSyncChanges(this.__wbg_ptr,o,a,t.__wbg_ptr,r,v(s)?0:E(s),c);if(d[2])throw l(d[1]);return l(d[0])}outgoingRequests(){return n.olmmachine_outgoingRequests(this.__wbg_ptr)}markRequestAsSent(e,t,r){const s=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u,o=p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),a=u,c=n.olmmachine_markRequestAsSent(this.__wbg_ptr,s,_,t,o,a);if(c[2])throw l(c[1]);return l(c[0])}encryptRoomEvent(e,t,r){b(e,R);const s=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u,o=p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),a=u,c=n.olmmachine_encryptRoomEvent(this.__wbg_ptr,e.__wbg_ptr,s,_,o,a);if(c[2])throw l(c[1]);return l(c[0])}encryptStateEvent(e,t,r,s){b(e,R);const _=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),o=u,a=p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),c=u,d=p(s,n.__wbindgen_malloc,n.__wbindgen_realloc),w=u,f=n.olmmachine_encryptStateEvent(this.__wbg_ptr,e.__wbg_ptr,_,o,a,c,d,w);if(f[2])throw l(f[1]);return l(f[0])}decryptRoomEvent(e,t,r){const s=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u;b(t,R),b(r,Oe);const o=n.olmmachine_decryptRoomEvent(this.__wbg_ptr,s,_,t.__wbg_ptr,r.__wbg_ptr);if(o[2])throw l(o[1]);return l(o[0])}getRoomEventEncryptionInfo(e,t){const r=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u;b(t,R);const _=n.olmmachine_getRoomEventEncryptionInfo(this.__wbg_ptr,r,s,t.__wbg_ptr);if(_[2])throw l(_[1]);return l(_[0])}crossSigningStatus(){return n.olmmachine_crossSigningStatus(this.__wbg_ptr)}exportSecretsBundle(){return n.olmmachine_exportSecretsBundle(this.__wbg_ptr)}importSecretsBundle(e){b(e,oe);var t=e.__destroy_into_raw();return n.olmmachine_importSecretsBundle(this.__wbg_ptr,t)}exportCrossSigningKeys(){return n.olmmachine_exportCrossSigningKeys(this.__wbg_ptr)}importCrossSigningKeys(e,t,r){var s=v(e)?0:p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u,o=v(t)?0:p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),a=u,c=v(r)?0:p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),d=u;return n.olmmachine_importCrossSigningKeys(this.__wbg_ptr,s,_,o,a,c,d)}bootstrapCrossSigning(e){return n.olmmachine_bootstrapCrossSigning(this.__wbg_ptr,e)}getIdentity(e){return b(e,h),n.olmmachine_getIdentity(this.__wbg_ptr,e.__wbg_ptr)}sign(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;return n.olmmachine_sign(this.__wbg_ptr,t,r)}invalidateGroupSession(e){return b(e,R),n.olmmachine_invalidateGroupSession(this.__wbg_ptr,e.__wbg_ptr)}shareRoomKey(e,t,r){b(e,R);const s=F(t,n.__wbindgen_malloc),_=u;return b(r,Sr),n.olmmachine_shareRoomKey(this.__wbg_ptr,e.__wbg_ptr,s,_,r.__wbg_ptr)}queryKeysForUsers(e){const t=F(e,n.__wbindgen_malloc),r=u,s=n.olmmachine_queryKeysForUsers(this.__wbg_ptr,t,r);if(s[2])throw l(s[1]);return we.__wrap(s[0])}getMissingSessions(e){const t=F(e,n.__wbindgen_malloc),r=u;return n.olmmachine_getMissingSessions(this.__wbg_ptr,t,r)}getUserDevices(e,t){return b(e,h),n.olmmachine_getUserDevices(this.__wbg_ptr,e.__wbg_ptr,!v(t),v(t)?0:t)}getDevice(e,t,r){return b(e,h),b(t,C),n.olmmachine_getDevice(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,!v(r),v(r)?0:r)}getVerification(e,t){b(e,h);const r=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u,_=n.olmmachine_getVerification(this.__wbg_ptr,e.__wbg_ptr,r,s);if(_[2])throw l(_[1]);return l(_[0])}getVerificationRequest(e,t){b(e,h);const r=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u,_=n.olmmachine_getVerificationRequest(this.__wbg_ptr,e.__wbg_ptr,r,s);return _===0?void 0:fe.__wrap(_)}getVerificationRequests(e){return b(e,h),n.olmmachine_getVerificationRequests(this.__wbg_ptr,e.__wbg_ptr)}receiveVerificationEvent(e,t){const r=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u;b(t,R);const _=n.olmmachine_receiveVerificationEvent(this.__wbg_ptr,r,s,t.__wbg_ptr);if(_[2])throw l(_[1]);return l(_[0])}exportRoomKeys(e){return n.olmmachine_exportRoomKeys(this.__wbg_ptr,e)}importRoomKeys(e,t){const r=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u,_=n.olmmachine_importRoomKeys(this.__wbg_ptr,r,s,t);if(_[2])throw l(_[1]);return l(_[0])}importExportedRoomKeys(e,t){const r=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u,_=n.olmmachine_importExportedRoomKeys(this.__wbg_ptr,r,s,t);if(_[2])throw l(_[1]);return l(_[0])}importBackedUpRoomKeys(e,t,r){const s=p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u,o=n.olmmachine_importBackedUpRoomKeys(this.__wbg_ptr,e,v(t)?0:E(t),s,_);if(o[2])throw l(o[1]);return l(o[0])}saveBackupDecryptionKey(e,t){b(e,V);const r=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u;return n.olmmachine_saveBackupDecryptionKey(this.__wbg_ptr,e.__wbg_ptr,r,s)}getBackupKeys(){return n.olmmachine_getBackupKeys(this.__wbg_ptr)}verifyBackup(e){const t=n.olmmachine_verifyBackup(this.__wbg_ptr,e);if(t[2])throw l(t[1]);return l(t[0])}enableBackupV1(e,t){const r=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u,_=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),o=u,a=n.olmmachine_enableBackupV1(this.__wbg_ptr,r,s,_,o);if(a[2])throw l(a[1]);return l(a[0])}isBackupEnabled(){return n.olmmachine_isBackupEnabled(this.__wbg_ptr)}disableBackup(){return n.olmmachine_disableBackup(this.__wbg_ptr)}backupRoomKeys(){return n.olmmachine_backupRoomKeys(this.__wbg_ptr)}roomKeyCounts(){return n.olmmachine_roomKeyCounts(this.__wbg_ptr)}static encryptExportedRoomKeys(e,t,r){let s,_;try{const c=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),d=u,w=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),f=u,m=n.olmmachine_encryptExportedRoomKeys(c,d,w,f,r);var o=m[0],a=m[1];if(m[3])throw o=0,a=0,l(m[2]);return s=o,_=a,y(o,a)}finally{n.__wbindgen_free(s,_,1)}}static decryptExportedRoomKeys(e,t){let r,s;try{const a=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),c=u,d=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),w=u,f=n.olmmachine_decryptExportedRoomKeys(a,c,d,w);var _=f[0],o=f[1];if(f[3])throw _=0,o=0,l(f[2]);return r=_,s=o,y(_,o)}finally{n.__wbindgen_free(r,s,1)}}registerRoomKeyUpdatedCallback(e){n.olmmachine_registerRoomKeyUpdatedCallback(this.__wbg_ptr,e)}registerRoomKeysWithheldCallback(e){n.olmmachine_registerRoomKeysWithheldCallback(this.__wbg_ptr,e)}registerUserIdentityUpdatedCallback(e){n.olmmachine_registerUserIdentityUpdatedCallback(this.__wbg_ptr,e)}registerDevicesUpdatedCallback(e){n.olmmachine_registerDevicesUpdatedCallback(this.__wbg_ptr,e)}registerReceiveSecretCallback(e){n.olmmachine_registerReceiveSecretCallback(this.__wbg_ptr,e)}getSecretsFromInbox(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;return n.olmmachine_getSecretsFromInbox(this.__wbg_ptr,t,r)}deleteSecretsFromInbox(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;return n.olmmachine_deleteSecretsFromInbox(this.__wbg_ptr,t,r)}requestMissingSecretsIfNeeded(){return n.olmmachine_requestMissingSecretsIfNeeded(this.__wbg_ptr)}getRoomSettings(e){return b(e,R),n.olmmachine_getRoomSettings(this.__wbg_ptr,e.__wbg_ptr)}setRoomSettings(e,t){return b(e,R),b(t,_e),n.olmmachine_setRoomSettings(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr)}dehydratedDevices(){const e=n.olmmachine_dehydratedDevices(this.__wbg_ptr);return Mt.__wrap(e)}buildRoomKeyBundle(e){return b(e,R),n.olmmachine_buildRoomKeyBundle(this.__wbg_ptr,e.__wbg_ptr)}shareRoomKeyBundleData(e,t,r,s,_){b(e,h),b(t,R);const o=p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),a=u;var c=v(s)?0:p(s,n.__wbindgen_malloc,n.__wbindgen_realloc),d=u;b(_,B);var w=_.__destroy_into_raw();const f=n.olmmachine_shareRoomKeyBundleData(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,o,a,c,d,w);if(f[2])throw l(f[1]);return l(f[0])}getReceivedRoomKeyBundleData(e,t){return b(e,R),b(t,h),n.olmmachine_getReceivedRoomKeyBundleData(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr)}receiveRoomKeyBundle(e,t){b(e,Ze);var r=e.__destroy_into_raw();const s=G(t,n.__wbindgen_malloc),_=u,o=n.olmmachine_receiveRoomKeyBundle(this.__wbg_ptr,r,s,_);if(o[2])throw l(o[1]);return l(o[0])}close(){const e=this.__destroy_into_raw();n.olmmachine_close(e)}}const si=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_otheruseridentity_free(i>>>0,1));class je{static __wrap(e){e=e>>>0;const t=Object.create(je.prototype);return t.__wbg_ptr=e,si.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,si.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_otheruseridentity_free(e,0)}isVerified(){return n.otheruseridentity_isVerified(this.__wbg_ptr)!==0}verify(){return n.otheruseridentity_verify(this.__wbg_ptr)}requestVerification(e,t,r){b(e,R),b(t,Rr);var s=v(r)?0:F(r,n.__wbindgen_malloc),_=u;const o=n.otheruseridentity_requestVerification(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,s,_);if(o[2])throw l(o[1]);return fe.__wrap(o[0])}verificationRequestContent(e){let t,r;try{var s=v(e)?0:F(e,n.__wbindgen_malloc),_=u;const c=n.otheruseridentity_verificationRequestContent(this.__wbg_ptr,s,_);var o=c[0],a=c[1];if(c[3])throw o=0,a=0,l(c[2]);return t=o,r=a,y(o,a)}finally{n.__wbindgen_free(t,r,1)}}get masterKey(){let e,t;try{const _=n.otheruseridentity_masterKey(this.__wbg_ptr);var r=_[0],s=_[1];if(_[3])throw r=0,s=0,l(_[2]);return e=r,t=s,y(r,s)}finally{n.__wbindgen_free(e,t,1)}}get selfSigningKey(){let e,t;try{const _=n.otheruseridentity_selfSigningKey(this.__wbg_ptr);var r=_[0],s=_[1];if(_[3])throw r=0,s=0,l(_[2]);return e=r,t=s,y(r,s)}finally{n.__wbindgen_free(e,t,1)}}pinCurrentMasterKey(){return n.otheruseridentity_pinCurrentMasterKey(this.__wbg_ptr)}identityNeedsUserApproval(){return n.otheruseridentity_identityNeedsUserApproval(this.__wbg_ptr)!==0}wasPreviouslyVerified(){return n.otheruseridentity_wasPreviouslyVerified(this.__wbg_ptr)!==0}withdrawVerification(){return n.otheruseridentity_withdrawVerification(this.__wbg_ptr)}hasVerificationViolation(){return n.otheruseridentity_hasVerificationViolation(this.__wbg_ptr)!==0}}const _i=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_outboundcreationresult_free(i>>>0,1));class Nt{static __wrap(e){e=e>>>0;const t=Object.create(Nt.prototype);return t.__wbg_ptr=e,_i.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,_i.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_outboundcreationresult_free(e,0)}get channel(){const e=n.__wbg_get_inboundcreationresult_channel(this.__wbg_ptr);return se.__wrap(e)}set channel(e){b(e,se);var t=e.__destroy_into_raw();n.__wbg_set_inboundcreationresult_channel(this.__wbg_ptr,t)}get initial_message(){let e,t;try{const r=n.__wbg_get_outboundcreationresult_initial_message(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set initial_message(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_key(this.__wbg_ptr,t,r)}}const oi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_ownuseridentity_free(i>>>0,1));class xe{static __wrap(e){e=e>>>0;const t=Object.create(xe.prototype);return t.__wbg_ptr=e,oi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,oi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_ownuseridentity_free(e,0)}isVerified(){return n.ownuseridentity_isVerified(this.__wbg_ptr)!==0}verify(){return n.ownuseridentity_verify(this.__wbg_ptr)}requestVerification(e){var t=v(e)?0:F(e,n.__wbindgen_malloc),r=u;const s=n.ownuseridentity_requestVerification(this.__wbg_ptr,t,r);if(s[2])throw l(s[1]);return l(s[0])}trustsOurOwnDevice(){return n.ownuseridentity_trustsOurOwnDevice(this.__wbg_ptr)}get masterKey(){let e,t;try{const _=n.ownuseridentity_masterKey(this.__wbg_ptr);var r=_[0],s=_[1];if(_[3])throw r=0,s=0,l(_[2]);return e=r,t=s,y(r,s)}finally{n.__wbindgen_free(e,t,1)}}get selfSigningKey(){let e,t;try{const _=n.ownuseridentity_selfSigningKey(this.__wbg_ptr);var r=_[0],s=_[1];if(_[3])throw r=0,s=0,l(_[2]);return e=r,t=s,y(r,s)}finally{n.__wbindgen_free(e,t,1)}}get userSigningKey(){let e,t;try{const _=n.ownuseridentity_userSigningKey(this.__wbg_ptr);var r=_[0],s=_[1];if(_[3])throw r=0,s=0,l(_[2]);return e=r,t=s,y(r,s)}finally{n.__wbindgen_free(e,t,1)}}wasPreviouslyVerified(){return n.ownuseridentity_wasPreviouslyVerified(this.__wbg_ptr)!==0}withdrawVerification(){return n.ownuseridentity_withdrawVerification(this.__wbg_ptr)}hasVerificationViolation(){return n.ownuseridentity_hasVerificationViolation(this.__wbg_ptr)!==0}}const ai=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_pickledinboundgroupsession_free(i>>>0,1));class Le{static __unwrap(e){return e instanceof Le?e.__destroy_into_raw():0}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ai.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_pickledinboundgroupsession_free(e,0)}get pickle(){let e,t;try{const r=n.__wbg_get_pickledinboundgroupsession_pickle(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set pickle(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_key(this.__wbg_ptr,t,r)}get senderKey(){let e,t;try{const r=n.__wbg_get_pickledinboundgroupsession_senderKey(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set senderKey(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_backup_version(this.__wbg_ptr,t,r)}get senderSigningKey(){const e=n.__wbg_get_pickledinboundgroupsession_senderSigningKey(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}set senderSigningKey(e){var t=v(e)?0:p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_basemigrationdata_backupRecoveryKey(this.__wbg_ptr,t,r)}get roomId(){const e=n.__wbg_get_pickledinboundgroupsession_roomId(this.__wbg_ptr);return e===0?void 0:R.__wrap(e)}set roomId(e){let t=0;v(e)||(b(e,R),t=e.__destroy_into_raw()),n.__wbg_set_pickledinboundgroupsession_roomId(this.__wbg_ptr,t)}get imported(){return n.__wbg_get_pickledinboundgroupsession_imported(this.__wbg_ptr)!==0}set imported(e){n.__wbg_set_pickledinboundgroupsession_imported(this.__wbg_ptr,e)}get backedUp(){return n.__wbg_get_pickledinboundgroupsession_backedUp(this.__wbg_ptr)!==0}set backedUp(e){n.__wbg_set_pickledinboundgroupsession_backedUp(this.__wbg_ptr,e)}constructor(){const e=n.pickledinboundgroupsession_new();return this.__wbg_ptr=e>>>0,ai.register(this,this.__wbg_ptr,this),this}}const ci=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_pickledsession_free(i>>>0,1));class We{static __unwrap(e){return e instanceof We?e.__destroy_into_raw():0}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ci.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_pickledsession_free(e,0)}get pickle(){let e,t;try{const r=n.__wbg_get_pickledsession_pickle(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set pickle(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_key(this.__wbg_ptr,t,r)}get senderKey(){let e,t;try{const r=n.__wbg_get_pickledsession_senderKey(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set senderKey(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_backup_version(this.__wbg_ptr,t,r)}get createdUsingFallbackKey(){return n.__wbg_get_pickledsession_createdUsingFallbackKey(this.__wbg_ptr)!==0}set createdUsingFallbackKey(e){n.__wbg_set_pickledsession_createdUsingFallbackKey(this.__wbg_ptr,e)}get creationTime(){return n.__wbg_get_pickledsession_creationTime(this.__wbg_ptr)}set creationTime(e){n.__wbg_set_pickledsession_creationTime(this.__wbg_ptr,e)}get lastUseTime(){return n.__wbg_get_pickledsession_lastUseTime(this.__wbg_ptr)}set lastUseTime(e){n.__wbg_set_pickledsession_lastUseTime(this.__wbg_ptr,e)}constructor(){const e=n.pickledsession_new();return this.__wbg_ptr=e>>>0,ci.register(this,this.__wbg_ptr,this),this}}const Or=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_pkdecryption_free(i>>>0,1));class At{static __wrap(e){e=e>>>0;const t=Object.create(At.prototype);return t.__wbg_ptr=e,Or.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Or.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_pkdecryption_free(e,0)}constructor(){const e=n.pkdecryption_new();return this.__wbg_ptr=e>>>0,Or.register(this,this.__wbg_ptr,this),this}static fromKey(e){b(e,te);const t=n.pkdecryption_fromKey(e.__wbg_ptr);return At.__wrap(t)}secretKey(){const e=n.pkdecryption_secretKey(this.__wbg_ptr);return te.__wrap(e)}publicKey(){const e=n.pkdecryption_publicKey(this.__wbg_ptr);return M.__wrap(e)}decryptString(e){let t,r;try{b(e,Q);const o=n.pkdecryption_decryptString(this.__wbg_ptr,e.__wbg_ptr);var s=o[0],_=o[1];if(o[3])throw s=0,_=0,l(o[2]);return t=s,r=_,y(s,_)}finally{n.__wbindgen_free(t,r,1)}}decrypt(e){b(e,Q);const t=n.pkdecryption_decrypt(this.__wbg_ptr,e.__wbg_ptr);if(t[3])throw l(t[2]);var r=L(t[0],t[1]).slice();return n.__wbindgen_free(t[0],t[1]*1,1),r}}const gi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_pkencryption_free(i>>>0,1));class jt{static __wrap(e){e=e>>>0;const t=Object.create(jt.prototype);return t.__wbg_ptr=e,gi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,gi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_pkencryption_free(e,0)}static fromKey(e){b(e,M);const t=n.pkencryption_fromKey(e.__wbg_ptr);return jt.__wrap(t)}encrypt(e){const t=G(e,n.__wbindgen_malloc),r=u,s=n.pkencryption_encrypt(this.__wbg_ptr,t,r);return Q.__wrap(s)}encryptString(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.pkencryption_encrypt(this.__wbg_ptr,t,r);return Q.__wrap(s)}}const ui=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_pkmessage_free(i>>>0,1));class Q{static __wrap(e){e=e>>>0;const t=Object.create(Q.prototype);return t.__wbg_ptr=e,ui.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ui.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_pkmessage_free(e,0)}ciphertext(){const e=n.pkmessage_ciphertext(this.__wbg_ptr);var t=L(e[0],e[1]).slice();return n.__wbindgen_free(e[0],e[1]*1,1),t}mac(){const e=n.pkmessage_mac(this.__wbg_ptr);var t=L(e[0],e[1]).slice();return n.__wbindgen_free(e[0],e[1]*1,1),t}ephemeralKey(){const e=n.pkmessage_ephemeralKey(this.__wbg_ptr);return M.__wrap(e)}static fromParts(e,t,r){const s=G(e,n.__wbindgen_malloc),_=u,o=G(t,n.__wbindgen_malloc),a=u;b(r,M);const c=n.pkmessage_fromParts(s,_,o,a,r.__wbg_ptr);return Q.__wrap(c)}static fromBase64(e){b(e,Be);const t=n.pkmessage_fromBase64(e.__wbg_ptr);if(t[2])throw l(t[1]);return Q.__wrap(t[0])}toBase64(){const e=n.pkmessage_toBase64(this.__wbg_ptr);return Be.__wrap(e)}}const di=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_plaintexttodeviceevent_free(i>>>0,1));class xt{static __wrap(e){e=e>>>0;const t=Object.create(xt.prototype);return t.__wbg_ptr=e,di.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,di.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_plaintexttodeviceevent_free(e,0)}get rawEvent(){return n.__wbg_get_plaintexttodeviceevent_rawEvent(this.__wbg_ptr)}get type(){return n.plaintexttodeviceevent_type(this.__wbg_ptr)}}const Mr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_putdehydrateddevicerequest_free(i>>>0,1));class Ge{static __wrap(e){e=e>>>0;const t=Object.create(Ge.prototype);return t.__wbg_ptr=e,Mr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Mr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_putdehydrateddevicerequest_free(e,0)}get body(){return n.__wbg_get_putdehydrateddevicerequest_body(this.__wbg_ptr)}constructor(e){const t=n.putdehydrateddevicerequest_new(e);return this.__wbg_ptr=t>>>0,Mr.register(this,this.__wbg_ptr,this),this}}const li=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_qr_free(i>>>0,1));class ye{static __wrap(e){e=e>>>0;const t=Object.create(ye.prototype);return t.__wbg_ptr=e,li.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,li.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_qr_free(e,0)}state(){return n.qr_state(this.__wbg_ptr)}hasBeenScanned(){return n.qr_hasBeenScanned(this.__wbg_ptr)!==0}hasBeenConfirmed(){return n.qr_hasBeenConfirmed(this.__wbg_ptr)!==0}get userId(){const e=n.qr_userId(this.__wbg_ptr);return h.__wrap(e)}get otherUserId(){const e=n.qr_otherUserId(this.__wbg_ptr);return h.__wrap(e)}get otherDeviceId(){const e=n.qr_otherDeviceId(this.__wbg_ptr);return C.__wrap(e)}weStarted(){return n.qr_weStarted(this.__wbg_ptr)!==0}cancelInfo(){const e=n.qr_cancelInfo(this.__wbg_ptr);return e===0?void 0:ue.__wrap(e)}isDone(){return n.qr_isDone(this.__wbg_ptr)!==0}isCancelled(){return n.qr_isCancelled(this.__wbg_ptr)!==0}isSelfVerification(){return n.qr_isSelfVerification(this.__wbg_ptr)!==0}reciprocated(){return n.qr_reciprocated(this.__wbg_ptr)!==0}get flowId(){let e,t;try{const r=n.qr_flowId(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get roomId(){const e=n.qr_roomId(this.__wbg_ptr);return e===0?void 0:R.__wrap(e)}toQrCode(){const e=n.qr_toQrCode(this.__wbg_ptr);if(e[2])throw l(e[1]);return Lt.__wrap(e[0])}toBytes(){const e=n.qr_toBytes(this.__wbg_ptr);if(e[2])throw l(e[1]);return l(e[0])}reciprocate(){const e=n.qr_reciprocate(this.__wbg_ptr);if(e[2])throw l(e[1]);return l(e[0])}confirmScanning(){const e=n.qr_confirmScanning(this.__wbg_ptr);if(e[2])throw l(e[1]);return l(e[0])}cancel(){const e=n.qr_cancel(this.__wbg_ptr);if(e[2])throw l(e[1]);return l(e[0])}cancelWithCode(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.qr_cancelWithCode(this.__wbg_ptr,t,r);if(s[2])throw l(s[1]);return l(s[0])}registerChangesCallback(e){n.qr_registerChangesCallback(this.__wbg_ptr,e)}}const pi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_qrcode_free(i>>>0,1));class Lt{static __wrap(e){e=e>>>0;const t=Object.create(Lt.prototype);return t.__wbg_ptr=e,pi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,pi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_qrcode_free(e,0)}renderIntoBuffer(){const e=n.qrcode_renderIntoBuffer(this.__wbg_ptr);if(e[2])throw l(e[1]);return l(e[0])}}const qr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_qrcodedata_free(i>>>0,1));class Je{static __wrap(e){e=e>>>0;const t=Object.create(Je.prototype);return t.__wbg_ptr=e,qr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,qr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_qrcodedata_free(e,0)}constructor(e,t,r){b(e,M);var s=e.__destroy_into_raw();const _=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),o=u;var a=v(r)?0:p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),c=u;const d=n.qrcodedata_new(s,_,o,a,c);if(d[2])throw l(d[1]);return this.__wbg_ptr=d[0]>>>0,qr.register(this,this.__wbg_ptr,this),this}static fromBytes(e){const t=G(e,n.__wbindgen_malloc),r=u,s=n.qrcodedata_fromBytes(t,r);if(s[2])throw l(s[1]);return Je.__wrap(s[0])}toBytes(){const e=n.qrcodedata_toBytes(this.__wbg_ptr);var t=L(e[0],e[1]).slice();return n.__wbindgen_free(e[0],e[1]*1,1),t}static fromBase64(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.qrcodedata_fromBase64(t,r);if(s[2])throw l(s[1]);return Je.__wrap(s[0])}toBase64(){let e,t;try{const r=n.qrcodedata_toBase64(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get publicKey(){const e=n.qrcodedata_publicKey(this.__wbg_ptr);return M.__wrap(e)}get rendezvousUrl(){let e,t;try{const r=n.qrcodedata_rendezvousUrl(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get serverName(){const e=n.qrcodedata_serverName(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}get mode(){return n.qrcodedata_mode(this.__wbg_ptr)}}const wi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_qrcodescan_free(i>>>0,1));class ve{static __wrap(e){e=e>>>0;const t=Object.create(ve.prototype);return t.__wbg_ptr=e,wi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,wi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_qrcodescan_free(e,0)}static fromBytes(e){const t=n.qrcodescan_fromBytes(e);if(t[2])throw l(t[1]);return ve.__wrap(t[0])}}const yi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_rehydrateddevice_free(i>>>0,1));class Wt{static __wrap(e){e=e>>>0;const t=Object.create(Wt.prototype);return t.__wbg_ptr=e,yi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,yi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_rehydrateddevice_free(e,0)}receiveEvents(e,t){const r=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u;let _=0;return v(t)||(b(t,Oe),_=t.__destroy_into_raw()),n.rehydrateddevice_receiveEvents(this.__wbg_ptr,r,s,_)}}const Br=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_roomid_free(i>>>0,1));class R{static __wrap(e){e=e>>>0;const t=Object.create(R.prototype);return t.__wbg_ptr=e,Br.register(t,t.__wbg_ptr,t),t}static __unwrap(e){return e instanceof R?e.__destroy_into_raw():0}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Br.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_roomid_free(e,0)}constructor(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.roomid_new(t,r);if(s[2])throw l(s[1]);return this.__wbg_ptr=s[0]>>>0,Br.register(this,this.__wbg_ptr,this),this}toString(){let e,t;try{const r=n.roomid_toString(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const bi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_roomkeycounts_free(i>>>0,1));class Gt{static __wrap(e){e=e>>>0;const t=Object.create(Gt.prototype);return t.__wbg_ptr=e,bi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,bi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_roomkeycounts_free(e,0)}get total(){return n.__wbg_get_roomkeycounts_total(this.__wbg_ptr)}set total(e){n.__wbg_set_roomkeycounts_total(this.__wbg_ptr,e)}get backedUp(){return n.__wbg_get_roomkeycounts_backedUp(this.__wbg_ptr)}set backedUp(e){n.__wbg_set_roomkeycounts_backedUp(this.__wbg_ptr,e)}}const hi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_roomkeyimportresult_free(i>>>0,1));class Jt{static __wrap(e){e=e>>>0;const t=Object.create(Jt.prototype);return t.__wbg_ptr=e,hi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,hi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_roomkeyimportresult_free(e,0)}get importedCount(){return n.__wbg_get_roomkeyimportresult_importedCount(this.__wbg_ptr)>>>0}get totalCount(){return n.__wbg_get_roomkeyimportresult_totalCount(this.__wbg_ptr)>>>0}keys(){return n.roomkeyimportresult_keys(this.__wbg_ptr)}}const fi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_roomkeyinfo_free(i>>>0,1));class Qt{static __wrap(e){e=e>>>0;const t=Object.create(Qt.prototype);return t.__wbg_ptr=e,fi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,fi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_roomkeyinfo_free(e,0)}get algorithm(){return n.roomkeyinfo_algorithm(this.__wbg_ptr)}get roomId(){const e=n.roomkeyinfo_roomId(this.__wbg_ptr);return R.__wrap(e)}get senderKey(){const e=n.roomkeyinfo_senderKey(this.__wbg_ptr);return M.__wrap(e)}get sessionId(){let e,t;try{const r=n.roomkeyinfo_sessionId(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const vi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_roomkeywithheldinfo_free(i>>>0,1));class Ht{static __wrap(e){e=e>>>0;const t=Object.create(Ht.prototype);return t.__wbg_ptr=e,vi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,vi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_roomkeywithheldinfo_free(e,0)}get sender(){const e=n.roomkeywithheldinfo_sender(this.__wbg_ptr);return h.__wrap(e)}get algorithm(){return n.roomkeywithheldinfo_algorithm(this.__wbg_ptr)}get withheldCode(){let e,t;try{const r=n.roomkeywithheldinfo_withheldCode(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get roomId(){const e=n.roomkeywithheldinfo_roomId(this.__wbg_ptr);return R.__wrap(e)}get sessionId(){let e,t;try{const r=n.roomkeywithheldinfo_sessionId(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const Ur=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_roommessagerequest_free(i>>>0,1));class Qe{static __wrap(e){e=e>>>0;const t=Object.create(Qe.prototype);return t.__wbg_ptr=e,Ur.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ur.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_roommessagerequest_free(e,0)}get id(){return n.__wbg_get_roommessagerequest_id(this.__wbg_ptr)}get room_id(){return n.__wbg_get_roommessagerequest_room_id(this.__wbg_ptr)}get txn_id(){return n.__wbg_get_roommessagerequest_txn_id(this.__wbg_ptr)}get event_type(){return n.__wbg_get_roommessagerequest_event_type(this.__wbg_ptr)}get body(){return n.__wbg_get_roommessagerequest_body(this.__wbg_ptr)}constructor(e,t,r,s,_){const o=n.roommessagerequest_new(e,t,r,s,_);return this.__wbg_ptr=o>>>0,Ur.register(this,this.__wbg_ptr,this),this}get type(){return n.roommessagerequest_type(this.__wbg_ptr)}}const Fr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_roomsettings_free(i>>>0,1));class _e{static __wrap(e){e=e>>>0;const t=Object.create(_e.prototype);return t.__wbg_ptr=e,Fr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Fr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_roomsettings_free(e,0)}get algorithm(){return n.__wbg_get_roomsettings_algorithm(this.__wbg_ptr)}set algorithm(e){n.__wbg_set_roomsettings_algorithm(this.__wbg_ptr,e)}get encryptStateEvents(){return n.__wbg_get_roomsettings_encryptStateEvents(this.__wbg_ptr)!==0}set encryptStateEvents(e){n.__wbg_set_roomsettings_encryptStateEvents(this.__wbg_ptr,e)}get onlyAllowTrustedDevices(){return n.__wbg_get_roomsettings_onlyAllowTrustedDevices(this.__wbg_ptr)!==0}set onlyAllowTrustedDevices(e){n.__wbg_set_roomsettings_onlyAllowTrustedDevices(this.__wbg_ptr,e)}get sessionRotationPeriodMs(){const e=n.__wbg_get_roomsettings_sessionRotationPeriodMs(this.__wbg_ptr);return e[0]===0?void 0:e[1]}set sessionRotationPeriodMs(e){n.__wbg_set_roomsettings_sessionRotationPeriodMs(this.__wbg_ptr,!v(e),v(e)?0:e)}get sessionRotationPeriodMessages(){const e=n.__wbg_get_roomsettings_sessionRotationPeriodMessages(this.__wbg_ptr);return e[0]===0?void 0:e[1]}set sessionRotationPeriodMessages(e){n.__wbg_set_roomsettings_sessionRotationPeriodMessages(this.__wbg_ptr,!v(e),v(e)?0:e)}constructor(){const e=n.roomsettings_new();return this.__wbg_ptr=e>>>0,Fr.register(this,this.__wbg_ptr,this),this}}const mi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_sas_free(i>>>0,1));class be{static __wrap(e){e=e>>>0;const t=Object.create(be.prototype);return t.__wbg_ptr=e,mi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,mi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_sas_free(e,0)}get userId(){const e=n.sas_userId(this.__wbg_ptr);return h.__wrap(e)}get deviceId(){const e=n.sas_deviceId(this.__wbg_ptr);return C.__wrap(e)}get otherUserId(){const e=n.sas_otherUserId(this.__wbg_ptr);return h.__wrap(e)}get otherDeviceId(){const e=n.sas_otherDeviceId(this.__wbg_ptr);return C.__wrap(e)}get flowId(){let e,t;try{const r=n.sas_flowId(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get roomId(){const e=n.sas_roomId(this.__wbg_ptr);return e===0?void 0:R.__wrap(e)}supportsEmoji(){return n.sas_supportsEmoji(this.__wbg_ptr)!==0}startedFromRequest(){return n.sas_startedFromRequest(this.__wbg_ptr)!==0}isSelfVerification(){return n.sas_isSelfVerification(this.__wbg_ptr)!==0}haveWeConfirmed(){return n.sas_haveWeConfirmed(this.__wbg_ptr)!==0}hasBeenAccepted(){return n.sas_hasBeenAccepted(this.__wbg_ptr)!==0}cancelInfo(){const e=n.sas_cancelInfo(this.__wbg_ptr);return e===0?void 0:ue.__wrap(e)}weStarted(){return n.sas_weStarted(this.__wbg_ptr)!==0}accept(){const e=n.sas_accept(this.__wbg_ptr);if(e[2])throw l(e[1]);return l(e[0])}confirm(){return n.sas_confirm(this.__wbg_ptr)}cancel(){const e=n.sas_cancel(this.__wbg_ptr);if(e[2])throw l(e[1]);return l(e[0])}cancelWithCode(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.sas_cancelWithCode(this.__wbg_ptr,t,r);if(s[2])throw l(s[1]);return l(s[0])}timedOut(){return n.sas_timedOut(this.__wbg_ptr)!==0}canBePresented(){return n.sas_canBePresented(this.__wbg_ptr)!==0}isDone(){return n.sas_isDone(this.__wbg_ptr)!==0}isCancelled(){return n.sas_isCancelled(this.__wbg_ptr)!==0}emoji(){const e=n.sas_emoji(this.__wbg_ptr);let t;return e[0]!==0&&(t=Ie(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*4,4)),t}emojiIndex(){const e=n.sas_emojiIndex(this.__wbg_ptr);let t;return e[0]!==0&&(t=L(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}decimals(){const e=n.sas_decimals(this.__wbg_ptr);let t;return e[0]!==0&&(t=hs(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*2,2)),t}registerChangesCallback(e){n.sas_registerChangesCallback(this.__wbg_ptr,e)}}const ki=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_secretsbundle_free(i>>>0,1));class oe{static __wrap(e){e=e>>>0;const t=Object.create(oe.prototype);return t.__wbg_ptr=e,ki.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ki.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_secretsbundle_free(e,0)}get masterKey(){let e,t;try{const r=n.secretsbundle_masterKey(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get selfSigningKey(){let e,t;try{const r=n.secretsbundle_selfSigningKey(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get userSigningKey(){let e,t;try{const r=n.secretsbundle_userSigningKey(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get backupBundle(){const e=n.secretsbundle_backupBundle(this.__wbg_ptr);return e===0?void 0:St.__wrap(e)}to_json(){const e=n.secretsbundle_to_json(this.__wbg_ptr);if(e[2])throw l(e[1]);return l(e[0])}static from_json(e){const t=n.secretsbundle_from_json(e);if(t[2])throw l(t[1]);return oe.__wrap(t[0])}}const Vr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_servername_free(i>>>0,1));class He{static __wrap(e){e=e>>>0;const t=Object.create(He.prototype);return t.__wbg_ptr=e,Vr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Vr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_servername_free(e,0)}constructor(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.servername_new(t,r);if(s[2])throw l(s[1]);return this.__wbg_ptr=s[0]>>>0,Vr.register(this,this.__wbg_ptr,this),this}get host(){let e,t;try{const r=n.servername_host(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get port(){const e=n.servername_port(this.__wbg_ptr);return e===16777215?void 0:e}isIpLiteral(){return n.servername_isIpLiteral(this.__wbg_ptr)!==0}}const Si=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_shieldstate_free(i>>>0,1));class Ye{static __wrap(e){e=e>>>0;const t=Object.create(Ye.prototype);return t.__wbg_ptr=e,Si.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Si.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_shieldstate_free(e,0)}get color(){return n.__wbg_get_shieldstate_color(this.__wbg_ptr)}set color(e){n.__wbg_set_shieldstate_color(this.__wbg_ptr,e)}get code(){const e=n.__wbg_get_shieldstate_code(this.__wbg_ptr);return e===7?void 0:e}set code(e){n.__wbg_set_shieldstate_code(this.__wbg_ptr,v(e)?7:e)}get message(){const e=n.shieldstate_message(this.__wbg_ptr);let t;return e[0]!==0&&(t=y(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*1,1)),t}}const Ri=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_signature_free(i>>>0,1));class Yt{static __wrap(e){e=e>>>0;const t=Object.create(Yt.prototype);return t.__wbg_ptr=e,Ri.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ri.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_signature_free(e,0)}get ed25519(){const e=n.signature_ed25519(this.__wbg_ptr);return e===0?void 0:le.__wrap(e)}toBase64(){let e,t;try{const r=n.signature_toBase64(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const Tr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_signatureuploadrequest_free(i>>>0,1));class he{static __wrap(e){e=e>>>0;const t=Object.create(he.prototype);return t.__wbg_ptr=e,Tr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Tr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_signatureuploadrequest_free(e,0)}get id(){return n.__wbg_get_signatureuploadrequest_id(this.__wbg_ptr)}get body(){return n.__wbg_get_signatureuploadrequest_body(this.__wbg_ptr)}constructor(e,t){const r=n.signatureuploadrequest_new(e,t);return this.__wbg_ptr=r>>>0,Tr.register(this,this.__wbg_ptr,this),this}get type(){return n.signatureuploadrequest_type(this.__wbg_ptr)}}const Ki=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_signatureverification_free(i>>>0,1));class $t{static __wrap(e){e=e>>>0;const t=Object.create($t.prototype);return t.__wbg_ptr=e,Ki.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ki.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_signatureverification_free(e,0)}get deviceState(){return n.signatureverification_deviceState(this.__wbg_ptr)}get userState(){return n.signatureverification_userState(this.__wbg_ptr)}trusted(){return n.signatureverification_trusted(this.__wbg_ptr)!==0}}const Pr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_signatures_free(i>>>0,1));class $e{static __wrap(e){e=e>>>0;const t=Object.create($e.prototype);return t.__wbg_ptr=e,Pr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Pr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_signatures_free(e,0)}constructor(){const e=n.signatures_new();return this.__wbg_ptr=e>>>0,Pr.register(this,this.__wbg_ptr,this),this}addSignature(e,t,r){b(e,h),b(t,de),b(r,le);const s=n.signatures_addSignature(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr);return s===0?void 0:ze.__wrap(s)}getSignature(e,t){b(e,h),b(t,de);const r=n.signatures_getSignature(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr);return r===0?void 0:le.__wrap(r)}get(e){return b(e,h),n.signatures_get(this.__wbg_ptr,e.__wbg_ptr)}clear(){n.signatures_clear(this.__wbg_ptr)}isEmpty(){return n.signatures_isEmpty(this.__wbg_ptr)!==0}get count(){return n.signatures_count(this.__wbg_ptr)>>>0}asJSON(){const e=n.signatures_asJSON(this.__wbg_ptr);if(e[2])throw l(e[1]);return l(e[0])}}const Ii=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_storehandle_free(i>>>0,1));class j{static __wrap(e){e=e>>>0;const t=Object.create(j.prototype);return t.__wbg_ptr=e,Ii.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ii.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_storehandle_free(e,0)}static open(e,t,r){var s=v(e)?0:p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u,o=v(t)?0:p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),a=u;return n.storehandle_open(s,_,o,a,v(r)?0:E(r))}static openWithKey(e,t,r){const s=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u,o=G(t,n.__wbindgen_malloc),a=u;return n.storehandle_openWithKey(s,_,o,a,v(r)?0:E(r))}}const Ci=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_storedroomkeybundledata_free(i>>>0,1));class Ze{static __wrap(e){e=e>>>0;const t=Object.create(Ze.prototype);return t.__wbg_ptr=e,Ci.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ci.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_storedroomkeybundledata_free(e,0)}get senderUser(){const e=n.storedroomkeybundledata_senderUser(this.__wbg_ptr);return h.__wrap(e)}get roomId(){const e=n.storedroomkeybundledata_roomId(this.__wbg_ptr);return R.__wrap(e)}get url(){let e,t;try{const r=n.storedroomkeybundledata_url(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get encryptionInfo(){let e,t;try{const r=n.storedroomkeybundledata_encryptionInfo(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}}const Di=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_todeviceencryptioninfo_free(i>>>0,1));class Zt{static __wrap(e){e=e>>>0;const t=Object.create(Zt.prototype);return t.__wbg_ptr=e,Di.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Di.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_todeviceencryptioninfo_free(e,0)}get senderCurve25519Key(){let e,t;try{const r=n.__wbg_get_todeviceencryptioninfo_senderCurve25519Key(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}set senderCurve25519Key(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.__wbg_set_backupsecretsbundle_key(this.__wbg_ptr,t,r)}get sender(){const e=n.__wbg_get_todeviceencryptioninfo_sender(this.__wbg_ptr);return h.__wrap(e)}set sender(e){b(e,h);var t=e.__destroy_into_raw();n.__wbg_set_todeviceencryptioninfo_sender(this.__wbg_ptr,t)}get senderDevice(){const e=n.__wbg_get_todeviceencryptioninfo_senderDevice(this.__wbg_ptr);return e===0?void 0:C.__wrap(e)}set senderDevice(e){let t=0;v(e)||(b(e,C),t=e.__destroy_into_raw()),n.__wbg_set_todeviceencryptioninfo_senderDevice(this.__wbg_ptr,t)}isSenderVerified(){return n.todeviceencryptioninfo_isSenderVerified(this.__wbg_ptr)!==0}}const zr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_todevicerequest_free(i>>>0,1));class Xe{static __wrap(e){e=e>>>0;const t=Object.create(Xe.prototype);return t.__wbg_ptr=e,zr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,zr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_todevicerequest_free(e,0)}get id(){return n.__wbg_get_todevicerequest_id(this.__wbg_ptr)}get event_type(){return n.__wbg_get_todevicerequest_event_type(this.__wbg_ptr)}get txn_id(){return n.__wbg_get_todevicerequest_txn_id(this.__wbg_ptr)}get body(){return n.__wbg_get_todevicerequest_body(this.__wbg_ptr)}constructor(e,t,r,s){const _=n.todevicerequest_new(e,t,r,s);return this.__wbg_ptr=_>>>0,zr.register(this,this.__wbg_ptr,this),this}get type(){return n.todevicerequest_type(this.__wbg_ptr)}}const Ei=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_todeviceunabletodecryptinfo_free(i>>>0,1));class Xt{static __wrap(e){e=e>>>0;const t=Object.create(Xt.prototype);return t.__wbg_ptr=e,Ei.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ei.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_todeviceunabletodecryptinfo_free(e,0)}get reason(){return n.__wbg_get_todeviceunabletodecryptinfo_reason(this.__wbg_ptr)}set reason(e){n.__wbg_set_todeviceunabletodecryptinfo_reason(this.__wbg_ptr,e)}}const Oi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_tracing_free(i>>>0,1));class Ps{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Oi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_tracing_free(e,0)}static isAvailable(){return n.tracing_isAvailable()!==0}constructor(e){const t=n.tracing_new(e);if(t[2])throw l(t[1]);return this.__wbg_ptr=t[0]>>>0,Oi.register(this,this.__wbg_ptr,this),this}set minLevel(e){const t=n.tracing_set_minLevel(this.__wbg_ptr,e);if(t[1])throw l(t[0])}turnOn(){const e=n.tracing_turnOn(this.__wbg_ptr);if(e[1])throw l(e[0])}turnOff(){const e=n.tracing_turnOff(this.__wbg_ptr);if(e[1])throw l(e[0])}}const Mi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_utdtodeviceevent_free(i>>>0,1));class er{static __wrap(e){e=e>>>0;const t=Object.create(er.prototype);return t.__wbg_ptr=e,Mi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Mi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_utdtodeviceevent_free(e,0)}get rawEvent(){return n.__wbg_get_utdtodeviceevent_rawEvent(this.__wbg_ptr)}get utdInfo(){const e=n.__wbg_get_utdtodeviceevent_utdInfo(this.__wbg_ptr);return Xt.__wrap(e)}get type(){return n.utdtodeviceevent_type(this.__wbg_ptr)}}const Nr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_uploadsigningkeysrequest_free(i>>>0,1));class et{static __wrap(e){e=e>>>0;const t=Object.create(et.prototype);return t.__wbg_ptr=e,Nr.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Nr.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_uploadsigningkeysrequest_free(e,0)}get body(){return n.__wbg_get_uploadsigningkeysrequest_body(this.__wbg_ptr)}constructor(e){const t=n.uploadsigningkeysrequest_new(e);return this.__wbg_ptr=t>>>0,Nr.register(this,this.__wbg_ptr,this),this}}const qi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_userdevices_free(i>>>0,1));class tr{static __wrap(e){e=e>>>0;const t=Object.create(tr.prototype);return t.__wbg_ptr=e,qi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,qi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_userdevices_free(e,0)}get(e){b(e,C);const t=n.userdevices_get(this.__wbg_ptr,e.__wbg_ptr);return t===0?void 0:Ue.__wrap(t)}isAnyVerified(){return n.userdevices_isAnyVerified(this.__wbg_ptr)!==0}keys(){return n.userdevices_keys(this.__wbg_ptr)}devices(){return n.userdevices_devices(this.__wbg_ptr)}}const Ar=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_userid_free(i>>>0,1));class h{static __wrap(e){e=e>>>0;const t=Object.create(h.prototype);return t.__wbg_ptr=e,Ar.register(t,t.__wbg_ptr,t),t}static __unwrap(e){return e instanceof h?e.__destroy_into_raw():0}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ar.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_userid_free(e,0)}constructor(e){const t=p(e,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,s=n.userid_new(t,r);if(s[2])throw l(s[1]);return this.__wbg_ptr=s[0]>>>0,Ar.register(this,this.__wbg_ptr,this),this}get localpart(){let e,t;try{const r=n.userid_localpart(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}get serverName(){const e=n.userid_serverName(this.__wbg_ptr);return He.__wrap(e)}isHistorical(){return n.userid_isHistorical(this.__wbg_ptr)!==0}toString(){let e,t;try{const r=n.userid_toString(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}clone(){const e=n.userid_clone(this.__wbg_ptr);return h.__wrap(e)}}const Bi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_verificationrequest_free(i>>>0,1));class fe{static __wrap(e){e=e>>>0;const t=Object.create(fe.prototype);return t.__wbg_ptr=e,Bi.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Bi.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_verificationrequest_free(e,0)}static request(e,t,r,s){let _,o;try{b(e,h),b(t,C),b(r,h);var a=v(s)?0:F(s,n.__wbindgen_malloc),c=u;const f=n.verificationrequest_request(e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,a,c);var d=f[0],w=f[1];if(f[3])throw d=0,w=0,l(f[2]);return _=d,o=w,y(d,w)}finally{n.__wbindgen_free(_,o,1)}}get ownUserId(){const e=n.verificationrequest_ownUserId(this.__wbg_ptr);return h.__wrap(e)}get otherUserId(){const e=n.verificationrequest_otherUserId(this.__wbg_ptr);return h.__wrap(e)}get otherDeviceId(){const e=n.verificationrequest_otherDeviceId(this.__wbg_ptr);return e===0?void 0:C.__wrap(e)}get roomId(){const e=n.verificationrequest_roomId(this.__wbg_ptr);return e===0?void 0:R.__wrap(e)}get cancelInfo(){const e=n.verificationrequest_cancelInfo(this.__wbg_ptr);return e===0?void 0:ue.__wrap(e)}isPassive(){return n.verificationrequest_isPassive(this.__wbg_ptr)!==0}isReady(){return n.verificationrequest_isReady(this.__wbg_ptr)!==0}timedOut(){return n.verificationrequest_timedOut(this.__wbg_ptr)!==0}timeRemainingMillis(){return n.verificationrequest_timeRemainingMillis(this.__wbg_ptr)}get theirSupportedMethods(){const e=n.verificationrequest_theirSupportedMethods(this.__wbg_ptr);if(e[3])throw l(e[2]);let t;return e[0]!==0&&(t=Ie(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*4,4)),t}get ourSupportedMethods(){const e=n.verificationrequest_ourSupportedMethods(this.__wbg_ptr);if(e[3])throw l(e[2]);let t;return e[0]!==0&&(t=Ie(e[0],e[1]).slice(),n.__wbindgen_free(e[0],e[1]*4,4)),t}get flowId(){let e,t;try{const r=n.verificationrequest_flowId(this.__wbg_ptr);return e=r[0],t=r[1],y(r[0],r[1])}finally{n.__wbindgen_free(e,t,1)}}isSelfVerification(){return n.verificationrequest_isSelfVerification(this.__wbg_ptr)!==0}weStarted(){return n.verificationrequest_weStarted(this.__wbg_ptr)!==0}isDone(){return n.verificationrequest_isDone(this.__wbg_ptr)!==0}phase(){return n.verificationrequest_phase(this.__wbg_ptr)}getVerification(){return n.verificationrequest_getVerification(this.__wbg_ptr)}registerChangesCallback(e){n.verificationrequest_registerChangesCallback(this.__wbg_ptr,e)}isCancelled(){return n.verificationrequest_isCancelled(this.__wbg_ptr)!==0}acceptWithMethods(e){const t=F(e,n.__wbindgen_malloc),r=u,s=n.verificationrequest_acceptWithMethods(this.__wbg_ptr,t,r);if(s[2])throw l(s[1]);return l(s[0])}accept(){const e=n.verificationrequest_accept(this.__wbg_ptr);if(e[2])throw l(e[1]);return l(e[0])}cancel(){const e=n.verificationrequest_cancel(this.__wbg_ptr);if(e[2])throw l(e[1]);return l(e[0])}startSas(){return n.verificationrequest_startSas(this.__wbg_ptr)}generateQrCode(){return n.verificationrequest_generateQrCode(this.__wbg_ptr)}scanQrCode(e){return b(e,ve),n.verificationrequest_scanQrCode(this.__wbg_ptr,e.__wbg_ptr)}}const Ui=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>n.__wbg_versions_free(i>>>0,1));class rr{static __wrap(e){e=e>>>0;const t=Object.create(rr.prototype);return t.__wbg_ptr=e,Ui.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ui.unregister(this),e}free(){const e=this.__destroy_into_raw();n.__wbg_versions_free(e,0)}get vodozemac(){return n.__wbg_get_versions_vodozemac(this.__wbg_ptr)}get matrix_sdk_crypto(){return n.__wbg_get_versions_matrix_sdk_crypto(this.__wbg_ptr)}get git_sha(){return n.__wbg_get_versions_git_sha(this.__wbg_ptr)}get git_description(){return n.__wbg_get_versions_git_description(this.__wbg_ptr)}}function zs(i,e){return Error(y(i,e))}function Ns(i,e){const t=String(e),r=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u;O().setInt32(i+4*1,s,!0),O().setInt32(i+4*0,r,!0)}function As(i){return i.Window}function js(i){return i.WorkerGlobalScope}function xs(){return S(function(i,e,t){return i.add(e,t)},arguments)}function Ls(i,e){return i.add(e)}function Ws(i,e){return i.at(e)}function Gs(i){return kt.__wrap(i)}function Js(){return S(function(i,e){return IDBKeyRange.bound(i,e)},arguments)}function Qs(){return S(function(i,e,t,r){return IDBKeyRange.bound(i,e,t!==0,r!==0)},arguments)}function Hs(i){return i.buffer}function Ys(){return S(function(i,e,t,r){return i.call(e,t,r)},arguments)}function $s(){return S(function(i,e,t,r,s){return i.call(e,t,r,s)},arguments)}function Zs(){return S(function(i,e,t){return i.call(e,t)},arguments)}function Xs(){return S(function(i,e){return i.call(e)},arguments)}function e_(i){return clearTimeout(i)}function t_(){return S(function(i){return i.clear()},arguments)}function r_(i){i.close()}function n_(i){return i.code}function i_(){return S(function(i){i.continue()},arguments)}function s_(){return S(function(i){return i.count()},arguments)}function __(){return S(function(i){return i.count()},arguments)}function o_(){return S(function(i,e,t,r){return i.createIndex(y(e,t),r)},arguments)}function a_(){return S(function(i,e,t,r,s){return i.createIndex(y(e,t),r,s)},arguments)}function c_(){return S(function(i,e,t){return i.createObjectStore(y(e,t))},arguments)}function g_(i){return Kt.__wrap(i)}function u_(i){return It.__wrap(i)}function d_(i){return Ct.__wrap(i)}function l_(i){return i.crypto}function p_(i){console.debug(i)}function w_(i,e){i.debug(e)}function y_(i){return Dt.__wrap(i)}function b_(i){return Et.__wrap(i)}function h_(i){return Ot.__wrap(i)}function f_(i){return x.__wrap(i)}function v_(){return S(function(i,e,t){i.deleteObjectStore(y(e,t))},arguments)}function m_(){return S(function(i){return i.delete()},arguments)}function k_(){return S(function(i,e){return i.delete(e)},arguments)}function S_(i){return Ue.__wrap(i)}function R_(i){return C.__wrap(i)}function K_(i){return Fe.__wrap(i)}function I_(i){return de.__wrap(i)}function C_(i){return i.done}function D_(i){return Bt.__wrap(i)}function E_(i){return pe.__wrap(i)}function O_(i){return Ut.__wrap(i)}function M_(i){return Object.entries(i)}function q_(i){return i.entries()}function B_(i,e){i.error(e)}function U_(){return S(function(i){const e=i.error;return v(e)?0:E(e)},arguments)}function F_(i){console.error(i)}function V_(i,e){let t,r;try{t=i,r=e,console.error(y(i,e))}finally{n.__wbindgen_free(t,r,1)}}function T_(i){return Array.from(i)}function P_(){return S(function(i){return i.getAllKeys()},arguments)}function z_(){return S(function(i){return i.getAll()},arguments)}function N_(){return S(function(i,e,t){return i.getAll(e,t>>>0)},arguments)}function A_(){return S(function(i,e){return i.getAll(e)},arguments)}function j_(){return S(function(i,e){globalThis.crypto.getRandomValues(L(i,e))},arguments)}function x_(){return S(function(i,e){i.getRandomValues(e)},arguments)}function L_(i){return i.getTime()}function W_(){return S(function(i,e){return Reflect.get(i,e)},arguments)}function G_(i,e){return i[e>>>0]}function J_(){return S(function(i,e){return i.get(e)},arguments)}function Q_(){return S(function(i,e){return i.get(e)},arguments)}function H_(i,e){return i[e]}function Y_(i){return i.global}function $_(i){return Tt.__wrap(i)}function Z_(){return S(function(i,e,t){return i.index(y(e,t))},arguments)}function X_(){return S(function(i){const e=i.indexedDB;return v(e)?0:E(e)},arguments)}function eo(){return S(function(i){const e=i.indexedDB;return v(e)?0:E(e)},arguments)}function to(){return S(function(i){const e=i.indexedDB;return v(e)?0:E(e)},arguments)}function ro(i){console.info(i)}function no(i,e){i.info(e)}function io(i){let e;try{e=i instanceof ArrayBuffer}catch{e=!1}return e}function so(i){let e;try{e=i instanceof Map}catch{e=!1}return e}function _o(i){let e;try{e=i instanceof Promise}catch{e=!1}return e}function oo(i){let e;try{e=i instanceof Uint8Array}catch{e=!1}return e}function ao(i){return Pt.__wrap(i)}function co(i){return Array.isArray(i)}function go(i){return Array.isArray(i)}function uo(i){return Number.isSafeInteger(i)}function lo(i,e,t){const r=e.item(t>>>0);var s=v(r)?0:p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u;O().setInt32(i+4*1,_,!0),O().setInt32(i+4*0,s,!0)}function po(){return Symbol.iterator}function wo(){return S(function(i){return i.key},arguments)}function yo(i){return Ve.__wrap(i)}function bo(i){return Te.__wrap(i)}function ho(i){return we.__wrap(i)}function fo(i){return Pe.__wrap(i)}function vo(i){return i.length}function mo(i){return i.length}function ko(i){return i.length}function So(){return S(function(i,e){return IDBKeyRange.lowerBound(i,e!==0)},arguments)}function Ro(i){return ze.__wrap(i)}function Ko(i){return Ne.__wrap(i)}function Io(i,e){const t=e.message,r=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u;O().setInt32(i+4*1,s,!0),O().setInt32(i+4*0,r,!0)}function Co(i){return i.msCrypto}function Do(i,e){const t=e.name,r=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u;O().setInt32(i+4*1,s,!0),O().setInt32(i+4*0,r,!0)}function Eo(){return new Object}function Oo(){return new Array}function Mo(){return new Error}function qo(i){return new Date(i)}function Bo(){return new Map}function Uo(i){return new Uint8ClampedArray(i)}function Fo(i){return new Set(i)}function Vo(i,e){try{var t={a:i,b:e},r=(s,_)=>{const o=t.a;t.a=0;try{return Ks(o,t.b,s,_)}finally{t.a=o}};return new Promise(r)}finally{t.a=t.b=0}}function To(i){return new Uint8Array(i)}function Po(i,e){return new Function(y(i,e))}function zo(i,e,t){return new Uint8ClampedArray(i,e>>>0,t>>>0)}function No(i,e,t){return new Uint8Array(i,e>>>0,t>>>0)}function Ao(i){return new Uint8Array(i>>>0)}function jo(i){return new Uint8ClampedArray(i>>>0)}function xo(){return S(function(i,e){return new DOMException(y(i,e))},arguments)}function Lo(i){return i.next}function Wo(){return S(function(i){return i.next()},arguments)}function Go(i){return i.node}function Jo(i){return i.now()}function Qo(){return Date.now()}function Ho(i){return i.objectStoreNames}function Yo(){return S(function(i,e,t){return i.objectStore(y(e,t))},arguments)}function $o(i){return i.oldVersion}function Zo(i){return Ae.__wrap(i)}function Xo(){return S(function(i){return i.openCursor()},arguments)}function ea(){return S(function(i,e){return i.openCursor(e)},arguments)}function ta(){return S(function(i){return i.openCursor()},arguments)}function ra(){return S(function(i,e,t,r){return i.open(y(e,t),r>>>0)},arguments)}function na(){return S(function(i,e,t){return i.open(y(e,t))},arguments)}function ia(i){return je.__wrap(i)}function sa(i){return xe.__wrap(i)}function _a(){return S(function(i,e){return JSON.parse(y(i,e))},arguments)}function oa(i){return i.performance}function aa(i){return Le.__unwrap(i)}function ca(i){return We.__unwrap(i)}function ga(i){return xt.__wrap(i)}function ua(i){return i.process}function da(i,e){return i.push(e)}function la(){return S(function(i,e,t){return i.put(e,t)},arguments)}function pa(i){return Ge.__wrap(i)}function wa(i){return ye.__wrap(i)}function ya(i){queueMicrotask(i)}function ba(i){return i.queueMicrotask}function ha(){return S(function(i,e){i.randomFillSync(e)},arguments)}function fa(i){const e=i.readyState;return(Bs.indexOf(e)+1||3)-1}function va(i){return Wt.__wrap(i)}function ma(){return S(function(){return module.require},arguments)}function ka(i){return Promise.resolve(i)}function Sa(){return S(function(i){return i.result},arguments)}function Ra(i){return R.__unwrap(i)}function Ka(i){return Gt.__wrap(i)}function Ia(i){return Jt.__wrap(i)}function Ca(i){return Qt.__wrap(i)}function Da(i){return Ht.__wrap(i)}function Ea(i){return Qe.__wrap(i)}function Oa(i){return _e.__wrap(i)}function Ma(i){return be.__wrap(i)}function qa(i){return oe.__wrap(i)}function Ba(){return S(function(i,e){return setTimeout(i,e)},arguments)}function Ua(i,e,t){i[e]=t}function Fa(i,e,t){i[e>>>0]=t}function Va(i,e,t){return i.set(e,t)}function Ta(i,e,t){i.set(e,t>>>0)}function Pa(i,e,t){i.set(e,t>>>0)}function za(i,e){i.onabort=e}function Na(i,e){i.onblocked=e}function Aa(i,e){i.oncomplete=e}function ja(i,e){i.onerror=e}function xa(i,e){i.onerror=e}function La(i,e){i.onsuccess=e}function Wa(i,e){i.onupgradeneeded=e}function Ga(i,e){i.onversionchange=e}function Ja(i,e){i.unique=e!==0}function Qa(i){return $e.__wrap(i)}function Ha(i){return he.__wrap(i)}function Ya(i){return $t.__wrap(i)}function $a(i,e){const t=e.stack,r=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u;O().setInt32(i+4*1,s,!0),O().setInt32(i+4*0,r,!0)}function Za(){const i=typeof global>"u"?null:global;return v(i)?0:E(i)}function Xa(){const i=typeof globalThis>"u"?null:globalThis;return v(i)?0:E(i)}function ec(){const i=typeof self>"u"?null:self;return v(i)?0:E(i)}function tc(){const i=typeof window>"u"?null:window;return v(i)?0:E(i)}function rc(i){return Ze.__wrap(i)}function nc(i){return j.__wrap(i)}function ic(){return S(function(i){return JSON.stringify(i)},arguments)}function sc(i,e,t){return i.subarray(e>>>0,t>>>0)}function _c(i){const e=i.target;return v(e)?0:E(e)}function oc(i,e,t){return i.then(e,t)}function ac(i,e){return i.then(e)}function cc(i){return Xe.__wrap(i)}function gc(i){const e=i.transaction;return v(e)?0:E(e)}function uc(){return S(function(i,e,t,r){return i.transaction(y(e,t),Sn[r])},arguments)}function dc(){return S(function(i,e,t){return i.transaction(e,Sn[t])},arguments)}function lc(){return S(function(i,e){return i.update(e)},arguments)}function pc(i){return tr.__wrap(i)}function wc(i){return h.__wrap(i)}function yc(i){return h.__unwrap(i)}function bc(i){return er.__wrap(i)}function hc(i){return i.value}function fc(){return S(function(i){return i.value},arguments)}function vc(i){return i.values()}function mc(i){return fe.__wrap(i)}function kc(i){return i.version}function Sc(i){return i.versions}function Rc(i,e){i.warn(e)}function Kc(i){console.warn(i)}function Ic(){return[]}function Cc(i,e){i.push(e)}function Dc(i){return+i}function Ec(i){return i}function Oc(i){return BigInt.asUintN(64,i)}function Mc(i,e){const t=e,r=typeof t=="bigint"?t:void 0;O().setBigInt64(i+8*1,v(r)?BigInt(0):r,!0),O().setInt32(i+4*0,!v(r),!0)}function qc(i){const e=i;return typeof e=="boolean"?e?1:0:2}function Bc(i){const e=i.original;return e.cnt--==1?(e.a=0,!0):!1}function Uc(i,e,t){return ur(i,e,40,vs)}function Fc(i,e,t){return ur(i,e,432,ms)}function Vc(i,e,t){return ur(i,e,432,ks)}function Tc(i,e,t){return mn(i,e,437,Ss)}function Pc(i,e,t){return mn(i,e,437,Rs)}function zc(i,e){const t=dr(e),r=p(t,n.__wbindgen_malloc,n.__wbindgen_realloc),s=u;O().setInt32(i+4*1,s,!0),O().setInt32(i+4*0,r,!0)}function Nc(i,e){return i in e}function Ac(){const i=n.__wbindgen_export_4,e=i.grow(4);i.set(0,void 0),i.set(e+0,void 0),i.set(e+1,null),i.set(e+2,!0),i.set(e+3,!1)}function jc(i){return typeof i=="bigint"}function xc(i){return typeof i=="function"}function Lc(i){return i===null}function Wc(i){const e=i;return typeof e=="object"&&e!==null}function Gc(i){return typeof i=="string"}function Jc(i){return i===void 0}function Qc(i,e){return i===e}function Hc(i,e){return i==e}function Yc(){return n.memory}function $c(i,e){const t=e,r=typeof t=="number"?t:void 0;O().setFloat64(i+8*1,v(r)?0:r,!0),O().setInt32(i+4*0,!v(r),!0)}function Zc(i){return i}function Xc(i,e){const t=e,r=typeof t=="string"?t:void 0;var s=v(r)?0:p(r,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u;O().setInt32(i+4*1,_,!0),O().setInt32(i+4*0,s,!0)}function eg(i,e){return y(i,e)}function tg(i,e){throw new Error(y(i,e))}function rg(i){let e;try{e=+i}catch(t){e=t}return e}const ng=Object.freeze(Object.defineProperty({__proto__:null,Attachment:Fs,BackupDecryptionKey:V,BackupKeys:kt,BackupSecretsBundle:St,Base64EncodedPkMessage:Be,BaseMigrationData:br,CancelInfo:ue,CheckCode:Rt,CollectStrategy:B,CrossSigningBootstrapRequests:Kt,CrossSigningKeyExport:It,CrossSigningStatus:Ct,Curve25519PublicKey:M,Curve25519SecretKey:te,DecryptedRoomEvent:Dt,DecryptedToDeviceEvent:Et,DecryptionErrorCode:$,DecryptionSettings:Oe,DehydratedDevice:Ot,DehydratedDeviceKey:x,DehydratedDevices:Mt,Device:Ue,DeviceId:C,DeviceKey:Fe,DeviceKeyAlgorithm:qt,DeviceKeyAlgorithmName:Is,DeviceKeyId:de,DeviceKeyName:Cs,DeviceLists:yt,Ecies:Vs,Ed25519PublicKey:ie,Ed25519Signature:le,Emoji:Bt,EncryptedAttachment:pe,EncryptionAlgorithm:ge,EncryptionInfo:Ut,EncryptionSettings:Sr,EstablishedEcies:se,EventId:Rr,HistoryVisibility:Ce,IdentityKeys:Ft,InboundCreationResult:Vt,InboundGroupSession:Tt,InvalidToDeviceEvent:Pt,KeysBackupRequest:Ve,KeysClaimRequest:Te,KeysQueryRequest:we,KeysUploadRequest:Pe,LocalTrust:lr,LoggerLevel:Ds,MaybeSignature:ze,MegolmDecryptionError:Ne,MegolmV1BackupKey:zt,Migration:bt,OlmMachine:Ae,OtherUserIdentity:je,OutboundCreationResult:Nt,OwnUserIdentity:xe,PickledInboundGroupSession:Le,PickledSession:We,PkDecryption:At,PkEncryption:jt,PkMessage:Q,PlainTextToDeviceEvent:xt,ProcessedToDeviceEventType:De,PutDehydratedDeviceRequest:Ge,Qr:ye,QrCode:Lt,QrCodeData:Je,QrCodeMode:Es,QrCodeScan:ve,QrState:ne,RehydratedDevice:Wt,RequestType:Os,RoomId:R,RoomKeyCounts:Gt,RoomKeyImportResult:Jt,RoomKeyInfo:Qt,RoomKeyWithheldInfo:Ht,RoomMessageRequest:Qe,RoomSettings:_e,Sas:be,SecretsBundle:oe,ServerName:He,ShieldColor:pr,ShieldState:Ye,ShieldStateCode:Z,Signature:Yt,SignatureState:Ms,SignatureUploadRequest:he,SignatureVerification:$t,Signatures:$e,StoreHandle:j,StoredRoomKeyBundleData:Ze,ToDeviceEncryptionInfo:Zt,ToDeviceRequest:Xe,ToDeviceUnableToDecryptInfo:Xt,ToDeviceUnableToDecryptReason:qs,Tracing:Ps,TrustRequirement:wr,UTDToDeviceEvent:er,UploadSigningKeysRequest:et,UserDevices:tr,UserId:h,VerificationMethod:Ee,VerificationRequest:fe,VerificationRequestPhase:X,Versions:rr,__wbg_Error_0497d5bdba9362e5:zs,__wbg_String_8f0eb39a4a4c2f66:Ns,__wbg_Window_b0044ac7db258535:As,__wbg_WorkerGlobalScope_b74cefefc62a37da:js,__wbg_add_64c6e51ab0ed12dd:xs,__wbg_add_dd833f9f523abe36:Ls,__wbg_at_5b2884630cb66ea6:Ws,__wbg_backupkeys_new:Gs,__wbg_bound_0274374bea7f6bca:Js,__wbg_bound_eb572b424befade3:Qs,__wbg_buffer_a1a27a0dfa70165d:Hs,__wbg_call_1b920c3ac0afee4b:Ys,__wbg_call_36f1bbf64b4cf7c7:$s,__wbg_call_f2db6205e5c51dc8:Zs,__wbg_call_fbe8be8bf6436ce5:Xs,__wbg_clearTimeout_5a54f8841c30079a:e_,__wbg_clear_e6ec1cc113e1555e:t_,__wbg_close_2079e209ea5709b5:r_,__wbg_code_5e459ca721f994f5:n_,__wbg_continue_7d9cdafc888cb902:i_,__wbg_count_2941fdbb8154c02d:s_,__wbg_count_5ceb291ba9a02b4b:__,__wbg_createIndex_32ba53785b2ef24e:o_,__wbg_createIndex_a343510ba567e58c:a_,__wbg_createObjectStore_b1f08961900155dd:c_,__wbg_crosssigningbootstraprequests_new:g_,__wbg_crosssigningkeyexport_new:u_,__wbg_crosssigningstatus_new:d_,__wbg_crypto_574e78ad8b13b65f:l_,__wbg_debug_58d16ea352cfbca1:p_,__wbg_debug_ada37632f0e8cdde:w_,__wbg_decryptedroomevent_new:y_,__wbg_decryptedtodeviceevent_new:b_,__wbg_dehydrateddevice_new:h_,__wbg_dehydrateddevicekey_new:f_,__wbg_deleteObjectStore_7b427b19378475fd:v_,__wbg_delete_1af2aac87b36c0f1:m_,__wbg_delete_71b7921c73aa9378:k_,__wbg_device_new:S_,__wbg_deviceid_new:R_,__wbg_devicekey_new:K_,__wbg_devicekeyid_new:I_,__wbg_done_4d01f352bade43b7:C_,__wbg_emoji_new:D_,__wbg_encryptedattachment_new:E_,__wbg_encryptioninfo_new:O_,__wbg_entries_41651c850143b957:M_,__wbg_entries_c951fa14164704e7:q_,__wbg_error_24afdcd463ac8bd9:B_,__wbg_error_4e978abc9692c0c5:U_,__wbg_error_51ecdd39ec054205:F_,__wbg_error_7534b8e9a36f1ab4:V_,__wbg_from_12ff8e47307bd4c7:T_,__wbg_getAllKeys_fce3f6ef8201c450:P_,__wbg_getAll_22a744d3b40f0fb5:z_,__wbg_getAll_654e689108532352:N_,__wbg_getAll_864be044b219e256:A_,__wbg_getRandomValues_38a1ff1ea09f6cc7:j_,__wbg_getRandomValues_b8f5dbd5f3995a9e:x_,__wbg_getTime_2afe67905d873e92:L_,__wbg_get_92470be87867c2e5:W_,__wbg_get_a131a44bd1eb6979:G_,__wbg_get_a4719581b0d717ad:J_,__wbg_get_d37904b955701f99:Q_,__wbg_getwithrefkey_1dc361bd10053bfe:H_,__wbg_global_b6f5c73312f62313:Y_,__wbg_inboundgroupsession_new:$_,__wbg_index_405783ca8da5f008:Z_,__wbg_indexedDB_317016dcb8a872d6:X_,__wbg_indexedDB_601ec26c63e333de:eo,__wbg_indexedDB_63b82e158eb67cbd:to,__wbg_info_e56933705c348038:ro,__wbg_info_f3589034369581f6:no,__wbg_instanceof_ArrayBuffer_a8b6f580b363f2bc:io,__wbg_instanceof_Map_80cc65041c96417a:so,__wbg_instanceof_Promise_66f94afc64d9039f:_o,__wbg_instanceof_Uint8Array_ca460677bc155827:oo,__wbg_invalidtodeviceevent_new:ao,__wbg_isArray_2a07fd175d45c496:co,__wbg_isArray_5f090bed72bd4f89:go,__wbg_isSafeInteger_90d7c4674047d684:uo,__wbg_item_15285ca2d766f142:lo,__wbg_iterator_4068add5b2aef7a6:po,__wbg_key_a17a68df9ec1b180:wo,__wbg_keysbackuprequest_new:yo,__wbg_keysclaimrequest_new:bo,__wbg_keysqueryrequest_new:ho,__wbg_keysuploadrequest_new:fo,__wbg_length_471141fa24df24b2:vo,__wbg_length_ab6d22b5ead75c72:mo,__wbg_length_f00ec12454a5d9fd:ko,__wbg_lowerBound_13c8e875a3fb9f7d:So,__wbg_maybesignature_new:Ro,__wbg_megolmdecryptionerror_new:Ko,__wbg_message_2d95ea5aff0d63b9:Io,__wbg_msCrypto_a61aeb35a24c1329:Co,__wbg_name_2acff1e83d9735f9:Do,__wbg_new_07b483f72211fd66:Eo,__wbg_new_58353953ad2097cc:Oo,__wbg_new_8a6f238a6ece86ea:Mo,__wbg_new_a2957aa5684de228:qo,__wbg_new_a979b4b45bd55c7f:Bo,__wbg_new_b3a08d2910ee5170:Uo,__wbg_new_db7d9b0ee94df522:Fo,__wbg_new_e30c39c06edaabf2:Vo,__wbg_new_e52b3efaaa774f96:To,__wbg_newnoargs_ff528e72d35de39a:Po,__wbg_newwithbyteoffsetandlength_06e8c938173769b5:zo,__wbg_newwithbyteoffsetandlength_3b01ecda099177e8:No,__wbg_newwithlength_08f872dc1e3ada2e:Ao,__wbg_newwithlength_8a0d31010560ce9a:jo,__wbg_newwithmessage_54042111509ba20c:xo,__wbg_next_8bb824d217961b5d:Lo,__wbg_next_e2da48d8fff7439a:Wo,__wbg_node_905d3e251edff8a2:Go,__wbg_now_2c95c9de01293173:Jo,__wbg_now_eb0821f3bd9f6529:Qo,__wbg_objectStoreNames_e82275eb2d403a92:Ho,__wbg_objectStore_b463d32c86d6b543:Yo,__wbg_oldVersion_af5af638a028177c:$o,__wbg_olmmachine_new:Zo,__wbg_openCursor_7c13a2cd32c6258b:Xo,__wbg_openCursor_a53133c898e0829c:ea,__wbg_openCursor_dbd279400634ae67:ta,__wbg_open_0f04f50fa4d98f67:ra,__wbg_open_b70fb421d97aad40:na,__wbg_otheruseridentity_new:ia,__wbg_ownuseridentity_new:sa,__wbg_parse_c7ba327fb6231e7f:_a,__wbg_performance_7a3ffd0b17f663ad:oa,__wbg_pickledinboundgroupsession_unwrap:aa,__wbg_pickledsession_unwrap:ca,__wbg_plaintexttodeviceevent_new:ga,__wbg_process_dc0fbacc7c1c06f7:ua,__wbg_push_73fd7b5550ebf707:da,__wbg_put_7f0b4dcc666f09e3:la,__wbg_putdehydrateddevicerequest_new:pa,__wbg_qr_new:wa,__wbg_queueMicrotask_46c1df247678729f:ya,__wbg_queueMicrotask_8acf3ccb75ed8d11:ba,__wbg_randomFillSync_ac0988aba3254290:ha,__wbg_readyState_249e5707a38b7a7a:fa,__wbg_rehydrateddevice_new:va,__wbg_require_60cc747a6bc5215a:ma,__wbg_resolve_0dac8c580ffd4678:ka,__wbg_result_a0f1bf2fe64a516c:Sa,__wbg_roomid_unwrap:Ra,__wbg_roomkeycounts_new:Ka,__wbg_roomkeyimportresult_new:Ia,__wbg_roomkeyinfo_new:Ca,__wbg_roomkeywithheldinfo_new:Da,__wbg_roommessagerequest_new:Ea,__wbg_roomsettings_new:Oa,__wbg_sas_new:Ma,__wbg_secretsbundle_new:qa,__wbg_setTimeout_db2dbaeefb6f39c7:Ba,__wbg_set_3f1d0b984ed272ed:Ua,__wbg_set_7422acbe992d64ab:Fa,__wbg_set_d6bdfd275fb8a4ce:Va,__wbg_set_fd40eacc85c5ab66:Ta,__wbg_set_fe4e79d1ed3b0e9b:Pa,__wbg_set_wasm:cr,__wbg_setonabort_479ebb5884fcb171:za,__wbg_setonblocked_046331b614d6f8e3:Na,__wbg_setoncomplete_27bdbca012e45c05:Aa,__wbg_setonerror_537b68f474e27d4e:ja,__wbg_setonerror_ce5c4d34aed931bb:xa,__wbg_setonsuccess_0b2b45bd8cc13b95:La,__wbg_setonupgradeneeded_be2e0ae927917f82:Wa,__wbg_setonversionchange_407ebf1ad930c84c:Ga,__wbg_setunique_727cefd7e14cf677:Ja,__wbg_signatures_new:Qa,__wbg_signatureuploadrequest_new:Ha,__wbg_signatureverification_new:Ya,__wbg_stack_0ed75d68575b0f3c:$a,__wbg_static_accessor_GLOBAL_487c52c58d65314d:Za,__wbg_static_accessor_GLOBAL_THIS_ee9704f328b6b291:Xa,__wbg_static_accessor_SELF_78c9e3071b912620:ec,__wbg_static_accessor_WINDOW_a093d21393777366:tc,__wbg_storedroomkeybundledata_new:rc,__wbg_storehandle_new:nc,__wbg_stringify_c242842b97f054cc:ic,__wbg_subarray_dd4ade7d53bd8e26:sc,__wbg_target_15f1da583855ac4e:_c,__wbg_then_82ab9fb4080f1707:oc,__wbg_then_db882932c0c714c6:ac,__wbg_todevicerequest_new:cc,__wbg_transaction_34c41b46ca391af6:gc,__wbg_transaction_36c8b28ed4349a9a:uc,__wbg_transaction_399fc15f5bba1880:dc,__wbg_update_297181dae0cc0af4:lc,__wbg_userdevices_new:pc,__wbg_userid_new:wc,__wbg_userid_unwrap:yc,__wbg_utdtodeviceevent_new:bc,__wbg_value_17b896954e14f896:hc,__wbg_value_648dc44894c8dc95:fc,__wbg_values_81045499c3c8e670:vc,__wbg_verificationrequest_new:mc,__wbg_version_2c3ed4a311fdabdf:kc,__wbg_versions_c01dfd4722a88165:Sc,__wbg_warn_9b968a0475b49f6b:Rc,__wbg_warn_d89f6637da554c8d:Kc,__wbindgen_array_new:Ic,__wbindgen_array_push:Cc,__wbindgen_as_number:Dc,__wbindgen_bigint_from_i64:Ec,__wbindgen_bigint_from_u64:Oc,__wbindgen_bigint_get_as_i64:Mc,__wbindgen_boolean_get:qc,__wbindgen_cb_drop:Bc,__wbindgen_closure_wrapper1160:Uc,__wbindgen_closure_wrapper2391:Fc,__wbindgen_closure_wrapper5618:Vc,__wbindgen_closure_wrapper7116:Tc,__wbindgen_closure_wrapper7121:Pc,__wbindgen_debug_string:zc,__wbindgen_in:Nc,__wbindgen_init_externref_table:Ac,__wbindgen_is_bigint:jc,__wbindgen_is_function:xc,__wbindgen_is_null:Lc,__wbindgen_is_object:Wc,__wbindgen_is_string:Gc,__wbindgen_is_undefined:Jc,__wbindgen_jsval_eq:Qc,__wbindgen_jsval_loose_eq:Hc,__wbindgen_memory:Yc,__wbindgen_number_get:$c,__wbindgen_number_new:Zc,__wbindgen_string_get:Xc,__wbindgen_string_new:eg,__wbindgen_throw:tg,__wbindgen_try_into_number:rg,getVersions:kn,start:fs},Symbol.toStringTag,{value:"Module"})),ig=new URL("/app/chat-assets/assets/matrix_sdk_crypto_wasm_bg-dMeGppz-.wasm",import.meta.url);cr(new Proxy({},{get(){throw new Error("@matrix-org/matrix-sdk-crypto-wasm was used before it was initialized. Call `initAsync` first.")}}));let jr=null;async function sg(i){const{instance:e}=await WebAssembly.instantiateStreaming(fetch(i),{"./matrix_sdk_crypto_wasm_bg.js":ng});cr(e.exports),e.exports.__wbindgen_start()}async function Fi(i=ig){jr||(jr=sg(i)),await jr}for(var Vi=/[\\\"\x00-\x1F]/g,J={},ht=0;ht<32;++ht)J[String.fromCharCode(ht)]="\\U"+("0000"+ht.toString(16)).slice(-4).toUpperCase();J["\b"]="\\b",J[" "]="\\t",J[`
3
- `]="\\n",J["\f"]="\\f",J["\r"]="\\r",J['"']='\\"',J["\\"]="\\\\";function Ti(i){return Vi.lastIndex=0,i.replace(Vi,function(e){return J[e]})}function xr(i){switch(typeof i){case"string":return'"'+Ti(i)+'"';case"number":return isFinite(i)?i:"null";case"boolean":return i;case"object":return i===null?"null":Array.isArray(i)?_g(i):og(i);default:throw new Error("Cannot stringify: "+typeof i)}}function _g(i){for(var e="[",t="",r=0;r<i.length;++r)t+=e,e=",",t+=xr(i[r]);return e!=","?"[]":t+"]"}function og(i){var e="{",t="",r=Object.keys(i);r.sort();for(var s=0;s<r.length;++s){var _=r[s];t+=e+'"'+Ti(_)+'":',e=",",t+=xr(i[_])}return e!=","?"{}":t+"}"}var ag={stringify:xr};const cg=ss(ag);class gg{constructor(e,t,r,s,_,o){this.prefixedLogger=e,this.olmMachine=t,this.keyClaimManager=r,this.outgoingRequestManager=s,this.room=_,this.encryptionSettings=o,k(this,"lazyLoadedMembersResolved",!1),k(this,"currentEncryptionPromise",Promise.resolve());var a=_.getJoinedMembers();this.olmMachine.updateTrackedUsers(a.map(c=>new h(c.userId))).catch(c=>this.prefixedLogger.error("Error initializing tracked users",c))}onCryptoEvent(e){if(JSON.stringify(this.encryptionSettings)!=JSON.stringify(e))throw new Error("Cannot reconfigure an active RoomEncryptor")}onRoomMembership(e){(e.membership==nt.Join||e.membership==nt.Invite&&this.room.shouldEncryptForInvitedMembers())&&this.olmMachine.updateTrackedUsers([new h(e.userId)]).catch(t=>{this.prefixedLogger.error("Unable to update tracked users",t)})}prepareForEncryption(e,t){var r=this;return g(function*(){yield r.encryptEvent(null,e,t)})()}encryptEvent(e,t,r){var s,_=this,o=new it(this.prefixedLogger,e?(s=e.getTxnId())!==null&&s!==void 0?s:"":"prepareForEncryption"),a=this.currentEncryptionPromise.catch(()=>{}).then(g(function*(){yield W(o,"ensureEncryptionSession",g(function*(){yield _.ensureEncryptionSession(o,t,r)})),e&&(yield W(o,"encryptEventInner",g(function*(){yield _.encryptEventInner(o,e)})))}));return this.currentEncryptionPromise=a,a}ensureEncryptionSession(e,t,r){var s=this;return g(function*(){if(s.encryptionSettings.algorithm!=="m.megolm.v1.aes-sha2")throw new Error("Cannot encrypt in ".concat(s.room.roomId," for unsupported algorithm '").concat(s.encryptionSettings.algorithm,"'"));e.debug("Starting encryption");var _=yield s.room.getEncryptionTargetMembers();s.lazyLoadedMembersResolved?(e.debug("Processing outgoing requests in background"),s.outgoingRequestManager.doProcessOutgoingRequests()):(yield W(e,"loadMembersIfNeeded: updateTrackedUsers",g(function*(){yield s.olmMachine.updateTrackedUsers(_.map(w=>new h(w.userId)))})),e.debug("Updated tracked users"),s.lazyLoadedMembersResolved=!0,e.debug("Processing outgoing requests"),yield W(e,"doProcessOutgoingRequests",g(function*(){yield s.outgoingRequestManager.doProcessOutgoingRequests()}))),e.debug("Encrypting for users (shouldEncryptForInvitedMembers: ".concat(s.room.shouldEncryptForInvitedMembers(),"):"),_.map(w=>"".concat(w.userId," (").concat(w.membership,")")));var o=_.map(w=>new h(w.userId));yield W(e,"ensureSessionsForUsers",g(function*(){yield s.keyClaimManager.ensureSessionsForUsers(e,o)}));var a=new Sr;switch(a.historyVisibility=ug(s.room.getHistoryVisibility()),a.algorithm=ge.MegolmV1AesSha2,typeof s.encryptionSettings.rotation_period_ms=="number"&&(a.rotationPeriod=BigInt(s.encryptionSettings.rotation_period_ms*1e3)),typeof s.encryptionSettings.rotation_period_msgs=="number"&&(a.rotationPeriodMessages=BigInt(s.encryptionSettings.rotation_period_msgs)),r.kind){case st.AllDevicesIsolationMode:{var c,d=(c=s.room.getBlacklistUnverifiedDevices())!==null&&c!==void 0?c:t;a.sharingStrategy=B.deviceBasedStrategy(d,r.errorOnVerifiedUserProblems)}break;case st.OnlySignedDevicesIsolationMode:a.sharingStrategy=B.identityBasedStrategy();break}yield W(e,"shareRoomKey",g(function*(){var w=yield s.olmMachine.shareRoomKey(new R(s.room.roomId),o,a);if(w)for(var f of w)yield s.outgoingRequestManager.outgoingRequestProcessor.makeOutgoingRequest(f)}))})()}forceDiscardSession(){var e=this;return g(function*(){var t=yield e.olmMachine.invalidateGroupSession(new R(e.room.roomId));t&&e.prefixedLogger.info("Discarded existing group session")})()}encryptEventInner(e,t){var r=this;return g(function*(){e.debug("Encrypting actual message content");var s=yield r.olmMachine.encryptRoomEvent(new R(r.room.roomId),t.getType(),JSON.stringify(t.getContent()));t.makeEncrypted(P.RoomMessageEncrypted,JSON.parse(s),r.olmMachine.identityKeys.curve25519.toBase64(),r.olmMachine.identityKeys.ed25519.toBase64()),e.debug("Encrypted event successfully")})()}}function ug(i){switch(i){case _t.Invited:return Ce.Invited;case _t.Joined:return Ce.Joined;case _t.Shared:return Ce.Shared;case _t.WorldReadable:return Ce.WorldReadable}}var Me="/_matrix/client/unstable/org.matrix.msc3814.v1",Lr="org.matrix.msc3814",dg=7*24*60*60*1e3;class lg extends me{constructor(e,t,r,s,_){super(),this.logger=e,this.olmMachine=t,this.http=r,this.outgoingRequestProcessor=s,this.secretStorage=_,k(this,"intervalId",void 0)}cacheKey(e){var t=this;return g(function*(){yield t.olmMachine.dehydratedDevices().saveDehydratedDeviceKey(e),t.emit(I.DehydrationKeyCached)})()}isSupported(){var e=this;return g(function*(){try{yield e.http.authedRequest(D.Get,"/dehydrated_device",void 0,void 0,{prefix:Me})}catch(r){var t=r;if(t.errcode==="M_UNRECOGNIZED")return!1;if(t.errcode==="M_NOT_FOUND")return!0;throw r}return!0})()}start(){var e=arguments,t=this;return g(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:{};if(typeof r=="boolean"&&(r={createNewKey:r}),!(r.onlyIfKeyCached&&!(yield t.olmMachine.dehydratedDevices().getDehydratedDeviceKey()))){if(t.stop(),r.rehydrate!==!1)try{yield t.rehydrateDeviceIfAvailable()}catch(s){t.logger.info("dehydration: Error rehydrating device:",s),t.emit(I.RehydrationError,s.message)}r.createNewKey&&(yield t.resetKey()),yield t.scheduleDeviceDehydration()}})()}isKeyStored(){var e=this;return g(function*(){return!!(yield e.secretStorage.isStored(Lr))})()}resetKey(){var e=this;return g(function*(){var t=x.createRandomKey();return yield e.secretStorage.store(Lr,t.toBase64()),yield e.cacheKey(t),t})()}getKey(e){var t=this;return g(function*(){var r=yield t.olmMachine.dehydratedDevices().getDehydratedDeviceKey();if(r)return r;var s=yield t.secretStorage.get(Lr);if(s===void 0)return e?yield t.resetKey():null;var _=_r(s);try{var o=x.createKeyFromArray(_);return yield t.cacheKey(o),o}finally{_.fill(0)}})()}rehydrateDeviceIfAvailable(){var e=this;return g(function*(){var t=yield e.getKey(!1);if(!t)return!1;var r;try{r=yield e.http.authedRequest(D.Get,"/dehydrated_device",void 0,void 0,{prefix:Me})}catch(m){var s=m;if(s.errcode==="M_NOT_FOUND"||s.errcode==="M_UNRECOGNIZED")return e.logger.info("dehydration: No dehydrated device"),!1;throw s}e.logger.info("dehydration: dehydrated device found"),e.emit(I.RehydrationStarted);var _=yield e.olmMachine.dehydratedDevices().rehydrate(t,new C(r.device_id),JSON.stringify(r.device_data));e.logger.info("dehydration: device rehydrated");for(var o=void 0,a=0,c=0,d=ot("/dehydrated_device/$device_id/events",{$device_id:r.device_id});;){var w=yield e.http.authedRequest(D.Post,d,void 0,o?{next_batch:o}:{},{prefix:Me});if(w.events.length===0)break;a+=w.events.length,o=w.next_batch;var f=yield _.receiveEvents(JSON.stringify(w.events));c+=f.length,e.emit(I.RehydrationProgress,c,a)}return e.logger.info("dehydration: received ".concat(c," room keys from ").concat(a," to-device events")),e.emit(I.RehydrationCompleted),!0})()}createAndUploadDehydratedDevice(){var e=this;return g(function*(){var t=yield e.getKey(!0),r=yield e.olmMachine.dehydratedDevices().create();e.emit(I.DehydratedDeviceCreated);var s=yield r.keysForUpload("Dehydrated device",t);yield e.outgoingRequestProcessor.makeOutgoingRequest(s),e.emit(I.DehydratedDeviceUploaded),e.logger.info("dehydration: uploaded device")})()}scheduleDeviceDehydration(){var e=this;return g(function*(){e.stop(),yield e.createAndUploadDehydratedDevice(),e.intervalId=setInterval(()=>{e.createAndUploadDehydratedDevice().catch(t=>{e.emit(I.DehydratedDeviceRotationError,t.message),e.logger.error("Error creating dehydrated device:",t)})},dg)})()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}delete(){var e=this;return g(function*(){e.stop();try{yield e.http.authedRequest(D.Delete,"/dehydrated_device",void 0,{},{prefix:Me})}catch(r){var t=r;if(t.errcode==="M_UNRECOGNIZED"||t.errcode==="M_NOT_FOUND")return;throw r}})()}}function Pi(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(i);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(i,s).enumerable})),t.push.apply(t,r)}return t}function pg(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Pi(Object(t),!0).forEach(function(r){k(i,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Pi(Object(t)).forEach(function(r){Object.defineProperty(i,r,Object.getOwnPropertyDescriptor(t,r))})}return i}class wg{constructor(e,t,r){this.logger=e,this.olmMachine=t,this.http=r}makeOutgoingRequest(e,t){var r=this;return g(function*(){var s;if(e instanceof Pe)s=yield r.requestWithRetry(D.Post,"/_matrix/client/v3/keys/upload",{},e.body);else if(e instanceof we)s=yield r.requestWithRetry(D.Post,"/_matrix/client/v3/keys/query",{},e.body);else if(e instanceof Te)s=yield r.requestWithRetry(D.Post,"/_matrix/client/v3/keys/claim",{},e.body);else if(e instanceof he)s=yield r.requestWithRetry(D.Post,"/_matrix/client/v3/keys/signatures/upload",{},e.body);else if(e instanceof Ve)s=yield r.requestWithRetry(D.Put,"/_matrix/client/v3/room_keys/keys",{version:e.version},e.body);else if(e instanceof Xe)s=yield r.sendToDeviceRequest(e);else if(e instanceof Qe){var _="/_matrix/client/v3/rooms/".concat(encodeURIComponent(e.room_id),"/send/")+"".concat(encodeURIComponent(e.event_type),"/").concat(encodeURIComponent(e.txn_id));s=yield r.requestWithRetry(D.Put,_,{},e.body)}else if(e instanceof et){yield r.makeRequestWithUIA(D.Post,"/_matrix/client/v3/keys/device_signing/upload",{},e.body,t);return}else if(e instanceof Ge){var o=Me+"/dehydrated_device";yield r.rawJsonRequest(D.Put,o,{},e.body);return}else r.logger.warn("Unsupported outgoing message",Object.getPrototypeOf(e)),s="";if(e.id)try{yield W(r.logger,"Mark Request as sent ".concat(e.type),g(function*(){yield r.olmMachine.markRequestAsSent(e.id,e.type,s)}))}catch(a){if(a instanceof Error&&(a.message==="Attempt to use a moved value"||a.message==="null pointer passed to rust"))r.logger.debug("Ignoring error '".concat(a.message,"': client is likely shutting down"));else throw a}else r.logger.trace("Outgoing request type:".concat(e.type," does not have an ID"))})()}sendToDeviceRequest(e){var t=this;return g(function*(){var r=JSON.parse(e.body),s=[];for(var[_,o]of Object.entries(r.messages))for(var[a,c]of Object.entries(o))s.push("".concat(_,"/").concat(a," (msgid ").concat(c[_s],")"));t.logger.info("Sending batch of to-device messages. type=".concat(e.event_type," txnid=").concat(e.txn_id),s);var d="/_matrix/client/v3/sendToDevice/".concat(encodeURIComponent(e.event_type),"/")+encodeURIComponent(e.txn_id);return yield t.requestWithRetry(D.Put,d,{},e.body)})()}makeRequestWithUIA(e,t,r,s,_){var o=this;return g(function*(){if(!_)return yield o.requestWithRetry(e,t,r,s);var a=JSON.parse(s),c=function(){var w=g(function*(f){var m=pg({},a);f!==null&&(m.auth=f);var K=yield o.requestWithRetry(e,t,r,JSON.stringify(m));return JSON.parse(K)});return function(f){return w.apply(this,arguments)}}(),d=yield _(c);return JSON.stringify(d)})()}requestWithRetry(e,t,r,s){var _=this;return g(function*(){for(var o=0;;)try{return yield _.rawJsonRequest(e,t,r,s)}catch(c){o++;var a=os(c,o,!0);if(a<0)throw c;yield re(a)}})()}rawJsonRequest(e,t,r,s){var _=this;return g(function*(){var o={json:!1,headers:{"Content-Type":"application/json",Accept:"application/json"},prefix:"",localTimeoutMs:6e4};return yield _.http.authedRequest(e,t,r,s,o)})()}}class yg{constructor(e,t){this.olmMachine=e,this.outgoingRequestProcessor=t,k(this,"currentClaimPromise",void 0),k(this,"stopped",!1),this.currentClaimPromise=Promise.resolve()}stop(){this.stopped=!0}ensureSessionsForUsers(e,t){var r=this.currentClaimPromise.catch(()=>{}).then(()=>this.ensureSessionsForUsersInner(e,t));return this.currentClaimPromise=r,r}ensureSessionsForUsersInner(e,t){var r=this;return g(function*(){if(r.stopped)throw new Error("Cannot ensure Olm sessions: shutting down");e.info("Checking for missing Olm sessions");var s=yield r.olmMachine.getMissingSessions(t.map(_=>_.clone()));s&&(e.info("Making /keys/claim request"),yield r.outgoingRequestProcessor.makeOutgoingRequest(s)),e.info("Olm sessions prepared")})()}}function bg(i,e){var t=new Map;for(var[r,s]of i.keys.entries())t.set(r.toString(),s.toBase64());var _=at.Unverified;i.isBlacklisted()?_=at.Blocked:i.isVerified()&&(_=at.Verified);var o=new Map,a=i.signatures.get(e);if(a){var c=new Map;for(var[d,w]of a.entries())w.isValid()&&w.signature&&c.set(d,w.signature.toBase64());o.set(e.toString(),c)}var f=i.algorithms,m=new Set;return f.forEach(K=>{switch(K){case ge.MegolmV1AesSha2:m.add("m.megolm.v1.aes-sha2");break;case ge.OlmV1Curve25519AesSha2:default:m.add("m.olm.v1.curve25519-aes-sha2");break}}),new cn({deviceId:i.deviceId.toString(),userId:e.toString(),keys:t,algorithms:Array.from(m),verified:_,signatures:o,displayName:i.displayName,dehydrated:i.isDehydrated})}function hg(i){return new Map(Object.entries(i).map(e=>{var[t,r]=e;return[t,fg(r)]}))}function fg(i){var e,t=new Map(Object.entries(i.keys)),r=(e=i.unsigned)===null||e===void 0?void 0:e.device_display_name,s=new Map;if(i.signatures)for(var _ in i.signatures)s.set(_,new Map(Object.entries(i.signatures[_])));return new cn({deviceId:i.device_id,userId:i.user_id,keys:t,algorithms:i.algorithms,verified:at.Unverified,signatures:s,displayName:r})}class vg{constructor(e,t,r,s){this.logger=e,this.olmMachine=t,this.outgoingRequestProcessor=r,this.secretStorage=s}bootstrapCrossSigning(e){var t=this;return g(function*(){if(e.setupNewCrossSigning){yield t.resetCrossSigning(e.authUploadDeviceSigningKeys);return}var r=yield t.olmMachine.crossSigningStatus(),s=yield t.secretStorage.get("m.cross_signing.master"),_=yield t.secretStorage.get("m.cross_signing.self_signing"),o=yield t.secretStorage.get("m.cross_signing.user_signing"),a=!!(s&&_&&o),c=r.hasMaster&&r.hasUserSigning&&r.hasSelfSigning;if(t.logger.debug("bootstrapCrossSigning: starting",{setupNewCrossSigning:e.setupNewCrossSigning,olmDeviceHasMaster:r.hasMaster,olmDeviceHasUserSigning:r.hasUserSigning,olmDeviceHasSelfSigning:r.hasSelfSigning,privateKeysInSecretStorage:a}),c)(yield t.secretStorage.hasKey())?a?t.logger.debug("bootstrapCrossSigning: Olm device has private keys and they are saved in secret storage; doing nothing"):(t.logger.debug("bootstrapCrossSigning: Olm device has private keys: exporting to secret storage"),yield t.exportCrossSigningKeysToStorage()):t.logger.warn("bootstrapCrossSigning: Olm device has private keys, but secret storage is not yet set up; doing nothing for now.");else if(a){t.logger.debug("bootstrapCrossSigning: Cross-signing private keys not found locally, but they are available in secret storage, reading storage and caching locally");var d=yield t.olmMachine.importCrossSigningKeys(s,_,o);if(!d.hasMaster||!d.hasSelfSigning||!d.hasUserSigning)throw new Error("importCrossSigningKeys failed to import the keys");var w=yield t.olmMachine.getDevice(t.olmMachine.userId,t.olmMachine.deviceId);try{var f=yield w.verify();yield t.outgoingRequestProcessor.makeOutgoingRequest(f)}finally{w.free()}}else t.logger.debug("bootstrapCrossSigning: Cross-signing private keys not found locally or in secret storage, creating new keys"),yield t.resetCrossSigning(e.authUploadDeviceSigningKeys);t.logger.debug("bootstrapCrossSigning: complete")})()}resetCrossSigning(e){var t=this;return g(function*(){var r=yield t.olmMachine.bootstrapCrossSigning(!0);(yield t.secretStorage.hasKey())?(t.logger.debug("resetCrossSigning: exporting private keys to secret storage"),yield t.exportCrossSigningKeysToStorage()):t.logger.warn("resetCrossSigning: Secret storage is not yet set up; not exporting keys to secret storage yet."),t.logger.debug("resetCrossSigning: publishing public keys to server");for(var s of[r.uploadKeysRequest,r.uploadSigningKeysRequest,r.uploadSignaturesRequest])s&&(yield t.outgoingRequestProcessor.makeOutgoingRequest(s,e))})()}exportCrossSigningKeysToStorage(){var e=this;return g(function*(){var t=yield e.olmMachine.exportCrossSigningKeys();t!=null&&t.masterKey?yield e.secretStorage.store("m.cross_signing.master",t.masterKey):e.logger.error("Cannot export MSK to secret storage, private key unknown"),t!=null&&t.self_signing_key?yield e.secretStorage.store("m.cross_signing.self_signing",t.self_signing_key):e.logger.error("Cannot export SSK to secret storage, private key unknown"),t!=null&&t.userSigningKey?yield e.secretStorage.store("m.cross_signing.user_signing",t.userSigningKey):e.logger.error("Cannot export USK to secret storage, private key unknown")})()}}function zi(i){return Wr.apply(this,arguments)}function Wr(){return Wr=g(function*(i){return Ni(i,["m.cross_signing.master","m.cross_signing.user_signing","m.cross_signing.self_signing"])}),Wr.apply(this,arguments)}function Ni(i,e){return Gr.apply(this,arguments)}function Gr(){return Gr=g(function*(i,e){var t=yield i.getDefaultKeyId();if(!t)return!1;for(var r of e){var s=(yield i.isStored(r))||{};if(!(t in s))return!1}return!0}),Gr.apply(this,arguments)}class mg extends me{constructor(e,t,r,s,_){super(),this.logger=e,this.olmMachine=t,this.inner=r,this.outgoingRequestProcessor=s,this.supportedVerificationMethods=_,k(this,"reEmitter",void 0),k(this,"_accepting",!1),k(this,"_cancelling",!1),k(this,"_verifier",void 0),this.reEmitter=new gn(this);var o=new WeakRef(this);r.registerChangesCallback(g(function*(){var a;return(a=o.deref())===null||a===void 0?void 0:a.onChange()}))}onChange(){var e=this.inner.getVerification();e instanceof be?this._verifier===void 0||this._verifier instanceof ji?this.setVerifier(new xi(e,this,this.outgoingRequestProcessor)):this._verifier instanceof xi&&this._verifier.replaceInner(e):e instanceof ye&&this._verifier===void 0&&this.setVerifier(new ji(e,this.outgoingRequestProcessor)),this.emit(ke.Change)}setVerifier(e){this._verifier&&this.reEmitter.stopReEmitting(this._verifier,[ke.Change]),this._verifier=e,this.reEmitter.reEmit(this._verifier,[ke.Change])}get transactionId(){return this.inner.flowId}get roomId(){var e;return(e=this.inner.roomId)===null||e===void 0?void 0:e.toString()}get initiatedByMe(){return this.inner.weStarted()}get otherUserId(){return this.inner.otherUserId.toString()}get otherDeviceId(){var e;return(e=this.inner.otherDeviceId)===null||e===void 0?void 0:e.toString()}getOtherDevice(){var e=this;return g(function*(){var t=e.inner.otherDeviceId;if(t)return yield e.olmMachine.getDevice(e.inner.otherUserId,t,5)})()}get isSelfVerification(){return this.inner.isSelfVerification()}get phase(){var e=this.inner.phase();switch(e){case X.Created:case X.Requested:return q.Requested;case X.Ready:return this._accepting?q.Requested:q.Ready;case X.Transitioned:if(!this._verifier)throw new Error("VerificationRequest: inner phase == Transitioned but no verifier!");return this._verifier.verificationPhase;case X.Done:return q.Done;case X.Cancelled:return q.Cancelled}throw new Error("Unknown verification phase ".concat(e))}get pending(){if(this.inner.isPassive())return!1;var e=this.phase;return e!==q.Done&&e!==q.Cancelled}get accepting(){return this._accepting}get declining(){return this._cancelling}get timeout(){return this.inner.timeRemainingMillis()}get methods(){throw new Error("not implemented")}get chosenMethod(){if(this.phase!==q.Started)return null;var e=this.inner.getVerification();return e instanceof be?N.Sas:e instanceof ye?N.Reciprocate:null}otherPartySupportsMethod(e){var t=this.inner.theirSupportedMethods;if(t===void 0)return!1;var r=Li[e];return t.some(s=>s===r)}accept(){var e=this;return g(function*(){if(e.inner.phase()!==X.Requested||e._accepting)throw new Error("Cannot accept a verification request in phase ".concat(e.phase));e._accepting=!0;try{var t=e.inner.acceptWithMethods(e.supportedVerificationMethods.map(ft));t&&(yield e.outgoingRequestProcessor.makeOutgoingRequest(t))}finally{e._accepting=!1}e.emit(ke.Change)})()}cancel(e){var t=this;return g(function*(){if(!t._cancelling){t.logger.info("Cancelling verification request with params:",e),t._cancelling=!0;try{var r=t.inner.cancel();r&&(yield t.outgoingRequestProcessor.makeOutgoingRequest(r))}finally{t._cancelling=!1}}})()}beginKeyVerification(e,t){throw new Error("not implemented")}startVerification(e){var t=this;return g(function*(){if(e!==N.Sas)throw new Error("Unsupported verification method ".concat(e));if(!(yield t.getOtherDevice()))throw new Error("startVerification(): other device is unknown");var r=yield t.inner.startSas();if(r){var[,s]=r;yield t.outgoingRequestProcessor.makeOutgoingRequest(s)}if(!t._verifier)throw new Error("Still no verifier after startSas() call");return t._verifier})()}scanQRCode(e){var t=this;return g(function*(){var r=ve.fromBytes(e),s=yield t.inner.scanQrCode(r);if(!t._verifier)throw new Error("Still no verifier after scanQrCode() call");var _=s.reciprocate();return _&&(yield t.outgoingRequestProcessor.makeOutgoingRequest(_)),t._verifier})()}get verifier(){return this.phase===q.Started?this._verifier:void 0}getQRCodeBytes(){throw new Error("getQRCodeBytes() unsupported in Rust Crypto; use generateQRCode() instead.")}generateQRCode(){var e=this;return g(function*(){if(!(yield e.getOtherDevice()))throw new Error("generateQRCode(): other device is unknown");var t=yield e.inner.generateQrCode();if(t)return t.toBytes()})()}get cancellationCode(){var e,t;return(e=(t=this.inner.cancelInfo)===null||t===void 0?void 0:t.cancelCode())!==null&&e!==void 0?e:null}get cancellingUserId(){var e=this.inner.cancelInfo;if(e)return e.cancelledbyUs()?this.olmMachine.userId.toString():this.inner.otherUserId.toString()}}class Ai extends me{constructor(e,t){super(),this.inner=e,this.outgoingRequestProcessor=t,k(this,"completionDeferred",void 0),this.completionDeferred=Promise.withResolvers();var r=new WeakRef(this);e.registerChangesCallback(g(function*(){var s;return(s=r.deref())===null||s===void 0?void 0:s.onChange()})),this.completionDeferred.promise.catch(()=>null)}onChange(){if(this.inner.isDone())this.completionDeferred.resolve(void 0);else if(this.inner.isCancelled()){var e=this.inner.cancelInfo();this.completionDeferred.reject(new Error("Verification cancelled by ".concat(e.cancelledbyUs()?"us":"them"," with code ").concat(e.cancelCode(),": ").concat(e.reason())))}this.emit(ke.Change)}get hasBeenCancelled(){return this.inner.isCancelled()}get userId(){return this.inner.otherUserId.toString()}cancel(e){var t=this.inner.cancel();t&&this.outgoingRequestProcessor.makeOutgoingRequest(t)}getShowSasCallbacks(){return null}getReciprocateQrCodeCallbacks(){return null}}class ji extends Ai{constructor(e,t){super(e,t),k(this,"callbacks",null)}onChange(){this.callbacks===null&&this.inner.hasBeenScanned()&&(this.callbacks={confirm:()=>{this.confirmScanning()},cancel:()=>this.cancel()}),super.onChange()}verify(){var e=this;return g(function*(){e.callbacks!==null&&e.emit(un.ShowReciprocateQr,e.callbacks),yield e.completionDeferred.promise})()}get verificationPhase(){switch(this.inner.state()){case ne.Created:return q.Ready;case ne.Scanned:return q.Started;case ne.Confirmed:return q.Started;case ne.Reciprocated:return q.Started;case ne.Done:return q.Done;case ne.Cancelled:return q.Cancelled;default:throw new Error("Unknown qr code state ".concat(this.inner.state()))}}getReciprocateQrCodeCallbacks(){return this.callbacks}confirmScanning(){var e=this;return g(function*(){var t=e.inner.confirmScanning();t&&(yield e.outgoingRequestProcessor.makeOutgoingRequest(t))})()}}class xi extends Ai{constructor(e,t,r){super(e,r),k(this,"callbacks",null)}verify(){var e=this;return g(function*(){yield e.sendAccept(),yield e.completionDeferred.promise})()}sendAccept(){var e=this;return g(function*(){var t=e.inner.accept();t&&(yield e.outgoingRequestProcessor.makeOutgoingRequest(t))})()}onChange(){var e=this;if(super.onChange(),this.callbacks===null){var t=this.inner.emoji(),r=this.inner.decimals();if(t===void 0&&r===void 0)return;var s={};t&&(s.emoji=t.map(_=>[_.symbol,_.description])),r&&(s.decimal=[r[0],r[1],r[2]]),this.callbacks={sas:s,confirm:function(){var _=g(function*(){var a=yield e.inner.confirm();for(var c of a)yield e.outgoingRequestProcessor.makeOutgoingRequest(c)});function o(){return _.apply(this,arguments)}return o}(),mismatch:()=>{var _=this.inner.cancelWithCode("m.mismatched_sas");_&&this.outgoingRequestProcessor.makeOutgoingRequest(_)},cancel:()=>{var _=this.inner.cancelWithCode("m.user");_&&this.outgoingRequestProcessor.makeOutgoingRequest(_)}},this.emit(un.ShowSas,this.callbacks)}}get verificationPhase(){return q.Started}getShowSasCallbacks(){return this.callbacks}replaceInner(e){if(this.inner!=e){this.inner=e;var t=new WeakRef(this);e.registerChangesCallback(g(function*(){var r;return(r=t.deref())===null||r===void 0?void 0:r.onChange()})),this.sendAccept(),this.onChange()}}}var Li={[N.Sas]:Ee.SasV1,[N.ScanQrCode]:Ee.QrCodeScanV1,[N.ShowQrCode]:Ee.QrCodeShowV1,[N.Reciprocate]:Ee.ReciprocateV1};function ft(i){var e=Li[i];if(e===void 0)throw new Error("Unknown verification method ".concat(i));return e}function kg(i){switch(i.getType()){case P.KeyVerificationCancel:case P.KeyVerificationDone:case P.KeyVerificationMac:case P.KeyVerificationStart:case P.KeyVerificationKey:case P.KeyVerificationReady:case P.KeyVerificationAccept:return!0;case P.RoomMessage:return i.getContent().msgtype===dn.KeyVerificationRequest;default:return!1}}class Sg extends me{constructor(e,t,r,s){super(),this.logger=e,this.olmMachine=t,this.http=r,this.outgoingRequestProcessor=s,k(this,"checkedForBackup",!1),k(this,"serverBackupInfo",void 0),k(this,"activeBackupVersion",null),k(this,"stopped",!1),k(this,"backupKeysLoopRunning",!1),k(this,"keyBackupCheckInProgress",null)}stop(){this.stopped=!0}getActiveBackupVersion(){var e=this;return g(function*(){return(yield e.olmMachine.isBackupEnabled())?e.activeBackupVersion:null})()}getServerBackupInfo(){var e=this;return g(function*(){return yield e.checkKeyBackupAndEnable(!1),e.serverBackupInfo})()}isKeyBackupTrusted(e){var t=this;return g(function*(){var r=yield t.olmMachine.verifyBackup(e),s=yield t.olmMachine.getBackupKeys(),_=s==null?void 0:s.decryptionKey,o=!!_&&t.backupInfoMatchesBackupDecryptionKey(e,_);return{matchesDecryptionKey:o,trusted:r.trusted()}})()}checkKeyBackupAndEnable(e){return!e&&this.checkedForBackup?Promise.resolve(null):(this.keyBackupCheckInProgress||(this.keyBackupCheckInProgress=this.doCheckKeyBackup().finally(()=>{this.keyBackupCheckInProgress=null})),this.keyBackupCheckInProgress)}handleBackupSecretReceived(e){var t=this;return g(function*(){var r,s;try{s=yield t.requestKeyBackupVersion()}catch(a){return t.logger.warn("handleBackupSecretReceived: Error checking for latest key backup",a),!1}if(!((r=s)!==null&&r!==void 0&&r.version))return t.logger.warn("handleBackupSecretReceived: Received a backup decryption key, but there is no trusted server-side key backup"),!1;try{var _=V.fromBase64(e),o=t.backupInfoMatchesBackupDecryptionKey(s,_);return o?(t.logger.info("handleBackupSecretReceived: A valid backup decryption key has been received and stored in cache."),yield t.saveBackupDecryptionKey(_,s.version),!0):(t.logger.warn("handleBackupSecretReceived: Private decryption key does not match the public key of the current remote backup."),!1)}catch(a){t.logger.warn("handleBackupSecretReceived: Invalid backup decryption key",a)}return!1})()}saveBackupDecryptionKey(e,t){var r=this;return g(function*(){yield r.olmMachine.saveBackupDecryptionKey(e,t),r.emit(I.KeyBackupDecryptionKeyCached,t)})()}importRoomKeys(e,t){var r=this;return g(function*(){yield r.importRoomKeysAsJson(JSON.stringify(e),t)})()}importRoomKeysAsJson(e,t){var r=this;return g(function*(){yield r.olmMachine.importExportedRoomKeys(e,(s,_)=>{var o,a={total:Number(_),successes:Number(s),stage:Re.LoadKeys,failures:0};t==null||(o=t.progressCallback)===null||o===void 0||o.call(t,a)})})()}importBackedUpRoomKeys(e,t,r){var s=this;return g(function*(){var _=new Map;for(var o of e){var a=new R(o.room_id);_.has(a)||_.set(a,new Map),_.get(a).set(o.session_id,o)}yield s.olmMachine.importBackedUpRoomKeys(_,(c,d,w)=>{var f,m={total:Number(d),successes:Number(c),stage:Re.LoadKeys,failures:Number(w)};r==null||(f=r.progressCallback)===null||f===void 0||f.call(r,m)},t)})()}doCheckKeyBackup(){var e=this;return g(function*(){e.logger.debug("Checking key backup status...");var t;try{t=yield e.requestKeyBackupVersion()}catch(_){return e.logger.warn("Error checking for active key backup",_),e.serverBackupInfo=void 0,null}e.checkedForBackup=!0,t&&!t.version&&(e.logger.warn("active backup lacks a useful 'version'; ignoring it"),t=void 0),e.serverBackupInfo=t;var r=yield e.getActiveBackupVersion();if(!t)return r!==null?(e.logger.debug("No key backup present on server: disabling key backup"),yield e.disableKeyBackup()):e.logger.debug("No key backup present on server: not enabling key backup"),null;var s=yield e.isKeyBackupTrusted(t);return!s.matchesDecryptionKey&&!s.trusted?r!==null?(e.logger.debug("Key backup present on server but not trusted: disabling key backup"),yield e.disableKeyBackup()):e.logger.debug("Key backup present on server but not trusted: not enabling key backup"):r===null?(e.logger.debug("Found usable key backup v".concat(t.version,": enabling key backups")),yield e.enableKeyBackup(t)):r!==t.version?(e.logger.debug("On backup version ".concat(r," but found version ").concat(t.version,": switching.")),yield e.disableKeyBackup(),yield e.enableKeyBackup(t)):e.logger.debug("Backup version ".concat(t.version," still current")),{backupInfo:t,trustInfo:s}})()}enableKeyBackup(e){var t=this;return g(function*(){yield t.olmMachine.enableBackupV1(e.auth_data.public_key,e.version),t.activeBackupVersion=e.version,t.emit(I.KeyBackupStatus,!0),t.backupKeysLoop()})()}maybeUploadKey(){var e=this;return g(function*(){e.activeBackupVersion!=null&&e.backupKeysLoop()})()}disableKeyBackup(){var e=this;return g(function*(){yield e.olmMachine.disableBackup(),e.activeBackupVersion=null,e.emit(I.KeyBackupStatus,!1)})()}backupKeysLoop(){var e=arguments,t=this;return g(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:1e4;if(t.backupKeysLoopRunning){t.logger.debug("Backup loop already running");return}t.backupKeysLoopRunning=!0,t.logger.debug("Backup: Starting keys upload loop for backup version:".concat(t.activeBackupVersion,"."));var s=Math.random()*r;yield re(s);try{for(var _=0,o=null,a=!0;!t.stopped;){var c=void 0;try{c=yield W(t.logger,"BackupRoomKeys: Get keys to backup from rust crypto-sdk",g(function*(){return yield t.olmMachine.backupRoomKeys()}))}catch(K){t.logger.error("Backup: Failed to get keys to backup from rust crypto-sdk",K)}if(!c||t.stopped||!t.activeBackupVersion){t.logger.debug("Backup: Ending loop for version ".concat(t.activeBackupVersion,".")),c||t.emit(I.KeyBackupSessionsRemaining,0);return}try{if(yield t.outgoingRequestProcessor.makeOutgoingRequest(c),_=0,t.stopped)break;if(!a&&o===null)try{var d=yield t.olmMachine.roomKeyCounts();o=d.total-d.backedUp}catch(K){t.logger.error("Backup: Failed to get key counts from rust crypto-sdk",K)}if(o!==null){t.emit(I.KeyBackupSessionsRemaining,o);var w=t.keysCountInBatch(c);o=Math.max(o-w,0)}}catch(K){if(_++,t.logger.error("Backup: Error processing backup request for rust crypto-sdk",K),K instanceof ln){var f=K.data.errcode;if(f=="M_NOT_FOUND"||f=="M_WRONG_ROOM_KEYS_VERSION"){t.logger.debug("Backup: Failed to upload keys to current vesion: ".concat(f,"."));try{yield t.disableKeyBackup()}catch(U){t.logger.error("Backup: An error occurred while disabling key backup:",U)}t.emit(I.KeyBackupFailed,K.data.errcode),t.backupKeysLoopRunning=!1,t.checkKeyBackupAndEnable(!0);return}else if(K.isRateLimitError())try{var m=K.getRetryAfterMs();if(m&&m>0){yield re(m);continue}}catch(U){t.logger.warn("Backup: An error occurred while retrieving a rate-limit retry delay",U)}}yield re(1e3*Math.pow(2,Math.min(_-1,4)))}a=!1}}finally{t.backupKeysLoopRunning=!1}})()}keysCountInBatch(e){var t=JSON.parse(e.body);return Gi(t)}requestKeyBackupVersion(e){var t=this;return g(function*(){return yield Wi(t.http,e)})()}setupKeyBackup(e){var t=this;return g(function*(){yield t.deleteAllKeyBackupVersions();var r=V.createRandomKey(),s=r.megolmV1PublicKey,_={public_key:s.publicKeyBase64};yield e(_);var o=yield t.http.authedRequest(D.Post,"/room_keys/version",void 0,{algorithm:s.algorithm,auth_data:_},{prefix:Se.V3});return yield t.saveBackupDecryptionKey(r,o.version),{version:o.version,algorithm:s.algorithm,authData:_,decryptionKey:r}})()}deleteAllKeyBackupVersions(){var e=this;return g(function*(){for(var t,r,s=(t=(r=yield e.requestKeyBackupVersion())===null||r===void 0?void 0:r.version)!==null&&t!==void 0?t:null;s!=null;){var _,o;yield e.deleteKeyBackupVersion(s),s=(_=(o=yield e.requestKeyBackupVersion())===null||o===void 0?void 0:o.version)!==null&&_!==void 0?_:null}})()}deleteKeyBackupVersion(e){var t=this;return g(function*(){t.logger.debug("deleteKeyBackupVersion v:".concat(e));var r=ot("/room_keys/version/$version",{$version:e});yield t.http.authedRequest(D.Delete,r,void 0,void 0,{prefix:Se.V3}),t.activeBackupVersion===e&&(t.serverBackupInfo=null,yield t.disableKeyBackup())})()}createBackupDecryptor(e){return new Rg(this.logger,e)}restoreKeyBackup(e,t,r){var s=this;return g(function*(){var _=yield s.downloadKeyBackup(e);return s.importKeyBackup(_,e,t,r)})()}downloadKeyBackup(e){return this.http.authedRequest(D.Get,"/room_keys/keys",{version:e},void 0,{prefix:Se.V3})}importKeyBackup(e,t,r,s){var _=this;return g(function*(){var o,a=200,c=Gi(e),d=0,w=0;s==null||(o=s.progressCallback)===null||o===void 0||o.call(s,{total:c,successes:d,stage:Re.LoadKeys,failures:w});var f=function(){var ts=g(function*(ir){var sr,tt=[],rs=function*(rt){var is=yield r.decryptSessions(ir.get(rt));is.forEach(an=>{an.room_id=rt,tt.push(an)})};for(var ns of ir.keys())yield*rs(ns);try{yield _.importBackedUpRoomKeys(tt,t),d+=tt.length}catch(rt){w+=tt.length,_.logger.error("Error importing keys from backup",rt)}s==null||(sr=s.progressCallback)===null||sr===void 0||sr.call(s,{total:c,successes:d,stage:Re.LoadKeys,failures:w})});return function(ir){return ts.apply(this,arguments)}}(),m=0,K=new Map;for(var[U,H]of Object.entries(e.rooms))if(H.sessions){K.set(U,{});for(var[nr,Xi]of Object.entries(H.sessions)){var es=K.get(U);es[nr]=Xi,m+=1,m>=a&&(yield f(K),K=new Map,K.set(U,{}),m=0)}}return m>0&&(yield f(K)),{total:c,imported:d}})()}backupInfoMatchesBackupDecryptionKey(e,t){var r;return e.algorithm!=="m.megolm_backup.v1.curve25519-aes-sha2"?(this.logger.warn("backupMatchesPrivateKey: Unsupported backup algorithm",e.algorithm),!1):((r=e.auth_data)===null||r===void 0?void 0:r.public_key)===t.megolmV1PublicKey.publicKeyBase64}}class Rg{constructor(e,t){this.logger=e,k(this,"decryptionKey",void 0),k(this,"sourceTrusted",void 0),this.decryptionKey=t,this.sourceTrusted=!1}decryptSessions(e){var t=this;return g(function*(){var r=[];for(var[s,_]of Object.entries(e))try{var o=JSON.parse(t.decryptionKey.decryptV1(_.session_data.ephemeral,_.session_data.mac,_.session_data.ciphertext));o.session_id=s,r.push(o)}catch(a){t.logger.debug("Failed to decrypt megolm session from backup",a,_)}return r})()}free(){this.decryptionKey.free()}}function Wi(i,e){return Jr.apply(this,arguments)}function Jr(){return Jr=g(function*(i,e){try{var t=e?ot("/room_keys/version/$version",{$version:e}):"/room_keys/version";return yield i.authedRequest(D.Get,t,void 0,void 0,{prefix:Se.V3})}catch(r){if(r.errcode==="M_NOT_FOUND")return null;throw r}}),Jr.apply(this,arguments)}function Qr(i,e){var t=e.auth_data;return t.public_key===i.megolmV1PublicKey.publicKeyBase64}function Gi(i){var e=0;for(var{sessions:t}of Object.values(i.rooms))e+=Object.keys(t).length;return e}class Kg{constructor(e,t,r){this.logger=e,this.olmMachine=t,this.outgoingRequestProcessor=r,k(this,"stopped",!1),k(this,"outgoingRequestLoopRunning",!1),k(this,"nextLoopDeferred",void 0)}stop(){this.stopped=!0}doProcessOutgoingRequests(){this.nextLoopDeferred||(this.nextLoopDeferred=Promise.withResolvers());var e=this.nextLoopDeferred.promise;return this.outgoingRequestLoopRunning||this.outgoingRequestLoop().catch(t=>{this.logger.error("Uncaught error in outgoing request loop",t)}),e}outgoingRequestLoop(){var e=this;return g(function*(){if(e.outgoingRequestLoopRunning)throw new Error("Cannot run two outgoing request loops");e.outgoingRequestLoopRunning=!0;try{for(;!e.stopped&&e.nextLoopDeferred;){var t=e.nextLoopDeferred;e.nextLoopDeferred=void 0,yield e.processOutgoingRequests().then(t.resolve,t.reject)}}finally{e.outgoingRequestLoopRunning=!1}e.nextLoopDeferred&&e.nextLoopDeferred.reject(new Error("OutgoingRequestsManager was stopped"))})()}processOutgoingRequests(){var e=this;return g(function*(){if(!e.stopped){var t=yield e.olmMachine.outgoingRequests(),r=function*(o){if(e.stopped)return{v:void 0};try{yield W(e.logger,"Make outgoing request ".concat(o.type),g(function*(){yield e.outgoingRequestProcessor.makeOutgoingRequest(o)}))}catch(a){e.logger.error("Failed to process outgoing request ".concat(o.type,": ").concat(a))}},s;for(var _ of t)if(s=yield*r(_),s)return s.v}})()}}var vt=5e3,ee=function(i){return i.MISSING_DECRYPTION_KEY="MISSING_DECRYPTION_KEY",i.NETWORK_ERROR="NETWORK_ERROR",i.STOPPED="STOPPED",i}(ee||{});class qe extends Error{constructor(e){super("Failed to get key from backup: ".concat(e)),this.code=e,this.name="KeyDownloadError"}}class Ji extends Error{constructor(e){super("Failed to get key from backup: rate limited"),this.retryMillis=e,this.name="KeyDownloadRateLimitError"}}class Ig{constructor(e,t,r,s){this.olmMachine=t,this.http=r,this.backupManager=s,k(this,"stopped",!1),k(this,"configuration",null),k(this,"sessionLastCheckAttemptedTime",new Map),k(this,"logger",void 0),k(this,"downloadLoopRunning",!1),k(this,"queuedRequests",[]),k(this,"hasConfigurationProblem",!1),k(this,"currentBackupVersionCheck",null),k(this,"onBackupStatusChanged",()=>{this.hasConfigurationProblem=!1,this.configuration=null,this.getOrCreateBackupConfiguration().then(_=>{_&&this.downloadKeysLoop()})}),this.logger=e.getChild("[PerSessionKeyBackupDownloader]"),s.on(I.KeyBackupStatus,this.onBackupStatusChanged),s.on(I.KeyBackupFailed,this.onBackupStatusChanged),s.on(I.KeyBackupDecryptionKeyCached,this.onBackupStatusChanged)}isKeyBackupDownloadConfigured(){return this.configuration!==null}getServerBackupInfo(){var e=this;return g(function*(){return yield e.backupManager.getServerBackupInfo()})()}onDecryptionKeyMissingError(e,t){if(this.isAlreadyInQueue(e,t)){this.logger.trace("Not checking key backup for session ".concat(t," as it is already queued"));return}if(this.wasRequestedRecently(t)){this.logger.trace("Not checking key backup for session ".concat(t," as it was already requested recently"));return}this.queuedRequests.push({roomId:e,megolmSessionId:t}),this.downloadKeysLoop()}stop(){this.stopped=!0,this.backupManager.off(I.KeyBackupStatus,this.onBackupStatusChanged),this.backupManager.off(I.KeyBackupFailed,this.onBackupStatusChanged),this.backupManager.off(I.KeyBackupDecryptionKeyCached,this.onBackupStatusChanged)}isAlreadyInQueue(e,t){return this.queuedRequests.some(r=>r.roomId==e&&r.megolmSessionId==t)}markAsNotFoundInBackup(e){var t=Date.now();this.sessionLastCheckAttemptedTime.set(e,t),this.sessionLastCheckAttemptedTime.size>100&&(this.sessionLastCheckAttemptedTime=new Map(Array.from(this.sessionLastCheckAttemptedTime).filter((r,s)=>Math.max(t-s,0)<vt)))}wasRequestedRecently(e){var t=this.sessionLastCheckAttemptedTime.get(e);return t?Math.max(Date.now()-t,0)<vt:!1}getBackupDecryptionKey(){var e=this;return g(function*(){try{return yield e.olmMachine.getBackupKeys()}catch{return null}})()}requestRoomKeyFromBackup(e,t,r){var s=this;return g(function*(){var _=ot("/room_keys/keys/$roomId/$sessionId",{$roomId:t,$sessionId:r});return yield s.http.authedRequest(D.Get,_,{version:e},void 0,{prefix:Se.V3})})()}downloadKeysLoop(){var e=this;return g(function*(){if(!e.downloadLoopRunning&&!e.hasConfigurationProblem){e.downloadLoopRunning=!0;try{for(;e.queuedRequests.length>0;){var t=e.queuedRequests[0];try{var r=yield e.getOrCreateBackupConfiguration();if(!r){e.downloadLoopRunning=!1;return}var s=yield e.queryKeyBackup(t.roomId,t.megolmSessionId,r);if(e.stopped)return;try{yield e.decryptAndImport(t,s,r)}catch(_){e.logger.error("Error while decrypting and importing key backup for session ".concat(t.megolmSessionId),_)}e.queuedRequests.shift()}catch(_){if(_ instanceof qe)switch(_.code){case ee.MISSING_DECRYPTION_KEY:e.markAsNotFoundInBackup(t.megolmSessionId),e.queuedRequests.shift();break;case ee.NETWORK_ERROR:yield re(vt);break;case ee.STOPPED:e.downloadLoopRunning=!1;return}else _ instanceof Ji&&(yield re(_.retryMillis))}}}finally{e.downloadLoopRunning=!1}}})()}queryKeyBackup(e,t,r){var s=this;return g(function*(){if(s.logger.debug("Checking key backup for session ".concat(t)),s.stopped)throw new qe(ee.STOPPED);try{var _=yield s.requestRoomKeyFromBackup(r.backupVersion,e,t);return s.logger.debug("Got key from backup for sessionId:".concat(t)),_}catch(d){if(s.stopped)throw new qe(ee.STOPPED);if(s.logger.info("No luck requesting key backup for session ".concat(t,": ").concat(d)),d instanceof ln){var o=d.data.errcode;if(o=="M_NOT_FOUND")throw new qe(ee.MISSING_DECRYPTION_KEY);if(d.isRateLimitError()){var a;try{var c;a=(c=d.getRetryAfterMs())!==null&&c!==void 0?c:void 0}catch(w){s.logger.warn("Error while retrieving a rate-limit retry delay",w)}throw a&&a>0&&s.logger.info("Rate limited by server, waiting ".concat(a,"ms")),new Ji(a??vt)}}throw new qe(ee.NETWORK_ERROR)}})()}decryptAndImport(e,t,r){var s=this;return g(function*(){var _={[e.megolmSessionId]:t},o=yield r.decryptor.decryptSessions(_);for(var a of o)a.room_id=e.roomId;yield s.backupManager.importBackedUpRoomKeys(o,r.backupVersion)})()}getOrCreateBackupConfiguration(){var e=this;return g(function*(){if(e.configuration)return e.configuration;if(e.hasConfigurationProblem)return null;if(e.currentBackupVersionCheck!=null)return e.logger.debug("Already checking server version, use current promise"),yield e.currentBackupVersionCheck;e.currentBackupVersionCheck=e.internalCheckFromServer();try{return yield e.currentBackupVersionCheck}finally{e.currentBackupVersionCheck=null}})()}internalCheckFromServer(){var e=this;return g(function*(){var t,r,s,_=null;try{_=yield e.backupManager.getServerBackupInfo()}catch(f){return e.logger.debug("Backup: error while checking server version: ".concat(f)),e.hasConfigurationProblem=!0,null}if(e.logger.debug("Got current backup version from server: ".concat((t=_)===null||t===void 0?void 0:t.version)),((r=_)===null||r===void 0?void 0:r.algorithm)!="m.megolm_backup.v1.curve25519-aes-sha2"){var o;return e.logger.info("Unsupported algorithm ".concat((o=_)===null||o===void 0?void 0:o.algorithm)),e.hasConfigurationProblem=!0,null}if(!((s=_)!==null&&s!==void 0&&s.version))return e.logger.info("No current key backup"),e.hasConfigurationProblem=!0,null;var a=yield e.backupManager.getActiveBackupVersion();if(a==null||_.version!=a)return e.logger.info("The current backup version on the server (".concat(_.version,") is not trusted. Version we are currently backing up to: ").concat(a)),e.hasConfigurationProblem=!0,null;var c=yield e.getBackupDecryptionKey();if(!(c!=null&&c.decryptionKey))return e.logger.debug("Not checking key backup for session (no decryption key)"),e.hasConfigurationProblem=!0,null;if(a!=c.backupVersion)return e.logger.debug("Version for which we have a decryption key (".concat(c.backupVersion,") doesn't match the version we are backing up to (").concat(a,")")),e.hasConfigurationProblem=!0,null;var d=_.auth_data;if(d.public_key!=c.decryptionKey.megolmV1PublicKey.publicKeyBase64)return e.logger.debug("Key backup on server does not match our decryption key"),e.hasConfigurationProblem=!0,null;var w=e.backupManager.createBackupDecryptor(c.decryptionKey);return e.hasConfigurationProblem=!1,e.configuration={decryptor:w,backupVersion:a},e.configuration})()}}function Cg(i,e){if(!i.private_key_salt||!i.private_key_iterations)throw new Error("Salt and/or iterations not found: this backup cannot be restored with a passphrase");return pn(e,i.private_key_salt,i.private_key_iterations,i.private_key_bits)}function Qi(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(i);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(i,s).enumerable})),t.push.apply(t,r)}return t}function Hi(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Qi(Object(t),!0).forEach(function(r){k(i,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Qi(Object(t)).forEach(function(r){Object.defineProperty(i,r,Object.getOwnPropertyDescriptor(t,r))})}return i}var Yi=[N.Sas,N.ScanQrCode,N.ShowQrCode,N.Reciprocate];class Dg extends me{constructor(e,t,r,s,_,o,a){super(),this.logger=e,this.olmMachine=t,this.http=r,this.userId=s,this.secretStorage=o,this.cryptoCallbacks=a,k(this,"RECOVERY_KEY_DERIVATION_ITERATIONS",5e5),k(this,"_trustCrossSignedDevices",!0),k(this,"deviceIsolationMode",new as(!1)),k(this,"stopped",!1),k(this,"roomEncryptors",{}),k(this,"eventDecryptor",void 0),k(this,"keyClaimManager",void 0),k(this,"outgoingRequestProcessor",void 0),k(this,"crossSigningIdentity",void 0),k(this,"backupManager",void 0),k(this,"outgoingRequestsManager",void 0),k(this,"perSessionBackupDownloader",void 0),k(this,"dehydratedDeviceManager",void 0),k(this,"reemitter",new gn(this)),k(this,"globalBlacklistUnverifiedDevices",!1),k(this,"_supportedVerificationMethods",Yi),this.outgoingRequestProcessor=new wg(e,t,r),this.outgoingRequestsManager=new Kg(this.logger,t,this.outgoingRequestProcessor),this.keyClaimManager=new yg(t,this.outgoingRequestProcessor),this.backupManager=new Sg(e,t,r,this.outgoingRequestProcessor),this.perSessionBackupDownloader=new Ig(this.logger,this.olmMachine,this.http,this.backupManager),this.dehydratedDeviceManager=new lg(this.logger,t,r,this.outgoingRequestProcessor,o),this.eventDecryptor=new Eg(this.logger,t,this.perSessionBackupDownloader),this.reemitter.reEmit(this.backupManager,[I.KeyBackupStatus,I.KeyBackupSessionsRemaining,I.KeyBackupFailed,I.KeyBackupDecryptionKeyCached]),this.reemitter.reEmit(this.dehydratedDeviceManager,[I.DehydratedDeviceCreated,I.DehydratedDeviceUploaded,I.RehydrationStarted,I.RehydrationProgress,I.RehydrationCompleted,I.RehydrationError,I.DehydrationKeyCached,I.DehydratedDeviceRotationError]),this.crossSigningIdentity=new vg(e,t,this.outgoingRequestProcessor,o),this.checkKeyBackupAndEnable()}getOlmMachineOrThrow(){if(this.stopped)throw new cs;return this.olmMachine}set globalErrorOnUnknownDevices(e){}get globalErrorOnUnknownDevices(){return!1}stop(){this.stopped||(this.stopped=!0,this.keyClaimManager.stop(),this.backupManager.stop(),this.outgoingRequestsManager.stop(),this.perSessionBackupDownloader.stop(),this.dehydratedDeviceManager.stop(),this.olmMachine.close())}encryptEvent(e,t){var r=this;return g(function*(){var s=e.getRoomId(),_=r.roomEncryptors[s];if(!_)throw new Error("Cannot encrypt event in unconfigured room ".concat(s));yield _.encryptEvent(e,r.globalBlacklistUnverifiedDevices,r.deviceIsolationMode)})()}decryptEvent(e){var t=this;return g(function*(){var r=e.getRoomId();if(!r)throw new Error("to-device event was not decrypted in preprocessToDeviceMessages");return yield t.eventDecryptor.attemptEventDecryption(e,t.deviceIsolationMode)})()}getBackupDecryptor(e,t){var r=this;return g(function*(){if(!(t instanceof Uint8Array))throw new Error("getBackupDecryptor: expects Uint8Array");if(e.algorithm!="m.megolm_backup.v1.curve25519-aes-sha2")throw new Error("getBackupDecryptor: Unsupported algorithm ".concat(e.algorithm));var s=V.fromBase64(or(t));if(!Qr(s,e))throw new Error("getBackupDecryptor: key backup on server does not match the decryption key");return r.backupManager.createBackupDecryptor(s)})()}importBackedUpRoomKeys(e,t,r){var s=this;return g(function*(){return yield s.backupManager.importBackedUpRoomKeys(e,t,r)})()}maybeAcceptKeyBundle(e,t){var r=this;return g(function*(){var s=new it(r.logger,"maybeAcceptKeyBundle(".concat(e,", ").concat(t,")")),_=yield r.olmMachine.getReceivedRoomKeyBundleData(new R(e),new h(t));if(!_){s.info("No key bundle found for user");return}s.info("Fetching key bundle ".concat(_.url));var o=gs(r.http.opts.baseUrl,_.url,void 0,void 0,void 0,!1,!0,!0),a;try{var c=new URL(o);a=yield r.http.authedRequest(D.Get,c.pathname+c.search,{},void 0,{rawResponseBody:!0,prefix:""})}catch(d){throw s.warn("Error downloading encrypted bundle from ".concat(o,":"),d),d}s.info("Received blob of length ".concat(a.size));try{yield r.olmMachine.receiveRoomKeyBundle(_,new Uint8Array(yield a.arrayBuffer()))}catch(d){throw s.warn("Error receiving encrypted bundle:",d),d}})()}getVersion(){var e=kn();return"Rust SDK ".concat(e.matrix_sdk_crypto," (").concat(e.git_sha,"), Vodozemac ").concat(e.vodozemac)}setDeviceIsolationMode(e){this.deviceIsolationMode=e}isEncryptionEnabledInRoom(e){var t=this;return g(function*(){var r=yield t.olmMachine.getRoomSettings(new R(e));return!!(r!=null&&r.algorithm)})()}getOwnDeviceKeys(){var e=this;return g(function*(){var t=e.olmMachine.identityKeys;return{ed25519:t.ed25519.toBase64(),curve25519:t.curve25519.toBase64()}})()}prepareToEncrypt(e){var t=this.roomEncryptors[e.roomId];t&&t.prepareForEncryption(this.globalBlacklistUnverifiedDevices,this.deviceIsolationMode)}forceDiscardSession(e){var t;return(t=this.roomEncryptors[e])===null||t===void 0?void 0:t.forceDiscardSession()}exportRoomKeys(){var e=this;return g(function*(){var t=yield e.olmMachine.exportRoomKeys(()=>!0);return JSON.parse(t)})()}exportRoomKeysAsJson(){var e=this;return g(function*(){return yield e.olmMachine.exportRoomKeys(()=>!0)})()}importRoomKeys(e,t){var r=this;return g(function*(){return yield r.backupManager.importRoomKeys(e,t)})()}importRoomKeysAsJson(e,t){var r=this;return g(function*(){return yield r.backupManager.importRoomKeysAsJson(e,t)})()}userHasCrossSigningKeys(){var e=arguments,t=this;return g(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:t.userId,s=e.length>1&&e[1]!==void 0?e[1]:!1,_=yield t.olmMachine.trackedUsers(),o;for(var a of _)if(r===a.toString()){o=a;break}if(o!==void 0){if(r===t.userId){var c=t.olmMachine.queryKeysForUsers([o.clone()]);yield t.outgoingRequestProcessor.makeOutgoingRequest(c)}var d=yield t.olmMachine.getIdentity(o);return d==null||d.free(),d!==void 0}else if(s){var w,f=yield t.downloadDeviceList(new Set([r])),m=(w=f.master_keys)===null||w===void 0?void 0:w[r];return m?!!Object.values(m.keys)[0]:!1}else return!1})()}getUserDeviceInfo(e){var t=arguments,r=this;return g(function*(){var s=t.length>1&&t[1]!==void 0?t[1]:!1,_=new Map,o=yield r.getOlmMachineOrThrow().trackedUsers(),a=new Set;o.forEach(f=>a.add(f.toString()));var c=new Set;for(var d of e)a.has(d)?_.set(d,yield r.getUserDevices(d)):c.add(d);if(s&&c.size>=1){var w=yield r.downloadDeviceList(c);Object.entries(w.device_keys).forEach(f=>{var[m,K]=f;return _.set(m,hg(K))})}return _})()}getUserDevices(e){var t=this;return g(function*(){var r=new h(e),s=yield t.olmMachine.getUserDevices(r,1);try{var _=s.devices();try{return new Map(_.map(o=>[o.deviceId.toString(),bg(o,r)]))}finally{_.forEach(o=>o.free())}}finally{s.free()}})()}downloadDeviceList(e){var t=this;return g(function*(){var r={device_keys:{}};return e.forEach(s=>r.device_keys[s]=[]),yield t.http.authedRequest(D.Post,"/_matrix/client/v3/keys/query",void 0,r,{prefix:""})})()}getTrustCrossSignedDevices(){return this._trustCrossSignedDevices}setTrustCrossSignedDevices(e){this._trustCrossSignedDevices=e}setDeviceVerified(e,t){var r=arguments,s=this;return g(function*(){var _=r.length>2&&r[2]!==void 0?r[2]:!0,o=yield s.olmMachine.getDevice(new h(e),new C(t));if(!o)throw new Error("Unknown device ".concat(e,"|").concat(t));try{yield o.setLocalTrust(_?lr.Verified:lr.Unset)}finally{o.free()}})()}crossSignDevice(e){var t=this;return g(function*(){var r=yield t.olmMachine.getDevice(new h(t.userId),new C(e));if(!r)throw new Error("Unknown device ".concat(e));try{var s=yield r.verify();yield t.outgoingRequestProcessor.makeOutgoingRequest(s)}finally{r.free()}})()}getDeviceVerificationStatus(e,t){var r=this;return g(function*(){var s=yield r.olmMachine.getDevice(new h(e),new C(t));if(!s)return null;try{return new us({signedByOwner:s.isCrossSignedByOwner(),crossSigningVerified:s.isCrossSigningTrusted(),localVerified:s.isLocallyTrusted(),trustCrossSignedDevices:r._trustCrossSignedDevices})}finally{s.free()}})()}getUserVerificationStatus(e){var t=this;return g(function*(){var r=yield t.getOlmMachineOrThrow().getIdentity(new h(e));if(r===void 0)return new wn(!1,!1,!1);var s=r.isVerified(),_=r.wasPreviouslyVerified(),o=r instanceof je?r.identityNeedsUserApproval():!1;return r.free(),new wn(s,_,!1,o)})()}pinCurrentUserIdentity(e){var t=this;return g(function*(){var r=yield t.getOlmMachineOrThrow().getIdentity(new h(e));if(r===void 0)throw new Error("Cannot pin identity of unknown user");if(r instanceof xe)throw new Error("Cannot pin identity of own user");yield r.pinCurrentMasterKey()})()}withdrawVerificationRequirement(e){var t=this;return g(function*(){var r=yield t.getOlmMachineOrThrow().getIdentity(new h(e));if(r===void 0)throw new Error("Cannot withdraw verification of unknown user");yield r.withdrawVerification()})()}isCrossSigningReady(){var e=this;return g(function*(){var{privateKeysInSecretStorage:t,privateKeysCachedLocally:r}=yield e.getCrossSigningStatus(),s=!!r.masterKey&&!!r.selfSigningKey&&!!r.userSigningKey,_=yield e.getOwnIdentity();return!!(_!=null&&_.isVerified())&&(s||t)})()}getCrossSigningKeyId(){var e=arguments,t=this;return g(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:ct.Master,s=yield t.olmMachine.getIdentity(new h(t.userId));if(!s)return null;try{var _=yield t.olmMachine.crossSigningStatus(),o=_.hasMaster&&_.hasUserSigning&&_.hasSelfSigning;if(!o||!s.isVerified())return null;var a;switch(r){case ct.Master:a=s.masterKey;break;case ct.SelfSigning:a=s.selfSigningKey;break;case ct.UserSigning:a=s.userSigningKey;break;default:return null}var c=JSON.parse(a);return Object.values(c.keys)[0]}finally{s.free()}})()}bootstrapCrossSigning(e){var t=this;return g(function*(){yield t.crossSigningIdentity.bootstrapCrossSigning(e)})()}isSecretStorageReady(){var e=this;return g(function*(){var t=["m.cross_signing.master","m.cross_signing.user_signing","m.cross_signing.self_signing"],r=(yield e.backupManager.getActiveBackupVersion())!=null;return r&&t.push("m.megolm_backup.v1"),Ni(e.secretStorage,t)})()}bootstrapSecretStorage(){var e=arguments,t=this;return g(function*(){var{createSecretStorageKey:r,setupNewSecretStorage:s,setupNewKeyBackup:_}=e.length>0&&e[0]!==void 0?e[0]:{},o=s||!(yield t.secretStorageHasAESKey());if(o){if(!r)throw new Error("unable to create a new secret storage key, createSecretStorageKey is not set");t.logger.info("bootstrapSecretStorage: creating new secret storage key");var a=yield r();if(!a)throw new Error("createSecretStorageKey() callback did not return a secret storage key");yield t.addSecretStorageKeyToSecretStorage(a)}var c=yield t.olmMachine.exportCrossSigningKeys(),d=c&&c.masterKey!==void 0&&c.self_signing_key!==void 0&&c.userSigningKey!==void 0;d&&(o||!(yield zi(t.secretStorage)))&&(t.logger.info("bootstrapSecretStorage: cross-signing keys not yet exported; doing so now."),yield t.secretStorage.store("m.cross_signing.master",c.masterKey),yield t.secretStorage.store("m.cross_signing.user_signing",c.userSigningKey),yield t.secretStorage.store("m.cross_signing.self_signing",c.self_signing_key)),_?yield t.resetKeyBackup():yield t.saveBackupKeyToStorage()})()}saveBackupKeyToStorage(){var e=this;return g(function*(){var t=yield e.backupManager.getServerBackupInfo();if(!t||!t.version){e.logger.info("Not saving backup key to secret storage: no backup info");return}var r=yield e.olmMachine.getBackupKeys();if(!r.decryptionKey){e.logger.info("Not saving backup key to secret storage: no backup key");return}if(!Qr(r.decryptionKey,t)){e.logger.info("Not saving backup key to secret storage: decryption key does not match backup info");return}var s=r.decryptionKey.toBase64();yield e.secretStorage.store("m.megolm_backup.v1",s)})()}addSecretStorageKeyToSecretStorage(e){var t=this;return g(function*(){var r,s,_,o,a=yield t.secretStorage.addKey(yn,{passphrase:(r=e.keyInfo)===null||r===void 0?void 0:r.passphrase,name:(s=e.keyInfo)===null||s===void 0?void 0:s.name,key:e.privateKey});yield t.secretStorage.setDefaultKeyId(a.keyId),(_=(o=t.cryptoCallbacks).cacheSecretStorageKey)===null||_===void 0||_.call(o,a.keyId,a.keyInfo,e.privateKey)})()}secretStorageHasAESKey(){var e=this;return g(function*(){var t=yield e.secretStorage.getKey();if(!t)return!1;var[,r]=t;return r.algorithm===yn})()}getCrossSigningStatus(){var e=this;return g(function*(){var t=yield e.getOlmMachineOrThrow().getIdentity(new h(e.userId)),r=!!(t!=null&&t.masterKey)&&!!(t!=null&&t.selfSigningKey)&&!!(t!=null&&t.userSigningKey);t==null||t.free();var s=yield zi(e.secretStorage),_=yield e.getOlmMachineOrThrow().crossSigningStatus();return{publicKeysOnDevice:r,privateKeysInSecretStorage:s,privateKeysCachedLocally:{masterKey:!!(_!=null&&_.hasMaster),userSigningKey:!!(_!=null&&_.hasUserSigning),selfSigningKey:!!(_!=null&&_.hasSelfSigning)}}})()}createRecoveryKeyFromPassphrase(e){var t=this;return g(function*(){if(e){var r=bn(32),s=yield pn(e,r,t.RECOVERY_KEY_DERIVATION_ITERATIONS);return{keyInfo:{passphrase:{algorithm:"m.pbkdf2",iterations:t.RECOVERY_KEY_DERIVATION_ITERATIONS,salt:r}},privateKey:s,encodedPrivateKey:hn(s)}}else{var _=new Uint8Array(32);return globalThis.crypto.getRandomValues(_),{privateKey:_,encodedPrivateKey:hn(_)}}})()}getEncryptionInfoForEvent(e){var t=this;return g(function*(){return t.eventDecryptor.getEncryptionInfoForEvent(e)})()}getVerificationRequestsToDeviceInProgress(e){var t=this.olmMachine.getVerificationRequests(new h(e));return t.filter(r=>r.roomId===void 0).map(r=>this.makeVerificationRequest(r))}findVerificationRequestDMInProgress(e,t){if(!t)throw new Error("missing userId");var r=this.olmMachine.getVerificationRequests(new h(t)),s=r.find(_=>{var o;return((o=_.roomId)===null||o===void 0?void 0:o.toString())===e});if(s)return this.makeVerificationRequest(s)}requestVerificationDM(e,t){var r=this;return g(function*(){var s=yield r.olmMachine.getIdentity(new h(e));if(!s)throw new Error("unknown userId ".concat(e));try{var _=r._supportedVerificationMethods.map(d=>ft(d)),o=yield s.verificationRequestContent(_),a=yield r.sendVerificationRequestContent(t,o),c=yield s.requestVerification(new R(t),new Rr(a),_);return r.makeVerificationRequest(c)}finally{s.free()}})()}sendVerificationRequestContent(e,t){var r=this;return g(function*(){var s=bn(32),{event_id:_}=yield r.http.authedRequest(D.Put,"/_matrix/client/v3/rooms/".concat(encodeURIComponent(e),"/send/m.room.message/").concat(encodeURIComponent(s)),void 0,t,{prefix:""});return _})()}setSupportedVerificationMethods(e){this._supportedVerificationMethods=e??Yi}requestOwnUserVerification(){var e=this;return g(function*(){var t=yield e.olmMachine.getIdentity(new h(e.userId));if(t===void 0)throw new Error("cannot request verification for this device when there is no existing cross-signing key");try{var[r,s]=yield t.requestVerification(e._supportedVerificationMethods.map(ft));return yield e.outgoingRequestProcessor.makeOutgoingRequest(s),e.makeVerificationRequest(r)}finally{t.free()}})()}requestDeviceVerification(e,t){var r=this;return g(function*(){var s=yield r.olmMachine.getDevice(new h(e),new C(t));if(!s)throw new Error("Not a known device");try{var[_,o]=s.requestVerification(r._supportedVerificationMethods.map(ft));return yield r.outgoingRequestProcessor.makeOutgoingRequest(o),r.makeVerificationRequest(_)}finally{s.free()}})()}getSessionBackupPrivateKey(){var e=this;return g(function*(){var t=yield e.olmMachine.getBackupKeys();return t.decryptionKey?_r(t.decryptionKey.toBase64()):null})()}storeSessionBackupPrivateKey(e,t){var r=this;return g(function*(){var s=or(e);if(!t)throw new Error("storeSessionBackupPrivateKey: version is required");yield r.backupManager.saveBackupDecryptionKey(V.fromBase64(s),t)})()}loadSessionBackupPrivateKeyFromSecretStorage(){var e=this;return g(function*(){var t=yield e.secretStorage.get("m.megolm_backup.v1");if(!t)throw new Error("loadSessionBackupPrivateKeyFromSecretStorage: missing decryption key in secret storage");var r=yield e.backupManager.getServerBackupInfo();if(!r||!r.version)throw new Error("loadSessionBackupPrivateKeyFromSecretStorage: unable to get backup version");var s=V.fromBase64(t);if(!Qr(s,r))throw new Error("loadSessionBackupPrivateKeyFromSecretStorage: decryption key does not match backup info");yield e.backupManager.saveBackupDecryptionKey(s,r.version)})()}getActiveSessionBackupVersion(){var e=this;return g(function*(){return yield e.backupManager.getActiveBackupVersion()})()}getKeyBackupInfo(){var e=this;return g(function*(){return(yield e.backupManager.getServerBackupInfo())||null})()}isKeyBackupTrusted(e){var t=this;return g(function*(){return yield t.backupManager.isKeyBackupTrusted(e)})()}checkKeyBackupAndEnable(){var e=this;return g(function*(){return yield e.backupManager.checkKeyBackupAndEnable(!0)})()}deleteKeyBackupVersion(e){var t=this;return g(function*(){yield t.backupManager.deleteKeyBackupVersion(e)})()}resetKeyBackup(){var e=this;return g(function*(){var t=yield e.backupManager.setupKeyBackup(r=>e.signObject(r));(yield e.secretStorageHasAESKey())&&(yield e.secretStorage.store("m.megolm_backup.v1",t.decryptionKey.toBase64())),e.checkKeyBackupAndEnable()})()}disableKeyStorage(){var e=this;return g(function*(){var t=yield e.getKeyBackupInfo();t!=null&&t.version?yield e.deleteKeyBackupVersion(t.version):e.logger.error("Can't delete key backup version: no version available"),yield e.deleteSecretStorage(),yield e.dehydratedDeviceManager.delete()})()}signObject(e){var t=this;return g(function*(){var r=new Map(Object.entries(e.signatures||{})),s=e.unsigned;delete e.signatures,delete e.unsigned;var _=r.get(t.userId)||{},o=cg.stringify(e),a=yield t.olmMachine.sign(o),c=JSON.parse(a.asJSON());r.set(t.userId,Hi(Hi({},_),c[t.userId])),s!==void 0&&(e.unsigned=s),e.signatures=Object.fromEntries(r.entries())})()}restoreKeyBackupWithPassphrase(e,t){var r=this;return g(function*(){var s=yield r.backupManager.getServerBackupInfo();if(!(s!=null&&s.version))throw new Error("No backup info available");var _=yield Cg(s.auth_data,e);return yield r.storeSessionBackupPrivateKey(_,s.version),r.restoreKeyBackup(t)})()}restoreKeyBackup(e){var t=this;return g(function*(){var r=yield t.olmMachine.getBackupKeys(),{decryptionKey:s,backupVersion:_}=r;if(!s||!_)throw new Error("No decryption key found in crypto store");var o=_r(s.toBase64()),a=yield t.backupManager.requestKeyBackupVersion(_);if(!a)throw new Error("Backup version to restore ".concat(_," not found on server"));var c=yield t.getBackupDecryptor(a,o);try{var d;return e==null||(d=e.progressCallback)===null||d===void 0||d.call(e,{stage:Re.Fetch}),yield t.backupManager.restoreKeyBackup(_,c,e)}finally{c.free()}})()}isDehydrationSupported(){var e=this;return g(function*(){return yield e.dehydratedDeviceManager.isSupported()})()}startDehydration(){var e=arguments,t=this;return g(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:{};if(!(yield t.isCrossSigningReady())||!(yield t.isSecretStorageReady()))throw new Error("Device dehydration requires cross-signing and secret storage to be set up");return yield t.dehydratedDeviceManager.start(r||{})})()}importSecretsBundle(e){var t=this;return g(function*(){var r=oe.from_json(e);yield t.getOlmMachineOrThrow().importSecretsBundle(r)})()}exportSecretsBundle(){var e=this;return g(function*(){var t=yield e.getOlmMachineOrThrow().exportSecretsBundle(),r=t.to_json();return t.free(),r})()}encryptToDeviceMessages(e,t,r){var s=this;return g(function*(){var _=new it(s.logger,"encryptToDeviceMessages"),o=new Set(t.map(c=>{var{userId:d}=c;return d}));yield s.keyClaimManager.ensureSessionsForUsers(_,Array.from(o).map(c=>new h(c)));var a={batch:[],eventType:P.RoomMessageEncrypted};return yield Promise.all(t.map(function(){var c=g(function*(d){var{userId:w,deviceId:f}=d,m=yield s.olmMachine.getDevice(new h(w),new C(f));if(m){var K=JSON.parse(yield m.encryptToDeviceEvent(e,r));a.batch.push({deviceId:f,userId:w,payload:K})}else s.logger.warn("encryptToDeviceMessages: unknown device ".concat(w,":").concat(f))});return function(d){return c.apply(this,arguments)}}())),a})()}resetEncryption(e){var t=this;return g(function*(){t.logger.debug("resetEncryption: resetting encryption"),t.dehydratedDeviceManager.delete(),yield t.backupManager.deleteAllKeyBackupVersions(),yield t.deleteSecretStorage(),yield t.crossSigningIdentity.bootstrapCrossSigning({setupNewCrossSigning:!0,authUploadDeviceSigningKeys:e}),yield t.resetKeyBackup(),t.logger.debug("resetEncryption: ended")})()}deleteSecretStorage(){var e=this;return g(function*(){yield e.secretStorage.store("m.cross_signing.master",null),yield e.secretStorage.store("m.cross_signing.self_signing",null),yield e.secretStorage.store("m.cross_signing.user_signing",null),yield e.secretStorage.store("m.megolm_backup.v1",null);var t=yield e.secretStorage.getDefaultKeyId();t&&(yield e.secretStorage.store("m.secret_storage.key.".concat(t),null)),yield e.secretStorage.setDefaultKeyId(null)})()}shareRoomHistoryWithUser(e,t){var r=this;return g(function*(){var s=new it(r.logger,"shareRoomHistoryWithUser(".concat(e,", ").concat(t,")")),_=yield r.getOwnIdentity();if(!(_!=null&&_.isVerified())){s.warn("Not sharing message history as the current device is not verified by our cross-signing identity");return}s.info("Sharing message history");var o=yield r.getOlmMachineOrThrow().buildRoomKeyBundle(new R(e));if(!o){s.info("No keys to share");return}var a=yield r.http.uploadContent(o.encryptedData);s.info("Uploaded encrypted key blob: ".concat(JSON.stringify(a)));var c=r.getOlmMachineOrThrow().queryKeysForUsers([new h(t)]);yield r.outgoingRequestProcessor.makeOutgoingRequest(c),yield r.keyClaimManager.ensureSessionsForUsers(s,[new h(t)]);var d=yield r.getOlmMachineOrThrow().shareRoomKeyBundleData(new h(t),new R(e),a.content_uri,o.mediaEncryptionInfo,B.identityBasedStrategy());for(var w of d)yield r.outgoingRequestProcessor.makeOutgoingRequest(w)})()}receiveSyncChanges(e){var t=this;return g(function*(){var{events:r,oneTimeKeysCounts:s=new Map,unusedFallbackKeys:_,devices:o=new yt}=e;return yield t.olmMachine.receiveSyncChanges(r?JSON.stringify(r):"[]",o,s,_)})()}preprocessToDeviceMessages(e){var t=this;return g(function*(){var r=yield t.receiveSyncChanges({events:e}),s=[];for(var _ of r){var o=JSON.parse(_.rawEvent);if(o.type===P.KeyVerificationRequest){var a=o.sender,c=o.content.transaction_id;c&&a&&t.onIncomingKeyVerificationRequest(a,c)}switch(_.type){case De.Decrypted:{var d,w=_.encryptionInfo;s.push({message:o,encryptionInfo:{sender:w.sender.toString(),senderDevice:(d=w.senderDevice)===null||d===void 0?void 0:d.toString(),senderCurve25519KeyBase64:w.senderCurve25519Key,senderVerified:w.isSenderVerified()}});break}case De.PlainText:{s.push({message:o,encryptionInfo:null});break}case De.UnableToDecrypt:break;case De.Invalid:break}}return s})()}processKeyCounts(e,t){var r=this;return g(function*(){var s=e&&new Map(Object.entries(e)),_=t&&new Set(t);(s!==void 0||_!==void 0)&&(yield r.receiveSyncChanges({oneTimeKeysCounts:s,unusedFallbackKeys:_}))})()}processDeviceLists(e){var t=this;return g(function*(){var r,s,_=new yt((r=e.changed)===null||r===void 0?void 0:r.map(o=>new h(o)),(s=e.left)===null||s===void 0?void 0:s.map(o=>new h(o)));yield t.receiveSyncChanges({devices:_})})()}onCryptoEvent(e,t){var r=this;return g(function*(){var s=t.getContent(),_=new _e;if(s.algorithm==="m.megolm.v1.aes-sha2")_.algorithm=ge.MegolmV1AesSha2;else{r.logger.warn("Room ".concat(e.roomId,": ignoring crypto event with invalid algorithm ").concat(s.algorithm));return}try{_.sessionRotationPeriodMs=s.rotation_period_ms,_.sessionRotationPeriodMessages=s.rotation_period_msgs,yield r.olmMachine.setRoomSettings(new R(e.roomId),_)}catch(a){r.logger.warn("Room ".concat(e.roomId,": ignoring crypto event which caused error: ").concat(a));return}var o=r.roomEncryptors[e.roomId];o?o.onCryptoEvent(s):r.roomEncryptors[e.roomId]=new gg(r.logger.getChild("[".concat(e.roomId," encryption]")),r.olmMachine,r.keyClaimManager,r.outgoingRequestsManager,e,s)})()}onSyncCompleted(e){this.outgoingRequestsManager.doProcessOutgoingRequests().catch(t=>{this.logger.warn("onSyncCompleted: Error processing outgoing requests",t)})}markAllTrackedUsersAsDirty(){var e=this;return g(function*(){yield e.olmMachine.markAllTrackedUsersAsDirty()})()}onIncomingKeyVerificationRequest(e,t){var r=this.olmMachine.getVerificationRequest(new h(e),t);r?this.emit(I.VerificationRequestReceived,this.makeVerificationRequest(r)):this.logger.info("Ignoring just-received verification request ".concat(t," which did not start a rust-side verification"))}makeVerificationRequest(e){return new mg(this.logger,this.olmMachine,e,this.outgoingRequestProcessor,this._supportedVerificationMethods)}onRoomMembership(e,t,r){var s=this.roomEncryptors[e.getRoomId()];s&&s.onRoomMembership(t)}onRoomKeysUpdated(e){var t=this;return g(function*(){for(var r of e)t.onRoomKeyUpdated(r);t.backupManager.maybeUploadKey()})()}onRoomKeyUpdated(e){var t=this;if(!this.stopped){this.logger.debug("Got update for session ".concat(e.sessionId," from sender ").concat(e.senderKey.toBase64()," in ").concat(e.roomId.toString()));var r=this.eventDecryptor.getEventsPendingRoomKey(e.roomId.toString(),e.sessionId);if(r.length!==0){this.logger.debug("Retrying decryption on events:",r.map(o=>"".concat(o.getId())));var s=function(o){o.attemptDecryption(t,{isRetry:!0}).catch(a=>{t.logger.info("Still unable to decrypt event ".concat(o.getId()," after receiving key"))})};for(var _ of r)s(_)}}}onRoomKeysWithheld(e){var t=this;return g(function*(){for(var r of e){t.logger.debug("Got withheld message for session ".concat(r.sessionId," in ").concat(r.roomId.toString()));var s=t.eventDecryptor.getEventsPendingRoomKey(r.roomId.toString(),r.sessionId);if(s.length===0)return;t.logger.debug("Retrying decryption on events:",s.map(o=>"".concat(o.getId())));for(var _ of s)_.attemptDecryption(t,{isRetry:!0}).catch(o=>{})}})()}onUserIdentityUpdated(e){var t=this;return g(function*(){var r=yield t.getUserVerificationStatus(e.toString());t.emit(I.UserTrustStatusChanged,e.toString(),r),e.toString()===t.userId&&(t.emit(I.KeysChanged,{}),yield t.checkKeyBackupAndEnable())})()}onDevicesUpdated(e){var t=this;return g(function*(){t.emit(I.WillUpdateDevices,e,!1),t.emit(I.DevicesUpdated,e,!1)})()}handleSecretReceived(e,t){var r=this;return g(function*(){return r.logger.debug("onReceiveSecret: Received secret ".concat(e)),e==="m.megolm_backup.v1"?yield r.backupManager.handleBackupSecretReceived(t):!1})()}checkSecrets(e){var t=this;return g(function*(){var r=yield t.olmMachine.getSecretsFromInbox(e);for(var s of r)if(yield t.handleSecretReceived(e,s))break;yield t.olmMachine.deleteSecretsFromInbox(e)})()}onLiveEventFromSync(e){var t=this;return g(function*(){if(!(e.isState()||e.getUnsigned().transaction_id)){var r=function(){var a=g(function*(c){kg(e)&&(yield t.onKeyVerificationEvent(c))});return function(c){return a.apply(this,arguments)}}();if(e.isDecryptionFailure()||e.isEncrypted()){var s=3e5,_=setTimeout(()=>e.off(ar.Decrypted,o),s),o=(a,c)=>{c||(clearTimeout(_),e.off(ar.Decrypted,o),r(a))};e.on(ar.Decrypted,o)}else yield r(e)}})()}onKeyVerificationEvent(e){var t=this;return g(function*(){var r=e.getRoomId();if(!r)throw new Error("missing roomId in the event");t.logger.debug("Incoming verification event ".concat(e.getId()," type ").concat(e.getType()," from ").concat(e.getSender())),yield t.olmMachine.receiveVerificationEvent(JSON.stringify({event_id:e.getId(),type:e.getType(),sender:e.getSender(),state_key:e.getStateKey(),content:e.getContent(),origin_server_ts:e.getTs()}),new R(r)),e.getType()===P.RoomMessage&&e.getContent().msgtype===dn.KeyVerificationRequest&&t.onIncomingKeyVerificationRequest(e.getSender(),e.getId()),t.outgoingRequestsManager.doProcessOutgoingRequests().catch(s=>{t.logger.warn("onKeyVerificationRequest: Error processing outgoing requests",s)})})()}getOwnIdentity(){var e=this;return g(function*(){return yield e.olmMachine.getIdentity(new h(e.userId))})()}}class Eg{constructor(e,t,r){this.logger=e,this.olmMachine=t,this.perSessionBackupDownloader=r,k(this,"eventsPendingKey",new fn(()=>new fn(()=>new Set)))}attemptEventDecryption(e,t){var r=this;return g(function*(){r.addEventToPendingList(e);var s;switch(t.kind){case st.AllDevicesIsolationMode:s=wr.Untrusted;break;case st.OnlySignedDevicesIsolationMode:s=wr.CrossSignedOrLegacy;break}try{var _=yield r.olmMachine.decryptRoomEvent($i(e),new R(e.getRoomId()),new Oe(s));return r.removeEventFromPendingList(e),{clearEvent:JSON.parse(_.event),claimedEd25519Key:_.senderClaimedEd25519Key,senderCurve25519Key:_.senderCurve25519Key,forwardingCurve25519KeyChain:_.forwardingCurve25519KeyChain}}catch(o){if(o instanceof Ne)r.onMegolmDecryptionError(e,o,yield r.perSessionBackupDownloader.getServerBackupInfo());else throw new z(T.UNKNOWN_ERROR,"Unknown error")}})()}onMegolmDecryptionError(e,t,r){var s=e.getWireContent(),_={sender_key:s.sender_key,session_id:s.session_id};if(t.code===$.MissingRoomKey||t.code===$.UnknownMessageIndex){this.perSessionBackupDownloader.onDecryptionKeyMissingError(e.getRoomId(),s.session_id);var o=e.getMembershipAtEvent();if(o&&o!==nt.Join&&o!==nt.Invite)throw new z(T.HISTORICAL_MESSAGE_USER_NOT_JOINED,"This message was sent when we were not a member of the room.",_);if(e.getTs()<=this.olmMachine.deviceCreationTimeMs)throw r===null?new z(T.HISTORICAL_MESSAGE_NO_KEY_BACKUP,"This message was sent before this device logged in, and there is no key backup on the server.",_):this.perSessionBackupDownloader.isKeyBackupDownloadConfigured()?new z(T.HISTORICAL_MESSAGE_WORKING_BACKUP,"This message was sent before this device logged in. Key backup is working, but we still do not (yet) have the key.",_):new z(T.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED,"This message was sent before this device logged in, and key backup is not working.",_)}if(t.maybe_withheld){var a=t.maybe_withheld==="The sender has disabled encrypting to unverified devices."?T.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE:T.MEGOLM_KEY_WITHHELD;throw new z(a,t.maybe_withheld,_)}switch(t.code){case $.MissingRoomKey:throw new z(T.MEGOLM_UNKNOWN_INBOUND_SESSION_ID,"The sender's device has not sent us the keys for this message.",_);case $.UnknownMessageIndex:throw new z(T.OLM_UNKNOWN_MESSAGE_INDEX,"The sender's device has not sent us the keys for this message at this index.",_);case $.SenderIdentityVerificationViolation:throw this.removeEventFromPendingList(e),new z(T.SENDER_IDENTITY_PREVIOUSLY_VERIFIED,"The sender identity is unverified, but was previously verified.");case $.UnknownSenderDevice:throw this.removeEventFromPendingList(e),new z(T.UNKNOWN_SENDER_DEVICE,"The sender device is not known.");case $.UnsignedSenderDevice:throw this.removeEventFromPendingList(e),new z(T.UNSIGNED_SENDER_DEVICE,"The sender identity is not cross-signed.");default:throw new z(T.UNKNOWN_ERROR,t.description,_)}}getEncryptionInfoForEvent(e){var t=this;return g(function*(){if(!e.getClearContent()||e.isDecryptionFailure())return null;if(e.status!==null)return{shieldColour:gt.NONE,shieldReason:null};var r=yield t.olmMachine.getRoomEventEncryptionInfo($i(e),new R(e.getRoomId()));return Og(t.logger,r)})()}getEventsPendingRoomKey(e,t){var r=this.eventsPendingKey.get(e);if(!r)return[];var s=r.get(t);return s?[...s]:[]}addEventToPendingList(e){var t=e.getRoomId();if(t){var r=this.eventsPendingKey.getOrCreate(t),s=r.getOrCreate(e.getWireContent().session_id);s.add(e)}}removeEventFromPendingList(e){var t=e.getRoomId();if(t){var r=this.eventsPendingKey.getOrCreate(t);if(r){var s=r.get(e.getWireContent().session_id);s&&(s.delete(e),s.size===0&&(r.delete(e.getWireContent().session_id),r.size===0&&this.eventsPendingKey.delete(t)))}}}}function $i(i){return JSON.stringify({event_id:i.getId(),type:i.getWireType(),sender:i.getSender(),state_key:i.getStateKey(),content:i.getWireContent(),origin_server_ts:i.getTs()})}function Og(i,e){if(e===void 0)return null;var t=e.shieldState(!1),r;switch(t.color){case pr.Grey:r=gt.GREY;break;case pr.None:r=gt.NONE;break;default:r=gt.RED}var s;switch(t.code){case void 0:case null:s=null;break;case Z.AuthenticityNotGuaranteed:s=Y.AUTHENTICITY_NOT_GUARANTEED;break;case Z.UnknownDevice:s=Y.UNKNOWN_DEVICE;break;case Z.UnsignedDevice:s=Y.UNSIGNED_DEVICE;break;case Z.UnverifiedIdentity:s=Y.UNVERIFIED_IDENTITY;break;case Z.SentInClear:s=Y.SENT_IN_CLEAR;break;case Z.VerificationViolation:s=Y.VERIFICATION_VIOLATION;break;case Z.MismatchedSender:s=Y.MISMATCHED_SENDER;break;default:s=Y.UNKNOWN;break}return{shieldColour:r,shieldReason:s}}function Mg(i){return Hr.apply(this,arguments)}function Hr(){return Hr=g(function*(i){var e,{logger:t,legacyStore:r}=i;if(yield Fi(),!(yield r.containsData()))return;yield r.startup();var s=null;if(yield r.doTxn("readonly",[Ke.STORE_ACCOUNT],m=>{r.getAccount(m,K=>{s=K})}),!s){t.debug("Legacy crypto store is not set up (no account found). Not migrating.");return}var _=yield r.getMigrationState();if(_>=A.MEGOLM_SESSIONS_MIGRATED)return;var o=yield Bg(t,r),a=yield Ug(t,r),c=1+o+a;t.info("Migrating data from legacy crypto store. ".concat(o," olm sessions and ").concat(a," megolm sessions to migrate."));var d=0;function w(m){var K;d+=m,(K=i.legacyMigrationProgressListener)===null||K===void 0||K.call(i,d,c)}w(0);var f=new TextEncoder().encode(i.legacyPickleKey);_===A.NOT_STARTED&&(t.info("Migrating data from legacy crypto store. Step 1: base data"),yield qg(i.http,i.userId,i.deviceId,r,f,i.storeHandle,t),_=A.INITIAL_DATA_MIGRATED,yield r.setMigrationState(_)),w(1),_===A.INITIAL_DATA_MIGRATED&&(t.info("Migrating data from legacy crypto store. Step 2: olm sessions (".concat(o," sessions to migrate).")),yield Fg(t,r,f,i.storeHandle,w),_=A.OLM_SESSIONS_MIGRATED,yield r.setMigrationState(_)),_===A.OLM_SESSIONS_MIGRATED&&(t.info("Migrating data from legacy crypto store. Step 3: megolm sessions (".concat(a," sessions to migrate).")),yield Vg(t,r,f,i.storeHandle,w),_=A.MEGOLM_SESSIONS_MIGRATED,yield r.setMigrationState(_)),(e=i.legacyMigrationProgressListener)===null||e===void 0||e.call(i,-1,-1),t.info("Migration from legacy crypto store complete")}),Hr.apply(this,arguments)}function qg(i,e,t,r,s,_,o){return Yr.apply(this,arguments)}function Yr(){return Yr=g(function*(i,e,t,r,s,_,o){var a=new br;a.userId=new h(e),a.deviceId=new C(t),yield r.doTxn("readonly",[Ke.STORE_ACCOUNT],H=>r.getAccount(H,nr=>{a.pickledAccount=nr??""}));var c=yield mt(r,s,"m.megolm_backup.v1");if(c){for(var d=!1,w=null;!d;)try{w=yield Wi(i),d=!0}catch(H){o.info("Failed to get backup version during migration, retrying in 2 seconds",H),yield re(2e3)}if(w&&w.algorithm=="m.megolm_backup.v1.curve25519-aes-sha2")try{var f,m=V.fromBase64(c),K=(f=w.auth_data)===null||f===void 0?void 0:f.public_key,U=m.megolmV1PublicKey.publicKeyBase64==K;U?(a.backupVersion=w.version,a.backupRecoveryKey=c):o.debug("The backup key to migrate does not match the active backup version","Cached pub key: ".concat(m.megolmV1PublicKey.publicKeyBase64),"Active pub key: ".concat(K))}catch(H){o.warn("Failed to check if the backup key to migrate matches the active backup version",H)}}a.privateCrossSigningMasterKey=yield mt(r,s,"master"),a.privateCrossSigningSelfSigningKey=yield mt(r,s,"self_signing"),a.privateCrossSigningUserSigningKey=yield mt(r,s,"user_signing"),yield bt.migrateBaseData(a,s,_,o)}),Yr.apply(this,arguments)}function Bg(i,e){return $r.apply(this,arguments)}function $r(){return $r=g(function*(i,e){i.debug("Counting olm sessions to be migrated");var t;return yield e.doTxn("readonly",[Ke.STORE_SESSIONS],r=>e.countEndToEndSessions(r,s=>t=s)),t}),$r.apply(this,arguments)}function Ug(i,e){return Zr.apply(this,arguments)}function Zr(){return Zr=g(function*(i,e){return i.debug("Counting megolm sessions to be migrated"),yield e.countEndToEndInboundGroupSessions()}),Zr.apply(this,arguments)}function Fg(i,e,t,r,s){return Xr.apply(this,arguments)}function Xr(){return Xr=g(function*(i,e,t,r,s){for(;;){var _=yield e.getEndToEndSessionsBatch();if(_===null)return;i.debug("Migrating batch of ".concat(_.length," olm sessions"));var o=[];for(var a of _){var c=new We;c.senderKey=a.deviceKey,c.pickle=a.session,c.lastUseTime=c.creationTime=new Date(a.lastReceivedMessageTs),o.push(c)}yield bt.migrateOlmSessions(o,t,r,i),yield e.deleteEndToEndSessionsBatch(_),s(_.length)}}),Xr.apply(this,arguments)}function Vg(i,e,t,r,s){return en.apply(this,arguments)}function en(){return en=g(function*(i,e,t,r,s){for(;;){var _=yield e.getEndToEndInboundGroupSessionsBatch();if(_===null)return;i.debug("Migrating batch of ".concat(_.length," megolm sessions"));var o=[];for(var a of _){var c,d=a.sessionData,w=new Le;w.pickle=d.session,w.roomId=new R(d.room_id),w.senderKey=a.senderKey,w.senderSigningKey=(c=d.keysClaimed)===null||c===void 0?void 0:c.ed25519,w.backedUp=!a.needsBackup,w.imported=d.untrusted===!0,o.push(w)}yield bt.migrateMegolmSessions(o,t,r,i),yield e.deleteEndToEndInboundGroupSessionsBatch(_),s(_.length)}}),en.apply(this,arguments)}function Tg(i){return tn.apply(this,arguments)}function tn(){return tn=g(function*(i){var{logger:e,legacyStore:t,olmMachine:r}=i;if(yield t.containsData()){var s=yield t.getMigrationState();if(!(s>=A.ROOM_SETTINGS_MIGRATED)){var _={};yield t.doTxn("readwrite",[Ke.STORE_ROOMS],d=>{t.getEndToEndRooms(d,w=>{_=w})}),e.debug("Migrating ".concat(Object.keys(_).length," sets of room settings"));for(var[o,a]of Object.entries(_))try{var c=new _e;if(a.algorithm!=="m.megolm.v1.aes-sha2"){e.warn("Room ".concat(o,": ignoring room with invalid algorithm ").concat(a.algorithm));continue}c.algorithm=ge.MegolmV1AesSha2,c.sessionRotationPeriodMs=a.rotation_period_ms,c.sessionRotationPeriodMessages=a.rotation_period_msgs,yield r.setRoomSettings(new R(o),c)}catch(d){e.warn("Room ".concat(o,": ignoring settings ").concat(JSON.stringify(a)," which caused error ").concat(d))}e.debug("Completed room settings migration"),yield t.setMigrationState(A.ROOM_SETTINGS_MIGRATED)}}}),tn.apply(this,arguments)}function mt(i,e,t){return rn.apply(this,arguments)}function rn(){return rn=g(function*(i,e,t){var r=yield new Promise(s=>{i.doTxn("readonly",[Ke.STORE_ACCOUNT],_=>{i.getSecretStorePrivateKey(_,s,t)})});return r&&r.ciphertext&&r.iv&&r.mac?yield ds(r,e,t):r instanceof Uint8Array?or(r):void 0}),rn.apply(this,arguments)}function Pg(i){return nn.apply(this,arguments)}function nn(){return nn=g(function*(i){var{legacyCryptoStore:e,rustCrypto:t,logger:r}=i,s=yield t.getOwnIdentity();if(s&&!s.isVerified()){var _=yield zg(e);if(_){var o=JSON.parse(s.masterKey);if(!o.keys||Object.keys(o.keys).length===0){r.error("Post Migration | Unexpected error: no master key in the rust session.");return}var a=Object.values(o.keys)[0];a&&a==_&&(r.info("Post Migration: Migrating legacy trusted MSK: ".concat(_," to locally verified.")),yield s.verify())}}}),nn.apply(this,arguments)}function zg(i){return sn.apply(this,arguments)}function sn(){return sn=g(function*(i){var e=null;return yield i.doTxn("readonly","account",t=>{i.getCrossSigningKeys(t,r=>{var s=r==null?void 0:r.master;s&&Object.keys(s.keys).length!=0&&(e=Object.values(s.keys)[0])})}),e}),sn.apply(this,arguments)}function Zi(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(i);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(i,s).enumerable})),t.push.apply(t,r)}return t}function Ng(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Zi(Object(t),!0).forEach(function(r){k(i,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Zi(Object(t)).forEach(function(r){Object.defineProperty(i,r,Object.getOwnPropertyDescriptor(t,r))})}return i}function Ag(i){return _n.apply(this,arguments)}function _n(){return _n=g(function*(i){var{logger:e}=i;e.debug("Initialising Rust crypto-sdk WASM artifact"),yield Fi(),e.debug("Opening Rust CryptoStore");var t;i.storePrefix?i.storeKey?t=yield j.openWithKey(i.storePrefix,i.storeKey,e):t=yield j.open(i.storePrefix,i.storePassphrase,e):t=yield j.open(null,null,e),i.legacyCryptoStore&&(yield Mg(Ng({legacyStore:i.legacyCryptoStore,storeHandle:t},i)));var r=yield jg(e,i.http,i.userId,i.deviceId,i.secretStorage,i.cryptoCallbacks,t,i.legacyCryptoStore);return t.free(),e.debug("Completed rust crypto-sdk setup"),r}),_n.apply(this,arguments)}function jg(i,e,t,r,s,_,o,a){return on.apply(this,arguments)}function on(){return on=g(function*(i,e,t,r,s,_,o,a){i.debug("Init OlmMachine");var c=yield Ae.initFromStore(new h(t),new C(r),o,i);a&&(yield Tg({logger:i,legacyStore:a,olmMachine:c})),c.roomKeyRequestsEnabled=!1;var d=new Dg(i,c,e,t,r,s,_);if(yield c.registerRoomKeyUpdatedCallback(m=>d.onRoomKeysUpdated(m)),yield c.registerRoomKeysWithheldCallback(m=>d.onRoomKeysWithheld(m)),yield c.registerUserIdentityUpdatedCallback(m=>d.onUserIdentityUpdated(m)),yield c.registerDevicesUpdatedCallback(m=>d.onDevicesUpdated(m)),d.checkSecrets("m.megolm_backup.v1"),yield c.registerReceiveSecretCallback((m,K)=>d.checkSecrets(m)),yield c.outgoingRequests(),a&&(yield a.containsData())){var w=yield a.getMigrationState();if(w<A.INITIAL_OWN_KEY_QUERY_DONE){i.debug("Performing initial key query after migration");for(var f=!1;!f;)try{yield d.userHasCrossSigningKeys(t),f=!0}catch(m){i.error("Failed to check for cross-signing keys after migration, retrying",m)}yield Pg({legacyCryptoStore:a,rustCrypto:d,logger:i}),yield a.setMigrationState(A.INITIAL_OWN_KEY_QUERY_DONE)}}return d}),on.apply(this,arguments)}export{Ag as initRustCrypto};
3
+ `]="\\n",J["\f"]="\\f",J["\r"]="\\r",J['"']='\\"',J["\\"]="\\\\";function Ti(i){return Vi.lastIndex=0,i.replace(Vi,function(e){return J[e]})}function xr(i){switch(typeof i){case"string":return'"'+Ti(i)+'"';case"number":return isFinite(i)?i:"null";case"boolean":return i;case"object":return i===null?"null":Array.isArray(i)?_g(i):og(i);default:throw new Error("Cannot stringify: "+typeof i)}}function _g(i){for(var e="[",t="",r=0;r<i.length;++r)t+=e,e=",",t+=xr(i[r]);return e!=","?"[]":t+"]"}function og(i){var e="{",t="",r=Object.keys(i);r.sort();for(var s=0;s<r.length;++s){var _=r[s];t+=e+'"'+Ti(_)+'":',e=",",t+=xr(i[_])}return e!=","?"{}":t+"}"}var ag={stringify:xr};const cg=ds(ag);class gg{constructor(e,t,r,s,_,o){this.prefixedLogger=e,this.olmMachine=t,this.keyClaimManager=r,this.outgoingRequestManager=s,this.room=_,this.encryptionSettings=o,k(this,"lazyLoadedMembersResolved",!1),k(this,"currentEncryptionPromise",Promise.resolve());var a=_.getJoinedMembers();this.olmMachine.updateTrackedUsers(a.map(c=>new h(c.userId))).catch(c=>this.prefixedLogger.error("Error initializing tracked users",c))}onCryptoEvent(e){if(JSON.stringify(this.encryptionSettings)!=JSON.stringify(e))throw new Error("Cannot reconfigure an active RoomEncryptor")}onRoomMembership(e){(e.membership==nt.Join||e.membership==nt.Invite&&this.room.shouldEncryptForInvitedMembers())&&this.olmMachine.updateTrackedUsers([new h(e.userId)]).catch(t=>{this.prefixedLogger.error("Unable to update tracked users",t)})}prepareForEncryption(e,t){var r=this;return g(function*(){yield r.encryptEvent(null,e,t)})()}encryptEvent(e,t,r){var s,_=this,o=new it(this.prefixedLogger,e?(s=e.getTxnId())!==null&&s!==void 0?s:"":"prepareForEncryption"),a=this.currentEncryptionPromise.catch(()=>{}).then(g(function*(){yield W(o,"ensureEncryptionSession",g(function*(){yield _.ensureEncryptionSession(o,t,r)})),e&&(yield W(o,"encryptEventInner",g(function*(){yield _.encryptEventInner(o,e)})))}));return this.currentEncryptionPromise=a,a}ensureEncryptionSession(e,t,r){var s=this;return g(function*(){if(s.encryptionSettings.algorithm!=="m.megolm.v1.aes-sha2")throw new Error("Cannot encrypt in ".concat(s.room.roomId," for unsupported algorithm '").concat(s.encryptionSettings.algorithm,"'"));e.debug("Starting encryption");var _=yield s.room.getEncryptionTargetMembers();s.lazyLoadedMembersResolved?(e.debug("Processing outgoing requests in background"),s.outgoingRequestManager.doProcessOutgoingRequests()):(yield W(e,"loadMembersIfNeeded: updateTrackedUsers",g(function*(){yield s.olmMachine.updateTrackedUsers(_.map(w=>new h(w.userId)))})),e.debug("Updated tracked users"),s.lazyLoadedMembersResolved=!0,e.debug("Processing outgoing requests"),yield W(e,"doProcessOutgoingRequests",g(function*(){yield s.outgoingRequestManager.doProcessOutgoingRequests()}))),e.debug("Encrypting for users (shouldEncryptForInvitedMembers: ".concat(s.room.shouldEncryptForInvitedMembers(),"):"),_.map(w=>"".concat(w.userId," (").concat(w.membership,")")));var o=_.map(w=>new h(w.userId));yield W(e,"ensureSessionsForUsers",g(function*(){yield s.keyClaimManager.ensureSessionsForUsers(e,o)}));var a=new Sr;switch(a.historyVisibility=ug(s.room.getHistoryVisibility()),a.algorithm=ge.MegolmV1AesSha2,typeof s.encryptionSettings.rotation_period_ms=="number"&&(a.rotationPeriod=BigInt(s.encryptionSettings.rotation_period_ms*1e3)),typeof s.encryptionSettings.rotation_period_msgs=="number"&&(a.rotationPeriodMessages=BigInt(s.encryptionSettings.rotation_period_msgs)),r.kind){case st.AllDevicesIsolationMode:{var c,d=(c=s.room.getBlacklistUnverifiedDevices())!==null&&c!==void 0?c:t;a.sharingStrategy=B.deviceBasedStrategy(d,r.errorOnVerifiedUserProblems)}break;case st.OnlySignedDevicesIsolationMode:a.sharingStrategy=B.identityBasedStrategy();break}yield W(e,"shareRoomKey",g(function*(){var w=yield s.olmMachine.shareRoomKey(new R(s.room.roomId),o,a);if(w)for(var f of w)yield s.outgoingRequestManager.outgoingRequestProcessor.makeOutgoingRequest(f)}))})()}forceDiscardSession(){var e=this;return g(function*(){var t=yield e.olmMachine.invalidateGroupSession(new R(e.room.roomId));t&&e.prefixedLogger.info("Discarded existing group session")})()}encryptEventInner(e,t){var r=this;return g(function*(){e.debug("Encrypting actual message content");var s=yield r.olmMachine.encryptRoomEvent(new R(r.room.roomId),t.getType(),JSON.stringify(t.getContent()));t.makeEncrypted(P.RoomMessageEncrypted,JSON.parse(s),r.olmMachine.identityKeys.curve25519.toBase64(),r.olmMachine.identityKeys.ed25519.toBase64()),e.debug("Encrypted event successfully")})()}}function ug(i){switch(i){case _t.Invited:return Ce.Invited;case _t.Joined:return Ce.Joined;case _t.Shared:return Ce.Shared;case _t.WorldReadable:return Ce.WorldReadable}}var Me="/_matrix/client/unstable/org.matrix.msc3814.v1",Lr="org.matrix.msc3814",dg=7*24*60*60*1e3;class lg extends me{constructor(e,t,r,s,_){super(),this.logger=e,this.olmMachine=t,this.http=r,this.outgoingRequestProcessor=s,this.secretStorage=_,k(this,"intervalId",void 0)}cacheKey(e){var t=this;return g(function*(){yield t.olmMachine.dehydratedDevices().saveDehydratedDeviceKey(e),t.emit(I.DehydrationKeyCached)})()}isSupported(){var e=this;return g(function*(){try{yield e.http.authedRequest(D.Get,"/dehydrated_device",void 0,void 0,{prefix:Me})}catch(r){var t=r;if(t.errcode==="M_UNRECOGNIZED")return!1;if(t.errcode==="M_NOT_FOUND")return!0;throw r}return!0})()}start(){var e=arguments,t=this;return g(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:{};if(typeof r=="boolean"&&(r={createNewKey:r}),!(r.onlyIfKeyCached&&!(yield t.olmMachine.dehydratedDevices().getDehydratedDeviceKey()))){if(t.stop(),r.rehydrate!==!1)try{yield t.rehydrateDeviceIfAvailable()}catch(s){t.logger.info("dehydration: Error rehydrating device:",s),t.emit(I.RehydrationError,s.message)}r.createNewKey&&(yield t.resetKey()),yield t.scheduleDeviceDehydration()}})()}isKeyStored(){var e=this;return g(function*(){return!!(yield e.secretStorage.isStored(Lr))})()}resetKey(){var e=this;return g(function*(){var t=x.createRandomKey();return yield e.secretStorage.store(Lr,t.toBase64()),yield e.cacheKey(t),t})()}getKey(e){var t=this;return g(function*(){var r=yield t.olmMachine.dehydratedDevices().getDehydratedDeviceKey();if(r)return r;var s=yield t.secretStorage.get(Lr);if(s===void 0)return e?yield t.resetKey():null;var _=_r(s);try{var o=x.createKeyFromArray(_);return yield t.cacheKey(o),o}finally{_.fill(0)}})()}rehydrateDeviceIfAvailable(){var e=this;return g(function*(){var t=yield e.getKey(!1);if(!t)return!1;var r;try{r=yield e.http.authedRequest(D.Get,"/dehydrated_device",void 0,void 0,{prefix:Me})}catch(m){var s=m;if(s.errcode==="M_NOT_FOUND"||s.errcode==="M_UNRECOGNIZED")return e.logger.info("dehydration: No dehydrated device"),!1;throw s}e.logger.info("dehydration: dehydrated device found"),e.emit(I.RehydrationStarted);var _=yield e.olmMachine.dehydratedDevices().rehydrate(t,new C(r.device_id),JSON.stringify(r.device_data));e.logger.info("dehydration: device rehydrated");for(var o=void 0,a=0,c=0,d=ot("/dehydrated_device/$device_id/events",{$device_id:r.device_id});;){var w=yield e.http.authedRequest(D.Post,d,void 0,o?{next_batch:o}:{},{prefix:Me});if(w.events.length===0)break;a+=w.events.length,o=w.next_batch;var f=yield _.receiveEvents(JSON.stringify(w.events));c+=f.length,e.emit(I.RehydrationProgress,c,a)}return e.logger.info("dehydration: received ".concat(c," room keys from ").concat(a," to-device events")),e.emit(I.RehydrationCompleted),!0})()}createAndUploadDehydratedDevice(){var e=this;return g(function*(){var t=yield e.getKey(!0),r=yield e.olmMachine.dehydratedDevices().create();e.emit(I.DehydratedDeviceCreated);var s=yield r.keysForUpload("Dehydrated device",t);yield e.outgoingRequestProcessor.makeOutgoingRequest(s),e.emit(I.DehydratedDeviceUploaded),e.logger.info("dehydration: uploaded device")})()}scheduleDeviceDehydration(){var e=this;return g(function*(){e.stop(),yield e.createAndUploadDehydratedDevice(),e.intervalId=setInterval(()=>{e.createAndUploadDehydratedDevice().catch(t=>{e.emit(I.DehydratedDeviceRotationError,t.message),e.logger.error("Error creating dehydrated device:",t)})},dg)})()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}delete(){var e=this;return g(function*(){e.stop();try{yield e.http.authedRequest(D.Delete,"/dehydrated_device",void 0,{},{prefix:Me})}catch(r){var t=r;if(t.errcode==="M_UNRECOGNIZED"||t.errcode==="M_NOT_FOUND")return;throw r}})()}}function Pi(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(i);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(i,s).enumerable})),t.push.apply(t,r)}return t}function pg(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Pi(Object(t),!0).forEach(function(r){k(i,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Pi(Object(t)).forEach(function(r){Object.defineProperty(i,r,Object.getOwnPropertyDescriptor(t,r))})}return i}class wg{constructor(e,t,r){this.logger=e,this.olmMachine=t,this.http=r}makeOutgoingRequest(e,t){var r=this;return g(function*(){var s;if(e instanceof Pe)s=yield r.requestWithRetry(D.Post,"/_matrix/client/v3/keys/upload",{},e.body);else if(e instanceof we)s=yield r.requestWithRetry(D.Post,"/_matrix/client/v3/keys/query",{},e.body);else if(e instanceof Te)s=yield r.requestWithRetry(D.Post,"/_matrix/client/v3/keys/claim",{},e.body);else if(e instanceof he)s=yield r.requestWithRetry(D.Post,"/_matrix/client/v3/keys/signatures/upload",{},e.body);else if(e instanceof Ve)s=yield r.requestWithRetry(D.Put,"/_matrix/client/v3/room_keys/keys",{version:e.version},e.body);else if(e instanceof Xe)s=yield r.sendToDeviceRequest(e);else if(e instanceof Qe){var _="/_matrix/client/v3/rooms/".concat(encodeURIComponent(e.room_id),"/send/")+"".concat(encodeURIComponent(e.event_type),"/").concat(encodeURIComponent(e.txn_id));s=yield r.requestWithRetry(D.Put,_,{},e.body)}else if(e instanceof et){yield r.makeRequestWithUIA(D.Post,"/_matrix/client/v3/keys/device_signing/upload",{},e.body,t);return}else if(e instanceof Ge){var o=Me+"/dehydrated_device";yield r.rawJsonRequest(D.Put,o,{},e.body);return}else r.logger.warn("Unsupported outgoing message",Object.getPrototypeOf(e)),s="";if(e.id)try{yield W(r.logger,"Mark Request as sent ".concat(e.type),g(function*(){yield r.olmMachine.markRequestAsSent(e.id,e.type,s)}))}catch(a){if(a instanceof Error&&(a.message==="Attempt to use a moved value"||a.message==="null pointer passed to rust"))r.logger.debug("Ignoring error '".concat(a.message,"': client is likely shutting down"));else throw a}else r.logger.trace("Outgoing request type:".concat(e.type," does not have an ID"))})()}sendToDeviceRequest(e){var t=this;return g(function*(){var r=JSON.parse(e.body),s=[];for(var[_,o]of Object.entries(r.messages))for(var[a,c]of Object.entries(o))s.push("".concat(_,"/").concat(a," (msgid ").concat(c[ss],")"));t.logger.info("Sending batch of to-device messages. type=".concat(e.event_type," txnid=").concat(e.txn_id),s);var d="/_matrix/client/v3/sendToDevice/".concat(encodeURIComponent(e.event_type),"/")+encodeURIComponent(e.txn_id);return yield t.requestWithRetry(D.Put,d,{},e.body)})()}makeRequestWithUIA(e,t,r,s,_){var o=this;return g(function*(){if(!_)return yield o.requestWithRetry(e,t,r,s);var a=JSON.parse(s),c=function(){var w=g(function*(f){var m=pg({},a);f!==null&&(m.auth=f);var K=yield o.requestWithRetry(e,t,r,JSON.stringify(m));return JSON.parse(K)});return function(f){return w.apply(this,arguments)}}(),d=yield _(c);return JSON.stringify(d)})()}requestWithRetry(e,t,r,s){var _=this;return g(function*(){for(var o=0;;)try{return yield _.rawJsonRequest(e,t,r,s)}catch(c){o++;var a=_s(c,o,!0);if(a<0)throw c;yield re(a)}})()}rawJsonRequest(e,t,r,s){var _=this;return g(function*(){var o={json:!1,headers:{"Content-Type":"application/json",Accept:"application/json"},prefix:"",localTimeoutMs:6e4};return yield _.http.authedRequest(e,t,r,s,o)})()}}class yg{constructor(e,t){this.olmMachine=e,this.outgoingRequestProcessor=t,k(this,"currentClaimPromise",void 0),k(this,"stopped",!1),this.currentClaimPromise=Promise.resolve()}stop(){this.stopped=!0}ensureSessionsForUsers(e,t){var r=this.currentClaimPromise.catch(()=>{}).then(()=>this.ensureSessionsForUsersInner(e,t));return this.currentClaimPromise=r,r}ensureSessionsForUsersInner(e,t){var r=this;return g(function*(){if(r.stopped)throw new Error("Cannot ensure Olm sessions: shutting down");e.info("Checking for missing Olm sessions");var s=yield r.olmMachine.getMissingSessions(t.map(_=>_.clone()));s&&(e.info("Making /keys/claim request"),yield r.outgoingRequestProcessor.makeOutgoingRequest(s)),e.info("Olm sessions prepared")})()}}function bg(i,e){var t=new Map;for(var[r,s]of i.keys.entries())t.set(r.toString(),s.toBase64());var _=at.Unverified;i.isBlacklisted()?_=at.Blocked:i.isVerified()&&(_=at.Verified);var o=new Map,a=i.signatures.get(e);if(a){var c=new Map;for(var[d,w]of a.entries())w.isValid()&&w.signature&&c.set(d,w.signature.toBase64());o.set(e.toString(),c)}var f=i.algorithms,m=new Set;return f.forEach(K=>{switch(K){case ge.MegolmV1AesSha2:m.add("m.megolm.v1.aes-sha2");break;case ge.OlmV1Curve25519AesSha2:default:m.add("m.olm.v1.curve25519-aes-sha2");break}}),new cn({deviceId:i.deviceId.toString(),userId:e.toString(),keys:t,algorithms:Array.from(m),verified:_,signatures:o,displayName:i.displayName,dehydrated:i.isDehydrated})}function hg(i){return new Map(Object.entries(i).map(e=>{var[t,r]=e;return[t,fg(r)]}))}function fg(i){var e,t=new Map(Object.entries(i.keys)),r=(e=i.unsigned)===null||e===void 0?void 0:e.device_display_name,s=new Map;if(i.signatures)for(var _ in i.signatures)s.set(_,new Map(Object.entries(i.signatures[_])));return new cn({deviceId:i.device_id,userId:i.user_id,keys:t,algorithms:i.algorithms,verified:at.Unverified,signatures:s,displayName:r})}class vg{constructor(e,t,r,s){this.logger=e,this.olmMachine=t,this.outgoingRequestProcessor=r,this.secretStorage=s}bootstrapCrossSigning(e){var t=this;return g(function*(){if(e.setupNewCrossSigning){yield t.resetCrossSigning(e.authUploadDeviceSigningKeys);return}var r=yield t.olmMachine.crossSigningStatus(),s=yield t.secretStorage.get("m.cross_signing.master"),_=yield t.secretStorage.get("m.cross_signing.self_signing"),o=yield t.secretStorage.get("m.cross_signing.user_signing"),a=!!(s&&_&&o),c=r.hasMaster&&r.hasUserSigning&&r.hasSelfSigning;if(t.logger.debug("bootstrapCrossSigning: starting",{setupNewCrossSigning:e.setupNewCrossSigning,olmDeviceHasMaster:r.hasMaster,olmDeviceHasUserSigning:r.hasUserSigning,olmDeviceHasSelfSigning:r.hasSelfSigning,privateKeysInSecretStorage:a}),c)(yield t.secretStorage.hasKey())?a?t.logger.debug("bootstrapCrossSigning: Olm device has private keys and they are saved in secret storage; doing nothing"):(t.logger.debug("bootstrapCrossSigning: Olm device has private keys: exporting to secret storage"),yield t.exportCrossSigningKeysToStorage()):t.logger.warn("bootstrapCrossSigning: Olm device has private keys, but secret storage is not yet set up; doing nothing for now.");else if(a){t.logger.debug("bootstrapCrossSigning: Cross-signing private keys not found locally, but they are available in secret storage, reading storage and caching locally");var d=yield t.olmMachine.importCrossSigningKeys(s,_,o);if(!d.hasMaster||!d.hasSelfSigning||!d.hasUserSigning)throw new Error("importCrossSigningKeys failed to import the keys");var w=yield t.olmMachine.getDevice(t.olmMachine.userId,t.olmMachine.deviceId);try{var f=yield w.verify();yield t.outgoingRequestProcessor.makeOutgoingRequest(f)}finally{w.free()}}else t.logger.debug("bootstrapCrossSigning: Cross-signing private keys not found locally or in secret storage, creating new keys"),yield t.resetCrossSigning(e.authUploadDeviceSigningKeys);t.logger.debug("bootstrapCrossSigning: complete")})()}resetCrossSigning(e){var t=this;return g(function*(){var r=yield t.olmMachine.bootstrapCrossSigning(!0);(yield t.secretStorage.hasKey())?(t.logger.debug("resetCrossSigning: exporting private keys to secret storage"),yield t.exportCrossSigningKeysToStorage()):t.logger.warn("resetCrossSigning: Secret storage is not yet set up; not exporting keys to secret storage yet."),t.logger.debug("resetCrossSigning: publishing public keys to server");for(var s of[r.uploadKeysRequest,r.uploadSigningKeysRequest,r.uploadSignaturesRequest])s&&(yield t.outgoingRequestProcessor.makeOutgoingRequest(s,e))})()}exportCrossSigningKeysToStorage(){var e=this;return g(function*(){var t=yield e.olmMachine.exportCrossSigningKeys();t!=null&&t.masterKey?yield e.secretStorage.store("m.cross_signing.master",t.masterKey):e.logger.error("Cannot export MSK to secret storage, private key unknown"),t!=null&&t.self_signing_key?yield e.secretStorage.store("m.cross_signing.self_signing",t.self_signing_key):e.logger.error("Cannot export SSK to secret storage, private key unknown"),t!=null&&t.userSigningKey?yield e.secretStorage.store("m.cross_signing.user_signing",t.userSigningKey):e.logger.error("Cannot export USK to secret storage, private key unknown")})()}}function zi(i){return Wr.apply(this,arguments)}function Wr(){return Wr=g(function*(i){return Ni(i,["m.cross_signing.master","m.cross_signing.user_signing","m.cross_signing.self_signing"])}),Wr.apply(this,arguments)}function Ni(i,e){return Gr.apply(this,arguments)}function Gr(){return Gr=g(function*(i,e){var t=yield i.getDefaultKeyId();if(!t)return!1;for(var r of e){var s=(yield i.isStored(r))||{};if(!(t in s))return!1}return!0}),Gr.apply(this,arguments)}class mg extends me{constructor(e,t,r,s,_){super(),this.logger=e,this.olmMachine=t,this.inner=r,this.outgoingRequestProcessor=s,this.supportedVerificationMethods=_,k(this,"reEmitter",void 0),k(this,"_accepting",!1),k(this,"_cancelling",!1),k(this,"_verifier",void 0),this.reEmitter=new gn(this);var o=new WeakRef(this);r.registerChangesCallback(g(function*(){var a;return(a=o.deref())===null||a===void 0?void 0:a.onChange()}))}onChange(){var e=this.inner.getVerification();e instanceof be?this._verifier===void 0||this._verifier instanceof ji?this.setVerifier(new xi(e,this,this.outgoingRequestProcessor)):this._verifier instanceof xi&&this._verifier.replaceInner(e):e instanceof ye&&this._verifier===void 0&&this.setVerifier(new ji(e,this.outgoingRequestProcessor)),this.emit(ke.Change)}setVerifier(e){this._verifier&&this.reEmitter.stopReEmitting(this._verifier,[ke.Change]),this._verifier=e,this.reEmitter.reEmit(this._verifier,[ke.Change])}get transactionId(){return this.inner.flowId}get roomId(){var e;return(e=this.inner.roomId)===null||e===void 0?void 0:e.toString()}get initiatedByMe(){return this.inner.weStarted()}get otherUserId(){return this.inner.otherUserId.toString()}get otherDeviceId(){var e;return(e=this.inner.otherDeviceId)===null||e===void 0?void 0:e.toString()}getOtherDevice(){var e=this;return g(function*(){var t=e.inner.otherDeviceId;if(t)return yield e.olmMachine.getDevice(e.inner.otherUserId,t,5)})()}get isSelfVerification(){return this.inner.isSelfVerification()}get phase(){var e=this.inner.phase();switch(e){case X.Created:case X.Requested:return q.Requested;case X.Ready:return this._accepting?q.Requested:q.Ready;case X.Transitioned:if(!this._verifier)throw new Error("VerificationRequest: inner phase == Transitioned but no verifier!");return this._verifier.verificationPhase;case X.Done:return q.Done;case X.Cancelled:return q.Cancelled}throw new Error("Unknown verification phase ".concat(e))}get pending(){if(this.inner.isPassive())return!1;var e=this.phase;return e!==q.Done&&e!==q.Cancelled}get accepting(){return this._accepting}get declining(){return this._cancelling}get timeout(){return this.inner.timeRemainingMillis()}get methods(){throw new Error("not implemented")}get chosenMethod(){if(this.phase!==q.Started)return null;var e=this.inner.getVerification();return e instanceof be?N.Sas:e instanceof ye?N.Reciprocate:null}otherPartySupportsMethod(e){var t=this.inner.theirSupportedMethods;if(t===void 0)return!1;var r=Li[e];return t.some(s=>s===r)}accept(){var e=this;return g(function*(){if(e.inner.phase()!==X.Requested||e._accepting)throw new Error("Cannot accept a verification request in phase ".concat(e.phase));e._accepting=!0;try{var t=e.inner.acceptWithMethods(e.supportedVerificationMethods.map(ft));t&&(yield e.outgoingRequestProcessor.makeOutgoingRequest(t))}finally{e._accepting=!1}e.emit(ke.Change)})()}cancel(e){var t=this;return g(function*(){if(!t._cancelling){t.logger.info("Cancelling verification request with params:",e),t._cancelling=!0;try{var r=t.inner.cancel();r&&(yield t.outgoingRequestProcessor.makeOutgoingRequest(r))}finally{t._cancelling=!1}}})()}beginKeyVerification(e,t){throw new Error("not implemented")}startVerification(e){var t=this;return g(function*(){if(e!==N.Sas)throw new Error("Unsupported verification method ".concat(e));if(!(yield t.getOtherDevice()))throw new Error("startVerification(): other device is unknown");var r=yield t.inner.startSas();if(r){var[,s]=r;yield t.outgoingRequestProcessor.makeOutgoingRequest(s)}if(!t._verifier)throw new Error("Still no verifier after startSas() call");return t._verifier})()}scanQRCode(e){var t=this;return g(function*(){var r=ve.fromBytes(e),s=yield t.inner.scanQrCode(r);if(!t._verifier)throw new Error("Still no verifier after scanQrCode() call");var _=s.reciprocate();return _&&(yield t.outgoingRequestProcessor.makeOutgoingRequest(_)),t._verifier})()}get verifier(){return this.phase===q.Started?this._verifier:void 0}getQRCodeBytes(){throw new Error("getQRCodeBytes() unsupported in Rust Crypto; use generateQRCode() instead.")}generateQRCode(){var e=this;return g(function*(){if(!(yield e.getOtherDevice()))throw new Error("generateQRCode(): other device is unknown");var t=yield e.inner.generateQrCode();if(t)return t.toBytes()})()}get cancellationCode(){var e,t;return(e=(t=this.inner.cancelInfo)===null||t===void 0?void 0:t.cancelCode())!==null&&e!==void 0?e:null}get cancellingUserId(){var e=this.inner.cancelInfo;if(e)return e.cancelledbyUs()?this.olmMachine.userId.toString():this.inner.otherUserId.toString()}}class Ai extends me{constructor(e,t){super(),this.inner=e,this.outgoingRequestProcessor=t,k(this,"completionDeferred",void 0),this.completionDeferred=Promise.withResolvers();var r=new WeakRef(this);e.registerChangesCallback(g(function*(){var s;return(s=r.deref())===null||s===void 0?void 0:s.onChange()})),this.completionDeferred.promise.catch(()=>null)}onChange(){if(this.inner.isDone())this.completionDeferred.resolve(void 0);else if(this.inner.isCancelled()){var e=this.inner.cancelInfo();this.completionDeferred.reject(new Error("Verification cancelled by ".concat(e.cancelledbyUs()?"us":"them"," with code ").concat(e.cancelCode(),": ").concat(e.reason())))}this.emit(ke.Change)}get hasBeenCancelled(){return this.inner.isCancelled()}get userId(){return this.inner.otherUserId.toString()}cancel(e){var t=this.inner.cancel();t&&this.outgoingRequestProcessor.makeOutgoingRequest(t)}getShowSasCallbacks(){return null}getReciprocateQrCodeCallbacks(){return null}}class ji extends Ai{constructor(e,t){super(e,t),k(this,"callbacks",null)}onChange(){this.callbacks===null&&this.inner.hasBeenScanned()&&(this.callbacks={confirm:()=>{this.confirmScanning()},cancel:()=>this.cancel()}),super.onChange()}verify(){var e=this;return g(function*(){e.callbacks!==null&&e.emit(un.ShowReciprocateQr,e.callbacks),yield e.completionDeferred.promise})()}get verificationPhase(){switch(this.inner.state()){case ne.Created:return q.Ready;case ne.Scanned:return q.Started;case ne.Confirmed:return q.Started;case ne.Reciprocated:return q.Started;case ne.Done:return q.Done;case ne.Cancelled:return q.Cancelled;default:throw new Error("Unknown qr code state ".concat(this.inner.state()))}}getReciprocateQrCodeCallbacks(){return this.callbacks}confirmScanning(){var e=this;return g(function*(){var t=e.inner.confirmScanning();t&&(yield e.outgoingRequestProcessor.makeOutgoingRequest(t))})()}}class xi extends Ai{constructor(e,t,r){super(e,r),k(this,"callbacks",null)}verify(){var e=this;return g(function*(){yield e.sendAccept(),yield e.completionDeferred.promise})()}sendAccept(){var e=this;return g(function*(){var t=e.inner.accept();t&&(yield e.outgoingRequestProcessor.makeOutgoingRequest(t))})()}onChange(){var e=this;if(super.onChange(),this.callbacks===null){var t=this.inner.emoji(),r=this.inner.decimals();if(t===void 0&&r===void 0)return;var s={};t&&(s.emoji=t.map(_=>[_.symbol,_.description])),r&&(s.decimal=[r[0],r[1],r[2]]),this.callbacks={sas:s,confirm:function(){var _=g(function*(){var a=yield e.inner.confirm();for(var c of a)yield e.outgoingRequestProcessor.makeOutgoingRequest(c)});function o(){return _.apply(this,arguments)}return o}(),mismatch:()=>{var _=this.inner.cancelWithCode("m.mismatched_sas");_&&this.outgoingRequestProcessor.makeOutgoingRequest(_)},cancel:()=>{var _=this.inner.cancelWithCode("m.user");_&&this.outgoingRequestProcessor.makeOutgoingRequest(_)}},this.emit(un.ShowSas,this.callbacks)}}get verificationPhase(){return q.Started}getShowSasCallbacks(){return this.callbacks}replaceInner(e){if(this.inner!=e){this.inner=e;var t=new WeakRef(this);e.registerChangesCallback(g(function*(){var r;return(r=t.deref())===null||r===void 0?void 0:r.onChange()})),this.sendAccept(),this.onChange()}}}var Li={[N.Sas]:Ee.SasV1,[N.ScanQrCode]:Ee.QrCodeScanV1,[N.ShowQrCode]:Ee.QrCodeShowV1,[N.Reciprocate]:Ee.ReciprocateV1};function ft(i){var e=Li[i];if(e===void 0)throw new Error("Unknown verification method ".concat(i));return e}function kg(i){switch(i.getType()){case P.KeyVerificationCancel:case P.KeyVerificationDone:case P.KeyVerificationMac:case P.KeyVerificationStart:case P.KeyVerificationKey:case P.KeyVerificationReady:case P.KeyVerificationAccept:return!0;case P.RoomMessage:return i.getContent().msgtype===dn.KeyVerificationRequest;default:return!1}}class Sg extends me{constructor(e,t,r,s){super(),this.logger=e,this.olmMachine=t,this.http=r,this.outgoingRequestProcessor=s,k(this,"checkedForBackup",!1),k(this,"serverBackupInfo",void 0),k(this,"activeBackupVersion",null),k(this,"stopped",!1),k(this,"backupKeysLoopRunning",!1),k(this,"keyBackupCheckInProgress",null)}stop(){this.stopped=!0}getActiveBackupVersion(){var e=this;return g(function*(){return(yield e.olmMachine.isBackupEnabled())?e.activeBackupVersion:null})()}getServerBackupInfo(){var e=this;return g(function*(){return yield e.checkKeyBackupAndEnable(!1),e.serverBackupInfo})()}isKeyBackupTrusted(e){var t=this;return g(function*(){var r=yield t.olmMachine.verifyBackup(e),s=yield t.olmMachine.getBackupKeys(),_=s==null?void 0:s.decryptionKey,o=!!_&&t.backupInfoMatchesBackupDecryptionKey(e,_);return{matchesDecryptionKey:o,trusted:r.trusted()}})()}checkKeyBackupAndEnable(e){return!e&&this.checkedForBackup?Promise.resolve(null):(this.keyBackupCheckInProgress||(this.keyBackupCheckInProgress=this.doCheckKeyBackup().finally(()=>{this.keyBackupCheckInProgress=null})),this.keyBackupCheckInProgress)}handleBackupSecretReceived(e){var t=this;return g(function*(){var r,s;try{s=yield t.requestKeyBackupVersion()}catch(a){return t.logger.warn("handleBackupSecretReceived: Error checking for latest key backup",a),!1}if(!((r=s)!==null&&r!==void 0&&r.version))return t.logger.warn("handleBackupSecretReceived: Received a backup decryption key, but there is no trusted server-side key backup"),!1;try{var _=V.fromBase64(e),o=t.backupInfoMatchesBackupDecryptionKey(s,_);return o?(t.logger.info("handleBackupSecretReceived: A valid backup decryption key has been received and stored in cache."),yield t.saveBackupDecryptionKey(_,s.version),!0):(t.logger.warn("handleBackupSecretReceived: Private decryption key does not match the public key of the current remote backup."),!1)}catch(a){t.logger.warn("handleBackupSecretReceived: Invalid backup decryption key",a)}return!1})()}saveBackupDecryptionKey(e,t){var r=this;return g(function*(){yield r.olmMachine.saveBackupDecryptionKey(e,t),r.emit(I.KeyBackupDecryptionKeyCached,t)})()}importRoomKeys(e,t){var r=this;return g(function*(){yield r.importRoomKeysAsJson(JSON.stringify(e),t)})()}importRoomKeysAsJson(e,t){var r=this;return g(function*(){yield r.olmMachine.importExportedRoomKeys(e,(s,_)=>{var o,a={total:Number(_),successes:Number(s),stage:Re.LoadKeys,failures:0};t==null||(o=t.progressCallback)===null||o===void 0||o.call(t,a)})})()}importBackedUpRoomKeys(e,t,r){var s=this;return g(function*(){var _=new Map;for(var o of e){var a=new R(o.room_id);_.has(a)||_.set(a,new Map),_.get(a).set(o.session_id,o)}yield s.olmMachine.importBackedUpRoomKeys(_,(c,d,w)=>{var f,m={total:Number(d),successes:Number(c),stage:Re.LoadKeys,failures:Number(w)};r==null||(f=r.progressCallback)===null||f===void 0||f.call(r,m)},t)})()}doCheckKeyBackup(){var e=this;return g(function*(){e.logger.debug("Checking key backup status...");var t;try{t=yield e.requestKeyBackupVersion()}catch(_){return e.logger.warn("Error checking for active key backup",_),e.serverBackupInfo=void 0,null}e.checkedForBackup=!0,t&&!t.version&&(e.logger.warn("active backup lacks a useful 'version'; ignoring it"),t=void 0),e.serverBackupInfo=t;var r=yield e.getActiveBackupVersion();if(!t)return r!==null?(e.logger.debug("No key backup present on server: disabling key backup"),yield e.disableKeyBackup()):e.logger.debug("No key backup present on server: not enabling key backup"),null;var s=yield e.isKeyBackupTrusted(t);return!s.matchesDecryptionKey&&!s.trusted?r!==null?(e.logger.debug("Key backup present on server but not trusted: disabling key backup"),yield e.disableKeyBackup()):e.logger.debug("Key backup present on server but not trusted: not enabling key backup"):r===null?(e.logger.debug("Found usable key backup v".concat(t.version,": enabling key backups")),yield e.enableKeyBackup(t)):r!==t.version?(e.logger.debug("On backup version ".concat(r," but found version ").concat(t.version,": switching.")),yield e.disableKeyBackup(),yield e.enableKeyBackup(t)):e.logger.debug("Backup version ".concat(t.version," still current")),{backupInfo:t,trustInfo:s}})()}enableKeyBackup(e){var t=this;return g(function*(){yield t.olmMachine.enableBackupV1(e.auth_data.public_key,e.version),t.activeBackupVersion=e.version,t.emit(I.KeyBackupStatus,!0),t.backupKeysLoop()})()}maybeUploadKey(){var e=this;return g(function*(){e.activeBackupVersion!=null&&e.backupKeysLoop()})()}disableKeyBackup(){var e=this;return g(function*(){yield e.olmMachine.disableBackup(),e.activeBackupVersion=null,e.emit(I.KeyBackupStatus,!1)})()}backupKeysLoop(){var e=arguments,t=this;return g(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:1e4;if(t.backupKeysLoopRunning){t.logger.debug("Backup loop already running");return}t.backupKeysLoopRunning=!0,t.logger.debug("Backup: Starting keys upload loop for backup version:".concat(t.activeBackupVersion,"."));var s=Math.random()*r;yield re(s);try{for(var _=0,o=null,a=!0;!t.stopped;){var c=void 0;try{c=yield W(t.logger,"BackupRoomKeys: Get keys to backup from rust crypto-sdk",g(function*(){return yield t.olmMachine.backupRoomKeys()}))}catch(K){t.logger.error("Backup: Failed to get keys to backup from rust crypto-sdk",K)}if(!c||t.stopped||!t.activeBackupVersion){t.logger.debug("Backup: Ending loop for version ".concat(t.activeBackupVersion,".")),c||t.emit(I.KeyBackupSessionsRemaining,0);return}try{if(yield t.outgoingRequestProcessor.makeOutgoingRequest(c),_=0,t.stopped)break;if(!a&&o===null)try{var d=yield t.olmMachine.roomKeyCounts();o=d.total-d.backedUp}catch(K){t.logger.error("Backup: Failed to get key counts from rust crypto-sdk",K)}if(o!==null){t.emit(I.KeyBackupSessionsRemaining,o);var w=t.keysCountInBatch(c);o=Math.max(o-w,0)}}catch(K){if(_++,t.logger.error("Backup: Error processing backup request for rust crypto-sdk",K),K instanceof ln){var f=K.data.errcode;if(f=="M_NOT_FOUND"||f=="M_WRONG_ROOM_KEYS_VERSION"){t.logger.debug("Backup: Failed to upload keys to current vesion: ".concat(f,"."));try{yield t.disableKeyBackup()}catch(U){t.logger.error("Backup: An error occurred while disabling key backup:",U)}t.emit(I.KeyBackupFailed,K.data.errcode),t.backupKeysLoopRunning=!1,t.checkKeyBackupAndEnable(!0);return}else if(K.isRateLimitError())try{var m=K.getRetryAfterMs();if(m&&m>0){yield re(m);continue}}catch(U){t.logger.warn("Backup: An error occurred while retrieving a rate-limit retry delay",U)}}yield re(1e3*Math.pow(2,Math.min(_-1,4)))}a=!1}}finally{t.backupKeysLoopRunning=!1}})()}keysCountInBatch(e){var t=JSON.parse(e.body);return Gi(t)}requestKeyBackupVersion(e){var t=this;return g(function*(){return yield Wi(t.http,e)})()}setupKeyBackup(e){var t=this;return g(function*(){yield t.deleteAllKeyBackupVersions();var r=V.createRandomKey(),s=r.megolmV1PublicKey,_={public_key:s.publicKeyBase64};yield e(_);var o=yield t.http.authedRequest(D.Post,"/room_keys/version",void 0,{algorithm:s.algorithm,auth_data:_},{prefix:Se.V3});return yield t.saveBackupDecryptionKey(r,o.version),{version:o.version,algorithm:s.algorithm,authData:_,decryptionKey:r}})()}deleteAllKeyBackupVersions(){var e=this;return g(function*(){for(var t,r,s=(t=(r=yield e.requestKeyBackupVersion())===null||r===void 0?void 0:r.version)!==null&&t!==void 0?t:null;s!=null;){var _,o;yield e.deleteKeyBackupVersion(s),s=(_=(o=yield e.requestKeyBackupVersion())===null||o===void 0?void 0:o.version)!==null&&_!==void 0?_:null}})()}deleteKeyBackupVersion(e){var t=this;return g(function*(){t.logger.debug("deleteKeyBackupVersion v:".concat(e));var r=ot("/room_keys/version/$version",{$version:e});yield t.http.authedRequest(D.Delete,r,void 0,void 0,{prefix:Se.V3}),t.activeBackupVersion===e&&(t.serverBackupInfo=null,yield t.disableKeyBackup())})()}createBackupDecryptor(e){return new Rg(this.logger,e)}restoreKeyBackup(e,t,r){var s=this;return g(function*(){var _=yield s.downloadKeyBackup(e);return s.importKeyBackup(_,e,t,r)})()}downloadKeyBackup(e){return this.http.authedRequest(D.Get,"/room_keys/keys",{version:e},void 0,{prefix:Se.V3})}importKeyBackup(e,t,r,s){var _=this;return g(function*(){var o,a=200,c=Gi(e),d=0,w=0;s==null||(o=s.progressCallback)===null||o===void 0||o.call(s,{total:c,successes:d,stage:Re.LoadKeys,failures:w});var f=function(){var ts=g(function*(ir){var sr,tt=[],rs=function*(rt){var is=yield r.decryptSessions(ir.get(rt));is.forEach(an=>{an.room_id=rt,tt.push(an)})};for(var ns of ir.keys())yield*rs(ns);try{yield _.importBackedUpRoomKeys(tt,t),d+=tt.length}catch(rt){w+=tt.length,_.logger.error("Error importing keys from backup",rt)}s==null||(sr=s.progressCallback)===null||sr===void 0||sr.call(s,{total:c,successes:d,stage:Re.LoadKeys,failures:w})});return function(ir){return ts.apply(this,arguments)}}(),m=0,K=new Map;for(var[U,H]of Object.entries(e.rooms))if(H.sessions){K.set(U,{});for(var[nr,Xi]of Object.entries(H.sessions)){var es=K.get(U);es[nr]=Xi,m+=1,m>=a&&(yield f(K),K=new Map,K.set(U,{}),m=0)}}return m>0&&(yield f(K)),{total:c,imported:d}})()}backupInfoMatchesBackupDecryptionKey(e,t){var r;return e.algorithm!=="m.megolm_backup.v1.curve25519-aes-sha2"?(this.logger.warn("backupMatchesPrivateKey: Unsupported backup algorithm",e.algorithm),!1):((r=e.auth_data)===null||r===void 0?void 0:r.public_key)===t.megolmV1PublicKey.publicKeyBase64}}class Rg{constructor(e,t){this.logger=e,k(this,"decryptionKey",void 0),k(this,"sourceTrusted",void 0),this.decryptionKey=t,this.sourceTrusted=!1}decryptSessions(e){var t=this;return g(function*(){var r=[];for(var[s,_]of Object.entries(e))try{var o=JSON.parse(t.decryptionKey.decryptV1(_.session_data.ephemeral,_.session_data.mac,_.session_data.ciphertext));o.session_id=s,r.push(o)}catch(a){t.logger.debug("Failed to decrypt megolm session from backup",a,_)}return r})()}free(){this.decryptionKey.free()}}function Wi(i,e){return Jr.apply(this,arguments)}function Jr(){return Jr=g(function*(i,e){try{var t=e?ot("/room_keys/version/$version",{$version:e}):"/room_keys/version";return yield i.authedRequest(D.Get,t,void 0,void 0,{prefix:Se.V3})}catch(r){if(r.errcode==="M_NOT_FOUND")return null;throw r}}),Jr.apply(this,arguments)}function Qr(i,e){var t=e.auth_data;return t.public_key===i.megolmV1PublicKey.publicKeyBase64}function Gi(i){var e=0;for(var{sessions:t}of Object.values(i.rooms))e+=Object.keys(t).length;return e}class Kg{constructor(e,t,r){this.logger=e,this.olmMachine=t,this.outgoingRequestProcessor=r,k(this,"stopped",!1),k(this,"outgoingRequestLoopRunning",!1),k(this,"nextLoopDeferred",void 0)}stop(){this.stopped=!0}doProcessOutgoingRequests(){this.nextLoopDeferred||(this.nextLoopDeferred=Promise.withResolvers());var e=this.nextLoopDeferred.promise;return this.outgoingRequestLoopRunning||this.outgoingRequestLoop().catch(t=>{this.logger.error("Uncaught error in outgoing request loop",t)}),e}outgoingRequestLoop(){var e=this;return g(function*(){if(e.outgoingRequestLoopRunning)throw new Error("Cannot run two outgoing request loops");e.outgoingRequestLoopRunning=!0;try{for(;!e.stopped&&e.nextLoopDeferred;){var t=e.nextLoopDeferred;e.nextLoopDeferred=void 0,yield e.processOutgoingRequests().then(t.resolve,t.reject)}}finally{e.outgoingRequestLoopRunning=!1}e.nextLoopDeferred&&e.nextLoopDeferred.reject(new Error("OutgoingRequestsManager was stopped"))})()}processOutgoingRequests(){var e=this;return g(function*(){if(!e.stopped){var t=yield e.olmMachine.outgoingRequests(),r=function*(o){if(e.stopped)return{v:void 0};try{yield W(e.logger,"Make outgoing request ".concat(o.type),g(function*(){yield e.outgoingRequestProcessor.makeOutgoingRequest(o)}))}catch(a){e.logger.error("Failed to process outgoing request ".concat(o.type,": ").concat(a))}},s;for(var _ of t)if(s=yield*r(_),s)return s.v}})()}}var vt=5e3,ee=function(i){return i.MISSING_DECRYPTION_KEY="MISSING_DECRYPTION_KEY",i.NETWORK_ERROR="NETWORK_ERROR",i.STOPPED="STOPPED",i}(ee||{});class qe extends Error{constructor(e){super("Failed to get key from backup: ".concat(e)),this.code=e,this.name="KeyDownloadError"}}class Ji extends Error{constructor(e){super("Failed to get key from backup: rate limited"),this.retryMillis=e,this.name="KeyDownloadRateLimitError"}}class Ig{constructor(e,t,r,s){this.olmMachine=t,this.http=r,this.backupManager=s,k(this,"stopped",!1),k(this,"configuration",null),k(this,"sessionLastCheckAttemptedTime",new Map),k(this,"logger",void 0),k(this,"downloadLoopRunning",!1),k(this,"queuedRequests",[]),k(this,"hasConfigurationProblem",!1),k(this,"currentBackupVersionCheck",null),k(this,"onBackupStatusChanged",()=>{this.hasConfigurationProblem=!1,this.configuration=null,this.getOrCreateBackupConfiguration().then(_=>{_&&this.downloadKeysLoop()})}),this.logger=e.getChild("[PerSessionKeyBackupDownloader]"),s.on(I.KeyBackupStatus,this.onBackupStatusChanged),s.on(I.KeyBackupFailed,this.onBackupStatusChanged),s.on(I.KeyBackupDecryptionKeyCached,this.onBackupStatusChanged)}isKeyBackupDownloadConfigured(){return this.configuration!==null}getServerBackupInfo(){var e=this;return g(function*(){return yield e.backupManager.getServerBackupInfo()})()}onDecryptionKeyMissingError(e,t){if(this.isAlreadyInQueue(e,t)){this.logger.trace("Not checking key backup for session ".concat(t," as it is already queued"));return}if(this.wasRequestedRecently(t)){this.logger.trace("Not checking key backup for session ".concat(t," as it was already requested recently"));return}this.queuedRequests.push({roomId:e,megolmSessionId:t}),this.downloadKeysLoop()}stop(){this.stopped=!0,this.backupManager.off(I.KeyBackupStatus,this.onBackupStatusChanged),this.backupManager.off(I.KeyBackupFailed,this.onBackupStatusChanged),this.backupManager.off(I.KeyBackupDecryptionKeyCached,this.onBackupStatusChanged)}isAlreadyInQueue(e,t){return this.queuedRequests.some(r=>r.roomId==e&&r.megolmSessionId==t)}markAsNotFoundInBackup(e){var t=Date.now();this.sessionLastCheckAttemptedTime.set(e,t),this.sessionLastCheckAttemptedTime.size>100&&(this.sessionLastCheckAttemptedTime=new Map(Array.from(this.sessionLastCheckAttemptedTime).filter((r,s)=>Math.max(t-s,0)<vt)))}wasRequestedRecently(e){var t=this.sessionLastCheckAttemptedTime.get(e);return t?Math.max(Date.now()-t,0)<vt:!1}getBackupDecryptionKey(){var e=this;return g(function*(){try{return yield e.olmMachine.getBackupKeys()}catch{return null}})()}requestRoomKeyFromBackup(e,t,r){var s=this;return g(function*(){var _=ot("/room_keys/keys/$roomId/$sessionId",{$roomId:t,$sessionId:r});return yield s.http.authedRequest(D.Get,_,{version:e},void 0,{prefix:Se.V3})})()}downloadKeysLoop(){var e=this;return g(function*(){if(!e.downloadLoopRunning&&!e.hasConfigurationProblem){e.downloadLoopRunning=!0;try{for(;e.queuedRequests.length>0;){var t=e.queuedRequests[0];try{var r=yield e.getOrCreateBackupConfiguration();if(!r){e.downloadLoopRunning=!1;return}var s=yield e.queryKeyBackup(t.roomId,t.megolmSessionId,r);if(e.stopped)return;try{yield e.decryptAndImport(t,s,r)}catch(_){e.logger.error("Error while decrypting and importing key backup for session ".concat(t.megolmSessionId),_)}e.queuedRequests.shift()}catch(_){if(_ instanceof qe)switch(_.code){case ee.MISSING_DECRYPTION_KEY:e.markAsNotFoundInBackup(t.megolmSessionId),e.queuedRequests.shift();break;case ee.NETWORK_ERROR:yield re(vt);break;case ee.STOPPED:e.downloadLoopRunning=!1;return}else _ instanceof Ji&&(yield re(_.retryMillis))}}}finally{e.downloadLoopRunning=!1}}})()}queryKeyBackup(e,t,r){var s=this;return g(function*(){if(s.logger.debug("Checking key backup for session ".concat(t)),s.stopped)throw new qe(ee.STOPPED);try{var _=yield s.requestRoomKeyFromBackup(r.backupVersion,e,t);return s.logger.debug("Got key from backup for sessionId:".concat(t)),_}catch(d){if(s.stopped)throw new qe(ee.STOPPED);if(s.logger.info("No luck requesting key backup for session ".concat(t,": ").concat(d)),d instanceof ln){var o=d.data.errcode;if(o=="M_NOT_FOUND")throw new qe(ee.MISSING_DECRYPTION_KEY);if(d.isRateLimitError()){var a;try{var c;a=(c=d.getRetryAfterMs())!==null&&c!==void 0?c:void 0}catch(w){s.logger.warn("Error while retrieving a rate-limit retry delay",w)}throw a&&a>0&&s.logger.info("Rate limited by server, waiting ".concat(a,"ms")),new Ji(a??vt)}}throw new qe(ee.NETWORK_ERROR)}})()}decryptAndImport(e,t,r){var s=this;return g(function*(){var _={[e.megolmSessionId]:t},o=yield r.decryptor.decryptSessions(_);for(var a of o)a.room_id=e.roomId;yield s.backupManager.importBackedUpRoomKeys(o,r.backupVersion)})()}getOrCreateBackupConfiguration(){var e=this;return g(function*(){if(e.configuration)return e.configuration;if(e.hasConfigurationProblem)return null;if(e.currentBackupVersionCheck!=null)return e.logger.debug("Already checking server version, use current promise"),yield e.currentBackupVersionCheck;e.currentBackupVersionCheck=e.internalCheckFromServer();try{return yield e.currentBackupVersionCheck}finally{e.currentBackupVersionCheck=null}})()}internalCheckFromServer(){var e=this;return g(function*(){var t,r,s,_=null;try{_=yield e.backupManager.getServerBackupInfo()}catch(f){return e.logger.debug("Backup: error while checking server version: ".concat(f)),e.hasConfigurationProblem=!0,null}if(e.logger.debug("Got current backup version from server: ".concat((t=_)===null||t===void 0?void 0:t.version)),((r=_)===null||r===void 0?void 0:r.algorithm)!="m.megolm_backup.v1.curve25519-aes-sha2"){var o;return e.logger.info("Unsupported algorithm ".concat((o=_)===null||o===void 0?void 0:o.algorithm)),e.hasConfigurationProblem=!0,null}if(!((s=_)!==null&&s!==void 0&&s.version))return e.logger.info("No current key backup"),e.hasConfigurationProblem=!0,null;var a=yield e.backupManager.getActiveBackupVersion();if(a==null||_.version!=a)return e.logger.info("The current backup version on the server (".concat(_.version,") is not trusted. Version we are currently backing up to: ").concat(a)),e.hasConfigurationProblem=!0,null;var c=yield e.getBackupDecryptionKey();if(!(c!=null&&c.decryptionKey))return e.logger.debug("Not checking key backup for session (no decryption key)"),e.hasConfigurationProblem=!0,null;if(a!=c.backupVersion)return e.logger.debug("Version for which we have a decryption key (".concat(c.backupVersion,") doesn't match the version we are backing up to (").concat(a,")")),e.hasConfigurationProblem=!0,null;var d=_.auth_data;if(d.public_key!=c.decryptionKey.megolmV1PublicKey.publicKeyBase64)return e.logger.debug("Key backup on server does not match our decryption key"),e.hasConfigurationProblem=!0,null;var w=e.backupManager.createBackupDecryptor(c.decryptionKey);return e.hasConfigurationProblem=!1,e.configuration={decryptor:w,backupVersion:a},e.configuration})()}}function Cg(i,e){if(!i.private_key_salt||!i.private_key_iterations)throw new Error("Salt and/or iterations not found: this backup cannot be restored with a passphrase");return pn(e,i.private_key_salt,i.private_key_iterations,i.private_key_bits)}function Qi(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(i);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(i,s).enumerable})),t.push.apply(t,r)}return t}function Hi(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Qi(Object(t),!0).forEach(function(r){k(i,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Qi(Object(t)).forEach(function(r){Object.defineProperty(i,r,Object.getOwnPropertyDescriptor(t,r))})}return i}var Yi=[N.Sas,N.ScanQrCode,N.ShowQrCode,N.Reciprocate];class Dg extends me{constructor(e,t,r,s,_,o,a){super(),this.logger=e,this.olmMachine=t,this.http=r,this.userId=s,this.secretStorage=o,this.cryptoCallbacks=a,k(this,"RECOVERY_KEY_DERIVATION_ITERATIONS",5e5),k(this,"_trustCrossSignedDevices",!0),k(this,"deviceIsolationMode",new os(!1)),k(this,"stopped",!1),k(this,"roomEncryptors",{}),k(this,"eventDecryptor",void 0),k(this,"keyClaimManager",void 0),k(this,"outgoingRequestProcessor",void 0),k(this,"crossSigningIdentity",void 0),k(this,"backupManager",void 0),k(this,"outgoingRequestsManager",void 0),k(this,"perSessionBackupDownloader",void 0),k(this,"dehydratedDeviceManager",void 0),k(this,"reemitter",new gn(this)),k(this,"globalBlacklistUnverifiedDevices",!1),k(this,"_supportedVerificationMethods",Yi),this.outgoingRequestProcessor=new wg(e,t,r),this.outgoingRequestsManager=new Kg(this.logger,t,this.outgoingRequestProcessor),this.keyClaimManager=new yg(t,this.outgoingRequestProcessor),this.backupManager=new Sg(e,t,r,this.outgoingRequestProcessor),this.perSessionBackupDownloader=new Ig(this.logger,this.olmMachine,this.http,this.backupManager),this.dehydratedDeviceManager=new lg(this.logger,t,r,this.outgoingRequestProcessor,o),this.eventDecryptor=new Eg(this.logger,t,this.perSessionBackupDownloader),this.reemitter.reEmit(this.backupManager,[I.KeyBackupStatus,I.KeyBackupSessionsRemaining,I.KeyBackupFailed,I.KeyBackupDecryptionKeyCached]),this.reemitter.reEmit(this.dehydratedDeviceManager,[I.DehydratedDeviceCreated,I.DehydratedDeviceUploaded,I.RehydrationStarted,I.RehydrationProgress,I.RehydrationCompleted,I.RehydrationError,I.DehydrationKeyCached,I.DehydratedDeviceRotationError]),this.crossSigningIdentity=new vg(e,t,this.outgoingRequestProcessor,o),this.checkKeyBackupAndEnable()}getOlmMachineOrThrow(){if(this.stopped)throw new as;return this.olmMachine}set globalErrorOnUnknownDevices(e){}get globalErrorOnUnknownDevices(){return!1}stop(){this.stopped||(this.stopped=!0,this.keyClaimManager.stop(),this.backupManager.stop(),this.outgoingRequestsManager.stop(),this.perSessionBackupDownloader.stop(),this.dehydratedDeviceManager.stop(),this.olmMachine.close())}encryptEvent(e,t){var r=this;return g(function*(){var s=e.getRoomId(),_=r.roomEncryptors[s];if(!_)throw new Error("Cannot encrypt event in unconfigured room ".concat(s));yield _.encryptEvent(e,r.globalBlacklistUnverifiedDevices,r.deviceIsolationMode)})()}decryptEvent(e){var t=this;return g(function*(){var r=e.getRoomId();if(!r)throw new Error("to-device event was not decrypted in preprocessToDeviceMessages");return yield t.eventDecryptor.attemptEventDecryption(e,t.deviceIsolationMode)})()}getBackupDecryptor(e,t){var r=this;return g(function*(){if(!(t instanceof Uint8Array))throw new Error("getBackupDecryptor: expects Uint8Array");if(e.algorithm!="m.megolm_backup.v1.curve25519-aes-sha2")throw new Error("getBackupDecryptor: Unsupported algorithm ".concat(e.algorithm));var s=V.fromBase64(or(t));if(!Qr(s,e))throw new Error("getBackupDecryptor: key backup on server does not match the decryption key");return r.backupManager.createBackupDecryptor(s)})()}importBackedUpRoomKeys(e,t,r){var s=this;return g(function*(){return yield s.backupManager.importBackedUpRoomKeys(e,t,r)})()}maybeAcceptKeyBundle(e,t){var r=this;return g(function*(){var s=new it(r.logger,"maybeAcceptKeyBundle(".concat(e,", ").concat(t,")")),_=yield r.olmMachine.getReceivedRoomKeyBundleData(new R(e),new h(t));if(!_){s.info("No key bundle found for user");return}s.info("Fetching key bundle ".concat(_.url));var o=cs(r.http.opts.baseUrl,_.url,void 0,void 0,void 0,!1,!0,!0),a;try{var c=new URL(o);a=yield r.http.authedRequest(D.Get,c.pathname+c.search,{},void 0,{rawResponseBody:!0,prefix:""})}catch(d){throw s.warn("Error downloading encrypted bundle from ".concat(o,":"),d),d}s.info("Received blob of length ".concat(a.size));try{yield r.olmMachine.receiveRoomKeyBundle(_,new Uint8Array(yield a.arrayBuffer()))}catch(d){throw s.warn("Error receiving encrypted bundle:",d),d}})()}getVersion(){var e=kn();return"Rust SDK ".concat(e.matrix_sdk_crypto," (").concat(e.git_sha,"), Vodozemac ").concat(e.vodozemac)}setDeviceIsolationMode(e){this.deviceIsolationMode=e}isEncryptionEnabledInRoom(e){var t=this;return g(function*(){var r=yield t.olmMachine.getRoomSettings(new R(e));return!!(r!=null&&r.algorithm)})()}getOwnDeviceKeys(){var e=this;return g(function*(){var t=e.olmMachine.identityKeys;return{ed25519:t.ed25519.toBase64(),curve25519:t.curve25519.toBase64()}})()}prepareToEncrypt(e){var t=this.roomEncryptors[e.roomId];t&&t.prepareForEncryption(this.globalBlacklistUnverifiedDevices,this.deviceIsolationMode)}forceDiscardSession(e){var t;return(t=this.roomEncryptors[e])===null||t===void 0?void 0:t.forceDiscardSession()}exportRoomKeys(){var e=this;return g(function*(){var t=yield e.olmMachine.exportRoomKeys(()=>!0);return JSON.parse(t)})()}exportRoomKeysAsJson(){var e=this;return g(function*(){return yield e.olmMachine.exportRoomKeys(()=>!0)})()}importRoomKeys(e,t){var r=this;return g(function*(){return yield r.backupManager.importRoomKeys(e,t)})()}importRoomKeysAsJson(e,t){var r=this;return g(function*(){return yield r.backupManager.importRoomKeysAsJson(e,t)})()}userHasCrossSigningKeys(){var e=arguments,t=this;return g(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:t.userId,s=e.length>1&&e[1]!==void 0?e[1]:!1,_=yield t.olmMachine.trackedUsers(),o;for(var a of _)if(r===a.toString()){o=a;break}if(o!==void 0){if(r===t.userId){var c=t.olmMachine.queryKeysForUsers([o.clone()]);yield t.outgoingRequestProcessor.makeOutgoingRequest(c)}var d=yield t.olmMachine.getIdentity(o);return d==null||d.free(),d!==void 0}else if(s){var w,f=yield t.downloadDeviceList(new Set([r])),m=(w=f.master_keys)===null||w===void 0?void 0:w[r];return m?!!Object.values(m.keys)[0]:!1}else return!1})()}getUserDeviceInfo(e){var t=arguments,r=this;return g(function*(){var s=t.length>1&&t[1]!==void 0?t[1]:!1,_=new Map,o=yield r.getOlmMachineOrThrow().trackedUsers(),a=new Set;o.forEach(f=>a.add(f.toString()));var c=new Set;for(var d of e)a.has(d)?_.set(d,yield r.getUserDevices(d)):c.add(d);if(s&&c.size>=1){var w=yield r.downloadDeviceList(c);Object.entries(w.device_keys).forEach(f=>{var[m,K]=f;return _.set(m,hg(K))})}return _})()}getUserDevices(e){var t=this;return g(function*(){var r=new h(e),s=yield t.olmMachine.getUserDevices(r,1);try{var _=s.devices();try{return new Map(_.map(o=>[o.deviceId.toString(),bg(o,r)]))}finally{_.forEach(o=>o.free())}}finally{s.free()}})()}downloadDeviceList(e){var t=this;return g(function*(){var r={device_keys:{}};return e.forEach(s=>r.device_keys[s]=[]),yield t.http.authedRequest(D.Post,"/_matrix/client/v3/keys/query",void 0,r,{prefix:""})})()}getTrustCrossSignedDevices(){return this._trustCrossSignedDevices}setTrustCrossSignedDevices(e){this._trustCrossSignedDevices=e}setDeviceVerified(e,t){var r=arguments,s=this;return g(function*(){var _=r.length>2&&r[2]!==void 0?r[2]:!0,o=yield s.olmMachine.getDevice(new h(e),new C(t));if(!o)throw new Error("Unknown device ".concat(e,"|").concat(t));try{yield o.setLocalTrust(_?lr.Verified:lr.Unset)}finally{o.free()}})()}crossSignDevice(e){var t=this;return g(function*(){var r=yield t.olmMachine.getDevice(new h(t.userId),new C(e));if(!r)throw new Error("Unknown device ".concat(e));try{var s=yield r.verify();yield t.outgoingRequestProcessor.makeOutgoingRequest(s)}finally{r.free()}})()}getDeviceVerificationStatus(e,t){var r=this;return g(function*(){var s=yield r.olmMachine.getDevice(new h(e),new C(t));if(!s)return null;try{return new gs({signedByOwner:s.isCrossSignedByOwner(),crossSigningVerified:s.isCrossSigningTrusted(),localVerified:s.isLocallyTrusted(),trustCrossSignedDevices:r._trustCrossSignedDevices})}finally{s.free()}})()}getUserVerificationStatus(e){var t=this;return g(function*(){var r=yield t.getOlmMachineOrThrow().getIdentity(new h(e));if(r===void 0)return new wn(!1,!1,!1);var s=r.isVerified(),_=r.wasPreviouslyVerified(),o=r instanceof je?r.identityNeedsUserApproval():!1;return r.free(),new wn(s,_,!1,o)})()}pinCurrentUserIdentity(e){var t=this;return g(function*(){var r=yield t.getOlmMachineOrThrow().getIdentity(new h(e));if(r===void 0)throw new Error("Cannot pin identity of unknown user");if(r instanceof xe)throw new Error("Cannot pin identity of own user");yield r.pinCurrentMasterKey()})()}withdrawVerificationRequirement(e){var t=this;return g(function*(){var r=yield t.getOlmMachineOrThrow().getIdentity(new h(e));if(r===void 0)throw new Error("Cannot withdraw verification of unknown user");yield r.withdrawVerification()})()}isCrossSigningReady(){var e=this;return g(function*(){var{privateKeysInSecretStorage:t,privateKeysCachedLocally:r}=yield e.getCrossSigningStatus(),s=!!r.masterKey&&!!r.selfSigningKey&&!!r.userSigningKey,_=yield e.getOwnIdentity();return!!(_!=null&&_.isVerified())&&(s||t)})()}getCrossSigningKeyId(){var e=arguments,t=this;return g(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:ct.Master,s=yield t.olmMachine.getIdentity(new h(t.userId));if(!s)return null;try{var _=yield t.olmMachine.crossSigningStatus(),o=_.hasMaster&&_.hasUserSigning&&_.hasSelfSigning;if(!o||!s.isVerified())return null;var a;switch(r){case ct.Master:a=s.masterKey;break;case ct.SelfSigning:a=s.selfSigningKey;break;case ct.UserSigning:a=s.userSigningKey;break;default:return null}var c=JSON.parse(a);return Object.values(c.keys)[0]}finally{s.free()}})()}bootstrapCrossSigning(e){var t=this;return g(function*(){yield t.crossSigningIdentity.bootstrapCrossSigning(e)})()}isSecretStorageReady(){var e=this;return g(function*(){var t=["m.cross_signing.master","m.cross_signing.user_signing","m.cross_signing.self_signing"],r=(yield e.backupManager.getActiveBackupVersion())!=null;return r&&t.push("m.megolm_backup.v1"),Ni(e.secretStorage,t)})()}bootstrapSecretStorage(){var e=arguments,t=this;return g(function*(){var{createSecretStorageKey:r,setupNewSecretStorage:s,setupNewKeyBackup:_}=e.length>0&&e[0]!==void 0?e[0]:{},o=s||!(yield t.secretStorageHasAESKey());if(o){if(!r)throw new Error("unable to create a new secret storage key, createSecretStorageKey is not set");t.logger.info("bootstrapSecretStorage: creating new secret storage key");var a=yield r();if(!a)throw new Error("createSecretStorageKey() callback did not return a secret storage key");yield t.addSecretStorageKeyToSecretStorage(a)}var c=yield t.olmMachine.exportCrossSigningKeys(),d=c&&c.masterKey!==void 0&&c.self_signing_key!==void 0&&c.userSigningKey!==void 0;d&&(o||!(yield zi(t.secretStorage)))&&(t.logger.info("bootstrapSecretStorage: cross-signing keys not yet exported; doing so now."),yield t.secretStorage.store("m.cross_signing.master",c.masterKey),yield t.secretStorage.store("m.cross_signing.user_signing",c.userSigningKey),yield t.secretStorage.store("m.cross_signing.self_signing",c.self_signing_key)),_?yield t.resetKeyBackup():yield t.saveBackupKeyToStorage()})()}saveBackupKeyToStorage(){var e=this;return g(function*(){var t=yield e.backupManager.getServerBackupInfo();if(!t||!t.version){e.logger.info("Not saving backup key to secret storage: no backup info");return}var r=yield e.olmMachine.getBackupKeys();if(!r.decryptionKey){e.logger.info("Not saving backup key to secret storage: no backup key");return}if(!Qr(r.decryptionKey,t)){e.logger.info("Not saving backup key to secret storage: decryption key does not match backup info");return}var s=r.decryptionKey.toBase64();yield e.secretStorage.store("m.megolm_backup.v1",s)})()}addSecretStorageKeyToSecretStorage(e){var t=this;return g(function*(){var r,s,_,o,a=yield t.secretStorage.addKey(yn,{passphrase:(r=e.keyInfo)===null||r===void 0?void 0:r.passphrase,name:(s=e.keyInfo)===null||s===void 0?void 0:s.name,key:e.privateKey});yield t.secretStorage.setDefaultKeyId(a.keyId),(_=(o=t.cryptoCallbacks).cacheSecretStorageKey)===null||_===void 0||_.call(o,a.keyId,a.keyInfo,e.privateKey)})()}secretStorageHasAESKey(){var e=this;return g(function*(){var t=yield e.secretStorage.getKey();if(!t)return!1;var[,r]=t;return r.algorithm===yn})()}getCrossSigningStatus(){var e=this;return g(function*(){var t=yield e.getOlmMachineOrThrow().getIdentity(new h(e.userId)),r=!!(t!=null&&t.masterKey)&&!!(t!=null&&t.selfSigningKey)&&!!(t!=null&&t.userSigningKey);t==null||t.free();var s=yield zi(e.secretStorage),_=yield e.getOlmMachineOrThrow().crossSigningStatus();return{publicKeysOnDevice:r,privateKeysInSecretStorage:s,privateKeysCachedLocally:{masterKey:!!(_!=null&&_.hasMaster),userSigningKey:!!(_!=null&&_.hasUserSigning),selfSigningKey:!!(_!=null&&_.hasSelfSigning)}}})()}createRecoveryKeyFromPassphrase(e){var t=this;return g(function*(){if(e){var r=bn(32),s=yield pn(e,r,t.RECOVERY_KEY_DERIVATION_ITERATIONS);return{keyInfo:{passphrase:{algorithm:"m.pbkdf2",iterations:t.RECOVERY_KEY_DERIVATION_ITERATIONS,salt:r}},privateKey:s,encodedPrivateKey:hn(s)}}else{var _=new Uint8Array(32);return globalThis.crypto.getRandomValues(_),{privateKey:_,encodedPrivateKey:hn(_)}}})()}getEncryptionInfoForEvent(e){var t=this;return g(function*(){return t.eventDecryptor.getEncryptionInfoForEvent(e)})()}getVerificationRequestsToDeviceInProgress(e){var t=this.olmMachine.getVerificationRequests(new h(e));return t.filter(r=>r.roomId===void 0).map(r=>this.makeVerificationRequest(r))}findVerificationRequestDMInProgress(e,t){if(!t)throw new Error("missing userId");var r=this.olmMachine.getVerificationRequests(new h(t)),s=r.find(_=>{var o;return((o=_.roomId)===null||o===void 0?void 0:o.toString())===e});if(s)return this.makeVerificationRequest(s)}requestVerificationDM(e,t){var r=this;return g(function*(){var s=yield r.olmMachine.getIdentity(new h(e));if(!s)throw new Error("unknown userId ".concat(e));try{var _=r._supportedVerificationMethods.map(d=>ft(d)),o=yield s.verificationRequestContent(_),a=yield r.sendVerificationRequestContent(t,o),c=yield s.requestVerification(new R(t),new Rr(a),_);return r.makeVerificationRequest(c)}finally{s.free()}})()}sendVerificationRequestContent(e,t){var r=this;return g(function*(){var s=bn(32),{event_id:_}=yield r.http.authedRequest(D.Put,"/_matrix/client/v3/rooms/".concat(encodeURIComponent(e),"/send/m.room.message/").concat(encodeURIComponent(s)),void 0,t,{prefix:""});return _})()}setSupportedVerificationMethods(e){this._supportedVerificationMethods=e??Yi}requestOwnUserVerification(){var e=this;return g(function*(){var t=yield e.olmMachine.getIdentity(new h(e.userId));if(t===void 0)throw new Error("cannot request verification for this device when there is no existing cross-signing key");try{var[r,s]=yield t.requestVerification(e._supportedVerificationMethods.map(ft));return yield e.outgoingRequestProcessor.makeOutgoingRequest(s),e.makeVerificationRequest(r)}finally{t.free()}})()}requestDeviceVerification(e,t){var r=this;return g(function*(){var s=yield r.olmMachine.getDevice(new h(e),new C(t));if(!s)throw new Error("Not a known device");try{var[_,o]=s.requestVerification(r._supportedVerificationMethods.map(ft));return yield r.outgoingRequestProcessor.makeOutgoingRequest(o),r.makeVerificationRequest(_)}finally{s.free()}})()}getSessionBackupPrivateKey(){var e=this;return g(function*(){var t=yield e.olmMachine.getBackupKeys();return t.decryptionKey?_r(t.decryptionKey.toBase64()):null})()}storeSessionBackupPrivateKey(e,t){var r=this;return g(function*(){var s=or(e);if(!t)throw new Error("storeSessionBackupPrivateKey: version is required");yield r.backupManager.saveBackupDecryptionKey(V.fromBase64(s),t)})()}loadSessionBackupPrivateKeyFromSecretStorage(){var e=this;return g(function*(){var t=yield e.secretStorage.get("m.megolm_backup.v1");if(!t)throw new Error("loadSessionBackupPrivateKeyFromSecretStorage: missing decryption key in secret storage");var r=yield e.backupManager.getServerBackupInfo();if(!r||!r.version)throw new Error("loadSessionBackupPrivateKeyFromSecretStorage: unable to get backup version");var s=V.fromBase64(t);if(!Qr(s,r))throw new Error("loadSessionBackupPrivateKeyFromSecretStorage: decryption key does not match backup info");yield e.backupManager.saveBackupDecryptionKey(s,r.version)})()}getActiveSessionBackupVersion(){var e=this;return g(function*(){return yield e.backupManager.getActiveBackupVersion()})()}getKeyBackupInfo(){var e=this;return g(function*(){return(yield e.backupManager.getServerBackupInfo())||null})()}isKeyBackupTrusted(e){var t=this;return g(function*(){return yield t.backupManager.isKeyBackupTrusted(e)})()}checkKeyBackupAndEnable(){var e=this;return g(function*(){return yield e.backupManager.checkKeyBackupAndEnable(!0)})()}deleteKeyBackupVersion(e){var t=this;return g(function*(){yield t.backupManager.deleteKeyBackupVersion(e)})()}resetKeyBackup(){var e=this;return g(function*(){var t=yield e.backupManager.setupKeyBackup(r=>e.signObject(r));(yield e.secretStorageHasAESKey())&&(yield e.secretStorage.store("m.megolm_backup.v1",t.decryptionKey.toBase64())),e.checkKeyBackupAndEnable()})()}disableKeyStorage(){var e=this;return g(function*(){var t=yield e.getKeyBackupInfo();t!=null&&t.version?yield e.deleteKeyBackupVersion(t.version):e.logger.error("Can't delete key backup version: no version available"),yield e.deleteSecretStorage(),yield e.dehydratedDeviceManager.delete()})()}signObject(e){var t=this;return g(function*(){var r=new Map(Object.entries(e.signatures||{})),s=e.unsigned;delete e.signatures,delete e.unsigned;var _=r.get(t.userId)||{},o=cg.stringify(e),a=yield t.olmMachine.sign(o),c=JSON.parse(a.asJSON());r.set(t.userId,Hi(Hi({},_),c[t.userId])),s!==void 0&&(e.unsigned=s),e.signatures=Object.fromEntries(r.entries())})()}restoreKeyBackupWithPassphrase(e,t){var r=this;return g(function*(){var s=yield r.backupManager.getServerBackupInfo();if(!(s!=null&&s.version))throw new Error("No backup info available");var _=yield Cg(s.auth_data,e);return yield r.storeSessionBackupPrivateKey(_,s.version),r.restoreKeyBackup(t)})()}restoreKeyBackup(e){var t=this;return g(function*(){var r=yield t.olmMachine.getBackupKeys(),{decryptionKey:s,backupVersion:_}=r;if(!s||!_)throw new Error("No decryption key found in crypto store");var o=_r(s.toBase64()),a=yield t.backupManager.requestKeyBackupVersion(_);if(!a)throw new Error("Backup version to restore ".concat(_," not found on server"));var c=yield t.getBackupDecryptor(a,o);try{var d;return e==null||(d=e.progressCallback)===null||d===void 0||d.call(e,{stage:Re.Fetch}),yield t.backupManager.restoreKeyBackup(_,c,e)}finally{c.free()}})()}isDehydrationSupported(){var e=this;return g(function*(){return yield e.dehydratedDeviceManager.isSupported()})()}startDehydration(){var e=arguments,t=this;return g(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:{};if(!(yield t.isCrossSigningReady())||!(yield t.isSecretStorageReady()))throw new Error("Device dehydration requires cross-signing and secret storage to be set up");return yield t.dehydratedDeviceManager.start(r||{})})()}importSecretsBundle(e){var t=this;return g(function*(){var r=oe.from_json(e);yield t.getOlmMachineOrThrow().importSecretsBundle(r)})()}exportSecretsBundle(){var e=this;return g(function*(){var t=yield e.getOlmMachineOrThrow().exportSecretsBundle(),r=t.to_json();return t.free(),r})()}encryptToDeviceMessages(e,t,r){var s=this;return g(function*(){var _=new it(s.logger,"encryptToDeviceMessages"),o=new Set(t.map(c=>{var{userId:d}=c;return d}));yield s.keyClaimManager.ensureSessionsForUsers(_,Array.from(o).map(c=>new h(c)));var a={batch:[],eventType:P.RoomMessageEncrypted};return yield Promise.all(t.map(function(){var c=g(function*(d){var{userId:w,deviceId:f}=d,m=yield s.olmMachine.getDevice(new h(w),new C(f));if(m){var K=JSON.parse(yield m.encryptToDeviceEvent(e,r));a.batch.push({deviceId:f,userId:w,payload:K})}else s.logger.warn("encryptToDeviceMessages: unknown device ".concat(w,":").concat(f))});return function(d){return c.apply(this,arguments)}}())),a})()}resetEncryption(e){var t=this;return g(function*(){t.logger.debug("resetEncryption: resetting encryption"),t.dehydratedDeviceManager.delete(),yield t.backupManager.deleteAllKeyBackupVersions(),yield t.deleteSecretStorage(),yield t.crossSigningIdentity.bootstrapCrossSigning({setupNewCrossSigning:!0,authUploadDeviceSigningKeys:e}),yield t.resetKeyBackup(),t.logger.debug("resetEncryption: ended")})()}deleteSecretStorage(){var e=this;return g(function*(){yield e.secretStorage.store("m.cross_signing.master",null),yield e.secretStorage.store("m.cross_signing.self_signing",null),yield e.secretStorage.store("m.cross_signing.user_signing",null),yield e.secretStorage.store("m.megolm_backup.v1",null);var t=yield e.secretStorage.getDefaultKeyId();t&&(yield e.secretStorage.store("m.secret_storage.key.".concat(t),null)),yield e.secretStorage.setDefaultKeyId(null)})()}shareRoomHistoryWithUser(e,t){var r=this;return g(function*(){var s=new it(r.logger,"shareRoomHistoryWithUser(".concat(e,", ").concat(t,")")),_=yield r.getOwnIdentity();if(!(_!=null&&_.isVerified())){s.warn("Not sharing message history as the current device is not verified by our cross-signing identity");return}s.info("Sharing message history");var o=yield r.getOlmMachineOrThrow().buildRoomKeyBundle(new R(e));if(!o){s.info("No keys to share");return}var a=yield r.http.uploadContent(o.encryptedData);s.info("Uploaded encrypted key blob: ".concat(JSON.stringify(a)));var c=r.getOlmMachineOrThrow().queryKeysForUsers([new h(t)]);yield r.outgoingRequestProcessor.makeOutgoingRequest(c),yield r.keyClaimManager.ensureSessionsForUsers(s,[new h(t)]);var d=yield r.getOlmMachineOrThrow().shareRoomKeyBundleData(new h(t),new R(e),a.content_uri,o.mediaEncryptionInfo,B.identityBasedStrategy());for(var w of d)yield r.outgoingRequestProcessor.makeOutgoingRequest(w)})()}receiveSyncChanges(e){var t=this;return g(function*(){var{events:r,oneTimeKeysCounts:s=new Map,unusedFallbackKeys:_,devices:o=new yt}=e;return yield t.olmMachine.receiveSyncChanges(r?JSON.stringify(r):"[]",o,s,_)})()}preprocessToDeviceMessages(e){var t=this;return g(function*(){var r=yield t.receiveSyncChanges({events:e}),s=[];for(var _ of r){var o=JSON.parse(_.rawEvent);if(o.type===P.KeyVerificationRequest){var a=o.sender,c=o.content.transaction_id;c&&a&&t.onIncomingKeyVerificationRequest(a,c)}switch(_.type){case De.Decrypted:{var d,w=_.encryptionInfo;s.push({message:o,encryptionInfo:{sender:w.sender.toString(),senderDevice:(d=w.senderDevice)===null||d===void 0?void 0:d.toString(),senderCurve25519KeyBase64:w.senderCurve25519Key,senderVerified:w.isSenderVerified()}});break}case De.PlainText:{s.push({message:o,encryptionInfo:null});break}case De.UnableToDecrypt:break;case De.Invalid:break}}return s})()}processKeyCounts(e,t){var r=this;return g(function*(){var s=e&&new Map(Object.entries(e)),_=t&&new Set(t);(s!==void 0||_!==void 0)&&(yield r.receiveSyncChanges({oneTimeKeysCounts:s,unusedFallbackKeys:_}))})()}processDeviceLists(e){var t=this;return g(function*(){var r,s,_=new yt((r=e.changed)===null||r===void 0?void 0:r.map(o=>new h(o)),(s=e.left)===null||s===void 0?void 0:s.map(o=>new h(o)));yield t.receiveSyncChanges({devices:_})})()}onCryptoEvent(e,t){var r=this;return g(function*(){var s=t.getContent(),_=new _e;if(s.algorithm==="m.megolm.v1.aes-sha2")_.algorithm=ge.MegolmV1AesSha2;else{r.logger.warn("Room ".concat(e.roomId,": ignoring crypto event with invalid algorithm ").concat(s.algorithm));return}try{_.sessionRotationPeriodMs=s.rotation_period_ms,_.sessionRotationPeriodMessages=s.rotation_period_msgs,yield r.olmMachine.setRoomSettings(new R(e.roomId),_)}catch(a){r.logger.warn("Room ".concat(e.roomId,": ignoring crypto event which caused error: ").concat(a));return}var o=r.roomEncryptors[e.roomId];o?o.onCryptoEvent(s):r.roomEncryptors[e.roomId]=new gg(r.logger.getChild("[".concat(e.roomId," encryption]")),r.olmMachine,r.keyClaimManager,r.outgoingRequestsManager,e,s)})()}onSyncCompleted(e){this.outgoingRequestsManager.doProcessOutgoingRequests().catch(t=>{this.logger.warn("onSyncCompleted: Error processing outgoing requests",t)})}markAllTrackedUsersAsDirty(){var e=this;return g(function*(){yield e.olmMachine.markAllTrackedUsersAsDirty()})()}onIncomingKeyVerificationRequest(e,t){var r=this.olmMachine.getVerificationRequest(new h(e),t);r?this.emit(I.VerificationRequestReceived,this.makeVerificationRequest(r)):this.logger.info("Ignoring just-received verification request ".concat(t," which did not start a rust-side verification"))}makeVerificationRequest(e){return new mg(this.logger,this.olmMachine,e,this.outgoingRequestProcessor,this._supportedVerificationMethods)}onRoomMembership(e,t,r){var s=this.roomEncryptors[e.getRoomId()];s&&s.onRoomMembership(t)}onRoomKeysUpdated(e){var t=this;return g(function*(){for(var r of e)t.onRoomKeyUpdated(r);t.backupManager.maybeUploadKey()})()}onRoomKeyUpdated(e){var t=this;if(!this.stopped){this.logger.debug("Got update for session ".concat(e.sessionId," from sender ").concat(e.senderKey.toBase64()," in ").concat(e.roomId.toString()));var r=this.eventDecryptor.getEventsPendingRoomKey(e.roomId.toString(),e.sessionId);if(r.length!==0){this.logger.debug("Retrying decryption on events:",r.map(o=>"".concat(o.getId())));var s=function(o){o.attemptDecryption(t,{isRetry:!0}).catch(a=>{t.logger.info("Still unable to decrypt event ".concat(o.getId()," after receiving key"))})};for(var _ of r)s(_)}}}onRoomKeysWithheld(e){var t=this;return g(function*(){for(var r of e){t.logger.debug("Got withheld message for session ".concat(r.sessionId," in ").concat(r.roomId.toString()));var s=t.eventDecryptor.getEventsPendingRoomKey(r.roomId.toString(),r.sessionId);if(s.length===0)return;t.logger.debug("Retrying decryption on events:",s.map(o=>"".concat(o.getId())));for(var _ of s)_.attemptDecryption(t,{isRetry:!0}).catch(o=>{})}})()}onUserIdentityUpdated(e){var t=this;return g(function*(){var r=yield t.getUserVerificationStatus(e.toString());t.emit(I.UserTrustStatusChanged,e.toString(),r),e.toString()===t.userId&&(t.emit(I.KeysChanged,{}),yield t.checkKeyBackupAndEnable())})()}onDevicesUpdated(e){var t=this;return g(function*(){t.emit(I.WillUpdateDevices,e,!1),t.emit(I.DevicesUpdated,e,!1)})()}handleSecretReceived(e,t){var r=this;return g(function*(){return r.logger.debug("onReceiveSecret: Received secret ".concat(e)),e==="m.megolm_backup.v1"?yield r.backupManager.handleBackupSecretReceived(t):!1})()}checkSecrets(e){var t=this;return g(function*(){var r=yield t.olmMachine.getSecretsFromInbox(e);for(var s of r)if(yield t.handleSecretReceived(e,s))break;yield t.olmMachine.deleteSecretsFromInbox(e)})()}onLiveEventFromSync(e){var t=this;return g(function*(){if(!(e.isState()||e.getUnsigned().transaction_id)){var r=function(){var a=g(function*(c){kg(e)&&(yield t.onKeyVerificationEvent(c))});return function(c){return a.apply(this,arguments)}}();if(e.isDecryptionFailure()||e.isEncrypted()){var s=3e5,_=setTimeout(()=>e.off(ar.Decrypted,o),s),o=(a,c)=>{c||(clearTimeout(_),e.off(ar.Decrypted,o),r(a))};e.on(ar.Decrypted,o)}else yield r(e)}})()}onKeyVerificationEvent(e){var t=this;return g(function*(){var r=e.getRoomId();if(!r)throw new Error("missing roomId in the event");t.logger.debug("Incoming verification event ".concat(e.getId()," type ").concat(e.getType()," from ").concat(e.getSender())),yield t.olmMachine.receiveVerificationEvent(JSON.stringify({event_id:e.getId(),type:e.getType(),sender:e.getSender(),state_key:e.getStateKey(),content:e.getContent(),origin_server_ts:e.getTs()}),new R(r)),e.getType()===P.RoomMessage&&e.getContent().msgtype===dn.KeyVerificationRequest&&t.onIncomingKeyVerificationRequest(e.getSender(),e.getId()),t.outgoingRequestsManager.doProcessOutgoingRequests().catch(s=>{t.logger.warn("onKeyVerificationRequest: Error processing outgoing requests",s)})})()}getOwnIdentity(){var e=this;return g(function*(){return yield e.olmMachine.getIdentity(new h(e.userId))})()}}class Eg{constructor(e,t,r){this.logger=e,this.olmMachine=t,this.perSessionBackupDownloader=r,k(this,"eventsPendingKey",new fn(()=>new fn(()=>new Set)))}attemptEventDecryption(e,t){var r=this;return g(function*(){r.addEventToPendingList(e);var s;switch(t.kind){case st.AllDevicesIsolationMode:s=wr.Untrusted;break;case st.OnlySignedDevicesIsolationMode:s=wr.CrossSignedOrLegacy;break}try{var _=yield r.olmMachine.decryptRoomEvent($i(e),new R(e.getRoomId()),new Oe(s));return r.removeEventFromPendingList(e),{clearEvent:JSON.parse(_.event),claimedEd25519Key:_.senderClaimedEd25519Key,senderCurve25519Key:_.senderCurve25519Key,forwardingCurve25519KeyChain:_.forwardingCurve25519KeyChain}}catch(o){if(o instanceof Ne)r.onMegolmDecryptionError(e,o,yield r.perSessionBackupDownloader.getServerBackupInfo());else throw new z(T.UNKNOWN_ERROR,"Unknown error")}})()}onMegolmDecryptionError(e,t,r){var s=e.getWireContent(),_={sender_key:s.sender_key,session_id:s.session_id};if(t.code===$.MissingRoomKey||t.code===$.UnknownMessageIndex){this.perSessionBackupDownloader.onDecryptionKeyMissingError(e.getRoomId(),s.session_id);var o=e.getMembershipAtEvent();if(o&&o!==nt.Join&&o!==nt.Invite)throw new z(T.HISTORICAL_MESSAGE_USER_NOT_JOINED,"This message was sent when we were not a member of the room.",_);if(e.getTs()<=this.olmMachine.deviceCreationTimeMs)throw r===null?new z(T.HISTORICAL_MESSAGE_NO_KEY_BACKUP,"This message was sent before this device logged in, and there is no key backup on the server.",_):this.perSessionBackupDownloader.isKeyBackupDownloadConfigured()?new z(T.HISTORICAL_MESSAGE_WORKING_BACKUP,"This message was sent before this device logged in. Key backup is working, but we still do not (yet) have the key.",_):new z(T.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED,"This message was sent before this device logged in, and key backup is not working.",_)}if(t.maybe_withheld){var a=t.maybe_withheld==="The sender has disabled encrypting to unverified devices."?T.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE:T.MEGOLM_KEY_WITHHELD;throw new z(a,t.maybe_withheld,_)}switch(t.code){case $.MissingRoomKey:throw new z(T.MEGOLM_UNKNOWN_INBOUND_SESSION_ID,"The sender's device has not sent us the keys for this message.",_);case $.UnknownMessageIndex:throw new z(T.OLM_UNKNOWN_MESSAGE_INDEX,"The sender's device has not sent us the keys for this message at this index.",_);case $.SenderIdentityVerificationViolation:throw this.removeEventFromPendingList(e),new z(T.SENDER_IDENTITY_PREVIOUSLY_VERIFIED,"The sender identity is unverified, but was previously verified.");case $.UnknownSenderDevice:throw this.removeEventFromPendingList(e),new z(T.UNKNOWN_SENDER_DEVICE,"The sender device is not known.");case $.UnsignedSenderDevice:throw this.removeEventFromPendingList(e),new z(T.UNSIGNED_SENDER_DEVICE,"The sender identity is not cross-signed.");default:throw new z(T.UNKNOWN_ERROR,t.description,_)}}getEncryptionInfoForEvent(e){var t=this;return g(function*(){if(!e.getClearContent()||e.isDecryptionFailure())return null;if(e.status!==null)return{shieldColour:gt.NONE,shieldReason:null};var r=yield t.olmMachine.getRoomEventEncryptionInfo($i(e),new R(e.getRoomId()));return Og(t.logger,r)})()}getEventsPendingRoomKey(e,t){var r=this.eventsPendingKey.get(e);if(!r)return[];var s=r.get(t);return s?[...s]:[]}addEventToPendingList(e){var t=e.getRoomId();if(t){var r=this.eventsPendingKey.getOrCreate(t),s=r.getOrCreate(e.getWireContent().session_id);s.add(e)}}removeEventFromPendingList(e){var t=e.getRoomId();if(t){var r=this.eventsPendingKey.getOrCreate(t);if(r){var s=r.get(e.getWireContent().session_id);s&&(s.delete(e),s.size===0&&(r.delete(e.getWireContent().session_id),r.size===0&&this.eventsPendingKey.delete(t)))}}}}function $i(i){return JSON.stringify({event_id:i.getId(),type:i.getWireType(),sender:i.getSender(),state_key:i.getStateKey(),content:i.getWireContent(),origin_server_ts:i.getTs()})}function Og(i,e){if(e===void 0)return null;var t=e.shieldState(!1),r;switch(t.color){case pr.Grey:r=gt.GREY;break;case pr.None:r=gt.NONE;break;default:r=gt.RED}var s;switch(t.code){case void 0:case null:s=null;break;case Z.AuthenticityNotGuaranteed:s=Y.AUTHENTICITY_NOT_GUARANTEED;break;case Z.UnknownDevice:s=Y.UNKNOWN_DEVICE;break;case Z.UnsignedDevice:s=Y.UNSIGNED_DEVICE;break;case Z.UnverifiedIdentity:s=Y.UNVERIFIED_IDENTITY;break;case Z.SentInClear:s=Y.SENT_IN_CLEAR;break;case Z.VerificationViolation:s=Y.VERIFICATION_VIOLATION;break;case Z.MismatchedSender:s=Y.MISMATCHED_SENDER;break;default:s=Y.UNKNOWN;break}return{shieldColour:r,shieldReason:s}}function Mg(i){return Hr.apply(this,arguments)}function Hr(){return Hr=g(function*(i){var e,{logger:t,legacyStore:r}=i;if(yield Fi(),!(yield r.containsData()))return;yield r.startup();var s=null;if(yield r.doTxn("readonly",[Ke.STORE_ACCOUNT],m=>{r.getAccount(m,K=>{s=K})}),!s){t.debug("Legacy crypto store is not set up (no account found). Not migrating.");return}var _=yield r.getMigrationState();if(_>=A.MEGOLM_SESSIONS_MIGRATED)return;var o=yield Bg(t,r),a=yield Ug(t,r),c=1+o+a;t.info("Migrating data from legacy crypto store. ".concat(o," olm sessions and ").concat(a," megolm sessions to migrate."));var d=0;function w(m){var K;d+=m,(K=i.legacyMigrationProgressListener)===null||K===void 0||K.call(i,d,c)}w(0);var f=new TextEncoder().encode(i.legacyPickleKey);_===A.NOT_STARTED&&(t.info("Migrating data from legacy crypto store. Step 1: base data"),yield qg(i.http,i.userId,i.deviceId,r,f,i.storeHandle,t),_=A.INITIAL_DATA_MIGRATED,yield r.setMigrationState(_)),w(1),_===A.INITIAL_DATA_MIGRATED&&(t.info("Migrating data from legacy crypto store. Step 2: olm sessions (".concat(o," sessions to migrate).")),yield Fg(t,r,f,i.storeHandle,w),_=A.OLM_SESSIONS_MIGRATED,yield r.setMigrationState(_)),_===A.OLM_SESSIONS_MIGRATED&&(t.info("Migrating data from legacy crypto store. Step 3: megolm sessions (".concat(a," sessions to migrate).")),yield Vg(t,r,f,i.storeHandle,w),_=A.MEGOLM_SESSIONS_MIGRATED,yield r.setMigrationState(_)),(e=i.legacyMigrationProgressListener)===null||e===void 0||e.call(i,-1,-1),t.info("Migration from legacy crypto store complete")}),Hr.apply(this,arguments)}function qg(i,e,t,r,s,_,o){return Yr.apply(this,arguments)}function Yr(){return Yr=g(function*(i,e,t,r,s,_,o){var a=new br;a.userId=new h(e),a.deviceId=new C(t),yield r.doTxn("readonly",[Ke.STORE_ACCOUNT],H=>r.getAccount(H,nr=>{a.pickledAccount=nr??""}));var c=yield mt(r,s,"m.megolm_backup.v1");if(c){for(var d=!1,w=null;!d;)try{w=yield Wi(i),d=!0}catch(H){o.info("Failed to get backup version during migration, retrying in 2 seconds",H),yield re(2e3)}if(w&&w.algorithm=="m.megolm_backup.v1.curve25519-aes-sha2")try{var f,m=V.fromBase64(c),K=(f=w.auth_data)===null||f===void 0?void 0:f.public_key,U=m.megolmV1PublicKey.publicKeyBase64==K;U?(a.backupVersion=w.version,a.backupRecoveryKey=c):o.debug("The backup key to migrate does not match the active backup version","Cached pub key: ".concat(m.megolmV1PublicKey.publicKeyBase64),"Active pub key: ".concat(K))}catch(H){o.warn("Failed to check if the backup key to migrate matches the active backup version",H)}}a.privateCrossSigningMasterKey=yield mt(r,s,"master"),a.privateCrossSigningSelfSigningKey=yield mt(r,s,"self_signing"),a.privateCrossSigningUserSigningKey=yield mt(r,s,"user_signing"),yield bt.migrateBaseData(a,s,_,o)}),Yr.apply(this,arguments)}function Bg(i,e){return $r.apply(this,arguments)}function $r(){return $r=g(function*(i,e){i.debug("Counting olm sessions to be migrated");var t;return yield e.doTxn("readonly",[Ke.STORE_SESSIONS],r=>e.countEndToEndSessions(r,s=>t=s)),t}),$r.apply(this,arguments)}function Ug(i,e){return Zr.apply(this,arguments)}function Zr(){return Zr=g(function*(i,e){return i.debug("Counting megolm sessions to be migrated"),yield e.countEndToEndInboundGroupSessions()}),Zr.apply(this,arguments)}function Fg(i,e,t,r,s){return Xr.apply(this,arguments)}function Xr(){return Xr=g(function*(i,e,t,r,s){for(;;){var _=yield e.getEndToEndSessionsBatch();if(_===null)return;i.debug("Migrating batch of ".concat(_.length," olm sessions"));var o=[];for(var a of _){var c=new We;c.senderKey=a.deviceKey,c.pickle=a.session,c.lastUseTime=c.creationTime=new Date(a.lastReceivedMessageTs),o.push(c)}yield bt.migrateOlmSessions(o,t,r,i),yield e.deleteEndToEndSessionsBatch(_),s(_.length)}}),Xr.apply(this,arguments)}function Vg(i,e,t,r,s){return en.apply(this,arguments)}function en(){return en=g(function*(i,e,t,r,s){for(;;){var _=yield e.getEndToEndInboundGroupSessionsBatch();if(_===null)return;i.debug("Migrating batch of ".concat(_.length," megolm sessions"));var o=[];for(var a of _){var c,d=a.sessionData,w=new Le;w.pickle=d.session,w.roomId=new R(d.room_id),w.senderKey=a.senderKey,w.senderSigningKey=(c=d.keysClaimed)===null||c===void 0?void 0:c.ed25519,w.backedUp=!a.needsBackup,w.imported=d.untrusted===!0,o.push(w)}yield bt.migrateMegolmSessions(o,t,r,i),yield e.deleteEndToEndInboundGroupSessionsBatch(_),s(_.length)}}),en.apply(this,arguments)}function Tg(i){return tn.apply(this,arguments)}function tn(){return tn=g(function*(i){var{logger:e,legacyStore:t,olmMachine:r}=i;if(yield t.containsData()){var s=yield t.getMigrationState();if(!(s>=A.ROOM_SETTINGS_MIGRATED)){var _={};yield t.doTxn("readwrite",[Ke.STORE_ROOMS],d=>{t.getEndToEndRooms(d,w=>{_=w})}),e.debug("Migrating ".concat(Object.keys(_).length," sets of room settings"));for(var[o,a]of Object.entries(_))try{var c=new _e;if(a.algorithm!=="m.megolm.v1.aes-sha2"){e.warn("Room ".concat(o,": ignoring room with invalid algorithm ").concat(a.algorithm));continue}c.algorithm=ge.MegolmV1AesSha2,c.sessionRotationPeriodMs=a.rotation_period_ms,c.sessionRotationPeriodMessages=a.rotation_period_msgs,yield r.setRoomSettings(new R(o),c)}catch(d){e.warn("Room ".concat(o,": ignoring settings ").concat(JSON.stringify(a)," which caused error ").concat(d))}e.debug("Completed room settings migration"),yield t.setMigrationState(A.ROOM_SETTINGS_MIGRATED)}}}),tn.apply(this,arguments)}function mt(i,e,t){return rn.apply(this,arguments)}function rn(){return rn=g(function*(i,e,t){var r=yield new Promise(s=>{i.doTxn("readonly",[Ke.STORE_ACCOUNT],_=>{i.getSecretStorePrivateKey(_,s,t)})});return r&&r.ciphertext&&r.iv&&r.mac?yield us(r,e,t):r instanceof Uint8Array?or(r):void 0}),rn.apply(this,arguments)}function Pg(i){return nn.apply(this,arguments)}function nn(){return nn=g(function*(i){var{legacyCryptoStore:e,rustCrypto:t,logger:r}=i,s=yield t.getOwnIdentity();if(s&&!s.isVerified()){var _=yield zg(e);if(_){var o=JSON.parse(s.masterKey);if(!o.keys||Object.keys(o.keys).length===0){r.error("Post Migration | Unexpected error: no master key in the rust session.");return}var a=Object.values(o.keys)[0];a&&a==_&&(r.info("Post Migration: Migrating legacy trusted MSK: ".concat(_," to locally verified.")),yield s.verify())}}}),nn.apply(this,arguments)}function zg(i){return sn.apply(this,arguments)}function sn(){return sn=g(function*(i){var e=null;return yield i.doTxn("readonly","account",t=>{i.getCrossSigningKeys(t,r=>{var s=r==null?void 0:r.master;s&&Object.keys(s.keys).length!=0&&(e=Object.values(s.keys)[0])})}),e}),sn.apply(this,arguments)}function Zi(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(i);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(i,s).enumerable})),t.push.apply(t,r)}return t}function Ng(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Zi(Object(t),!0).forEach(function(r){k(i,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Zi(Object(t)).forEach(function(r){Object.defineProperty(i,r,Object.getOwnPropertyDescriptor(t,r))})}return i}function Ag(i){return _n.apply(this,arguments)}function _n(){return _n=g(function*(i){var{logger:e}=i;e.debug("Initialising Rust crypto-sdk WASM artifact"),yield Fi(),e.debug("Opening Rust CryptoStore");var t;i.storePrefix?i.storeKey?t=yield j.openWithKey(i.storePrefix,i.storeKey,e):t=yield j.open(i.storePrefix,i.storePassphrase,e):t=yield j.open(null,null,e),i.legacyCryptoStore&&(yield Mg(Ng({legacyStore:i.legacyCryptoStore,storeHandle:t},i)));var r=yield jg(e,i.http,i.userId,i.deviceId,i.secretStorage,i.cryptoCallbacks,t,i.legacyCryptoStore);return t.free(),e.debug("Completed rust crypto-sdk setup"),r}),_n.apply(this,arguments)}function jg(i,e,t,r,s,_,o,a){return on.apply(this,arguments)}function on(){return on=g(function*(i,e,t,r,s,_,o,a){i.debug("Init OlmMachine");var c=yield Ae.initFromStore(new h(t),new C(r),o,i);a&&(yield Tg({logger:i,legacyStore:a,olmMachine:c})),c.roomKeyRequestsEnabled=!1;var d=new Dg(i,c,e,t,r,s,_);if(yield c.registerRoomKeyUpdatedCallback(m=>d.onRoomKeysUpdated(m)),yield c.registerRoomKeysWithheldCallback(m=>d.onRoomKeysWithheld(m)),yield c.registerUserIdentityUpdatedCallback(m=>d.onUserIdentityUpdated(m)),yield c.registerDevicesUpdatedCallback(m=>d.onDevicesUpdated(m)),d.checkSecrets("m.megolm_backup.v1"),yield c.registerReceiveSecretCallback((m,K)=>d.checkSecrets(m)),yield c.outgoingRequests(),a&&(yield a.containsData())){var w=yield a.getMigrationState();if(w<A.INITIAL_OWN_KEY_QUERY_DONE){i.debug("Performing initial key query after migration");for(var f=!1;!f;)try{yield d.userHasCrossSigningKeys(t),f=!0}catch(m){i.error("Failed to check for cross-signing keys after migration, retrying",m)}yield Pg({legacyCryptoStore:a,rustCrypto:d,logger:i}),yield a.setMigrationState(A.INITIAL_OWN_KEY_QUERY_DONE)}}return d}),on.apply(this,arguments)}export{Ag as initRustCrypto};