@matrix-widget-sdk/compat-wrapper 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,392 @@
1
- # Temporary Holding Version
1
+ # Widget compat wrapper
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A hosted widget that makes a **legacy widget** (built on [matrix-widget-api], `api: fromWidget | toWidget`)
4
+ look like an **MSC4412 widget** to its host. The host embeds the wrapper; the wrapper embeds the legacy
5
+ widget in an inner iframe and translates between the two protocols.
6
+
7
+ It contains **no action logic**. It translates envelopes, action names and capability names,
8
+ forwards every other body untouched except file payloads (converted between `Blob` and base64,
9
+ see below) and the error responses of the legacy widget (which get the `code` MSC4412 requires),
10
+ and implements only two things itself:
11
+ the legacy **URL templating** (`$matrix_user_id` & co., fed by the `get_matrix_context` /
12
+ `get_client_context` actions) and the startup handshake, where the two protocols are structurally
13
+ different.
14
+
15
+ The wrapper is the **only** place the legacy names are understood. The host knows the action and
16
+ capability names of [`capability-naming-proposal.md`](../../docs/spec-appendix/capability-naming-proposal.md)
17
+ and nothing else.
18
+
19
+ ![Using legacy widgets with the new driver](../../docs/diagrams/02-legacy-widgets.svg)
20
+
21
+ ## How a client uses it during the transition
22
+
23
+ The client speaks MSC4412 only (for example through `matrix-widget-host-driver`) and keeps one piece of
24
+ transition code: a check on the widget state event.
25
+
26
+ 1. The client reads the widget state event of the room.
27
+ 2. **Legacy event** (`im.vector.modular.widgets`): embed
28
+ `https://example.org/myHostedCompatWidget?legacy_widget_url=<urlencoded content.url>&legacy_widget_id=<state_key>`
29
+ as a new-style widget with `usesWidgetAPI: true`. The URL is passed **untemplated**; the host
30
+ knows nothing about template variables. The wrapper resolves them (it asks the host for
31
+ `get_matrix_context` and `get_client_context`), appends the `widgetId` / `parentUrl` query parameters
32
+ legacy clients used to add, and loads the result in its inner iframe.
33
+ 3. **New event** (`m.widget`): embed `content.url` directly, unless it is a page of the client's
34
+ own compat wrapper: that runs on the client's origin and loads the `legacy_widget_url` the
35
+ event put into its query, unchecked by the client
36
+ ([Which URLs the wrapper loads](#which-urls-the-wrapper-loads)).
37
+
38
+ That URL construction is the only client code specific to the transition. Once legacy widgets are
39
+ gone, delete it and the wrapper. The host keeps no template engine at all. `matrix-widget-host-driver`
40
+ has it: a `WidgetHostDriver` made from a legacy widget's definition, with the client's wrapper URL
41
+ in `EmbedOptions`, hands the wrapper's URL to the client (`WidgetHostPlatform::load_iframe`). It
42
+ makes the URL check of the widget and of the wrapper, and refuses a widget of either kind whose URL
43
+ is a page of the wrapper; it sets `legacy_widget_url`, `legacy_widget_id`,
44
+ `legacy_wait_for_iframe_load` and `legacy_widget_data`.
45
+
46
+ ## Query parameters
47
+
48
+ | parameter | required | from the legacy state event | meaning |
49
+ |---|---|---|---|
50
+ | `legacy_widget_url` | yes | `content.url`, **untemplated** | Template variables are resolved by the wrapper. `widgetId` is added if missing and `parentUrl` is always set to the wrapper's own URL, because the widget's parent is now the wrapper. Only an absolute `http:` / `https:` URL is loaded, see [below](#which-urls-the-wrapper-loads). |
51
+ | `legacy_widget_id` | no | `state_key` | `widgetId` put on every legacy message and value of `$matrix_widget_id`. Default: the `widgetId` query parameter of `legacy_widget_url`. One of the two must exist. |
52
+ | `legacy_widget_name` | no | `content.name` | Accessible name (`title`) of the inner iframe. Default: the widget id. |
53
+ | `legacy_wait_for_iframe_load` | no | `content.waitForIframeLoad` (default `true`) | Decides when the legacy capability round starts, see below. |
54
+ | `legacy_widget_data` | no | `content.data` as JSON | Extra `$key` template variables, as in legacy clients. |
55
+ | `client_origin` | no | | Target origin for `postMessage` to the host. Default `*`. Set it in production. |
56
+ | `log_level` | no | | What the wrapper writes to the console (prefix `[widget-compat-wrapper]`): `off`, `error`, `warn` (default), `info`, `debug`. `warn` reports dropped responses and refused requests, `debug` adds one line per message. |
57
+
58
+ ## What the wrapper does
59
+
60
+ ### Bootstrap: templating the legacy URL
61
+
62
+ Before the inner iframe exists the wrapper sends `request_capabilities` for
63
+ `widget:org.matrix.mscXXXX.get_matrix_context` and `widget:org.matrix.mscXXXX.get_client_context`
64
+ (and the webview capabilities of a legacy client's iframe, see [The iframes](#the-iframes)),
65
+ waits for the host's `update_capabilities`, requests both contexts
66
+ (`org.matrix.mscXXXX.get_matrix_context`, `org.matrix.mscXXXX.get_client_context`) and
67
+ renders the URL:
68
+
69
+ | variable | source |
70
+ |---|---|
71
+ | `$matrix_user_id`, `$matrix_room_id`, `$matrix_display_name`, `$matrix_avatar_url` | `get_matrix_context` |
72
+ | `$org.matrix.msc3819.matrix_device_id`, `$org.matrix.msc4039.matrix_base_url` | `get_matrix_context` |
73
+ | `$org.matrix.msc2873.client_id`, `$org.matrix.msc2873.client_theme`, `$org.matrix.msc2873.client_language` | `get_client_context` |
74
+ | `$matrix_widget_id` | `legacy_widget_id` |
75
+ | `$<key>` | `legacy_widget_data` |
76
+
77
+ Values are URI-encoded, unknown variables stay as they are, and if the host denies a capability
78
+ or does not implement an action the corresponding variables are empty (the widget still loads).
79
+ Any other host request during this phase is answered with an `invalid_request` error, since there
80
+ is no widget yet.
81
+
82
+ This means a host prompts twice for a wrapped widget: once for the wrapper's context
83
+ capabilities, once for the capabilities the legacy widget itself asks for. A host may of course
84
+ grant the context capabilities without prompting.
85
+
86
+ ### The iframes
87
+
88
+ A host with strict iframes ([`spec/patch/msc4411/strict-webview-defaults.md`](../../spec/patch/msc4411/strict-webview-defaults.md))
89
+ gives a widget only `sandbox="allow-scripts allow-same-origin"` until it holds webview capabilities
90
+ ([`spec/patch/new/webview-capabilities.md`](../../spec/patch/new/webview-capabilities.md)). A legacy
91
+ widget was written for the iframe Element Web gives every widget, so the wrapper requests that set
92
+ in its first `request_capabilities` (`LEGACY_WEBVIEW_CAPABILITIES` in `src/capabilities.ts`, fifteen
93
+ in all):
94
+
95
+ | `sandbox` (`webview:org.matrix.mscXXXX.sandbox:<token>`) | `allow` (`webview:org.matrix.mscXXXX.allow:<feature>`) |
96
+ |---|---|
97
+ | `allow-forms`, `allow-popups`, `allow-popups-to-escape-sandbox`, `allow-same-origin`, `allow-scripts`, `allow-presentation`, `allow-downloads` | `microphone`, `camera`, `encrypted-media`, `autoplay`, `display-capture`, `clipboard-write`, `clipboard-read`, `fullscreen` |
98
+
99
+ A host that keeps legacy widgets working grants them without a prompt and builds the wrapper's
100
+ iframe with them from the start, so the request needs no reload (`matrix-widget-host-driver` does both for
101
+ a legacy widget: `legacy_auto_approved`, the same set).
102
+ The wrapper's own iframe for the legacy widget (`innerIframe` in `src/wrapper.ts`) always has these
103
+ attributes (`INNER_SANDBOX`, `INNER_ALLOW`), whatever the host granted: a legacy widget cannot request
104
+ webview capabilities (a `webview:` string in its list expands to nothing). One exception: a legacy
105
+ widget on the wrapper's own origin, which is often the client's, would share that origin with
106
+ `allow-same-origin`. It loads without it, so its origin is opaque, and the wrapper posts to it with
107
+ the target origin `*` (it is still only that iframe's window that gets the message).
108
+
109
+ ### Which URLs the wrapper loads
110
+
111
+ The wrapper is often served from its client's own origin (this repository's test host does that),
112
+ and the client gives its iframe `allow-same-origin`. A
113
+ `javascript:` URL in the inner iframe would run on the client's origin, and `data:`, `blob:`,
114
+ `about:` pages or a URL resolved against the wrapper page (`/x`, `http:/x`) would be pages of that
115
+ origin. So the wrapper loads only an **absolute `http:` or `https:` URL that names its own host**:
116
+ the rule of `widget_url_problem` in `matrix-widget-host-driver` (`src/url.ts`; its tests run the driver's
117
+ URL table, `crates/matrix-widget-host-driver/tests/widget_urls.json`). It checks:
118
+
119
+ 1. the template in `legacy_widget_url`, when it reads its configuration: a refused one stops the
120
+ wrapper before it talks to the host (a template that starts with a `$variable` has no scheme
121
+ and is refused);
122
+ 2. the template again and the templated URL, before the inner iframe is created: that is what
123
+ the iframe loads, and it gets the URL as the URL parser serialised it. A value cannot change
124
+ the scheme (it is URI-encoded), but it can make the URL invalid (`https://$server/` with
125
+ `server` = `widgets.example:8443`).
126
+
127
+ A refused URL creates no inner iframe. The wrapper logs the reason (`console.error`, also at
128
+ `log_level=warn`), shows it in its page ("Widget compat wrapper: refused …", the same place as the
129
+ errors of a missing parameter), never sends `notify_ready` (so the host's widget stays in its
130
+ loading state until the host gives up) and answers every later host request with
131
+ `invalid_request`. The texts name the scheme, never the URL.
132
+
133
+ A client should still check the URL first (the driver's `WidgetDefinition::embed` does, before
134
+ templating) and should not load its own compat wrapper as a widget (`embed` refuses that too):
135
+ the wrapper's check protects clients that do not, and copies of the wrapper the client does not
136
+ know about.
137
+
138
+ ### Envelope translation (both directions, stateless)
139
+
140
+ | legacy | MSC4412 |
141
+ |---|---|
142
+ | `api: "fromWidget"` / `"toWidget"` | `source: "widget"` / `"host"` |
143
+ | `widgetId` | absent; added from `legacy_widget_id` |
144
+ | `data` | `request` |
145
+ | response = echo of the request + `response` | response = header + `response` |
146
+ | `requestId` | `request_id`, same value, so responses correlate without extra state |
147
+ | `response.error: { message }` from the widget | `response.error: { code: "org.matrix.msc4412.unknown", message }` |
148
+ | `response.error` from the host | unchanged: the widget reads `message` (and `matrix_api_error`) and ignores `code` |
149
+
150
+ Neither format has a version. They are told apart by `api` versus `source`; the wrapper routes by
151
+ window (`event.source`) and ignores a message of the wrong format.
152
+
153
+ ### Action names (`src/envelope.ts`)
154
+
155
+ The host does not accept the legacy names of the actions below, so the wrapper renames them.
156
+ MSC4412 demands a namespace on every action, so that includes every legacy name without one. The
157
+ table depends on the direction, because `send_event` and `send_to_device` are legacy names in both.
158
+
159
+ `…` is `org.matrix.mscXXXX.`, the placeholder namespace of actions without an MSC of their own.
160
+
161
+ | direction | legacy widget | host |
162
+ |---|---|---|
163
+ | widget → host | `content_loaded` | `org.matrix.msc4412.notify_ready` (sent by the wrapper itself, see the handshake) |
164
+ | widget → host | `org.matrix.msc2974.request_capabilities` | `org.matrix.msc4412.request_capabilities` |
165
+ | widget → host | `send_event` | `…send_event` |
166
+ | widget → host | `send_to_device` | `…send_to_device` |
167
+ | widget → host | `get_openid` | `…get_openid`, sent by the wrapper itself (see [OpenID](#openid-get_openid-and-openid_credentials)) |
168
+ | widget → host | `watch_turn_servers` / `unwatch_turn_servers` | `…watch_turn_servers` / `…unwatch_turn_servers` |
169
+ | widget → host | `set_always_on_screen` | `…set_always_on_screen` |
170
+ | widget → host | `org.matrix.msc3973.user_directory_search` | `org.matrix.msc3973.search_user_directory` |
171
+ | widget → host | `org.matrix.msc4533.rtc_livekit_get_token` | `org.matrix.msc4533.get_rtc_livekit_token` |
172
+ | widget → host | `org.matrix.msc4533.rtc_livekit_delegate_delayed_leave` | `org.matrix.msc4533.delegate_rtc_livekit_delayed_leave` |
173
+ | host → widget | `notify_capabilities` | `org.matrix.msc4412.update_capabilities` (body rewritten, see below) |
174
+ | host → widget | `send_event` | `…forward_event` |
175
+ | host → widget | `send_to_device` | `…forward_to_device` |
176
+ | host → widget | `update_state` | `…update_state` |
177
+ | host → widget | `update_turn_servers` | `…update_turn_servers` |
178
+ | host → widget | `theme_change` | `…update_theme` |
179
+ | host → widget | `language_change` | `…update_language` |
180
+ | host → widget | `visibility` | `…update_visibility` |
181
+
182
+ Everything else passes through unchanged (the host emits and accepts the unstable MSC spellings
183
+ such as `org.matrix.msc3869.read_relations` itself, see `docs/parity.md`), so an
184
+ action the host does not implement is answered by the host's own error response, which is
185
+ forwarded to the widget as is.
186
+
187
+ ### Reading events (`src/readEvents.ts`)
188
+
189
+ The host has no `org.matrix.msc2876.read_events`: it reads its timeline cache with
190
+ `…read_timeline`, `…paginate_timeline` and `…notify_timeline_update`
191
+ ([draft](../../spec/patch/new/timeline-reading.md)). The wrapper answers the legacy action itself:
192
+
193
+ - **Timeline read** (no `state_key`): `read_timeline` with the legacy `type` / `msgtype` as filter.
194
+ While the answer is short of `limit` and the host's pagination is `idle`, it sends
195
+ `paginate_timeline`, waits for the `notify_timeline_update` that ends it and reads on below the
196
+ oldest event it has. It stops at `limit`, at `start_reached`, at a failed or refused pagination
197
+ and after 7 seconds (under the 10 seconds a legacy widget waits), and answers with what it has,
198
+ **newest first** (as Element Web does). Without `limit` it answers from the cache only. `since`
199
+ is not supported.
200
+ - **State read** (`state_key` a string or `true`): answered from the state the host pushed with
201
+ `update_state` (the wrapper keeps the last set per type); refused when the widget does not hold
202
+ `host:…update_state:<type>`.
203
+ - `room_ids`: only the widget's room is served; a list without it reads nothing.
204
+ - The host's `notify_timeline_update` is acknowledged by the wrapper and never reaches the legacy
205
+ widget.
206
+
207
+ ### Capabilities (`src/capabilities.ts`)
208
+
209
+ A legacy widget asks for matrix-widget-api capabilities; the host grants one capability per
210
+ action. Every legacy capability stands for a fixed set of new ones. The wrapper requests that set
211
+ and tells the widget a legacy capability is approved when the host approved **all** of its set.
212
+
213
+ | legacy capability (its MSC prefix or `m.`) | requested from the host (`…` = the unstable namespace of the action) |
214
+ |---|---|
215
+ | `send.event:<t>` | `widget:…send_event.timeline:<t>` |
216
+ | `send.state_event:<t>` | `widget:…send_event.state:<t>` |
217
+ | `receive.event:<t>` | `widget:…read_timeline:<t>`, `widget:…read_relations:<t>`, `host:…forward_event.timeline:<t>`, `widget:…paginate_timeline`, `host:…notify_timeline_update` (the last three for the legacy `read_events`) |
218
+ | `receive.state_event:<t>` | `host:…update_state:<t>` (also answers the legacy state reads), `host:…forward_event.state:<t>` |
219
+ | `timeline:<room>` | nothing: never requested, never reported as approved |
220
+ | `send.to_device:<t>` / `receive.to_device:<t>` | `widget:…send_to_device:<t>` / `host:…forward_to_device:<t>` |
221
+ | `receive.room_account_data:<t>` | `widget:…read_room_account_data:<t>` |
222
+ | `send.delayed_event` / `update_delayed_event` | `widget:…send_event.delayed` / `widget:…update_delayed_event` |
223
+ | `send.sticky_event` / `receive.sticky_event` | `widget:…send_event.sticky` / `host:…forward_event.sticky` |
224
+ | `turn_servers` | `host:…update_turn_servers` |
225
+ | `rtc_transports` | `widget:…get_rtc_transports` |
226
+ | `user_directory_search` | `widget:…search_user_directory` |
227
+ | `upload_file` | `widget:…upload_file`, `widget:…get_media_config` |
228
+ | `download_file` | `widget:…download_file` |
229
+ | `navigate` | `widget:…navigate` |
230
+ | `rtc_livekit_get_token` / `rtc_livekit_delegate_delayed_leave` | `widget:…get_rtc_livekit_token` / `widget:…delegate_rtc_livekit_delayed_leave` |
231
+ | `m.always_on_screen` | `widget:…set_always_on_screen` |
232
+ | anything else (`m.sticker`, custom strings) | the same string, unchanged |
233
+
234
+ `<t>` keeps its `#<msgtype>` / `#<state_key>` suffix.
235
+
236
+ A capability embeds the wire name of its action, so `…` is the prefix the host sends that action
237
+ with: `org.matrix.msc3869.` (`read_relations`),
238
+ `org.matrix.msc4157.` (`update_delayed_event`), `org.matrix.msc4515.` (`get_rtc_transports`),
239
+ `org.matrix.msc3973.` (`search_user_directory`), `org.matrix.msc4039.` (`upload_file`,
240
+ `download_file`, `get_media_config`), `org.matrix.msc4533.` (the LiveKit actions),
241
+ `org.matrix.msc2931.` (`navigate`), `com.beeper.` (`read_room_account_data`) and
242
+ `org.matrix.mscXXXX.` for everything else. A host that answers in the stable spelling
243
+ (`widget:m.navigate`) is understood as well.
244
+
245
+ - **Always requested**, whatever the widget asks for: `host:…update_theme`,
246
+ `host:…update_language`, `host:…update_visibility`. The legacy api has no capability for these;
247
+ a legacy host simply allows them. A host that wants the legacy behaviour grants them without a
248
+ prompt (`matrix-widget-host-driver` does for a legacy widget: `legacy_auto_approved`).
249
+ - **Webview capabilities** (`webview:…`) of a legacy client's iframe are requested when the wrapper
250
+ starts (see [The iframes](#the-iframes)); the legacy widget cannot request any.
251
+ - **`widget:…get_openid` is requested per token**, when the widget asks for one (see
252
+ [OpenID](#openid-get_openid-and-openid_credentials)), not up front: a host grants it for one
253
+ token at a time.
254
+ - **`timeline:<room>` is never granted.** One widget, one room: nothing reaches another room. A
255
+ request that names the widget's own room works without it.
256
+ - **`update_capabilities { allowed }` becomes `notify_capabilities { requested, approved }`** for
257
+ the widget: `requested` is the widget's own latest list, `approved` every legacy capability it
258
+ has ever requested whose whole set is in `allowed`. `allowed` is always the full list, so
259
+ `approved` shrinks when the host takes capabilities away. The widget only ever sees legacy
260
+ names, in the spelling it used.
261
+ - A partially approved set (the host grants reading but not `forward_event`, say) is reported as
262
+ **not** approved. The host still holds the partial grant, so the parts that were approved work.
263
+
264
+ ![How the envelope changed](../../docs/diagrams/03-wire-format-changes.svg)
265
+
266
+ ### OpenID: `get_openid` and `openid_credentials`
267
+
268
+ A legacy widget may always ask for an OpenID token, and a legacy host asked the user per token
269
+ (MSC1960). An MSC4412 host hands a token out only while the widget holds `widget:…get_openid`,
270
+ which it grants for one token at a time
271
+ ([`spec/patch/new/openid-capability.md`](../../spec/patch/new/openid-capability.md)); there is no
272
+ host action for a late answer. The wrapper (`src/bridge.ts`) plays the legacy host:
273
+
274
+ - While the host's last `update_capabilities` allowed `widget:…get_openid`, the widget's
275
+ `get_openid` is sent to the host as `…get_openid`, and the token comes back to the widget as
276
+ `{ state: "allowed", ...token }`. If the host answers `missing_capability` (the grant ended
277
+ before the request arrived), the wrapper goes on as below.
278
+ - Otherwise the widget gets `{ state: "request" }` at once, and the wrapper requests
279
+ `widget:…get_openid` (once for every request that waits). The host's first
280
+ `update_capabilities` after it acknowledged that request is the answer: granted, the wrapper
281
+ asks for one token and sends every waiting request `openid_credentials { state: "allowed",
282
+ original_request_id, ...token }`; refused (or no token), `openid_credentials { state:
283
+ "blocked", original_request_id }`. A host that takes capabilities away in between is read as a
284
+ refusal.
285
+
286
+ ### File payloads: Blob → base64
287
+
288
+ > **The MSC4412 file format is base64.** A file always travels between widget and host as
289
+ > `{ "mimetype": "image/png", "base64": "iVBORw0…" }`. Only legacy widgets send files as `Blob`,
290
+ > and only the wrapper ever sees one.
291
+
292
+ matrix-widget-api passes files as `Blob` (`XMLHttpRequestBodyInit`) through `postMessage`
293
+ structured cloning. That does not survive the JSON string boundary every MSC4412 host has: the
294
+ UniFFI layer and the Android / iOS WebView bridges carry strings only (`JSON.stringify(blob)` is
295
+ `{}`, so the file would be silently lost). The wrapper converts on the two actions that carry a
296
+ file (`src/files.ts`):
297
+
298
+ | action | direction | conversion |
299
+ |---|---|---|
300
+ | `org.matrix.msc4039.upload_file` | widget → host, request `file` | `Blob` → base64 |
301
+ | `org.matrix.msc4039.download_file` | host → widget, response `file` | base64 → `Blob` |
302
+
303
+ Any `XMLHttpRequestBodyInit` (Blob, ArrayBuffer, typed array, string, ...) is accepted; the
304
+ `mimetype` is the content type the browser would send for that body. The widget still gets its
305
+ own request echoed back with the original `Blob`. Base64 adds about 33% to the size, which is
306
+ fine for widget-sized files.
307
+
308
+ The legacy `screenshot` action (host → widget) is **intentionally not supported**: there is no
309
+ conversion for it, and an MSC4412 host never asks for one.
310
+
311
+ ### Startup handshake
312
+
313
+ After the bootstrap above has loaded the inner iframe. Legacy capabilities are **host-initiated**
314
+ (`toWidget capabilities` → the widget answers with its list), MSC4412 capabilities are
315
+ **widget-initiated** (`request_capabilities`). The wrapper plays the legacy host towards the
316
+ inner iframe:
317
+
318
+ `waitForIframeLoad = true` (legacy default)
319
+
320
+ ```
321
+ inner iframe load ──► host: notify_ready (once per wrapper lifetime)
322
+ ──► widget: capabilities {}
323
+ widget: { capabilities } ──► host: request_capabilities { capabilities } (host acks, ignored)
324
+ host: update_capabilities ──► widget: notify_capabilities (legacy) ──► widget ack ──► host ack
325
+ ```
326
+
327
+ A `content_loaded` from the widget in this mode is answered with the legacy error
328
+ "Improper sequence: not expecting ContentLoaded event" and never forwarded.
329
+
330
+ `waitForIframeLoad = false`
331
+
332
+ ```
333
+ inner iframe load ──► nothing
334
+ widget: content_loaded ──► widget: {} ack, host: notify_ready, then the same capability round
335
+ ```
336
+
337
+ A second `content_loaded` before a reload is answered with an error, as legacy hosts do.
338
+
339
+ Always:
340
+
341
+ - `supported_api_versions` from the widget is **answered locally** with matrix-widget-api's
342
+ `CurrentApiVersions`. The widget asks during `start()` and again while handling `capabilities`;
343
+ forwarding it would make the widget believe the host supports nothing (no MSC2871 → `ready`
344
+ before capabilities are approved, no MSC2974 → no renegotiation).
345
+ - Renegotiation (`org.matrix.msc2974.request_capabilities`) is forwarded with its capability list
346
+ translated like the first round's; the resulting `update_capabilities` is translated back.
347
+ - On an inner reload the capability round runs again (legacy hosts do the same); `notify_ready`
348
+ is sent to the host only once.
349
+ - Messages are routed by `event.source` (parent window vs. inner iframe), never by sniffing the
350
+ format. Messages with another `widgetId`, and messages from the parent that are not MSC4412
351
+ (no `source` / `request_id`), are ignored.
352
+
353
+ ### Parity notes
354
+
355
+ - Legacy widgets overwrite their approved list with `notify_capabilities.approved`, so it must be
356
+ the full set. MSC4412's `update_capabilities.allowed` is exactly that.
357
+ - The wrapper needs the host to wait for `notify_ready` (`uses_widget_api: true`); the driver
358
+ always does for a legacy widget, whatever its state event says.
359
+ - Legacy widgets built with `new WidgetApi(widgetId, clientOrigin)` only accept a parent at
360
+ `clientOrigin`; widgets derive it from `parentUrl`, which the wrapper sets to itself. A widget
361
+ that passes `null` cannot talk to any parent, wrapper or not.
362
+ - The legacy 10 s request timeout still applies between widget and host.
363
+
364
+ ## From npm
365
+
366
+ ```sh
367
+ npm install @matrix-widget-sdk/compat-wrapper
368
+ ```
369
+
370
+ The package is the built page and nothing else: `dist/index.html` plus `dist/assets/`, with
371
+ relative asset paths. Copy `node_modules/@matrix-widget-sdk/compat-wrapper/dist/` into the
372
+ client's web root (for example to `/widget_compatibility_wrapper/`) and pass that URL as
373
+ `EmbedOptions.wrapperUrl`. Pinning the package version pins the wrapper the client serves.
374
+
375
+ ## Development
376
+
377
+ ```sh
378
+ npm install # from the repository root (npm workspaces)
379
+ npm test # vitest: envelope translation, handshake state machine, config parsing, URL check
380
+ npm run dev # http://localhost:5174/ (standalone; the test host serves its own copy and does not need this)
381
+ npm run build # static output in dist/, serve it under its own origin
382
+ ```
383
+
384
+ Source layout: `src/envelope.ts` (translation tables), `src/template.ts` (legacy URL
385
+ templating), `src/url.ts` (which legacy URLs are loaded), `src/files.ts` (Blob ↔ base64), `src/bridge.ts` (bootstrap and handshake state machine, transport free),
386
+ `src/wrapper.ts` (URL config, iframe, `postMessage` routing), `src/main.ts`.
387
+
388
+ For an end-to-end run use the test host in `../widget-host` with the legacy test widget from
389
+ `../test-widgets`. The host builds `src/main.ts` into its own page `/widget_compatibility_wrapper/`,
390
+ so changes here show up there without starting this package's dev server.
391
+
392
+ [matrix-widget-api]: https://github.com/matrix-org/matrix-widget-api
@@ -0,0 +1,7 @@
1
+ var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports);(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var t=e(((e,t)=>{var n=typeof Reflect==`object`?Reflect:null,r=n&&typeof n.apply==`function`?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},i=n&&typeof n.ownKeys==`function`?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function a(e){console&&console.warn&&console.warn(e)}var o=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}t.exports=s,t.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function l(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);c=e}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function u(e){return e._maxListeners===void 0?s.defaultMaxListeners:e._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)r(c,this,t);else for(var l=c.length,u=g(c,l),n=0;n<l;++n)r(u[n],this,t);return!0};function d(e,t,n,r){var i,o,s;if(l(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),s=o[t]),s===void 0)s=o[t]=n,++e._eventsCount;else if(typeof s==`function`?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=u(e),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=Error(`Possible EventEmitter memory leak detected. `+s.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);c.name=`MaxListenersExceededWarning`,c.emitter=e,c.type=t,c.count=s.length,a(c)}return e}s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}s.prototype.once=function(e,t){return l(t),this.on(e,p(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,p(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,a,o;if(l(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():_(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function m(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?v(i):g(i,i.length)}s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h;function h(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function g(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function _(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function v(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function y(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}x(e,t,a,{once:!0}),t!==`error`&&b(e,i,{once:!0})})}function b(e,t,n){typeof e.on==`function`&&x(e,`error`,t,n)}function x(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}})),n=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.VideoConferenceCapabilities=e.StickerpickerCapabilities=e.MatrixCapabilities=void 0,e.getTimelineRoomIDFromCapability=i,e.isTimelineCapability=n,e.isTimelineCapabilityFor=r;var t=function(e){return e.Screenshots=`m.capability.screenshot`,e.StickerSending=`m.sticker`,e.AlwaysOnScreen=`m.always_on_screen`,e.RequiresClient=`io.element.requires_client`,e.MSC2931Navigate=`org.matrix.msc2931.navigate`,e.MSC3846TurnServers=`town.robin.msc3846.turn_servers`,e.MSC3973UserDirectorySearch=`org.matrix.msc3973.user_directory_search`,e.MSC4039UploadFile=`org.matrix.msc4039.upload_file`,e.MSC4039DownloadFile=`org.matrix.msc4039.download_file`,e.MSC4157SendDelayedEvent=`org.matrix.msc4157.send.delayed_event`,e.MSC4157UpdateDelayedEvent=`org.matrix.msc4157.update_delayed_event`,e.MSC4407SendStickyEvent=`org.matrix.msc4407.send.sticky_event`,e.MSC4407ReceiveStickyEvent=`org.matrix.msc4407.receive.sticky_event`,e.MSC4515RtcTransports=`org.matrix.msc4515.rtc_transports`,e.MSC4533RtcLivekitGetToken=`org.matrix.msc4533.rtc_livekit_get_token`,e.MSC4533RtcLivekitDelegateDelayedLeave=`org.matrix.msc4533.rtc_livekit_delegate_delayed_leave`,e}({});e.MatrixCapabilities=t,e.StickerpickerCapabilities=[t.StickerSending],e.VideoConferenceCapabilities=[t.AlwaysOnScreen];function n(e){return e?.startsWith(`org.matrix.msc2762.timeline:`)}function r(e,t){return e===`org.matrix.msc2762.timeline:${t}`}function i(e){return e.substring(e.indexOf(`:`)+1)}})),r=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WidgetApiDirection=void 0,e.invertedDirection=n;var t=function(e){return e.ToWidget=`toWidget`,e.FromWidget=`fromWidget`,e}({});e.WidgetApiDirection=t;function n(e){if(e===t.ToWidget)return t.FromWidget;if(e===t.FromWidget)return t.ToWidget;throw Error(`Invalid direction`)}})),i=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.UnstableApiVersion=e.MatrixApiVersion=e.CurrentApiVersions=void 0;var t=function(e){return e.Prerelease1=`0.0.1`,e.Prerelease2=`0.0.2`,e}({});e.MatrixApiVersion=t;var n=function(e){return e.MSC2762=`org.matrix.msc2762`,e.MSC2762_UPDATE_STATE=`org.matrix.msc2762_update_state`,e.MSC2871=`org.matrix.msc2871`,e.MSC2873=`org.matrix.msc2873`,e.MSC2931=`org.matrix.msc2931`,e.MSC2974=`org.matrix.msc2974`,e.MSC2876=`org.matrix.msc2876`,e.MSC3819=`org.matrix.msc3819`,e.MSC3846=`town.robin.msc3846`,e.MSC3869=`org.matrix.msc3869`,e.MSC3973=`org.matrix.msc3973`,e.MSC4039=`org.matrix.msc4039`,e.MSC4515=`org.matrix.msc4515`,e.MSC4533=`org.matrix.msc4533`,e}({});e.UnstableApiVersion=n,e.CurrentApiVersions=[t.Prerelease1,t.Prerelease2,n.MSC2762,n.MSC2762_UPDATE_STATE,n.MSC2871,n.MSC2873,n.MSC2931,n.MSC2974,n.MSC2876,n.MSC3819,n.MSC3846,n.MSC3869,n.MSC3973,n.MSC4039,n.MSC4515,n.MSC4533]})),a=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PostmessageTransport=void 0;var n=t(),r=w(),i=[`message`];function a(e){"@babel/helpers - typeof";return a=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},a(e)}function o(e,t){if(e==null)return{};var n,r,i=s(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function s(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function c(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function l(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?c(Object(n),!0).forEach(function(t){b(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):c(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function u(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function d(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,x(r.key),r)}}function f(e,t,n){return t&&d(e.prototype,t),n&&d(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function p(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Super expression must either be null or a function`);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&m(e,t)}function m(e,t){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},m(e,t)}function h(e){var t=v();return function(){var n,r=y(e);if(t){var i=y(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return g(this,n)}}function g(e,t){if(t&&(a(t)==`object`||typeof t==`function`))return t;if(t!==void 0)throw TypeError(`Derived constructors may only return object or undefined`);return _(e)}function _(e){if(e===void 0)throw ReferenceError(`this hasn't been initialised - super() hasn't been called`);return e}function v(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(v=function(){return!!e})()}function y(e){return y=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},y(e)}function b(e,t,n){return(t=x(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function x(e){var t=ee(e,`string`);return a(t)==`symbol`?t:t+``}function ee(e,t){if(a(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(a(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}e.PostmessageTransport=function(e){p(n,e);var t=h(n);function n(e,i,a,o){var s;return u(this,n),s=t.call(this),s.sendDirection=e,s.transportWindow=a,s.inboundWindow=o,b(_(s),`strictOriginCheck`,!1),b(_(s),`targetOrigin`,`*`),b(_(s),`timeoutSeconds`,10),b(_(s),`_ready`,!1),b(_(s),`_widgetId`,void 0),b(_(s),`outboundRequests`,new Map),b(_(s),`stopController`,new AbortController),b(_(s),`handleMessage`,function(e){if(!s.stopController.signal.aborted&&e.data&&!(s.strictOriginCheck&&e.origin!==globalThis.origin)){var t=e.data;if(t.action&&t.requestId&&t.widgetId){if(t.response){if(t.api!==s.sendDirection)return;s.handleResponse(t)}else{var n=t;if(n.api!==(0,r.invertedDirection)(s.sendDirection))return;s.handleRequest(n)}}}}),s._widgetId=i,s}return f(n,[{key:`ready`,get:function(){return this._ready}},{key:`widgetId`,get:function(){return this._widgetId||null}},{key:`nextRequestId`,get:function(){for(var e=`widgetapi-${Date.now()}`,t=0,n=e;this.outboundRequests.has(n);)n=`${e}-${t++}`;return this.outboundRequests.set(n,null),n}},{key:`sendInternal`,value:function(e){console.log(`[PostmessageTransport] Sending object to ${this.targetOrigin}: `,e),this.transportWindow.postMessage(e,this.targetOrigin)}},{key:`reply`,value:function(e,t){return this.sendInternal(l(l({},e),{},{response:t}))}},{key:`send`,value:function(e,t){return this.sendComplete(e,t).then(function(e){return e.response})}},{key:`sendComplete`,value:function(e,t){var n=this;if(!this.ready||!this.widgetId)return Promise.reject(Error(`Not ready or unknown widget ID`));var i={api:this.sendDirection,widgetId:this.widgetId,requestId:this.nextRequestId,action:e,data:t};return e===r.WidgetApiToWidgetAction.UpdateVisibility&&(i.visible=t.visible),new Promise(function(e,t){var r=function(t){c(),e(t)},a=function(e){c(),t(e)},o=setTimeout(function(){return a(Error(`Request timed out`))},(n.timeoutSeconds||1)*1e3),s=function(){return a(Error(`Transport stopped`))};n.stopController.signal.addEventListener(`abort`,s);var c=function(){n.outboundRequests.delete(i.requestId),clearTimeout(o),n.stopController.signal.removeEventListener(`abort`,s)};n.outboundRequests.set(i.requestId,{request:i,resolve:r,reject:a}),n.sendInternal(i)})}},{key:`start`,value:function(){this.inboundWindow.addEventListener(`message`,this.handleMessage),this._ready=!0}},{key:`stop`,value:function(){this._ready=!1,this.stopController.abort(),this.inboundWindow.removeEventListener(`message`,this.handleMessage)}},{key:`handleRequest`,value:function(e){if(this.widgetId){if(this.widgetId!==e.widgetId)return}else this._widgetId=e.widgetId;this.emit(`message`,new CustomEvent(`message`,{detail:e}))}},{key:`handleResponse`,value:function(e){if(e.widgetId===this.widgetId){var t=this.outboundRequests.get(e.requestId);if(t){if((0,r.isErrorResponse)(e.response)){var n=e.response.error,a=n.message,s=o(n,i);t.reject(new r.WidgetApiResponseError(a,s))}else t.resolve(e)}}}}]),n}(n.EventEmitter)})),o=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WidgetApiToWidgetAction=e.WidgetApiFromWidgetAction=void 0,e.WidgetApiToWidgetAction=function(e){return e.SupportedApiVersions=`supported_api_versions`,e.Capabilities=`capabilities`,e.NotifyCapabilities=`notify_capabilities`,e.ThemeChange=`theme_change`,e.LanguageChange=`language_change`,e.TakeScreenshot=`screenshot`,e.UpdateVisibility=`visibility`,e.OpenIDCredentials=`openid_credentials`,e.WidgetConfig=`widget_config`,e.CloseModalWidget=`close_modal`,e.ButtonClicked=`button_clicked`,e.SendEvent=`send_event`,e.SendToDevice=`send_to_device`,e.UpdateState=`update_state`,e.UpdateTurnServers=`update_turn_servers`,e}({}),e.WidgetApiFromWidgetAction=function(e){return e.SupportedApiVersions=`supported_api_versions`,e.ContentLoaded=`content_loaded`,e.SendSticker=`m.sticker`,e.UpdateAlwaysOnScreen=`set_always_on_screen`,e.GetOpenIDCredentials=`get_openid`,e.CloseModalWidget=`close_modal`,e.OpenModalWidget=`open_modal`,e.SetModalButtonEnabled=`set_button_enabled`,e.SendEvent=`send_event`,e.SendToDevice=`send_to_device`,e.WatchTurnServers=`watch_turn_servers`,e.UnwatchTurnServers=`unwatch_turn_servers`,e.BeeperReadRoomAccountData=`com.beeper.read_room_account_data`,e.MSC2876ReadEvents=`org.matrix.msc2876.read_events`,e.MSC2931Navigate=`org.matrix.msc2931.navigate`,e.MSC2974RenegotiateCapabilities=`org.matrix.msc2974.request_capabilities`,e.MSC3869ReadRelations=`org.matrix.msc3869.read_relations`,e.MSC3973UserDirectorySearch=`org.matrix.msc3973.user_directory_search`,e.MSC4039GetMediaConfigAction=`org.matrix.msc4039.get_media_config`,e.MSC4039UploadFileAction=`org.matrix.msc4039.upload_file`,e.MSC4039DownloadFileAction=`org.matrix.msc4039.download_file`,e.MSC4157UpdateDelayedEvent=`org.matrix.msc4157.update_delayed_event`,e.MSC4515GetRtcTransports=`org.matrix.msc4515.get_rtc_transports`,e.MSC4533RtcLivekitGetToken=`org.matrix.msc4533.rtc_livekit_get_token`,e.MSC4533RtcLivekitDelegateDelayedLeave=`org.matrix.msc4533.rtc_livekit_delegate_delayed_leave`,e}({})})),s=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OpenIDRequestState=void 0,e.OpenIDRequestState=function(e){return e.Allowed=`allowed`,e.Blocked=`blocked`,e.PendingUserConfirmation=`request`,e}({})})),c=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MatrixWidgetType=void 0,e.MatrixWidgetType=function(e){return e.Custom=`m.custom`,e.JitsiMeet=`m.jitsi`,e.Stickerpicker=`m.stickerpicker`,e}({})})),l=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BuiltInModalButtonID=void 0,e.BuiltInModalButtonID=function(e){return e.Close=`m.close`,e}({})})),u=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WidgetEventCapability=e.EventKind=e.EventDirection=void 0;function t(e){"@babel/helpers - typeof";return t=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},t(e)}function n(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=r(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var i=0,a=function(){};return{s:a,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:a}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
2
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o,s=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){c=!0,o=e},f:function(){try{s||n.return==null||n.return()}finally{if(c)throw o}}}}function r(e,t){if(e){if(typeof e==`string`)return i(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?i(e,t):void 0}}function i(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function a(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,c(r.key),r)}}function s(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function c(e){var n=l(e,`string`);return t(n)==`symbol`?n:n+``}function l(e,n){if(t(e)!=`object`||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,n||`default`);if(t(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(n===`string`?String:Number)(e)}var u=function(e){return e.Event=`event`,e.State=`state_event`,e.ToDevice=`to_device`,e.RoomAccount=`room_account`,e}({});e.EventKind=u;var d=function(e){return e.Send=`send`,e.Receive=`receive`,e}({});e.EventDirection=d,e.WidgetEventCapability=function(){function e(t,n,r,i,o){a(this,e),this.direction=t,this.eventType=n,this.kind=r,this.keyStr=i,this.raw=o}return s(e,[{key:`matchesAsStateEvent`,value:function(e,t,n){return this.kind!==u.State||this.direction!==e||this.eventType!==t?!1:this.keyStr===null||this.keyStr===n}},{key:`matchesAsToDeviceEvent`,value:function(e,t){return this.kind===u.ToDevice&&this.direction===e&&this.eventType===t}},{key:`matchesAsRoomEvent`,value:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(this.kind!==u.Event||this.direction!==e||this.eventType!==t)return!1;if(this.eventType===`m.room.message`){if(this.keyStr===null||this.keyStr===n)return!0}else return!0;return!1}},{key:`matchesAsRoomAccountData`,value:function(e,t){return this.kind===u.RoomAccount&&this.direction===e&&this.eventType===t}}],[{key:`forStateEvent`,value:function(t,n,r){n=n.replace(/#/g,`\\#`),r=r==null?``:`#${r}`;var i=`org.matrix.msc2762.${t}.state_event:${n}${r}`;return e.findEventCapabilities([i])[0]}},{key:`forToDeviceEvent`,value:function(t,n){var r=`org.matrix.msc3819.${t}.to_device:${n}`;return e.findEventCapabilities([r])[0]}},{key:`forRoomEvent`,value:function(t,n){var r=`org.matrix.msc2762.${t}.event:${n}`;return e.findEventCapabilities([r])[0]}},{key:`forRoomMessageEvent`,value:function(t,n){n??=``;var r=`org.matrix.msc2762.${t}.event:m.room.message#${n}`;return e.findEventCapabilities([r])[0]}},{key:`forRoomAccountData`,value:function(t,n){var r=`com.beeper.capabilities.${t}.room_account_data:${n}`;return e.findEventCapabilities([r])[0]}},{key:`findEventCapabilities`,value:function(t){var r=[],i=n(t),a;try{for(i.s();!(a=i.n()).done;){var o=a.value,s=null,c=void 0,l=null;if(o.startsWith(`org.matrix.msc2762.send.event:`)?(s=d.Send,l=u.Event,c=o.substring(30)):o.startsWith(`org.matrix.msc2762.send.state_event:`)?(s=d.Send,l=u.State,c=o.substring(36)):o.startsWith(`org.matrix.msc3819.send.to_device:`)?(s=d.Send,l=u.ToDevice,c=o.substring(34)):o.startsWith(`org.matrix.msc2762.receive.event:`)?(s=d.Receive,l=u.Event,c=o.substring(33)):o.startsWith(`org.matrix.msc2762.receive.state_event:`)?(s=d.Receive,l=u.State,c=o.substring(39)):o.startsWith(`org.matrix.msc3819.receive.to_device:`)?(s=d.Receive,l=u.ToDevice,c=o.substring(37)):o.startsWith(`com.beeper.capabilities.receive.room_account_data:`)&&(s=d.Receive,l=u.RoomAccount,c=o.substring(50)),s!==null&&l!==null&&c!==void 0){var f=c.startsWith(`m.room.message#`)||l===u.State,p=null;if(c.includes(`#`)&&f){var m=c.split(`#`),h=m.findIndex(function(e){return!e.endsWith(`\\`)});c=m.slice(0,h+1).map(function(e){return e.endsWith(`\\`)?e.substring(0,e.length-1):e}).join(`#`),p=m.slice(h+1).join(`#`)}r.push(new e(s,c,l,p,o))}}}catch(e){i.e(e)}finally{i.f()}return r}}]),e}()})),d=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Symbols=void 0,e.Symbols=function(e){return e.AnyRoom=`*`,e}({})})),f=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.UpdateDelayedEventAction=void 0,e.UpdateDelayedEventAction=function(e){return e.Cancel=`cancel`,e.Restart=`restart`,e.Send=`send`,e}({})})),p=e((e=>{function p(e){"@babel/helpers - typeof";return p=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},p(e)}Object.defineProperty(e,"__esModule",{value:!0}),e.WidgetApiResponseError=e.WidgetApi=void 0;var m=t(),h=n(),g=r(),_=i(),v=a(),y=o(),b=s(),x=c(),ee=l(),S=u(),C=d(),w=f();function T(){var e=A(),t=e.m(T),n=(Object.getPrototypeOf?Object.getPrototypeOf(t):t.__proto__).constructor;function r(e){var t=typeof e==`function`&&e.constructor;return!!t&&(t===n||(t.displayName||t.name)===`GeneratorFunction`)}var i={throw:1,return:2,break:3,continue:3};function a(e){var t,n;return function(r){t||(t={stop:function(){return n(r.a,2)},catch:function(){return r.v},abrupt:function(e,t){return n(r.a,i[e],t)},delegateYield:function(e,i,a){return t.resultName=i,n(r.d,E(e),a)},finish:function(e){return n(r.f,e)}},n=function(e,n,i){r.p=t.prev,r.n=t.next;try{return e(n,i)}finally{t.next=r.n}}),t.resultName&&(t[t.resultName]=r.v,t.resultName=void 0),t.sent=r.v,t.next=r.n;try{return e.call(this,t)}finally{r.p=t.prev,r.n=t.next}}}return(T=function(){return{wrap:function(t,n,r,i){return e.w(a(t),n,r,i&&i.reverse())},isGeneratorFunction:r,mark:e.m,awrap:function(e,t){return new le(e,t)},AsyncIterator:k,async:function(e,t,n,i,o){return(r(t)?O:D)(a(e),t,n,i,o)},keys:te,values:E}})()}function E(e){if(e!=null){var t=e[typeof Symbol==`function`&&Symbol.iterator||`@@iterator`],n=0;if(t)return t.call(e);if(typeof e.next==`function`)return e;if(!isNaN(e.length))return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}throw TypeError(p(e)+` is not iterable`)}function te(e){var t=Object(e),n=[];for(var r in t)n.unshift(r);return function e(){for(;n.length;)if((r=n.pop())in t)return e.value=r,e.done=!1,e;return e.done=!0,e}}function D(e,t,n,r,i){var a=O(e,t,n,r,i);return a.next().then(function(e){return e.done?e.value:a.next()})}function O(e,t,n,r,i){return new k(A().w(e,t,n,r),i||Promise)}function k(e,t){function n(r,i,a,o){try{var s=e[r](i),c=s.value;return c instanceof le?t.resolve(c.v).then(function(e){n(`next`,e,a,o)},function(e){n(`throw`,e,a,o)}):t.resolve(c).then(function(e){s.value=e,a(s)},function(e){return n(`throw`,e,a,o)})}catch(e){o(e)}}var r;this.next||(j(k.prototype),j(k.prototype,typeof Symbol==`function`&&Symbol.asyncIterator||`@asyncIterator`,function(){return this})),j(this,`_invoke`,function(e,i,a){function o(){return new t(function(t,r){n(e,a,t,r)})}return r=r?r.then(o,o):o()},!0)}function A(){var e,t,n=typeof Symbol==`function`?Symbol:{},r=n.iterator||`@@iterator`,i=n.toStringTag||`@@toStringTag`;function a(n,r,i,a){var c=r&&r.prototype instanceof s?r:s,l=Object.create(c.prototype);return j(l,`_invoke`,function(n,r,i){var a,s,c,l=0,u=i||[],d=!1,f={p:0,n:0,v:e,a:p,f:p.bind(e,4),d:function(t,n){return a=t,s=0,c=e,f.n=n,o}};function p(n,r){for(s=n,c=r,t=0;!d&&l&&!i&&t<u.length;t++){var i,a=u[t],p=f.p,m=a[2];n>3?(i=m===r)&&(c=a[(s=a[4])?5:(s=3,3)],a[4]=a[5]=e):a[0]<=p&&((i=n<2&&p<a[1])?(s=0,f.v=r,f.n=a[1]):p<m&&(i=n<3||a[0]>r||r>m)&&(a[4]=n,a[5]=r,f.n=m,s=0))}if(i||n>1)return o;throw d=!0,r}return function(i,u,m){if(l>1)throw TypeError(`Generator is already running`);for(d&&u===1&&p(u,m),s=u,c=m;(t=s<2?e:c)||!d;){a||(s?s<3?(s>1&&(f.n=-1),p(s,c)):f.n=c:f.v=c);try{if(l=2,a){if(s||(i=`next`),t=a[i]){if(!(t=t.call(a,c)))throw TypeError(`iterator result is not an object`);if(!t.done)return t;c=t.value,s<2&&(s=0)}else s===1&&(t=a.return)&&t.call(a),s<2&&(c=TypeError(`The iterator does not provide a '`+i+`' method`),s=1);a=e}else if((t=(d=f.n<0)?c:n.call(r,f))!==o)break}catch(t){a=e,s=1,c=t}finally{l=1}}return{value:t,done:d}}}(n,i,a),!0),l}var o={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][r]?t(t([][r]())):(j(t={},r,function(){return this}),t),d=l.prototype=s.prototype=Object.create(u);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,j(e,i,`GeneratorFunction`)),e.prototype=Object.create(d),e}return c.prototype=l,j(d,`constructor`,l),j(l,`constructor`,c),c.displayName=`GeneratorFunction`,j(l,i,`GeneratorFunction`),j(d),j(d,i,`Generator`),j(d,r,function(){return this}),j(d,`toString`,function(){return`[object Generator]`}),(A=function(){return{w:a,m:f}})()}function j(e,t,n,r){var i=Object.defineProperty;try{i({},``,{})}catch{i=0}j=function(e,t,n,r){function a(t,n){j(e,t,function(e){return this._invoke(t,n,e)})}t?i?i(e,t,{value:n,enumerable:!r,configurable:!r,writable:!r}):e[t]=n:(a(`next`,0),a(`throw`,1),a(`return`,2))},j(e,t,n,r)}function M(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function N(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var a=e.apply(t,n);function o(e){M(a,r,i,o,s,`next`,e)}function s(e){M(a,r,i,o,s,`throw`,e)}o(void 0)})}}function ne(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function P(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ne(Object(n),!0).forEach(function(t){R(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ne(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function F(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=I(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
3
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,a=e},f:function(){try{o||n.return==null||n.return()}finally{if(s)throw a}}}}function I(e,t){if(e){if(typeof e==`string`)return L(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?L(e,t):void 0}}function L(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function R(e,t,n){return(t=V(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function z(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,V(r.key),r)}}function B(e,t,n){return t&&z(e.prototype,t),n&&z(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function V(e){var t=re(e,`string`);return p(t)==`symbol`?t:t+``}function re(e,t){if(p(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(p(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function H(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function ie(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Super expression must either be null or a function`);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Y(e,t)}function U(e){var t=q();return function(){var n,r=X(e);if(t){var i=X(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return W(this,n)}}function W(e,t){if(t&&(p(t)==`object`||typeof t==`function`))return t;if(t!==void 0)throw TypeError(`Derived constructors may only return object or undefined`);return G(e)}function G(e){if(e===void 0)throw ReferenceError(`this hasn't been initialised - super() hasn't been called`);return e}function K(e){var t=typeof Map==`function`?new Map:void 0;return K=function(e){if(e===null||!J(e))return e;if(typeof e!=`function`)throw TypeError(`Super expression must either be null or a function`);if(t!==void 0){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return ae(e,arguments,X(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Y(n,e)},K(e)}function ae(e,t,n){if(q())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&Y(i,n.prototype),i}function q(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(q=function(){return!!e})()}function J(e){try{return Function.toString.call(e).indexOf(`[native code]`)!==-1}catch{return typeof e==`function`}}function Y(e,t){return Y=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Y(e,t)}function X(e){return X=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},X(e)}function oe(e){return new le(e,0)}function se(e){return function(){return new ce(e.apply(this,arguments))}}function ce(e){var t,n;function r(t,n){try{var a=e[t](n),o=a.value,s=o instanceof le;Promise.resolve(s?o.v:o).then(function(n){if(s){var c=t===`return`&&o.k?t:`next`;if(!o.k||n.done)return r(c,n);n=e[c](n).value}i(!!a.done,n)},function(e){r(`throw`,e)})}catch(e){i(2,e)}}function i(e,i){e===2?t.reject(i):t.resolve({value:i,done:e}),(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,i){return new Promise(function(a,o){var s={key:e,arg:i,resolve:a,reject:o,next:null};n?n=n.next=s:(t=n=s,r(e,i))})},typeof e.return!=`function`&&(this.return=void 0)}ce.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},ce.prototype.next=function(e){return this._invoke(`next`,e)},ce.prototype.throw=function(e){return this._invoke(`throw`,e)},ce.prototype.return=function(e){return this._invoke(`return`,e)};function le(e,t){this.v=e,this.k=t}var Z=function(e){ie(n,e);var t=U(n);function n(e,r){var i;return H(this,n),i=t.call(this,e),i.data=r,i}return B(n)}(K(Error));e.WidgetApiResponseError=Z,Z.prototype.name=Z.name,e.WidgetApi=function(e){ie(n,e);var t=U(n);function n(){var e,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(H(this,n),e=t.call(this),R(G(e),`transport`,void 0),R(G(e),`capabilitiesFinished`,!1),R(G(e),`supportsMSC2974Renegotiate`,!1),R(G(e),`requestedCapabilities`,[]),R(G(e),`approvedCapabilities`,void 0),R(G(e),`cachedClientVersions`,void 0),R(G(e),`turnServerWatchers`,0),!globalThis.parent)throw Error(`No parent window. This widget doesn't appear to be embedded properly.`);return e.transport=new v.PostmessageTransport(g.WidgetApiDirection.FromWidget,r,globalThis.parent,globalThis),e.transport.targetOrigin=i,e.transport.on(`message`,e.handleMessage.bind(G(e))),e}return B(n,[{key:`hasCapability`,value:function(e){return Array.isArray(this.approvedCapabilities)?this.approvedCapabilities.includes(e):this.requestedCapabilities.includes(e)}},{key:`requestCapability`,value:function(e){if(this.capabilitiesFinished&&!this.supportsMSC2974Renegotiate)throw Error(`Capabilities have already been negotiated`);this.requestedCapabilities.push(e)}},{key:`requestCapabilities`,value:function(e){var t=F(e),n;try{for(t.s();!(n=t.n()).done;){var r=n.value;this.requestCapability(r)}}catch(e){t.e(e)}finally{t.f()}}},{key:`requestCapabilityForRoomTimeline`,value:function(e){this.requestCapability(`org.matrix.msc2762.timeline:${e}`)}},{key:`requestCapabilityToSendState`,value:function(e,t){this.requestCapability(S.WidgetEventCapability.forStateEvent(S.EventDirection.Send,e,t).raw)}},{key:`requestCapabilityToReceiveState`,value:function(e,t){this.requestCapability(S.WidgetEventCapability.forStateEvent(S.EventDirection.Receive,e,t).raw)}},{key:`requestCapabilityToSendToDevice`,value:function(e){this.requestCapability(S.WidgetEventCapability.forToDeviceEvent(S.EventDirection.Send,e).raw)}},{key:`requestCapabilityToReceiveToDevice`,value:function(e){this.requestCapability(S.WidgetEventCapability.forToDeviceEvent(S.EventDirection.Receive,e).raw)}},{key:`requestCapabilityToSendEvent`,value:function(e){this.requestCapability(S.WidgetEventCapability.forRoomEvent(S.EventDirection.Send,e).raw)}},{key:`requestCapabilityToReceiveEvent`,value:function(e){this.requestCapability(S.WidgetEventCapability.forRoomEvent(S.EventDirection.Receive,e).raw)}},{key:`requestCapabilityToSendMessage`,value:function(e){this.requestCapability(S.WidgetEventCapability.forRoomMessageEvent(S.EventDirection.Send,e).raw)}},{key:`requestCapabilityToReceiveMessage`,value:function(e){this.requestCapability(S.WidgetEventCapability.forRoomMessageEvent(S.EventDirection.Receive,e).raw)}},{key:`requestCapabilityToReceiveRoomAccountData`,value:function(e){this.requestCapability(S.WidgetEventCapability.forRoomAccountData(S.EventDirection.Receive,e).raw)}},{key:`requestCapabilityToGetRtcLivekitToken`,value:function(){this.requestCapability(h.MatrixCapabilities.MSC4533RtcLivekitGetToken)}},{key:`requestCapabilityToDelegateRtcLivekitDelayedLeave`,value:function(){this.requestCapability(h.MatrixCapabilities.MSC4533RtcLivekitDelegateDelayedLeave)}},{key:`requestOpenIDConnectToken`,value:function(){var e=this;return new Promise(function(t,n){e.transport.sendComplete(y.WidgetApiFromWidgetAction.GetOpenIDCredentials,{}).then(function(r){var i=r.response;i.state===b.OpenIDRequestState.Allowed?t(i):i.state===b.OpenIDRequestState.Blocked?n(Error(`User declined to verify their identity`)):i.state===b.OpenIDRequestState.PendingUserConfirmation?e.on(`action:${y.WidgetApiToWidgetAction.OpenIDCredentials}`,function a(o){o.preventDefault();var s=o.detail;s.data.original_request_id===r.requestId&&(s.data.state===b.OpenIDRequestState.Allowed?(t(s.data),e.transport.reply(s,{})):s.data.state===b.OpenIDRequestState.Blocked?(n(Error(`User declined to verify their identity`)),e.transport.reply(s,{})):(n(Error(`Invalid state on reply: `+i.state)),e.transport.reply(s,{error:{message:`Invalid state`}})),e.off(`action:${y.WidgetApiToWidgetAction.OpenIDCredentials}`,a))}):n(Error(`Invalid state: `+i.state))}).catch(n)})}},{key:`updateRequestedCapabilities`,value:function(){return this.transport.send(y.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities,{capabilities:this.requestedCapabilities}).then()}},{key:`sendContentLoaded`,value:function(){return this.transport.send(y.WidgetApiFromWidgetAction.ContentLoaded,{}).then()}},{key:`sendSticker`,value:function(e){return this.transport.send(y.WidgetApiFromWidgetAction.SendSticker,e).then()}},{key:`setAlwaysOnScreen`,value:function(e){return this.transport.send(y.WidgetApiFromWidgetAction.UpdateAlwaysOnScreen,{value:e}).then(function(e){return e.success})}},{key:`openModalWidget`,value:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:x.MatrixWidgetType.Custom;return this.transport.send(y.WidgetApiFromWidgetAction.OpenModalWidget,{type:i,url:e,name:t,buttons:n,data:r}).then()}},{key:`closeModalWidget`,value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.transport.send(y.WidgetApiFromWidgetAction.CloseModalWidget,e).then()}},{key:`sendRoomEvent`,value:function(e,t,n,r,i,a){var o;return typeof i==`number`?a=i:o=i,this.sendEvent(e,void 0,t,n,r,o,a)}},{key:`sendStateEvent`,value:function(e,t,n,r,i,a){return this.sendEvent(e,t,n,r,i,a)}},{key:`sendEvent`,value:function(e,t,n,r,i,a,o){return this.transport.send(y.WidgetApiFromWidgetAction.SendEvent,P(P(P(P(P({type:e,content:n},t!==void 0&&{state_key:t}),r!==void 0&&{room_id:r}),i!==void 0&&{delay:i}),a!==void 0&&{parent_delay_id:a}),o!==void 0&&{sticky_duration_ms:o}))}},{key:`cancelScheduledDelayedEvent`,value:function(e){return this.transport.send(y.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent,{delay_id:e,action:w.UpdateDelayedEventAction.Cancel})}},{key:`restartScheduledDelayedEvent`,value:function(e){return this.transport.send(y.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent,{delay_id:e,action:w.UpdateDelayedEventAction.Restart})}},{key:`sendScheduledDelayedEvent`,value:function(e){return this.transport.send(y.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent,{delay_id:e,action:w.UpdateDelayedEventAction.Send})}},{key:`sendToDevice`,value:function(e,t,n){return this.transport.send(y.WidgetApiFromWidgetAction.SendToDevice,{type:e,encrypted:t,messages:n})}},{key:`readRoomAccountData`,value:function(e,t){var n={type:e};return t&&(n.room_ids=t.includes(C.Symbols.AnyRoom)?C.Symbols.AnyRoom:t),this.transport.send(y.WidgetApiFromWidgetAction.BeeperReadRoomAccountData,n).then(function(e){return e.events})}},{key:`readRoomEvents`,value:function(e,t,n,r,i){var a={type:e,msgtype:n};return t!==void 0&&(a.limit=t),r&&(a.room_ids=r.includes(C.Symbols.AnyRoom)?C.Symbols.AnyRoom:r),i&&(a.since=i),this.transport.send(y.WidgetApiFromWidgetAction.MSC2876ReadEvents,a).then(function(e){return e.events})}},{key:`readEventRelations`,value:function(){var e=N(T().mark(function e(t,n,r,i,a,o,s,c){var l,u;return T().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(l=e.sent,l.includes(_.UnstableApiVersion.MSC3869)){e.next=5;break}throw Error(`The read_relations action is not supported by the client.`);case 5:return u={event_id:t,rel_type:r,event_type:i,room_id:n,to:s,from:o,limit:a,direction:c},e.abrupt(`return`,this.transport.send(y.WidgetApiFromWidgetAction.MSC3869ReadRelations,u));case 7:case`end`:return e.stop()}},e,this)}));function t(t,n,r,i,a,o,s,c){return e.apply(this,arguments)}return t}()},{key:`readStateEvents`,value:function(e,t,n,r){var i={type:e,state_key:n===void 0||n};return t!==void 0&&(i.limit=t),r&&(i.room_ids=r.includes(C.Symbols.AnyRoom)?C.Symbols.AnyRoom:r),this.transport.send(y.WidgetApiFromWidgetAction.MSC2876ReadEvents,i).then(function(e){return e.events})}},{key:`setModalButtonEnabled`,value:function(e,t){if(e===ee.BuiltInModalButtonID.Close)throw Error(`The close button cannot be disabled`);return this.transport.send(y.WidgetApiFromWidgetAction.SetModalButtonEnabled,{button:e,enabled:t}).then()}},{key:`navigateTo`,value:function(e){if(!e||!e.startsWith(`https://matrix.to/#`))throw Error(`Invalid matrix.to URI`);return this.transport.send(y.WidgetApiFromWidgetAction.MSC2931Navigate,{uri:e}).then()}},{key:`getTurnServers`,value:function(){var e=this;return se(T().mark(function t(){var n,r;return T().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(r=function(){var t=N(T().mark(function t(r){return T().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:r.preventDefault(),n(r.detail.data),e.transport.reply(r.detail,{});case 3:case`end`:return t.stop()}},t)}));return function(e){return t.apply(this,arguments)}}(),e.on(`action:${y.WidgetApiToWidgetAction.UpdateTurnServers}`,r),e.turnServerWatchers!==0){t.next=12;break}return t.prev=3,t.next=6,oe(e.transport.send(y.WidgetApiFromWidgetAction.WatchTurnServers,{}));case 6:t.next=12;break;case 8:throw t.prev=8,t.t0=t.catch(3),e.off(`action:${y.WidgetApiToWidgetAction.UpdateTurnServers}`,r),t.t0;case 12:e.turnServerWatchers++,t.prev=13;case 14:return t.next=17,oe(new Promise(function(e){return n=e}));case 17:return t.next=19,t.sent;case 19:t.next=14;break;case 21:if(t.prev=21,e.off(`action:${y.WidgetApiToWidgetAction.UpdateTurnServers}`,r),e.turnServerWatchers--,e.turnServerWatchers!==0){t.next=27;break}return t.next=27,oe(e.transport.send(y.WidgetApiFromWidgetAction.UnwatchTurnServers,{}));case 27:return t.finish(21);case 28:case`end`:return t.stop()}},t,null,[[3,8],[13,,21,28]])}))()}},{key:`searchUserDirectory`,value:function(){var e=N(T().mark(function e(t,n){var r,i;return T().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(r=e.sent,r.includes(_.UnstableApiVersion.MSC3973)){e.next=5;break}throw Error(`The user_directory_search action is not supported by the client.`);case 5:return i={search_term:t,limit:n},e.abrupt(`return`,this.transport.send(y.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch,i));case 7:case`end`:return e.stop()}},e,this)}));function t(t,n){return e.apply(this,arguments)}return t}()},{key:`getMediaConfig`,value:function(){var e=N(T().mark(function e(){var t,n;return T().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(t=e.sent,t.includes(_.UnstableApiVersion.MSC4039)){e.next=5;break}throw Error(`The get_media_config action is not supported by the client.`);case 5:return n={},e.abrupt(`return`,this.transport.send(y.WidgetApiFromWidgetAction.MSC4039GetMediaConfigAction,n));case 7:case`end`:return e.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:`getRtcTransports`,value:function(){var e=N(T().mark(function e(){var t,n;return T().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(t=e.sent,t.includes(_.UnstableApiVersion.MSC4515)){e.next=5;break}throw Error(`The get_rtc_transports action is not supported by the client.`);case 5:return n={},e.abrupt(`return`,this.transport.send(y.WidgetApiFromWidgetAction.MSC4515GetRtcTransports,n));case 7:case`end`:return e.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:`uploadFile`,value:function(){var e=N(T().mark(function e(t){var n,r;return T().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(n=e.sent,n.includes(_.UnstableApiVersion.MSC4039)){e.next=5;break}throw Error(`The upload_file action is not supported by the client.`);case 5:return r={file:t},e.abrupt(`return`,this.transport.send(y.WidgetApiFromWidgetAction.MSC4039UploadFileAction,r));case 7:case`end`:return e.stop()}},e,this)}));function t(t){return e.apply(this,arguments)}return t}()},{key:`downloadFile`,value:function(){var e=N(T().mark(function e(t){var n,r;return T().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(n=e.sent,n.includes(_.UnstableApiVersion.MSC4039)){e.next=5;break}throw Error(`The download_file action is not supported by the client.`);case 5:return r={content_uri:t},e.abrupt(`return`,this.transport.send(y.WidgetApiFromWidgetAction.MSC4039DownloadFileAction,r));case 7:case`end`:return e.stop()}},e,this)}));function t(t){return e.apply(this,arguments)}return t}()},{key:`getRtcLivekitToken`,value:function(){var e=N(T().mark(function e(t){var n;return T().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(n=e.sent,n.includes(_.UnstableApiVersion.MSC4533)){e.next=5;break}throw Error(`The rtc_livekit_get_token action is not supported by the client.`);case 5:return e.abrupt(`return`,this.transport.send(y.WidgetApiFromWidgetAction.MSC4533RtcLivekitGetToken,t));case 6:case`end`:return e.stop()}},e,this)}));function t(t){return e.apply(this,arguments)}return t}()},{key:`delegateRtcLivekitDelayedLeave`,value:function(){var e=N(T().mark(function e(t){var n;return T().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(n=e.sent,n.includes(_.UnstableApiVersion.MSC4533)){e.next=5;break}throw Error(`The rtc_livekit_delegate_delayed_leave action is not supported by the client.`);case 5:return e.abrupt(`return`,this.transport.send(y.WidgetApiFromWidgetAction.MSC4533RtcLivekitDelegateDelayedLeave,t));case 6:case`end`:return e.stop()}},e,this)}));function t(t){return e.apply(this,arguments)}return t}()},{key:`start`,value:function(){var e=this;this.transport.start(),this.getClientVersions().then(function(t){t.includes(_.UnstableApiVersion.MSC2974)&&(e.supportsMSC2974Renegotiate=!0)})}},{key:`handleMessage`,value:function(e){var t=new CustomEvent(`action:${e.detail.action}`,{detail:e.detail,cancelable:!0});if(this.emit(`action:${e.detail.action}`,t),!t.defaultPrevented)switch(e.detail.action){case y.WidgetApiToWidgetAction.SupportedApiVersions:return this.replyVersions(e.detail);case y.WidgetApiToWidgetAction.Capabilities:return this.handleCapabilities(e.detail);case y.WidgetApiToWidgetAction.UpdateVisibility:return this.transport.reply(e.detail,{});case y.WidgetApiToWidgetAction.NotifyCapabilities:return this.transport.reply(e.detail,{});default:return this.transport.reply(e.detail,{error:{message:`Unknown or unsupported to-widget action: `+e.detail.action}})}}},{key:`replyVersions`,value:function(e){this.transport.reply(e,{supported_versions:_.CurrentApiVersions})}},{key:`getClientVersions`,value:function(){var e=this;return Array.isArray(this.cachedClientVersions)?Promise.resolve(this.cachedClientVersions):this.transport.send(y.WidgetApiFromWidgetAction.SupportedApiVersions,{}).then(function(t){return e.cachedClientVersions=t.supported_versions,t.supported_versions}).catch(function(e){return console.warn(`non-fatal error getting supported client versions: `,e),[]})}},{key:`handleCapabilities`,value:function(e){var t=this;return this.capabilitiesFinished?this.transport.reply(e,{error:{message:`Capability negotiation already completed`}}):this.getClientVersions().then(function(n){return n.includes(_.UnstableApiVersion.MSC2871)?t.once(`action:${y.WidgetApiToWidgetAction.NotifyCapabilities}`,function(e){t.approvedCapabilities=e.detail.data.approved,t.emit(`ready`)}):t.emit(`ready`),t.capabilitiesFinished=!0,t.transport.reply(e,{capabilities:t.requestedCapabilities})})}}]),n}(m.EventEmitter)})),m=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SimpleObservable=void 0;function t(e){"@babel/helpers - typeof";return t=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},t(e)}function n(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=r(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var i=0,a=function(){};return{s:a,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:a}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
4
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o,s=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){c=!0,o=e},f:function(){try{s||n.return==null||n.return()}finally{if(c)throw o}}}}function r(e,t){if(e){if(typeof e==`string`)return i(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?i(e,t):void 0}}function i(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function a(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,l(r.key),r)}}function s(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function c(e,t,n){return(t=l(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l(e){var n=u(e,`string`);return t(n)==`symbol`?n:n+``}function u(e,n){if(t(e)!=`object`||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,n||`default`);if(t(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(n===`string`?String:Number)(e)}e.SimpleObservable=function(){function e(t){a(this,e),c(this,`listeners`,[]),t&&this.listeners.push(t)}return s(e,[{key:`onUpdate`,value:function(e){this.listeners.push(e)}},{key:`update`,value:function(e){var t=n(this.listeners),r;try{for(t.s();!(r=t.n()).done;){var i=r.value;i(e)}}catch(e){t.e(e)}finally{t.f()}}},{key:`close`,value:function(){this.listeners=[]}}]),e}()})),h=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ClientWidgetApi=void 0;var c=t(),l=a(),p=r(),h=o(),g=n(),_=i(),v=u(),y=s(),b=m(),x=d(),ee=f();function S(e){"@babel/helpers - typeof";return S=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},S(e)}function C(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function w(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?C(Object(n),!0).forEach(function(t){J(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):C(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function T(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=D(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
5
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,a=e},f:function(){try{o||n.return==null||n.return()}finally{if(s)throw a}}}}function E(e){return k(e)||O(e)||D(e)||te()}function te(){throw TypeError(`Invalid attempt to spread non-iterable instance.
6
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function D(e,t){if(e){if(typeof e==`string`)return A(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?A(e,t):void 0}}function O(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function k(e){if(Array.isArray(e))return A(e)}function A(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function j(){var e=I(),t=e.m(j),n=(Object.getPrototypeOf?Object.getPrototypeOf(t):t.__proto__).constructor;function r(e){var t=typeof e==`function`&&e.constructor;return!!t&&(t===n||(t.displayName||t.name)===`GeneratorFunction`)}var i={throw:1,return:2,break:3,continue:3};function a(e){var t,n;return function(r){t||(t={stop:function(){return n(r.a,2)},catch:function(){return r.v},abrupt:function(e,t){return n(r.a,i[e],t)},delegateYield:function(e,i,a){return t.resultName=i,n(r.d,M(e),a)},finish:function(e){return n(r.f,e)}},n=function(e,n,i){r.p=t.prev,r.n=t.next;try{return e(n,i)}finally{t.next=r.n}}),t.resultName&&(t[t.resultName]=r.v,t.resultName=void 0),t.sent=r.v,t.next=r.n;try{return e.call(this,t)}finally{r.p=t.prev,r.n=t.next}}}return(j=function(){return{wrap:function(t,n,r,i){return e.w(a(t),n,r,i&&i.reverse())},isGeneratorFunction:r,mark:e.m,awrap:function(e,t){return new R(e,t)},AsyncIterator:F,async:function(e,t,n,i,o){return(r(t)?P:ne)(a(e),t,n,i,o)},keys:N,values:M}})()}function M(e){if(e!=null){var t=e[typeof Symbol==`function`&&Symbol.iterator||`@@iterator`],n=0;if(t)return t.call(e);if(typeof e.next==`function`)return e;if(!isNaN(e.length))return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}throw TypeError(S(e)+` is not iterable`)}function N(e){var t=Object(e),n=[];for(var r in t)n.unshift(r);return function e(){for(;n.length;)if((r=n.pop())in t)return e.value=r,e.done=!1,e;return e.done=!0,e}}function ne(e,t,n,r,i){var a=P(e,t,n,r,i);return a.next().then(function(e){return e.done?e.value:a.next()})}function P(e,t,n,r,i){return new F(I().w(e,t,n,r),i||Promise)}function F(e,t){function n(r,i,a,o){try{var s=e[r](i),c=s.value;return c instanceof R?t.resolve(c.v).then(function(e){n(`next`,e,a,o)},function(e){n(`throw`,e,a,o)}):t.resolve(c).then(function(e){s.value=e,a(s)},function(e){return n(`throw`,e,a,o)})}catch(e){o(e)}}var r;this.next||(L(F.prototype),L(F.prototype,typeof Symbol==`function`&&Symbol.asyncIterator||`@asyncIterator`,function(){return this})),L(this,`_invoke`,function(e,i,a){function o(){return new t(function(t,r){n(e,a,t,r)})}return r=r?r.then(o,o):o()},!0)}function I(){var e,t,n=typeof Symbol==`function`?Symbol:{},r=n.iterator||`@@iterator`,i=n.toStringTag||`@@toStringTag`;function a(n,r,i,a){var c=r&&r.prototype instanceof s?r:s,l=Object.create(c.prototype);return L(l,`_invoke`,function(n,r,i){var a,s,c,l=0,u=i||[],d=!1,f={p:0,n:0,v:e,a:p,f:p.bind(e,4),d:function(t,n){return a=t,s=0,c=e,f.n=n,o}};function p(n,r){for(s=n,c=r,t=0;!d&&l&&!i&&t<u.length;t++){var i,a=u[t],p=f.p,m=a[2];n>3?(i=m===r)&&(c=a[(s=a[4])?5:(s=3,3)],a[4]=a[5]=e):a[0]<=p&&((i=n<2&&p<a[1])?(s=0,f.v=r,f.n=a[1]):p<m&&(i=n<3||a[0]>r||r>m)&&(a[4]=n,a[5]=r,f.n=m,s=0))}if(i||n>1)return o;throw d=!0,r}return function(i,u,m){if(l>1)throw TypeError(`Generator is already running`);for(d&&u===1&&p(u,m),s=u,c=m;(t=s<2?e:c)||!d;){a||(s?s<3?(s>1&&(f.n=-1),p(s,c)):f.n=c:f.v=c);try{if(l=2,a){if(s||(i=`next`),t=a[i]){if(!(t=t.call(a,c)))throw TypeError(`iterator result is not an object`);if(!t.done)return t;c=t.value,s<2&&(s=0)}else s===1&&(t=a.return)&&t.call(a),s<2&&(c=TypeError(`The iterator does not provide a '`+i+`' method`),s=1);a=e}else if((t=(d=f.n<0)?c:n.call(r,f))!==o)break}catch(t){a=e,s=1,c=t}finally{l=1}}return{value:t,done:d}}}(n,i,a),!0),l}var o={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][r]?t(t([][r]())):(L(t={},r,function(){return this}),t),d=l.prototype=s.prototype=Object.create(u);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,L(e,i,`GeneratorFunction`)),e.prototype=Object.create(d),e}return c.prototype=l,L(d,`constructor`,l),L(l,`constructor`,c),c.displayName=`GeneratorFunction`,L(l,i,`GeneratorFunction`),L(d),L(d,i,`Generator`),L(d,r,function(){return this}),L(d,`toString`,function(){return`[object Generator]`}),(I=function(){return{w:a,m:f}})()}function L(e,t,n,r){var i=Object.defineProperty;try{i({},``,{})}catch{i=0}L=function(e,t,n,r){function a(t,n){L(e,t,function(e){return this._invoke(t,n,e)})}t?i?i(e,t,{value:n,enumerable:!r,configurable:!r,writable:!r}):e[t]=n:(a(`next`,0),a(`throw`,1),a(`return`,2))},L(e,t,n,r)}function R(e,t){this.v=e,this.k=t}function z(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function B(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var a=e.apply(t,n);function o(e){z(a,r,i,o,s,`next`,e)}function s(e){z(a,r,i,o,s,`throw`,e)}o(void 0)})}}function V(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function re(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,Y(r.key),r)}}function H(e,t,n){return t&&re(e.prototype,t),n&&re(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function ie(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Super expression must either be null or a function`);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&U(e,t)}function U(e,t){return U=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},U(e,t)}function W(e){var t=ae();return function(){var n,r=q(e);if(t){var i=q(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return G(this,n)}}function G(e,t){if(t&&(S(t)==`object`||typeof t==`function`))return t;if(t!==void 0)throw TypeError(`Derived constructors may only return object or undefined`);return K(e)}function K(e){if(e===void 0)throw ReferenceError(`this hasn't been initialised - super() hasn't been called`);return e}function ae(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(ae=function(){return!!e})()}function q(e){return q=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},q(e)}function J(e,t,n){return(t=Y(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Y(e){var t=X(e,`string`);return S(t)==`symbol`?t:t+``}function X(e,t){if(S(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(S(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function oe(e){var t,n,r,i=2;for(typeof Symbol<`u`&&(n=Symbol.asyncIterator,r=Symbol.iterator);i--;){if(n&&(t=e[n])!=null)return t.call(e);if(r&&(t=e[r])!=null)return new se(t.call(e));n=`@@asyncIterator`,r=`@@iterator`}throw TypeError(`Object is not async iterable`)}function se(e){function t(e){if(Object(e)!==e)return Promise.reject(TypeError(e+` is not an object.`));var t=e.done;return Promise.resolve(e.value).then(function(e){return{value:e,done:t}})}return se=function(e){this.s=e,this.n=e.next},se.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return n===void 0?Promise.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return n===void 0?Promise.reject(e):t(n.apply(this.s,arguments))}},new se(e)}e.ClientWidgetApi=function(e){ie(n,e);var t=W(n);function n(e,r,i){var a;if(V(this,n),a=t.call(this),a.widget=e,a.driver=i,J(K(a),`transport`,void 0),J(K(a),`cachedWidgetVersions`,null),J(K(a),`contentLoadedActionSent`,!1),J(K(a),`allowedCapabilities`,new Set),J(K(a),`allowedEvents`,[]),J(K(a),`isStopped`,!1),J(K(a),`turnServers`,null),J(K(a),`contentLoadedWaitTimer`,void 0),J(K(a),`pushRoomStateTasks`,new Set),J(K(a),`pushRoomStateResult`,new Map),J(K(a),`flushRoomStateTask`,null),J(K(a),`viewedRoomId`,null),!(r!=null&&r.contentWindow))throw Error(`No iframe supplied`);if(!e)throw Error(`Invalid widget`);if(!i)throw Error(`Invalid driver`);return a.transport=new l.PostmessageTransport(p.WidgetApiDirection.ToWidget,e.id,r.contentWindow,globalThis),a.transport.targetOrigin=e.origin,a.transport.on(`message`,a.handleMessage.bind(K(a))),r.addEventListener(`load`,a.onIframeLoad.bind(K(a))),a.transport.start(),a}return H(n,[{key:`hasCapability`,value:function(e){return this.allowedCapabilities.has(e)}},{key:`canUseRoomTimeline`,value:function(e){return this.hasCapability(`org.matrix.msc2762.timeline:${x.Symbols.AnyRoom}`)||this.hasCapability(`org.matrix.msc2762.timeline:${e}`)}},{key:`canSendRoomEvent`,value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return this.allowedEvents.some(function(n){return n.matchesAsRoomEvent(v.EventDirection.Send,e,t)})}},{key:`canSendStateEvent`,value:function(e,t){return this.allowedEvents.some(function(n){return n.matchesAsStateEvent(v.EventDirection.Send,e,t)})}},{key:`canSendToDeviceEvent`,value:function(e){return this.allowedEvents.some(function(t){return t.matchesAsToDeviceEvent(v.EventDirection.Send,e)})}},{key:`canReceiveRoomEvent`,value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return this.allowedEvents.some(function(n){return n.matchesAsRoomEvent(v.EventDirection.Receive,e,t)})}},{key:`canReceiveStateEvent`,value:function(e,t){return this.allowedEvents.some(function(n){return n.matchesAsStateEvent(v.EventDirection.Receive,e,t)})}},{key:`canReceiveToDeviceEvent`,value:function(e){return this.allowedEvents.some(function(t){return t.matchesAsToDeviceEvent(v.EventDirection.Receive,e)})}},{key:`canReceiveRoomAccountData`,value:function(e){return this.allowedEvents.some(function(t){return t.matchesAsRoomAccountData(v.EventDirection.Receive,e)})}},{key:`stop`,value:function(){this.isStopped=!0,this.transport.stop()}},{key:`getWidgetVersions`,value:function(){var e=B(j().mark(function e(){var t;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!Array.isArray(this.cachedWidgetVersions)){e.next=2;break}return e.abrupt(`return`,this.cachedWidgetVersions);case 2:return e.prev=2,e.next=5,this.transport.send(h.WidgetApiToWidgetAction.SupportedApiVersions,{});case 5:return t=e.sent,this.cachedWidgetVersions=t.supported_versions,e.abrupt(`return`,t.supported_versions);case 10:return e.prev=10,e.t0=e.catch(2),console.warn(`non-fatal error getting supported widget versions: `,e.t0),e.abrupt(`return`,[]);case 14:case`end`:return e.stop()}},e,this,[[2,10]])}));function t(){return e.apply(this,arguments)}return t}()},{key:`beginCapabilities`,value:function(){var e=this;this.emit(`preparing`);var t;this.transport.send(h.WidgetApiToWidgetAction.Capabilities,{}).then(function(n){return t=n.capabilities,e.driver.validateCapabilities(new Set(n.capabilities))}).then(function(n){e.allowCapabilities(E(n),t),e.emit(`ready`)}).catch(function(t){e.emit(`error:preparing`,t)})}},{key:`allowCapabilities`,value:function(e,t){var n,r=this;console.log(`Widget ${this.widget.id} is allowed capabilities:`,e);var i=T(e),a;try{for(i.s();!(a=i.n()).done;){var o=a.value;this.allowedCapabilities.add(o)}}catch(e){i.e(e)}finally{i.f()}var s=v.WidgetEventCapability.findEventCapabilities(e);(n=this.allowedEvents).push.apply(n,E(s)),this.transport.send(h.WidgetApiToWidgetAction.NotifyCapabilities,{requested:t,approved:Array.from(this.allowedCapabilities)}).catch(function(e){console.warn(`non-fatal error notifying widget of approved capabilities:`,e)}).then(function(){r.emit(`capabilitiesNotified`)});var c=T(e),l;try{for(c.s();!(l=c.n()).done;){var u=l.value;if((0,g.isTimelineCapability)(u)){var d=(0,g.getTimelineRoomIDFromCapability)(u);if(d===x.Symbols.AnyRoom){var f=T(this.driver.getKnownRooms()),p;try{for(f.s();!(p=f.n()).done;){var m=p.value;this.pushRoomState(m)}}catch(e){f.e(e)}finally{f.f()}}else this.pushRoomState(d)}}}catch(e){c.e(e)}finally{c.f()}if(e.includes(g.MatrixCapabilities.MSC4407ReceiveStickyEvent)){console.debug(`Widget ${this.widget.id} is allowed to receive sticky events, check current sticky state.`);var _=e.filter(function(e){return(0,g.isTimelineCapability)(e)}).map(function(e){return(0,g.getTimelineRoomIDFromCapability)(e)}).flatMap(function(e){return e===x.Symbols.AnyRoom?r.driver.getKnownRooms():e});console.debug(`Widget ${this.widget.id} is allowed to receive sticky events in rooms:`,_);var y=T(_),b;try{var ee=function(){var e=b.value;r.pushStickyState(e).catch(function(t){console.error(`Failed to push sticky events to widget ${r.widget.id} for room ${e}:`,t)})};for(y.s();!(b=y.n()).done;)ee()}catch(e){y.e(e)}finally{y.f()}}s.length>0&&this.viewedRoomId!==null&&!this.canUseRoomTimeline(this.viewedRoomId)&&this.pushRoomState(this.viewedRoomId)}},{key:`onIframeLoad`,value:function(e){this.widget.waitForIframeLoad?this.beginCapabilities():(console.log(`waitForIframeLoad is false: waiting for widget to send contentLoaded`),this.contentLoadedWaitTimer=setTimeout(function(){console.error(`Widget specified waitForIframeLoad=false but timed out waiting for contentLoaded event!`)},1e4),this.contentLoadedActionSent=!1)}},{key:`handleContentLoadedAction`,value:function(e){if(this.contentLoadedWaitTimer!==void 0&&(clearTimeout(this.contentLoadedWaitTimer),this.contentLoadedWaitTimer=void 0),this.contentLoadedActionSent)throw Error(`Improper sequence: ContentLoaded Action can only be sent once after the widget loaded and should only be used if waitForIframeLoad is false (default=true)`);this.widget.waitForIframeLoad?this.transport.reply(e,{error:{message:`Improper sequence: not expecting ContentLoaded event if waitForIframeLoad is true (default=true)`}}):(this.transport.reply(e,{}),this.beginCapabilities()),this.contentLoadedActionSent=!0}},{key:`replyVersions`,value:function(e){this.transport.reply(e,{supported_versions:_.CurrentApiVersions})}},{key:`supportsUpdateState`,value:function(){var e=B(j().mark(function e(){return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getWidgetVersions();case 2:return e.abrupt(`return`,e.sent.includes(_.UnstableApiVersion.MSC2762_UPDATE_STATE));case 3:case`end`:return e.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:`handleCapabilitiesRenegotiate`,value:function(e){var t=this;this.transport.reply(e,{});var n=e.data?.capabilities||[],r=new Set(n.filter(function(e){return!t.hasCapability(e)}));r.size===0&&this.allowCapabilities([],[]),this.driver.validateCapabilities(r).then(function(e){return t.allowCapabilities(E(e),E(r))})}},{key:`handleNavigate`,value:function(e){var t,n=this;if(!this.hasCapability(g.MatrixCapabilities.MSC2931Navigate))return this.transport.reply(e,{error:{message:`Missing capability`}});if(!((t=e.data)!=null&&t.uri.startsWith(`https://matrix.to/#`)))return this.transport.reply(e,{error:{message:`Invalid matrix.to URI`}});var r=function(t){console.error(`[ClientWidgetApi] Failed to handle navigation: `,t),n.handleDriverError(t,e,`Error handling navigation`)};try{this.driver.navigate(e.data.uri.toString()).catch(function(e){return r(e)}).then(function(){return n.transport.reply(e,{})})}catch(e){return r(e)}}},{key:`handleOIDC`,value:function(e){var t=this,n=1,r=function(r,i){return i||={},n>1?t.transport.send(h.WidgetApiToWidgetAction.OpenIDCredentials,w({state:r,original_request_id:e.requestId},i)):t.transport.reply(e,w({state:r},i))},i=function(i){return console.error(`[ClientWidgetApi] Failed to handle OIDC: `,i),n>1?r(y.OpenIDRequestState.Blocked):t.transport.reply(e,{error:{message:i}})},a=new b.SimpleObservable(function(e){if(e.state===y.OpenIDRequestState.PendingUserConfirmation&&n>1)return a.close(),i(`client provided out-of-phase response to OIDC flow`);if(e.state===y.OpenIDRequestState.PendingUserConfirmation)r(e.state),n++;else return e.state===y.OpenIDRequestState.Allowed&&!e.token?i(`client provided invalid OIDC token for an allowed request`):(e.state===y.OpenIDRequestState.Blocked&&(e.token=void 0),a.close(),r(e.state,e.token))});this.driver.askOpenID(a)}},{key:`handleReadRoomAccountData`,value:function(e){var t=this,n=this.driver.readRoomAccountData(e.data.type);return this.canReceiveRoomAccountData(e.data.type)?n.then(function(n){t.transport.reply(e,{events:n})}):this.transport.reply(e,{error:{message:`Cannot read room account data of this type`}})}},{key:`handleReadEvents`,value:function(){var e=B(j().mark(function e(t){var n=this,r,i,a,o,s,c,l,u,d;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t.data.type){e.next=2;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Invalid request - missing event type`}}));case 2:if(!(t.data.limit!==void 0&&(!t.data.limit||t.data.limit<0))){e.next=4;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Invalid request - limit out of range`}}));case 4:if(t.data.room_ids!==void 0){e.next=8;break}r=this.viewedRoomId===null?[]:[this.viewedRoomId],e.next=30;break;case 8:if(t.data.room_ids!==x.Symbols.AnyRoom){e.next=12;break}r=this.driver.getKnownRooms().filter(function(e){return n.canUseRoomTimeline(e)}),e.next=30;break;case 12:r=t.data.room_ids,i=T(r),e.prev=14,i.s();case 16:if((a=i.n()).done){e.next=22;break}if(o=a.value,this.canUseRoomTimeline(o)){e.next=20;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Unable to access room timeline: ${o}`}}));case 20:e.next=16;break;case 22:e.next=27;break;case 24:e.prev=24,e.t0=e.catch(14),i.e(e.t0);case 27:return e.prev=27,i.f(),e.finish(27);case 30:if(s=t.data.limit||0,c=t.data.since,l=void 0,u=void 0,t.data.state_key===void 0){e.next=40;break}if(l=t.data.state_key===!0?void 0:t.data.state_key.toString(),this.canReceiveStateEvent(t.data.type,l??null)){e.next=38;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Cannot read state events of this type`}}));case 38:e.next=43;break;case 40:if(u=t.data.msgtype,this.canReceiveRoomEvent(t.data.type,u)){e.next=43;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Cannot read room events of this type`}}));case 43:if(t.data.room_ids!==void 0||r.length!==0){e.next=50;break}return console.warn("The widgetDriver uses deprecated behaviour:\n It does not set the viewedRoomId using `setViewedRoomId`"),e.next=47,t.data.state_key===void 0?this.driver.readRoomEvents(t.data.type,u,s,null,c):this.driver.readStateEvents(t.data.type,l,s,null);case 47:d=e.sent,e.next=68;break;case 50:return e.next=52,this.supportsUpdateState();case 52:if(!e.sent){e.next=58;break}return e.next=55,Promise.all(r.map(function(e){return n.driver.readRoomTimeline(e,t.data.type,u,l,s,c)}));case 55:d=e.sent.flat(1),e.next=68;break;case 58:if(t.data.state_key!==void 0){e.next=64;break}return e.next=61,Promise.all(r.map(function(e){return n.driver.readRoomTimeline(e,t.data.type,u,l,s,c)}));case 61:e.t1=e.sent,e.next=67;break;case 64:return e.next=66,Promise.all(r.map(function(e){return n.driver.readRoomState(e,t.data.type,l)}));case 66:e.t1=e.sent;case 67:d=e.t1.flat(1);case 68:this.transport.reply(t,{events:d});case 69:case`end`:return e.stop()}},e,this,[[14,24,27,30]])}));function t(t){return e.apply(this,arguments)}return t}()},{key:`handleSendEvent`,value:function(e){var t=this;if(!e.data.type)return this.transport.reply(e,{error:{message:`Invalid request - missing event type`}});if(e.data.room_id&&!this.canUseRoomTimeline(e.data.room_id))return this.transport.reply(e,{error:{message:`Unable to access room timeline: ${e.data.room_id}`}});e.data.parent_delay_id!==void 0&&console.warn(`Data includes parent_delay_id, but the widgetDriver ignores it`);var n=e.data.delay;if(n!==void 0&&!this.hasCapability(g.MatrixCapabilities.MSC4157SendDelayedEvent))return this.transport.reply(e,{error:{message:`Missing capability for ${g.MatrixCapabilities.MSC4157SendDelayedEvent}`}});var r=e.data.sticky_duration_ms!==void 0;if(r&&!this.hasCapability(g.MatrixCapabilities.MSC4407SendStickyEvent))return this.transport.reply(e,{error:{message:`Missing capability for ${g.MatrixCapabilities.MSC4407SendStickyEvent}`}});var i;if(e.data.state_key!==void 0){if(!this.canSendStateEvent(e.data.type,e.data.state_key))return this.transport.reply(e,{error:{message:`Cannot send state events of this type`}});if(r)return this.transport.reply(e,{error:{message:`Cannot send a state event with a sticky duration`}});i=n===void 0?this.driver.sendEvent(e.data.type,e.data.content||{},e.data.state_key,e.data.room_id):this.driver.sendDelayedEvent(n,e.data.type,e.data.content||{},e.data.state_key,e.data.room_id)}else{var a=e.data.content||{},o=a.msgtype;if(!this.canSendRoomEvent(e.data.type,o))return this.transport.reply(e,{error:{message:`Cannot send room events of this type`}});var s=[e.data.type,a,null,e.data.room_id];if(n!==void 0&&e.data.sticky_duration_ms)i=this.driver.sendDelayedStickyEvent(n,e.data.sticky_duration_ms,e.data.type,a,e.data.room_id);else if(n!==void 0){var c;i=(c=this.driver).sendDelayedEvent.apply(c,[n].concat(s))}else if(e.data.sticky_duration_ms)i=this.driver.sendStickyEvent(e.data.sticky_duration_ms,e.data.type,a,e.data.room_id);else{var l;i=(l=this.driver).sendEvent.apply(l,s)}}i.then(function(n){return t.transport.reply(e,w({room_id:n.roomId},`eventId`in n?{event_id:n.eventId}:{delay_id:n.delayId}))}).catch(function(n){console.error(`error sending event: `,n),t.handleDriverError(n,e,`Error sending event`)})}},{key:`handleUpdateDelayedEvent`,value:function(e){var t=this;if(!e.data.delay_id)return this.transport.reply(e,{error:{message:`Invalid request - missing delay_id`}});if(!this.hasCapability(g.MatrixCapabilities.MSC4157UpdateDelayedEvent))return this.transport.reply(e,{error:{message:`Missing capability`}});var n;switch(e.data.action){case ee.UpdateDelayedEventAction.Cancel:n=this.driver.cancelScheduledDelayedEvent;break;case ee.UpdateDelayedEventAction.Restart:n=this.driver.restartScheduledDelayedEvent;break;case ee.UpdateDelayedEventAction.Send:n=this.driver.sendScheduledDelayedEvent;break;default:return this.transport.reply(e,{error:{message:`Invalid request - unsupported action`}})}n.call(this.driver,e.data.delay_id).then(function(){return t.transport.reply(e,{})}).catch(function(n){console.error(`error updating delayed event: `,n),t.handleDriverError(n,e,`Error updating delayed event`)})}},{key:`handleSendToDevice`,value:function(){var e=B(j().mark(function e(t){return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t.data.type){e.next=4;break}this.transport.reply(t,{error:{message:`Invalid request - missing event type`}}),e.next=26;break;case 4:if(t.data.messages){e.next=8;break}this.transport.reply(t,{error:{message:`Invalid request - missing event contents`}}),e.next=26;break;case 8:if(typeof t.data.encrypted==`boolean`){e.next=12;break}this.transport.reply(t,{error:{message:`Invalid request - missing encryption flag`}}),e.next=26;break;case 12:if(this.canSendToDeviceEvent(t.data.type)){e.next=16;break}this.transport.reply(t,{error:{message:`Cannot send to-device events of this type`}}),e.next=26;break;case 16:return e.prev=16,e.next=19,this.driver.sendToDevice(t.data.type,t.data.encrypted,t.data.messages);case 19:this.transport.reply(t,{}),e.next=26;break;case 22:e.prev=22,e.t0=e.catch(16),console.error(`error sending to-device event`,e.t0),this.handleDriverError(e.t0,t,`Error sending event`);case 26:case`end`:return e.stop()}},e,this,[[16,22]])}));function t(t){return e.apply(this,arguments)}return t}()},{key:`pollTurnServers`,value:function(){var e=B(j().mark(function e(t,n){var r,i,a,o,s,c;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.transport.send(h.WidgetApiToWidgetAction.UpdateTurnServers,n);case 3:r=!1,i=!1,e.prev=5,o=oe(t);case 7:return e.next=9,o.next();case 9:if(!(r=!(s=e.sent).done)){e.next=16;break}return c=s.value,e.next=13,this.transport.send(h.WidgetApiToWidgetAction.UpdateTurnServers,c);case 13:r=!1,e.next=7;break;case 16:e.next=22;break;case 18:e.prev=18,e.t0=e.catch(5),i=!0,a=e.t0;case 22:if(e.prev=22,e.prev=23,!(r&&o.return!=null)){e.next=27;break}return e.next=27,o.return();case 27:if(e.prev=27,!i){e.next=30;break}throw a;case 30:return e.finish(27);case 31:return e.finish(22);case 32:e.next=37;break;case 34:e.prev=34,e.t1=e.catch(0),console.error(`error polling for TURN servers`,e.t1);case 37:case`end`:return e.stop()}},e,this,[[0,34],[5,18,22,32],[23,,27,31]])}));function t(t,n){return e.apply(this,arguments)}return t}()},{key:`handleWatchTurnServers`,value:function(){var e=B(j().mark(function e(t){var n,r,i,a;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(g.MatrixCapabilities.MSC3846TurnServers)){e.next=4;break}this.transport.reply(t,{error:{message:`Missing capability`}}),e.next=26;break;case 4:if(!this.turnServers){e.next=8;break}this.transport.reply(t,{}),e.next=26;break;case 8:return e.prev=8,n=this.driver.getTurnServers(),e.next=12,n.next();case 12:if(r=e.sent,i=r.done,a=r.value,!i){e.next=17;break}throw Error(`Client refuses to provide any TURN servers`);case 17:this.transport.reply(t,{}),this.pollTurnServers(n,a),this.turnServers=n,e.next=26;break;case 22:e.prev=22,e.t0=e.catch(8),console.error(`error getting first TURN server results`,e.t0),this.transport.reply(t,{error:{message:`TURN servers not available`}});case 26:case`end`:return e.stop()}},e,this,[[8,22]])}));function t(t){return e.apply(this,arguments)}return t}()},{key:`handleUnwatchTurnServers`,value:function(){var e=B(j().mark(function e(t){return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(g.MatrixCapabilities.MSC3846TurnServers)){e.next=4;break}this.transport.reply(t,{error:{message:`Missing capability`}}),e.next=12;break;case 4:if(this.turnServers){e.next=8;break}this.transport.reply(t,{}),e.next=12;break;case 8:return e.next=10,this.turnServers.return(void 0);case 10:this.turnServers=null,this.transport.reply(t,{});case 12:case`end`:return e.stop()}},e,this)}));function t(t){return e.apply(this,arguments)}return t}()},{key:`handleReadRelations`,value:function(){var e=B(j().mark(function e(t){var n=this,r,i;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t.data.event_id){e.next=2;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Invalid request - missing event ID`}}));case 2:if(!(t.data.limit!==void 0&&t.data.limit<0)){e.next=4;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Invalid request - limit out of range`}}));case 4:if(t.data.room_id===void 0||this.canUseRoomTimeline(t.data.room_id)){e.next=6;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Unable to access room timeline: ${t.data.room_id}`}}));case 6:return e.prev=6,e.next=9,this.driver.readEventRelations(t.data.event_id,t.data.room_id,t.data.rel_type,t.data.event_type,t.data.from,t.data.to,t.data.limit,t.data.direction);case 9:return r=e.sent,i=r.chunk.filter(function(e){return e.state_key===void 0?n.canReceiveRoomEvent(e.type,e.content.msgtype):n.canReceiveStateEvent(e.type,e.state_key)}),e.abrupt(`return`,this.transport.reply(t,{chunk:i,prev_batch:r.prevBatch,next_batch:r.nextBatch}));case 14:e.prev=14,e.t0=e.catch(6),console.error(`error getting the relations`,e.t0),this.handleDriverError(e.t0,t,`Unexpected error while reading relations`);case 18:case`end`:return e.stop()}},e,this,[[6,14]])}));function t(t){return e.apply(this,arguments)}return t}()},{key:`handleUserDirectorySearch`,value:function(){var e=B(j().mark(function e(t){var n;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(g.MatrixCapabilities.MSC3973UserDirectorySearch)){e.next=2;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Missing capability`}}));case 2:if(typeof t.data.search_term==`string`){e.next=4;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Invalid request - missing search term`}}));case 4:if(!(t.data.limit!==void 0&&t.data.limit<0)){e.next=6;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Invalid request - limit out of range`}}));case 6:return e.prev=6,e.next=9,this.driver.searchUserDirectory(t.data.search_term,t.data.limit);case 9:return n=e.sent,e.abrupt(`return`,this.transport.reply(t,{limited:n.limited,results:n.results.map(function(e){return{user_id:e.userId,display_name:e.displayName,avatar_url:e.avatarUrl}})}));case 13:e.prev=13,e.t0=e.catch(6),console.error(`error searching in the user directory`,e.t0),this.handleDriverError(e.t0,t,`Unexpected error while searching in the user directory`);case 17:case`end`:return e.stop()}},e,this,[[6,13]])}));function t(t){return e.apply(this,arguments)}return t}()},{key:`handleGetMediaConfig`,value:function(){var e=B(j().mark(function e(t){var n;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(g.MatrixCapabilities.MSC4039UploadFile)){e.next=2;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Missing capability`}}));case 2:return e.prev=2,e.next=5,this.driver.getMediaConfig();case 5:return n=e.sent,e.abrupt(`return`,this.transport.reply(t,n));case 9:e.prev=9,e.t0=e.catch(2),console.error(`error while getting the media configuration`,e.t0),this.handleDriverError(e.t0,t,`Unexpected error while getting the media configuration`);case 13:case`end`:return e.stop()}},e,this,[[2,9]])}));function t(t){return e.apply(this,arguments)}return t}()},{key:`handleRtcTransports`,value:function(){var e=B(j().mark(function e(t){var n;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(g.MatrixCapabilities.MSC4515RtcTransports)){e.next=2;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Missing capability`}}));case 2:return e.prev=2,e.next=5,this.driver.getRtcTransports();case 5:return n=e.sent,e.abrupt(`return`,this.transport.reply(t,{rtc_transports:n.rtc_transports}));case 9:e.prev=9,e.t0=e.catch(2),console.error(`error while getting the RTC transports`,e.t0),this.handleDriverError(e.t0,t,`Unexpected error while getting the RTC transports`);case 13:case`end`:return e.stop()}},e,this,[[2,9]])}));function t(t){return e.apply(this,arguments)}return t}()},{key:`handleUploadFile`,value:function(){var e=B(j().mark(function e(t){var n;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(g.MatrixCapabilities.MSC4039UploadFile)){e.next=2;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Missing capability`}}));case 2:return e.prev=2,e.next=5,this.driver.uploadFile(t.data.file);case 5:return n=e.sent,e.abrupt(`return`,this.transport.reply(t,{content_uri:n.contentUri}));case 9:e.prev=9,e.t0=e.catch(2),console.error(`error while uploading a file`,e.t0),this.handleDriverError(e.t0,t,`Unexpected error while uploading a file`);case 13:case`end`:return e.stop()}},e,this,[[2,9]])}));function t(t){return e.apply(this,arguments)}return t}()},{key:`handleDownloadFile`,value:function(){var e=B(j().mark(function e(t){var n;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(g.MatrixCapabilities.MSC4039DownloadFile)){e.next=2;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Missing capability`}}));case 2:return e.prev=2,e.next=5,this.driver.downloadFile(t.data.content_uri);case 5:return n=e.sent,e.abrupt(`return`,this.transport.reply(t,{file:n.file}));case 9:e.prev=9,e.t0=e.catch(2),console.error(`error while downloading a file`,e.t0),this.handleDriverError(e.t0,t,`Unexpected error while downloading a file`);case 13:case`end`:return e.stop()}},e,this,[[2,9]])}));function t(t){return e.apply(this,arguments)}return t}()},{key:`handleRtcLivekitGetToken`,value:function(){var e=B(j().mark(function e(t){var n;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(g.MatrixCapabilities.MSC4533RtcLivekitGetToken)){e.next=2;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Missing capability`}}));case 2:return e.prev=2,e.next=5,this.driver.getRtcLivekitToken(t.data);case 5:return n=e.sent,e.abrupt(`return`,this.transport.reply(t,n));case 9:e.prev=9,e.t0=e.catch(2),console.error(`error while getting a LiveKit token`,e.t0),this.handleDriverError(e.t0,t,`Unexpected error while getting a LiveKit token`);case 13:case`end`:return e.stop()}},e,this,[[2,9]])}));function t(t){return e.apply(this,arguments)}return t}()},{key:`handleRtcLivekitDelegateDelayedLeave`,value:function(){var e=B(j().mark(function e(t){var n;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(g.MatrixCapabilities.MSC4533RtcLivekitDelegateDelayedLeave)){e.next=2;break}return e.abrupt(`return`,this.transport.reply(t,{error:{message:`Missing capability`}}));case 2:return e.prev=2,e.next=5,this.driver.delegateRtcLivekitDelayedLeave(t.data);case 5:return n=e.sent,e.abrupt(`return`,this.transport.reply(t,n));case 9:e.prev=9,e.t0=e.catch(2),console.error(`error while delegating a LiveKit delayed leave`,e.t0),this.handleDriverError(e.t0,t,`Unexpected error while delegating a LiveKit delayed leave`);case 13:case`end`:return e.stop()}},e,this,[[2,9]])}));function t(t){return e.apply(this,arguments)}return t}()},{key:`handleDriverError`,value:function(e,t,n){var r=this.driver.processError(e);this.transport.reply(t,{error:w({message:n},r)})}},{key:`handleMessage`,value:function(e){if(!this.isStopped){var t=new CustomEvent(`action:${e.detail.action}`,{detail:e.detail,cancelable:!0});if(this.emit(`action:${e.detail.action}`,t),!t.defaultPrevented)switch(e.detail.action){case h.WidgetApiFromWidgetAction.ContentLoaded:return this.handleContentLoadedAction(e.detail);case h.WidgetApiFromWidgetAction.SupportedApiVersions:return this.replyVersions(e.detail);case h.WidgetApiFromWidgetAction.SendEvent:return this.handleSendEvent(e.detail);case h.WidgetApiFromWidgetAction.SendToDevice:return this.handleSendToDevice(e.detail);case h.WidgetApiFromWidgetAction.GetOpenIDCredentials:return this.handleOIDC(e.detail);case h.WidgetApiFromWidgetAction.MSC2931Navigate:return this.handleNavigate(e.detail);case h.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities:return this.handleCapabilitiesRenegotiate(e.detail);case h.WidgetApiFromWidgetAction.MSC2876ReadEvents:return this.handleReadEvents(e.detail);case h.WidgetApiFromWidgetAction.WatchTurnServers:return this.handleWatchTurnServers(e.detail);case h.WidgetApiFromWidgetAction.UnwatchTurnServers:return this.handleUnwatchTurnServers(e.detail);case h.WidgetApiFromWidgetAction.MSC3869ReadRelations:return this.handleReadRelations(e.detail);case h.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch:return this.handleUserDirectorySearch(e.detail);case h.WidgetApiFromWidgetAction.BeeperReadRoomAccountData:return this.handleReadRoomAccountData(e.detail);case h.WidgetApiFromWidgetAction.MSC4039GetMediaConfigAction:return this.handleGetMediaConfig(e.detail);case h.WidgetApiFromWidgetAction.MSC4515GetRtcTransports:return this.handleRtcTransports(e.detail);case h.WidgetApiFromWidgetAction.MSC4039UploadFileAction:return this.handleUploadFile(e.detail);case h.WidgetApiFromWidgetAction.MSC4039DownloadFileAction:return this.handleDownloadFile(e.detail);case h.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent:return this.handleUpdateDelayedEvent(e.detail);case h.WidgetApiFromWidgetAction.MSC4533RtcLivekitGetToken:return this.handleRtcLivekitGetToken(e.detail);case h.WidgetApiFromWidgetAction.MSC4533RtcLivekitDelegateDelayedLeave:return this.handleRtcLivekitDelegateDelayedLeave(e.detail);default:return this.transport.reply(e.detail,{error:{message:`Unknown or unsupported from-widget action: `+e.detail.action}})}}}},{key:`updateTheme`,value:function(e){return this.transport.send(h.WidgetApiToWidgetAction.ThemeChange,e)}},{key:`updateLanguage`,value:function(e){return this.transport.send(h.WidgetApiToWidgetAction.LanguageChange,{lang:e})}},{key:`takeScreenshot`,value:function(){return this.transport.send(h.WidgetApiToWidgetAction.TakeScreenshot,{})}},{key:`updateVisibility`,value:function(e){return this.transport.send(h.WidgetApiToWidgetAction.UpdateVisibility,{visible:e})}},{key:`sendWidgetConfig`,value:function(e){return this.transport.send(h.WidgetApiToWidgetAction.WidgetConfig,e).then()}},{key:`notifyModalWidgetButtonClicked`,value:function(e){return this.transport.send(h.WidgetApiToWidgetAction.ButtonClicked,{id:e}).then()}},{key:`notifyModalWidgetClose`,value:function(e){return this.transport.send(h.WidgetApiToWidgetAction.CloseModalWidget,e).then()}},{key:`feedEvent`,value:function(){var e=B(j().mark(function e(t,n){return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(n!==void 0&&this.setViewedRoomId(n),t.room_id===this.viewedRoomId||this.canUseRoomTimeline(t.room_id)){e.next=3;break}return e.abrupt(`return`);case 3:if(t.state_key===void 0||t.state_key===null){e.next=8;break}if(this.canReceiveStateEvent(t.type,t.state_key)){e.next=6;break}return e.abrupt(`return`);case 6:e.next=10;break;case 8:if(this.canReceiveRoomEvent(t.type,t.content?.msgtype)){e.next=10;break}return e.abrupt(`return`);case 10:return e.next=12,this.transport.send(h.WidgetApiToWidgetAction.SendEvent,t);case 12:case`end`:return e.stop()}},e,this)}));function t(t,n){return e.apply(this,arguments)}return t}()},{key:`feedToDevice`,value:function(){var e=B(j().mark(function e(t,n){return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.canReceiveToDeviceEvent(t.type)){e.next=3;break}return e.next=3,this.transport.send(h.WidgetApiToWidgetAction.SendToDevice,w(w({},t),{},{encrypted:n}));case 3:case`end`:return e.stop()}},e,this)}));function t(t,n){return e.apply(this,arguments)}return t}()},{key:`setViewedRoomId`,value:function(e){this.viewedRoomId=e,e!==null&&!this.canUseRoomTimeline(e)&&this.pushRoomState(e)}},{key:`flushRoomState`,value:function(){var e=B(j().mark(function e(){var t,n,r,i,a,o,s;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=3,Promise.all(this.pushRoomStateTasks);case 3:if(this.pushRoomStateTasks.size>0){e.next=1;break}case 4:t=[],n=T(this.pushRoomStateResult.values());try{for(n.s();!(r=n.n()).done;){i=r.value,a=T(i.values());try{for(a.s();!(o=a.n()).done;)s=o.value,t.push.apply(t,E(s.values()))}catch(e){a.e(e)}finally{a.f()}}}catch(e){n.e(e)}finally{n.f()}return e.next=9,this.getWidgetVersions();case 9:if(!e.sent.includes(_.UnstableApiVersion.MSC2762_UPDATE_STATE)){e.next=12;break}return e.next=12,this.transport.send(h.WidgetApiToWidgetAction.UpdateState,{state:t});case 12:return e.prev=12,this.flushRoomStateTask=null,e.finish(12);case 15:case`end`:return e.stop()}},e,this,[[0,,12,15]])}));function t(){return e.apply(this,arguments)}return t}()},{key:`pushStickyState`,value:function(){var e=B(j().mark(function e(t){var n=this;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return console.debug(`Pushing sticky state to widget for room`,t),e.abrupt(`return`,this.driver.readStickyEvents(t).then(function(e){return{roomId:t,stickyEvents:e.filter(function(e){return n.canReceiveRoomEvent(e.type,typeof e.content?.msgtype==`string`?e.content.msgtype:null)})}}).then(function(){var e=B(j().mark(function e(t){var r,i,a;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.roomId,i=t.stickyEvents,console.debug(`Pushing`,i.length,`sticky events to widget for room`,r),a=i.map(function(e){return n.transport.send(h.WidgetApiToWidgetAction.SendEvent,e)}),e.next=5,Promise.all(a);case 5:case`end`:return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}()));case 2:case`end`:return e.stop()}},e,this)}));function t(t){return e.apply(this,arguments)}return t}()},{key:`pushRoomState`,value:function(e){var t=this,n=T(this.allowedEvents),r;try{var i=function(){var n=r.value;if(n.kind===v.EventKind.State&&n.direction===v.EventDirection.Receive){var i=t.driver.readRoomState(e,n.eventType,n.keyStr??void 0).then(function(r){var i=T(r),a;try{for(i.s();!(a=i.n()).done;){var o=a.value,s=t.pushRoomStateResult.get(e);s===void 0&&(s=new Map,t.pushRoomStateResult.set(e,s));var c=s.get(n.eventType);c===void 0&&(c=new Map,s.set(n.eventType,c)),c.has(o.state_key)||c.set(o.state_key,o)}}catch(e){i.e(e)}finally{i.f()}},function(t){return console.error(`Failed to read room state for ${e} (${n.eventType}, ${n.keyStr})`,t)}).then(function(){t.pushRoomStateTasks.delete(i)});t.pushRoomStateTasks.add(i),t.flushRoomStateTask??=t.flushRoomState(),t.flushRoomStateTask.catch(function(e){return console.error(`Failed to push room state`,e)})}};for(n.s();!(r=n.n()).done;)i()}catch(e){n.e(e)}finally{n.f()}}},{key:`feedStateUpdate`,value:function(){var e=B(j().mark(function e(t){var n,r;return j().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t.state_key!==void 0){e.next=2;break}throw Error(`Not a state event`);case 2:if(t.room_id!==this.viewedRoomId&&!this.canUseRoomTimeline(t.room_id)||!this.canReceiveStateEvent(t.type,t.state_key)){e.next=21;break}if(this.pushRoomStateTasks.size!==0){e.next=11;break}return e.next=6,this.getWidgetVersions();case 6:if(!e.sent.includes(_.UnstableApiVersion.MSC2762_UPDATE_STATE)){e.next=9;break}return e.next=9,this.transport.send(h.WidgetApiToWidgetAction.UpdateState,{state:[t]});case 9:e.next=21;break;case 11:n=this.pushRoomStateResult.get(t.room_id),n===void 0&&(n=new Map,this.pushRoomStateResult.set(t.room_id,n)),r=n.get(t.type),r===void 0&&(r=new Map,n.set(t.type,r)),r.has(t.type)||r.set(t.state_key,t);case 16:return e.next=18,Promise.all(this.pushRoomStateTasks);case 18:if(this.pushRoomStateTasks.size>0){e.next=16;break}case 19:return e.next=21,this.flushRoomStateTask;case 21:case`end`:return e.stop()}},e,this)}));function t(t){return e.apply(this,arguments)}return t}()}]),n}(c.EventEmitter)})),g=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isErrorResponse=n;function t(e){"@babel/helpers - typeof";return t=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},t(e)}function n(e){var n=e.error;return t(n)===`object`&&n!==null&&`message`in n&&typeof n.message==`string`}})),_=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WidgetKind=void 0,e.WidgetKind=function(e){return e.Room=`room`,e.Account=`account`,e.Modal=`modal`,e}({})})),v=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ModalButtonKind=void 0,e.ModalButtonKind=function(e){return e.Primary=`m.primary`,e.Secondary=`m.secondary`,e.Warning=`m.warning`,e.Danger=`m.danger`,e.Link=`m.link`,e}({})})),y=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isValidUrl=t;function t(e){if(!e)return!1;try{var t=new URL(e);return t.protocol===`http`||t.protocol===`https`}catch(e){if(e instanceof TypeError)return!1;throw e}}})),b=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assertPresent=t;function t(e,t){if(!e[t])throw Error(`${String(t)} is required`)}})),x=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Widget=void 0;var t=w(),n=b();function r(e){"@babel/helpers - typeof";return r=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},r(e)}function i(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function a(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,s(r.key),r)}}function o(e,t,n){return t&&a(e.prototype,t),n&&a(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function s(e){var t=c(e,`string`);return r(t)==`symbol`?t:t+``}function c(e,t){if(r(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var i=n.call(e,t||`default`);if(r(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}e.Widget=function(){function e(t){if(i(this,e),this.definition=t,!this.definition)throw Error(`Definition is required`);(0,n.assertPresent)(t,`id`),(0,n.assertPresent)(t,`creatorUserId`),(0,n.assertPresent)(t,`type`),(0,n.assertPresent)(t,`url`)}return o(e,[{key:`creatorUserId`,get:function(){return this.definition.creatorUserId}},{key:`type`,get:function(){return this.definition.type}},{key:`id`,get:function(){return this.definition.id}},{key:`name`,get:function(){return this.definition.name||null}},{key:`title`,get:function(){return this.rawData.title||null}},{key:`templateUrl`,get:function(){return this.definition.url}},{key:`origin`,get:function(){return new URL(this.templateUrl).origin}},{key:`waitForIframeLoad`,get:function(){return this.definition.waitForIframeLoad!==!1&&(this.definition.waitForIframeLoad,!0)}},{key:`rawData`,get:function(){return this.definition.data||{}}},{key:`getCompleteUrl`,value:function(e){return(0,t.runTemplate)(this.templateUrl,this.definition,e)}}]),e}()})),ee=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WidgetParser=void 0;var t=x(),n=y();function r(e){"@babel/helpers - typeof";return r=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},r(e)}function i(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=a(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
7
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o,s=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){c=!0,o=e},f:function(){try{s||n.return==null||n.return()}finally{if(c)throw o}}}}function a(e,t){if(e){if(typeof e==`string`)return o(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?o(e,t):void 0}}function o(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function s(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function c(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,u(r.key),r)}}function l(e,t,n){return t&&c(e.prototype,t),n&&c(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function u(e){var t=d(e,`string`);return r(t)==`symbol`?t:t+``}function d(e,t){if(r(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var i=n.call(e,t||`default`);if(r(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}e.WidgetParser=function(){function e(){s(this,e)}return l(e,null,[{key:`parseAccountData`,value:function(t){if(!t)return[];for(var n=[],r=0,i=Object.keys(t);r<i.length;r++){var a=i[r],o=t[a];if(o&&(o.type===`m.widget`||o.type===`im.vector.modular.widgets`)&&o.sender&&(o.state_key||o.id)===a){var s={content:o.content,sender:o.sender,type:`m.widget`,state_key:a,event_id:`$example`,room_id:`!example`,origin_server_ts:1},c=e.parseRoomWidget(s);c&&n.push(c)}}return n}},{key:`parseWidgetsFromRoomState`,value:function(t){if(!t)return[];var n=[],r=i(t),a;try{for(r.s();!(a=r.n()).done;){var o=a.value,s=e.parseRoomWidget(o);s&&n.push(s)}}catch(e){r.e(e)}finally{r.f()}return n}},{key:`parseRoomWidget`,value:function(t){if(!t||t.type!==`m.widget`&&t.type!==`im.vector.modular.widgets`)return null;var n=t.content||{},r={id:t.state_key,creatorUserId:n.creatorUserId||t.sender,name:n.name,type:n.type,url:n.url,waitForIframeLoad:n.waitForIframeLoad,data:n.data};return e.processEstimatedWidget(r)}},{key:`processEstimatedWidget`,value:function(e){return!e.id||!e.creatorUserId||!e.type||!(0,n.isValidUrl)(e.url)?null:new t.Widget(e)}}]),e}()})),S=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.runTemplate=t,e.toString=n;function t(e,t,r){for(var i=Object.assign({},t.data,{matrix_room_id:r.widgetRoomId||``,matrix_user_id:r.currentUserId,matrix_display_name:r.userDisplayName||r.currentUserId,matrix_avatar_url:r.userHttpAvatarUrl||``,matrix_widget_id:t.id,"org.matrix.msc2873.client_id":r.clientId||``,"org.matrix.msc2873.client_theme":r.clientTheme||``,"org.matrix.msc2873.client_language":r.clientLanguage||``,"org.matrix.msc3819.matrix_device_id":r.deviceId||``,"org.matrix.msc4039.matrix_base_url":r.baseUrl||``}),a=e,o=0,s=Object.keys(i);o<s.length;o++){var c=s[o],l=`$${c}`.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),u=new RegExp(l,`g`);a=a.replace(u,encodeURIComponent(n(i[c])))}return a}function n(e){return e==null?`${e}`:String(e)}})),C=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WidgetDriver=void 0;var t=w();function n(e){"@babel/helpers - typeof";return n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},n(e)}function r(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,o(r.key),r)}}function a(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function o(e){var t=s(e,`string`);return n(t)==`symbol`?t:t+``}function s(e,t){if(n(e)!=`object`||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t||`default`);if(n(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}e.WidgetDriver=function(){function e(){r(this,e)}return a(e,[{key:`validateCapabilities`,value:function(e){return Promise.resolve(new Set)}},{key:`sendEvent`,value:function(e,t){return arguments.length>2&&arguments[2]!==void 0&&arguments[2],arguments.length>3&&arguments[3]!==void 0&&arguments[3],Promise.reject(Error(`Failed to override function`))}},{key:`sendStickyEvent`,value:function(e,t,n){throw arguments.length>3&&arguments[3]!==void 0&&arguments[3],Error(`Method not implemented.`)}},{key:`sendDelayedEvent`,value:function(e,t,n){return arguments.length>3&&arguments[3]!==void 0&&arguments[3],arguments.length>4&&arguments[4]!==void 0&&arguments[4],Promise.reject(Error(`Failed to override function`))}},{key:`sendDelayedStickyEvent`,value:function(e,t,n,r){throw arguments.length>4&&arguments[4]!==void 0&&arguments[4],Error(`Method not implemented.`)}},{key:`cancelScheduledDelayedEvent`,value:function(e){return Promise.reject(Error(`Failed to override function`))}},{key:`restartScheduledDelayedEvent`,value:function(e){return Promise.reject(Error(`Failed to override function`))}},{key:`sendScheduledDelayedEvent`,value:function(e){return Promise.reject(Error(`Failed to override function`))}},{key:`sendToDevice`,value:function(e,t,n){return Promise.reject(Error(`Failed to override function`))}},{key:`readRoomAccountData`,value:function(e){return arguments.length>1&&arguments[1]!==void 0&&arguments[1],Promise.resolve([])}},{key:`readRoomEvents`,value:function(e,t,n){return arguments.length>3&&arguments[3]!==void 0&&arguments[3],arguments.length>4&&arguments[4],Promise.resolve([])}},{key:`readStateEvents`,value:function(e,t,n){return arguments.length>3&&arguments[3]!==void 0&&arguments[3],Promise.resolve([])}},{key:`readStickyEvents`,value:function(e){throw Error(`readStickyEvents is not implemented`)}},{key:`readRoomTimeline`,value:function(e,t,n,r,i,a){return r===void 0?this.readRoomEvents(t,n,i,[e],a):this.readStateEvents(t,r,i,[e])}},{key:`readRoomState`,value:function(e,t,n){return this.readStateEvents(t,n,2**53-1,[e])}},{key:`readEventRelations`,value:function(e,t,n,r,i,a,o,s){return Promise.resolve({chunk:[]})}},{key:`askOpenID`,value:function(e){e.update({state:t.OpenIDRequestState.Blocked})}},{key:`navigate`,value:function(e){throw Error(`Navigation is not implemented`)}},{key:`getTurnServers`,value:function(){throw Error(`TURN server support is not implemented`)}},{key:`searchUserDirectory`,value:function(e,t){return Promise.resolve({limited:!1,results:[]})}},{key:`getMediaConfig`,value:function(){throw Error(`Get media config is not implemented`)}},{key:`getRtcTransports`,value:function(){throw Error(`Get RTC transports is not implemented`)}},{key:`uploadFile`,value:function(e){throw Error(`Upload file is not implemented`)}},{key:`downloadFile`,value:function(e){throw Error(`Download file is not implemented`)}},{key:`getRtcLivekitToken`,value:function(e){throw Error(`Getting a LiveKit token is not implemented`)}},{key:`delegateRtcLivekitDelayedLeave`,value:function(e){throw Error(`Delegating a LiveKit delayed leave is not implemented`)}},{key:`getKnownRooms`,value:function(){throw Error(`Querying known rooms is not implemented`)}},{key:`processError`,value:function(e){}}]),e}()})),w=e((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=p();Object.keys(t).forEach(function(n){n!=="default"&&n!=="__esModule"&&(n in e&&e[n]===t[n]||Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[n]}}))});var w=h();Object.keys(w).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===w[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return w[t]}}))});var T=d();Object.keys(T).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===T[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return T[t]}}))});var E=a();Object.keys(E).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===E[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return E[t]}}))});var te=c();Object.keys(te).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===te[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return te[t]}}))});var D=g();Object.keys(D).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===D[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return D[t]}}))});var O=o();Object.keys(O).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===O[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return O[t]}}))});var k=r();Object.keys(k).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===k[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return k[t]}}))});var A=i();Object.keys(A).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===A[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return A[t]}}))});var j=n();Object.keys(j).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===j[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return j[t]}}))});var M=s();Object.keys(M).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===M[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return M[t]}}))});var N=_();Object.keys(N).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===N[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return N[t]}}))});var ne=v();Object.keys(ne).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===ne[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return ne[t]}}))});var P=l();Object.keys(P).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===P[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return P[t]}}))});var F=f();Object.keys(F).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===F[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return F[t]}}))});var I=u();Object.keys(I).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===I[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return I[t]}}))});var L=y();Object.keys(L).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===L[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return L[t]}}))});var R=b();Object.keys(R).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===R[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return R[t]}}))});var z=x();Object.keys(z).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===z[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return z[t]}}))});var B=ee();Object.keys(B).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===B[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return B[t]}}))});var V=S();Object.keys(V).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===V[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return V[t]}}))});var re=m();Object.keys(re).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===re[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return re[t]}}))});var H=C();Object.keys(H).forEach(function(t){t!=="default"&&t!=="__esModule"&&(t in e&&e[t]===H[t]||Object.defineProperty(e,t,{enumerable:!0,get:function(){return H[t]}}))})})),T=w(),E=`org.matrix.mscXXXX`,te={read_relations:`org.matrix.msc3869`,update_delayed_event:`org.matrix.msc4157`,get_rtc_transports:`org.matrix.msc4515`,search_user_directory:`org.matrix.msc3973`,get_media_config:`org.matrix.msc4039`,upload_file:`org.matrix.msc4039`,download_file:`org.matrix.msc4039`,get_rtc_livekit_token:`org.matrix.msc4533`,delegate_rtc_livekit_delayed_leave:`org.matrix.msc4533`,navigate:`org.matrix.msc2931`,read_room_account_data:`com.beeper`};function D(e){let t=/^[^.:]*/.exec(e)[0];return Object.hasOwn(te,t)?te[t]:E}var O=e=>`widget:${D(e)}.${e}`,k=e=>`host:${D(e)}.${e}`,A=e=>`webview:${E}.${e}`,j=[`allow-forms`,`allow-popups`,`allow-popups-to-escape-sandbox`,`allow-same-origin`,`allow-scripts`,`allow-presentation`,`allow-downloads`],M=[`microphone`,`camera`,`encrypted-media`,`autoplay`,`display-capture`,`clipboard-write`,`clipboard-read`,`fullscreen`],N=[...j.map(e=>A(`sandbox:${e}`)),...M.map(e=>A(`allow:${e}`))],ne=[k(`update_theme`),k(`update_language`),k(`update_visibility`)],P=`m.`,F=`org.matrix.msc2762.`,I=`org.matrix.msc3819.`,L=`org.matrix.msc4157.`,R=`org.matrix.msc4407.`,z=(e,t,...n)=>({prefix:e,body:t,expand:()=>n}),B=[{prefix:F,body:`send.event:`,expand:e=>[O(`send_event.timeline:${e}`)]},{prefix:F,body:`send.state_event:`,expand:e=>[O(`send_event.state:${e}`)]},{prefix:F,body:`receive.event:`,expand:e=>[O(`read_timeline:${e}`),O(`read_relations:${e}`),k(`forward_event.timeline:${e}`),O(`paginate_timeline`),k(`notify_timeline_update`)]},{prefix:F,body:`receive.state_event:`,expand:e=>[k(`update_state:${e}`),k(`forward_event.state:${e}`)]},{prefix:F,body:`timeline:`,expand:()=>[]},{prefix:I,body:`send.to_device:`,expand:e=>[O(`send_to_device:${e}`)]},{prefix:I,body:`receive.to_device:`,expand:e=>[k(`forward_to_device:${e}`)]},{prefix:`com.beeper.capabilities.`,body:`receive.room_account_data:`,expand:e=>[O(`read_room_account_data:${e}`)]},z(L,`send.delayed_event`,O(`send_event.delayed`)),z(L,`update_delayed_event`,O(`update_delayed_event`)),z(R,`send.sticky_event`,O(`send_event.sticky`)),z(R,`receive.sticky_event`,k(`forward_event.sticky`)),z(`town.robin.msc3846.`,`turn_servers`,k(`update_turn_servers`)),z(`org.matrix.msc4515.`,`rtc_transports`,O(`get_rtc_transports`)),z(`org.matrix.msc3973.`,`user_directory_search`,O(`search_user_directory`)),z(`org.matrix.msc4039.`,`upload_file`,O(`upload_file`),O(`get_media_config`)),z(`org.matrix.msc4039.`,`download_file`,O(`download_file`)),z(`org.matrix.msc2931.`,`navigate`,O(`navigate`)),z(`org.matrix.msc4533.`,`rtc_livekit_get_token`,O(`get_rtc_livekit_token`)),z(`org.matrix.msc4533.`,`rtc_livekit_delegate_delayed_leave`,O(`delegate_rtc_livekit_delayed_leave`)),z(P,`always_on_screen`,O(`set_always_on_screen`))];function V(e){if(e.startsWith(`webview:`))return[];for(let t of B)for(let n of[t.prefix,P]){if(!e.startsWith(n+t.body))continue;let r=e.slice(n.length+t.body.length);if(t.body.endsWith(`:`)?r!==``:r===``)return t.expand(r)}return[e]}function re(e){return[...new Set([...ne,...e.flatMap(V)])]}function H(e){let t=/^(widget|host|webview):m\./.exec(e);if(!t)return e;let n=e.slice(t[0].length);return t[1]===`webview`?A(n):`${t[1]}:${D(n)}.${n}`}function ie(e,t){let n=new Set(t.map(H));return[...new Set(e)].filter(e=>{let t=V(e);return t.length>0&&t.every(e=>n.has(H(e)))})}var U=`org.matrix.msc4412`,W=`org.matrix.mscXXXX`,G=`${U}.notify_ready`,K=`${U}.request_capabilities`,ae=`${U}.update_capabilities`,q=`${U}.unknown`,J=`${U}.invalid_request`;`${U}`;var Y={widget:{content_loaded:G,"org.matrix.msc2974.request_capabilities":K,send_event:`${W}.send_event`,send_to_device:`${W}.send_to_device`,get_openid:`${W}.get_openid`,watch_turn_servers:`${W}.watch_turn_servers`,unwatch_turn_servers:`${W}.unwatch_turn_servers`,set_always_on_screen:`${W}.set_always_on_screen`,"org.matrix.msc3973.user_directory_search":`org.matrix.msc3973.search_user_directory`,"org.matrix.msc4533.rtc_livekit_get_token":`org.matrix.msc4533.get_rtc_livekit_token`,"org.matrix.msc4533.rtc_livekit_delegate_delayed_leave":`org.matrix.msc4533.delegate_rtc_livekit_delayed_leave`},host:{notify_capabilities:ae,send_event:`${W}.forward_event`,send_to_device:`${W}.forward_to_device`,update_state:`${W}.update_state`,update_turn_servers:`${W}.update_turn_servers`,theme_change:`${W}.update_theme`,language_change:`${W}.update_language`,visibility:`${W}.update_visibility`}},X=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),oe={widget:X(Y.widget),host:X(Y.host)},se=(e,t)=>Object.hasOwn(e,t)?e[t]:t,ce=(e,t)=>se(Y[t],e),le=(e,t)=>se(oe[t],e),Z=e=>typeof e==`object`&&!!e;function ue(e){return Z(e)&&(e.api===`fromWidget`||e.api===`toWidget`)&&typeof e.widgetId==`string`&&typeof e.requestId==`string`&&typeof e.action==`string`}function de(e){return Z(e)&&(e.source===`widget`||e.source===`host`)&&typeof e.request_id==`string`&&typeof e.action==`string`}function fe(e){let t=e.api===`fromWidget`?`widget`:`host`;return{source:t,request_id:e.requestId,action:ce(e.action,t),request:e.data??{}}}function pe(e,t){return{api:e.source===`host`?`toWidget`:`fromWidget`,widgetId:t,requestId:e.request_id,action:le(e.action,e.source),data:e.request??{}}}function Q(e,t){return{...e,response:t}}function me(e,t){return{source:e.source,request_id:e.request_id,action:e.action,response:t}}var he=e=>({error:{message:e}}),ge=(e,t)=>({error:{code:e,message:t}}),_e=e=>Z(e)&&Z(e.error);function ve(e){if(!Z(e)||!Z(e.error))return e;let{code:t,message:n}=e.error;return{...e,error:{...e.error,code:typeof t==`string`?t:q,message:typeof n==`string`?n:`The widget rejected the request`}}}var ye=`org.matrix.msc4039.upload_file`,be=e=>typeof e==`object`&&!!e&&typeof e.base64==`string`;async function xe(e){let t=e??{};return{...t,file:await Ce(t.file)}}function Se(e){let t=e?.file;return be(t)?{...e,file:we(t)}:e}async function Ce(e){if(be(e))return e;let t=new Response(e),n=new Uint8Array(await t.arrayBuffer()),r=t.headers.get(`content-type`)??void 0;return r?{mimetype:r,base64:Te(n)}:{base64:Te(n)}}function we(e){return new Blob([Ee(e.base64)],e.mimetype?{type:e.mimetype}:void 0)}function Te(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function Ee(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var De=`org.matrix.msc2876.read_events`,Oe=`${W}.read_timeline`,ke=`${W}.paginate_timeline`,Ae=`${W}.notify_timeline_update`,je=1e3,Me=50,Ne=Symbol(`timeout`),Pe=class{o;state=new Map;waiters=new Set;constructor(e){this.o=e}onUpdateState(e){let t=e?.state;if(!Array.isArray(t))return;let n=new Map;for(let e of t)typeof e?.type==`string`&&n.set(e.type,[...n.get(e.type)??[],e]);for(let[e,t]of n)this.state.set(e,t)}onTimelineUpdate(e){let{pagination:t,reset:n}=e??{};if((t===void 0||t.status===`paginating`)&&n!==!0)return;let r={...t?.error===void 0?{}:{error:t.error},...n===!0?{reset:!0}:{}};for(let e of[...this.waiters])e(r)}async read(e){let{type:t,msgtype:n,state_key:r,limit:i,room_ids:a}=e??{};if(typeof t!=`string`||t===``)return he(`Invalid request - missing event type`);if(i!==void 0&&!(typeof i==`number`&&i>0))return he(`Invalid request - limit out of range`);if(!this.servesOwnRoom(a))return{events:[]};let o=typeof i==`number`?Math.min(Math.floor(i),je):void 0;return r===void 0?this.readTimeline(t,typeof n==`string`?n:void 0,o):this.readState(t,r===!0?void 0:String(r),o)}servesOwnRoom(e){if(!Array.isArray(e))return!0;let t=this.o.roomId();return t===void 0||e.includes(t)}readState(e,t,n){if(!this.o.holdsUpdateState(e))return he(`Cannot read state events of this type`);let r=(this.state.get(e)??[]).filter(e=>t===void 0||e.state_key===t);return{events:n===void 0?r:r.slice(0,n)}}async readTimeline(e,t,n){let r=n??je,i=[{type:e,...t===void 0?{}:{msgtype:t}}],a=Date.now()+(this.o.deadlineMs??7e3),o=[],s;for(let e=0;e<Me;e++){let e=await this.within(a,this.o.call(Oe,{...s===void 0?{}:{from:s},limit:r-o.length,filter:i}));if(e===Ne)break;if(_e(e)){if(o.length===0)return e;break}let t=e,c=Array.isArray(t.events)?t.events:[];o.push(...c);let l=c.at(-1)?.event_id;if(typeof l==`string`&&(s=l),o.length>=r||n===void 0||t.pagination===`start_reached`)break;let u=this.nextSettled(a);if(t.pagination!==`paginating`){let e=await this.within(a,this.o.call(ke,{limit:r-o.length})),t=e===Ne||_e(e)?void 0:e.pagination;if(t!==`paginating`){if(u.cancel(),t===`start_reached`)continue;break}}let d=await u.promise;if(d===void 0||d.error!==void 0)break}return{events:o.slice(0,r)}}nextSettled(e){let t,n=new Promise(e=>{t=n=>{this.waiters.delete(t),e(n)},this.waiters.add(t)}),r=()=>{t&&this.waiters.delete(t)};return{promise:this.within(e,n).then(e=>(r(),e===Ne?void 0:e)),cancel:r}}within(e,t){let n,r=new Promise(t=>n=setTimeout(()=>t(Ne),Math.max(0,e-Date.now())));return Promise.race([t,r]).finally(()=>clearTimeout(n))}};function Fe({widgetId:e,matrix:t,client:n,data:r}){return{...Object.fromEntries(Object.entries(r??{}).map(([e,t])=>[e,String(t)])),matrix_user_id:t.user_id??``,matrix_room_id:t.room_id??``,matrix_widget_id:e,matrix_display_name:t.display_name??t.user_id??``,matrix_avatar_url:t.avatar_url??``,"org.matrix.msc3819.matrix_device_id":t.device_id??``,"org.matrix.msc4039.matrix_base_url":t.matrix_base_url??``,"org.matrix.msc2873.client_id":n.client_id??``,"org.matrix.msc2873.client_theme":n.client_theme??``,"org.matrix.msc2873.client_language":n.client_language??``}}function Ie(e,t){let n=Fe(t),r=e.replace(/\$([\w.]+)/g,(e,t)=>t in n?encodeURIComponent(n[t]):e),i=new URL(r);return i.searchParams.has(`widgetId`)||i.searchParams.set(`widgetId`,t.widgetId),i.searchParams.set(`parentUrl`,t.wrapperUrl),i.toString()}var Le=`the URL is not an absolute http: or https: URL`;function Re(e){if(!URL.canParse(e))return Le;let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)return`${t.protocol} URLs are not allowed, only http: and https:`;let n=n=>new URL(e,`${t.protocol}//${n}/`).href===t.href;return n(`a.invalid`)&&n(`b.invalid`)?void 0:Le}function ze(e,t){let n=Re(e);if(n!==void 0)return{problem:n};let r;try{r=Ie(e,t)}catch{return{problem:Le}}let i=Re(r);return i===void 0?{url:new URL(r).href}:{problem:i}}var Be=[`off`,`error`,`warn`,`info`,`debug`],Ve=`[widget-compat-wrapper]`,He=`warn`;function Ue(e){He=e}function We(e){return e===null?`warn`:Be.includes(e)?e:(console.warn(Ve,`unknown log_level "${e}", using "warn"; expected one of ${Be.join(`, `)}`),`warn`)}var Ge=e=>Be.indexOf(e)<=Be.indexOf(He),Ke=e=>(...t)=>{Ge(e)&&console[e](Ve,...t)},$={error:Ke(`error`),warn:Ke(`warn`),info:Ke(`info`),debug:Ke(`debug`)},qe=`${W}.get_matrix_context`,Je=`${W}.get_client_context`,Ye=[O(`get_matrix_context`),O(`get_client_context`),...N],Xe=`get_openid`,Ze=ce(Xe,`widget`),Qe=O(`get_openid`),$e=`${W}.update_state`,et=`openid_credentials`,tt=e=>_e(e)?e.error.code:void 0,nt=e=>{let t=e?.capabilities;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},rt=class{o;fromWidget=new Map;fromHost=new Map;own=new Map;phase=`bootstrap`;readySentToHost=!1;contentLoadedFromWidget=!1;legacyRequested=[];legacyKnown=new Set;held=new Set;openIdWaiting=[];openIdStep=`none`;roomId;reader;constructor(e){this.o=e,this.reader=new Pe({call:(e,t)=>new Promise(n=>this.requestHost(e,t,n)),holdsUpdateState:e=>{let t=k(`update_state:${e}`);return[...this.held].some(e=>e===t||e.startsWith(`${t}#`))},roomId:()=>this.roomId,deadlineMs:e.readDeadlineMs})}start(){this.requestHost(K,{capabilities:Ye})}onIframeLoad(){this.contentLoadedFromWidget=!1,this.o.waitForIframeLoad&&(this.sendReadyOnce(),this.negotiateCapabilities())}onWidgetMessage(e){if(!ue(e)||e.widgetId!==this.o.widgetId)return $.debug(`ignored a message from the inner iframe that is not for this widget`,e);if($.debug(`from widget: ${e.action} (${e.response===void 0?`request`:`response`} ${e.requestId})`),e.response!==void 0)return this.onWidgetResponse(e);e.api===`fromWidget`&&this.onWidgetRequest(e)}onHostMessage(e){if(!de(e))return $.debug(`ignored a message from the host that is not MSC4412`,e);if($.debug(`from host: ${e.action} (${e.response===void 0?`request`:`response`} ${e.request_id})`),e.response!==void 0)return this.onHostResponse(e);e.source===`host`&&this.onHostRequest(e)}bootstrap(){let e={},t={},n=2,r=()=>{if(--n>0)return;let r={widgetId:this.o.widgetId,wrapperUrl:this.o.wrapperUrl,matrix:e,client:t,data:this.o.widgetData},i=ze(this.o.legacyWidgetUrl,r);if(`problem`in i)return this.phase=`refused`,$.error(`refused to load the legacy widget: ${i.problem}`),this.o.refuseWidget(i.problem);this.phase=`running`,typeof e.room_id==`string`&&(this.roomId=e.room_id),this.o.loadWidget(i.url)};this.requestHost(qe,{},t=>(_e(t)||Object.assign(e,t),r())),this.requestHost(Je,{},e=>(_e(e)||Object.assign(t,e),r()))}onWidgetRequest(e){switch(e.action){case`supported_api_versions`:return this.o.sendToWidget(Q(e,{supported_versions:this.o.supportedVersions??T.CurrentApiVersions}));case`content_loaded`:return this.onWidgetContentLoaded(e);case Xe:return this.onWidgetGetOpenId(e);case De:this.reader.read(e.data).then(t=>this.o.sendToWidget(Q(e,t)));return;case ye:xe(e.data).then(t=>this.forwardToHost(e,t),t=>this.o.sendToWidget(Q(e,he(`Could not read the file: ${String(t)}`))));return;default:if(ce(e.action,`widget`)===`org.matrix.msc4412.request_capabilities`)return this.forwardToHost(e,{capabilities:this.translateRequested(nt(e.data))});this.forwardToHost(e)}}forwardToHost(e,t=e.data){this.fromWidget.set(e.requestId,e),this.o.sendToHost(fe({...e,data:t}))}onWidgetContentLoaded(e){if(this.contentLoadedFromWidget)return this.o.sendToWidget(Q(e,he(`Improper sequence: ContentLoaded Action can only be sent once`)));if(this.contentLoadedFromWidget=!0,this.o.waitForIframeLoad)return this.o.sendToWidget(Q(e,he(`Improper sequence: not expecting ContentLoaded event`)));this.o.sendToWidget(Q(e,{})),this.sendReadyOnce(),this.negotiateCapabilities()}onHostResponse(e){if(this.answerOwnRequest(e.request_id,e.response))return;let t=this.fromWidget.get(e.request_id);if(!t)return $.warn(`dropped the host's response to ${e.action}: no request with id ${e.request_id}`);this.fromWidget.delete(e.request_id);let n=t.action===`org.matrix.msc4039.download_file`?Se(e.response):e.response;this.o.sendToWidget(Q(t,n))}onHostRequest(e){if(e.action===Ae)return this.o.sendToHost(me(e,{})),this.reader.onTimelineUpdate(e.request);if(this.phase===`refused`)return $.warn(`refused ${e.action} from the host: the legacy widget's URL was refused`),this.o.sendToHost(me(e,ge(J,`The wrapped widget's URL was refused`)));if(this.phase===`bootstrap`){if(e.action!==`org.matrix.msc4412.update_capabilities`){$.warn(`refused ${e.action} from the host: the wrapped widget is not loaded yet`);let t=ge(J,`The wrapped widget is not loaded yet`);return this.o.sendToHost(me(e,t))}return this.o.sendToHost(me(e,{})),this.rememberAllowed(e.request),this.bootstrap()}e.action===$e&&this.reader.onUpdateState(e.request),this.fromHost.set(e.request_id,e);let t=e.action===`org.matrix.msc4412.update_capabilities`?this.translateUpdate(e.request):e.request;this.o.sendToWidget(pe({...e,request:t},this.o.widgetId)),e.action===`org.matrix.msc4412.update_capabilities`&&this.openIdStep===`acked`&&this.onOpenIdCapabilityAnswered()}onWidgetResponse(e){if(this.answerOwnRequest(e.requestId,e.response))return;let t=this.fromHost.get(e.requestId);if(!t)return $.warn(`dropped the widget's response to ${e.action}: no request with id ${e.requestId}`);this.fromHost.delete(e.requestId),this.o.sendToHost(me(t,ve(e.response)))}sendReadyOnce(){this.readySentToHost||(this.readySentToHost=!0,this.requestHost(G,{}))}negotiateCapabilities(){this.requestWidget(`capabilities`,{},e=>{let t=this.translateRequested(nt(e));this.requestHost(K,{capabilities:t})})}translateRequested(e){this.legacyRequested=e;for(let t of e)this.legacyKnown.add(t);return re(e)}translateUpdate(e){return this.rememberAllowed(e),{requested:this.legacyRequested,approved:ie([...this.legacyKnown],[...this.held])}}rememberAllowed(e){let t=e?.allowed;this.held=new Set((Array.isArray(t)?t:[]).filter(e=>typeof e==`string`).map(H))}onWidgetGetOpenId(e){if(this.openIdWaiting.length>0||!this.held.has(Qe))return this.waitForOpenId(e);this.requestHost(Ze,{},t=>{if(tt(t)===`org.matrix.msc4412.missing_capability`)return this.waitForOpenId(e);this.o.sendToWidget(Q(e,_e(t)?t:{state:`allowed`,...t}))})}waitForOpenId(e){this.o.sendToWidget(Q(e,{state:`request`})),this.openIdWaiting.push(e),this.openIdStep===`none`&&(this.openIdStep=`sent`,this.requestHost(K,{capabilities:[Qe]},e=>{if(_e(e))return this.finishOpenId(void 0);this.openIdStep=`acked`}))}onOpenIdCapabilityAnswered(){if(!this.held.has(Qe))return this.finishOpenId(void 0);this.openIdStep=`fetching`,this.requestHost(Ze,{},e=>this.finishOpenId(_e(e)?void 0:e))}finishOpenId(e){let t=this.openIdWaiting;this.openIdWaiting=[],this.openIdStep=`none`,e||$.warn(`no OpenID token for ${t.length} request(s) of the widget`);for(let n of t){let t=e?{state:`allowed`,original_request_id:n.requestId,...e}:{state:`blocked`,original_request_id:n.requestId};this.requestWidget(et,t,()=>{})}}requestHost(e,t,n=()=>{}){let r=this.nextId();this.own.set(r,n),this.o.sendToHost({source:`widget`,request_id:r,action:e,request:t})}requestWidget(e,t,n){let r=this.nextId();this.own.set(r,n),this.o.sendToWidget({api:`toWidget`,widgetId:this.o.widgetId,requestId:r,action:e,data:t})}answerOwnRequest(e,t){let n=this.own.get(e);return n?(this.own.delete(e),n(t),!0):!1}nextId(){return this.o.nextId?this.o.nextId():crypto.randomUUID()}},it=j.join(` `),at=M.join(`; `);function ot(e,t){let n=new URL(e).origin;return n===t?{sandbox:j.filter(e=>e!==`allow-same-origin`).join(` `),allow:at,targetOrigin:`*`}:{sandbox:it,allow:at,targetOrigin:n}}function st(e){let t=e.get(`legacy_widget_url`);if(!t)throw Error("missing `legacy_widget_url` query parameter");let n=Re(t);if(n)throw Error(`refused \`legacy_widget_url\`: ${n}`);let r=e.get(`legacy_widget_id`)??new URL(t).searchParams.get(`widgetId`);if(!r)throw Error("missing `legacy_widget_id` (and no `widgetId` in the legacy url)");let i=e.get(`legacy_widget_data`);return{legacyWidgetUrl:t,widgetId:r,widgetName:e.get(`legacy_widget_name`)??r,waitForIframeLoad:e.get(`legacy_wait_for_iframe_load`)!==`false`,widgetData:i?JSON.parse(i):void 0,clientOrigin:e.get(`client_origin`)??`*`,logLevel:We(e.get(`log_level`))}}function ct(e,t=document.body){let n=document.createElement(`div`);n.id=`error`,n.textContent=`Widget compat wrapper: ${e}`,t.append(n)}function lt(e,t,n=window.parent){Ue(e.logLevel),$.info(`wrapping legacy widget ${e.widgetId}`);let r,i=`*`,a=new rt({widgetId:e.widgetId,waitForIframeLoad:e.waitForIframeLoad,legacyWidgetUrl:e.legacyWidgetUrl,widgetData:e.widgetData,wrapperUrl:location.origin+location.pathname,sendToHost:t=>n.postMessage(t,e.clientOrigin),sendToWidget:e=>r?.contentWindow?.postMessage(e,i),loadWidget:n=>{let o=ot(n,location.origin);i=o.targetOrigin,$.info(`loading the legacy widget from ${new URL(n).origin}${i===`*`?` (the wrapper's own origin: without allow-same-origin)`:``}`),r=document.createElement(`iframe`),r.setAttribute(`sandbox`,o.sandbox),r.allow=o.allow,r.title=e.widgetName,r.addEventListener(`load`,()=>a.onIframeLoad()),r.src=n,t.append(r)},refuseWidget:e=>ct(`refused to load the legacy widget: ${e}`,t)});return window.addEventListener(`message`,e=>{e.source===n?a.onHostMessage(e.data):r&&e.source===r.contentWindow&&a.onWidgetMessage(e.data)}),a.start(),a}try{if(window.parent===window)throw Error(`the compat wrapper must be embedded by a widget host`);lt(st(new URLSearchParams(location.search)),document.body)}catch(e){console.error(`[widget-compat-wrapper] could not start:`,e),ct(e.message)}
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Widget compat wrapper</title>
7
+ <style>html,body{background:#fff;height:100%;margin:0}iframe{border:0;width:100%;height:100%;display:block}#error{color:#b00020;white-space:pre-wrap;padding:16px;font:14px system-ui}</style>
8
+ <script type="module" crossorigin src="./assets/index-BfNOkYpg.js"></script>
9
+ </head>
10
+ <body>
11
+ </body>
12
+ </html>
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@matrix-widget-sdk/compat-wrapper",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Static page that wraps a legacy (matrix-widget-api) widget and speaks MSC4412 to the host. Serve dist/ under the client's own origin.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/toger5/matrix-widget-sdk.git",
9
+ "directory": "packages/widget-compat-wrapper"
10
+ },
11
+ "homepage": "https://github.com/toger5/matrix-widget-sdk/tree/main/packages/widget-compat-wrapper#readme",
12
+ "bugs": "https://github.com/toger5/matrix-widget-sdk/issues",
13
+ "type": "module",
14
+ "keywords": [
15
+ "matrix",
16
+ "widget",
17
+ "msc4412",
18
+ "matrix-widget-api"
19
+ ],
20
+ "exports": {
21
+ "./*": "./dist/*",
22
+ "./package.json": "./package.json"
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "README.md"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ }
31
+ }