@lavitre/apps 1.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +121 -0
  3. package/dist/Common/AiChannel.d.ts +59 -0
  4. package/dist/Common/AiChannel.js +97 -0
  5. package/dist/Common/AiChannel.js.map +1 -0
  6. package/dist/Common/BlobStore.d.ts +44 -0
  7. package/dist/Common/BlobStore.js +186 -0
  8. package/dist/Common/BlobStore.js.map +1 -0
  9. package/dist/Common/Common.Model.d.ts +1020 -0
  10. package/dist/Common/Common.Model.js +21 -0
  11. package/dist/Common/Common.Model.js.map +1 -0
  12. package/dist/Common/CrdtChannel.d.ts +198 -0
  13. package/dist/Common/CrdtChannel.js +659 -0
  14. package/dist/Common/CrdtChannel.js.map +1 -0
  15. package/dist/Common/Version.d.ts +21 -0
  16. package/dist/Common/Version.js +62 -0
  17. package/dist/Common/Version.js.map +1 -0
  18. package/dist/Common/index.d.ts +6 -0
  19. package/dist/Common/index.js +32 -0
  20. package/dist/Common/index.js.map +1 -0
  21. package/dist/CompanionConnector/CompanionConnector.Model.d.ts +85 -0
  22. package/dist/CompanionConnector/CompanionConnector.Model.js +17 -0
  23. package/dist/CompanionConnector/CompanionConnector.Model.js.map +1 -0
  24. package/dist/CompanionConnector/CompanionConnector.d.ts +28 -0
  25. package/dist/CompanionConnector/CompanionConnector.js +385 -0
  26. package/dist/CompanionConnector/CompanionConnector.js.map +1 -0
  27. package/dist/CompanionConnector/index.d.ts +2 -0
  28. package/dist/CompanionConnector/index.js +3 -0
  29. package/dist/CompanionConnector/index.js.map +1 -0
  30. package/dist/CompanionFrame/CompanionFrame.d.ts +103 -0
  31. package/dist/CompanionFrame/CompanionFrame.js +100 -0
  32. package/dist/CompanionFrame/CompanionFrame.js.map +1 -0
  33. package/dist/CompanionFrame/index.d.ts +1 -0
  34. package/dist/CompanionFrame/index.js +2 -0
  35. package/dist/CompanionFrame/index.js.map +1 -0
  36. package/dist/Connector/Connector.Model.d.ts +567 -0
  37. package/dist/Connector/Connector.Model.js +2 -0
  38. package/dist/Connector/Connector.Model.js.map +1 -0
  39. package/dist/Connector/Connector.d.ts +227 -0
  40. package/dist/Connector/Connector.js +1337 -0
  41. package/dist/Connector/Connector.js.map +1 -0
  42. package/dist/Connector/index.d.ts +2 -0
  43. package/dist/Connector/index.js +3 -0
  44. package/dist/Connector/index.js.map +1 -0
  45. package/dist/Frame/Frame.Model.d.ts +533 -0
  46. package/dist/Frame/Frame.Model.js +2 -0
  47. package/dist/Frame/Frame.Model.js.map +1 -0
  48. package/dist/Frame/Frame.d.ts +309 -0
  49. package/dist/Frame/Frame.js +1408 -0
  50. package/dist/Frame/Frame.js.map +1 -0
  51. package/dist/Frame/SyncAdapter.d.ts +75 -0
  52. package/dist/Frame/SyncAdapter.js +134 -0
  53. package/dist/Frame/SyncAdapter.js.map +1 -0
  54. package/dist/Frame/index.d.ts +3 -0
  55. package/dist/Frame/index.js +4 -0
  56. package/dist/Frame/index.js.map +1 -0
  57. package/dist/MediaLink/MediaLink.d.ts +178 -0
  58. package/dist/MediaLink/MediaLink.js +1432 -0
  59. package/dist/MediaLink/MediaLink.js.map +1 -0
  60. package/dist/MediaLink/index.d.ts +1 -0
  61. package/dist/MediaLink/index.js +2 -0
  62. package/dist/MediaLink/index.js.map +1 -0
  63. package/dist/Native/index.d.ts +170 -0
  64. package/dist/Native/index.js +19 -0
  65. package/dist/Native/index.js.map +1 -0
  66. package/dist/Version.d.ts +1 -0
  67. package/dist/Version.js +2 -0
  68. package/dist/Version.js.map +1 -0
  69. package/package.json +76 -0
@@ -0,0 +1,1337 @@
1
+ /// <reference path="./insertable-streams.d.ts" />
2
+ import { v4 as uuid } from 'uuid';
3
+ import { CrdtChannel, MIN_CRDT_HOST_VERSION } from '../Common/CrdtChannel.js';
4
+ import { BlobStore } from '../Common/BlobStore.js';
5
+ import { isMinVersion } from '../Common/index.js';
6
+ import { apiVersion } from '../Version.js';
7
+ export class Connector {
8
+ /** @deprecated Use `crdt.doc`. The setter forwards to `crdt.attach(doc)`
9
+ * so legacy callers that ever assigned `connector.yjsDoc = myDoc` keep
10
+ * working — without it, getter-only would throw `TypeError: Cannot set
11
+ * property yjsDoc which has only a getter` under strict mode / ESM. */
12
+ get yjsDoc() {
13
+ return this.crdt.doc;
14
+ }
15
+ set yjsDoc(doc) {
16
+ this.crdt.attach(doc);
17
+ }
18
+ constructor(postMessage, initMessage, options) {
19
+ Object.defineProperty(this, "postMessage", {
20
+ enumerable: true,
21
+ configurable: true,
22
+ writable: true,
23
+ value: postMessage
24
+ });
25
+ Object.defineProperty(this, "options", {
26
+ enumerable: true,
27
+ configurable: true,
28
+ writable: true,
29
+ value: options
30
+ });
31
+ Object.defineProperty(this, "onDeviceJoined", {
32
+ enumerable: true,
33
+ configurable: true,
34
+ writable: true,
35
+ value: void 0
36
+ });
37
+ Object.defineProperty(this, "onDeviceLeft", {
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true,
41
+ value: void 0
42
+ });
43
+ Object.defineProperty(this, "onDeviceMessageReceived", {
44
+ enumerable: true,
45
+ configurable: true,
46
+ writable: true,
47
+ value: void 0
48
+ });
49
+ Object.defineProperty(this, "onMenuClicked", {
50
+ enumerable: true,
51
+ configurable: true,
52
+ writable: true,
53
+ value: void 0
54
+ });
55
+ Object.defineProperty(this, "onFieldUpdated", {
56
+ enumerable: true,
57
+ configurable: true,
58
+ writable: true,
59
+ value: void 0
60
+ });
61
+ Object.defineProperty(this, "onFrameConnectorLoading", {
62
+ enumerable: true,
63
+ configurable: true,
64
+ writable: true,
65
+ value: void 0
66
+ });
67
+ Object.defineProperty(this, "onShareDataReceived", {
68
+ enumerable: true,
69
+ configurable: true,
70
+ writable: true,
71
+ value: void 0
72
+ });
73
+ Object.defineProperty(this, "onShareFileReceived", {
74
+ enumerable: true,
75
+ configurable: true,
76
+ writable: true,
77
+ value: void 0
78
+ });
79
+ Object.defineProperty(this, "onFrameLoaded", {
80
+ enumerable: true,
81
+ configurable: true,
82
+ writable: true,
83
+ value: void 0
84
+ });
85
+ Object.defineProperty(this, "onFrameConnectorLoaded", {
86
+ enumerable: true,
87
+ configurable: true,
88
+ writable: true,
89
+ value: void 0
90
+ });
91
+ Object.defineProperty(this, "onFrameUnloaded", {
92
+ enumerable: true,
93
+ configurable: true,
94
+ writable: true,
95
+ value: void 0
96
+ });
97
+ Object.defineProperty(this, "onLocalConnectorMessageReceived", {
98
+ enumerable: true,
99
+ configurable: true,
100
+ writable: true,
101
+ value: void 0
102
+ });
103
+ Object.defineProperty(this, "onPrivacyChanged", {
104
+ enumerable: true,
105
+ configurable: true,
106
+ writable: true,
107
+ value: void 0
108
+ });
109
+ /** @deprecated Use onEmbedMessage */
110
+ Object.defineProperty(this, "onExtensionMessage", {
111
+ enumerable: true,
112
+ configurable: true,
113
+ writable: true,
114
+ value: void 0
115
+ });
116
+ /** @deprecated Use onEmbedMessage */
117
+ Object.defineProperty(this, "onAppMessage", {
118
+ enumerable: true,
119
+ configurable: true,
120
+ writable: true,
121
+ value: void 0
122
+ });
123
+ Object.defineProperty(this, "onEmbedMessage", {
124
+ enumerable: true,
125
+ configurable: true,
126
+ writable: true,
127
+ value: void 0
128
+ });
129
+ Object.defineProperty(this, "onKnockKnockReceived", {
130
+ enumerable: true,
131
+ configurable: true,
132
+ writable: true,
133
+ value: void 0
134
+ });
135
+ Object.defineProperty(this, "onPendingDevicesConnectionRequested", {
136
+ enumerable: true,
137
+ configurable: true,
138
+ writable: true,
139
+ value: void 0
140
+ });
141
+ Object.defineProperty(this, "onSettingsUpdated", {
142
+ enumerable: true,
143
+ configurable: true,
144
+ writable: true,
145
+ value: void 0
146
+ });
147
+ Object.defineProperty(this, "onVitreSettingsUpdated", {
148
+ enumerable: true,
149
+ configurable: true,
150
+ writable: true,
151
+ value: void 0
152
+ });
153
+ Object.defineProperty(this, "onConnectionCodeUpdated", {
154
+ enumerable: true,
155
+ configurable: true,
156
+ writable: true,
157
+ value: void 0
158
+ });
159
+ Object.defineProperty(this, "onNotificationDismissed", {
160
+ enumerable: true,
161
+ configurable: true,
162
+ writable: true,
163
+ value: void 0
164
+ });
165
+ Object.defineProperty(this, "onNotificationButtonClicked", {
166
+ enumerable: true,
167
+ configurable: true,
168
+ writable: true,
169
+ value: void 0
170
+ });
171
+ Object.defineProperty(this, "onDevicePrivacyChanged", {
172
+ enumerable: true,
173
+ configurable: true,
174
+ writable: true,
175
+ value: void 0
176
+ });
177
+ Object.defineProperty(this, "onFrameZIndexChanged", {
178
+ enumerable: true,
179
+ configurable: true,
180
+ writable: true,
181
+ value: void 0
182
+ });
183
+ Object.defineProperty(this, "onDeviceFrameLoaded", {
184
+ enumerable: true,
185
+ configurable: true,
186
+ writable: true,
187
+ value: void 0
188
+ });
189
+ Object.defineProperty(this, "onDeviceFrameConnectorLoaded", {
190
+ enumerable: true,
191
+ configurable: true,
192
+ writable: true,
193
+ value: void 0
194
+ });
195
+ Object.defineProperty(this, "onDeviceFrameUnloaded", {
196
+ enumerable: true,
197
+ configurable: true,
198
+ writable: true,
199
+ value: void 0
200
+ });
201
+ Object.defineProperty(this, "onMessageReceived", {
202
+ enumerable: true,
203
+ configurable: true,
204
+ writable: true,
205
+ value: void 0
206
+ });
207
+ Object.defineProperty(this, "onVoiceActionDetected", {
208
+ enumerable: true,
209
+ configurable: true,
210
+ writable: true,
211
+ value: void 0
212
+ });
213
+ Object.defineProperty(this, "onDeviceFullscreenUpdated", {
214
+ enumerable: true,
215
+ configurable: true,
216
+ writable: true,
217
+ value: void 0
218
+ });
219
+ Object.defineProperty(this, "onDeviceScalingUpdated", {
220
+ enumerable: true,
221
+ configurable: true,
222
+ writable: true,
223
+ value: void 0
224
+ });
225
+ Object.defineProperty(this, "onFramePositionUpdated", {
226
+ enumerable: true,
227
+ configurable: true,
228
+ writable: true,
229
+ value: void 0
230
+ });
231
+ Object.defineProperty(this, "onStateReplaced", {
232
+ enumerable: true,
233
+ configurable: true,
234
+ writable: true,
235
+ value: void 0
236
+ });
237
+ Object.defineProperty(this, "onExternalMessageReceived", {
238
+ enumerable: true,
239
+ configurable: true,
240
+ writable: true,
241
+ value: void 0
242
+ });
243
+ Object.defineProperty(this, "onAppTokenRefreshed", {
244
+ enumerable: true,
245
+ configurable: true,
246
+ writable: true,
247
+ value: void 0
248
+ });
249
+ Object.defineProperty(this, "onMediaDevicesChanged", {
250
+ enumerable: true,
251
+ configurable: true,
252
+ writable: true,
253
+ value: void 0
254
+ });
255
+ /// Called when an already-open shared frame's owner is reassigned via
256
+ /// `setFrameOwner` — INCLUDING a change initiated by another device in the
257
+ /// space (every vitre/companion running this app is notified). The owner
258
+ /// drives the languette colour and (when a Vitre) hosting/survival, and is
259
+ /// what an app should key its per-frame stored state on. `owner` is the new
260
+ /// owner's device id (`HostInformation.devicesInSpace[].id`). Not fired for
261
+ /// the initial open: a frame opened with `OpenFrameOptions.owner` is created
262
+ /// already-owned, so the opener already knows its owner.
263
+ Object.defineProperty(this, "onFrameOwnerChanged", {
264
+ enumerable: true,
265
+ configurable: true,
266
+ writable: true,
267
+ value: void 0
268
+ });
269
+ /// Called when the companion-side `CompanionConnector` for the same
270
+ /// `appId` sent a message via `sendMessageToVitreConnector`. The
271
+ /// `fromCompanionId` identifies which companion sent it so the Vitre
272
+ /// connector can reply targeted-back via `sendMessageToCompanionConnector`.
273
+ Object.defineProperty(this, "onMessageFromCompanionConnector", {
274
+ enumerable: true,
275
+ configurable: true,
276
+ writable: true,
277
+ value: void 0
278
+ });
279
+ /// Called when a companion FRAME of this app sent a message via
280
+ /// `CompanionFrame.sendMessageToVitreConnector` — including a local
281
+ /// companion frame with no paired Vitre frame. `frameConnectorId` is the
282
+ /// companion frame that spoke; `fromCompanionId` is the companion. Reply
283
+ /// targeted-back via `sendMessageToCompanionConnector`.
284
+ Object.defineProperty(this, "onMessageFromCompanionFrame", {
285
+ enumerable: true,
286
+ configurable: true,
287
+ writable: true,
288
+ value: void 0
289
+ });
290
+ /// Called when a companion clicked a menu entry that lives on one of
291
+ /// THIS app's frames' options menu AND was declared with
292
+ /// `availability: 'companion'` (or `'companionAdmin'`). The click never
293
+ /// reaches the Vitre-side UI — it is intercepted on the companion and
294
+ /// routed here so the app can decide what to do (typically: dispatch
295
+ /// the companion's main connector to call `openCompanionFrame` for the
296
+ /// matching frame).
297
+ ///
298
+ /// `frameConnectorId` is the frame whose menu entry was clicked.
299
+ /// `fromCompanionId` is the connection-id of the clicker so the app
300
+ /// can target a targeted reply back. The remaining fields mirror the
301
+ /// regular `onMenuClicked` shape.
302
+ Object.defineProperty(this, "onFrameMenuClickedOnCompanion", {
303
+ enumerable: true,
304
+ configurable: true,
305
+ writable: true,
306
+ value: void 0
307
+ });
308
+ /** @deprecated Use `crdt.onSynced` */
309
+ Object.defineProperty(this, "onYjsSynced", {
310
+ enumerable: true,
311
+ configurable: true,
312
+ writable: true,
313
+ value: void 0
314
+ });
315
+ /** @deprecated Subscribe via `crdt.doc.on('update', ...)` instead. */
316
+ Object.defineProperty(this, "onYjsUpdate", {
317
+ enumerable: true,
318
+ configurable: true,
319
+ writable: true,
320
+ value: void 0
321
+ });
322
+ Object.defineProperty(this, "appId", {
323
+ enumerable: true,
324
+ configurable: true,
325
+ writable: true,
326
+ value: void 0
327
+ });
328
+ Object.defineProperty(this, "hostInformation", {
329
+ enumerable: true,
330
+ configurable: true,
331
+ writable: true,
332
+ value: void 0
333
+ });
334
+ Object.defineProperty(this, "openedFrames", {
335
+ enumerable: true,
336
+ configurable: true,
337
+ writable: true,
338
+ value: []
339
+ });
340
+ Object.defineProperty(this, "state", {
341
+ enumerable: true,
342
+ configurable: true,
343
+ writable: true,
344
+ value: {}
345
+ });
346
+ Object.defineProperty(this, "appToken", {
347
+ enumerable: true,
348
+ configurable: true,
349
+ writable: true,
350
+ value: null
351
+ });
352
+ Object.defineProperty(this, "appTokenRefreshTimer", {
353
+ enumerable: true,
354
+ configurable: true,
355
+ writable: true,
356
+ value: null
357
+ });
358
+ /**
359
+ * CRDT channel — Yjs doc + Awareness piped over the la Vitre transport.
360
+ * Libraries (Carbone, …) can call `crdt.attach(doc, awareness)` to bring
361
+ * their own; simple apps use `crdt.doc` / `crdt.awareness` directly.
362
+ */
363
+ Object.defineProperty(this, "crdt", {
364
+ enumerable: true,
365
+ configurable: true,
366
+ writable: true,
367
+ value: void 0
368
+ });
369
+ /**
370
+ * CRDT-backed blob store built on `crdt.attachSubdoc`. `put` / `get` /
371
+ * `list` / `onProgress` for heavy binaries (images, PDFs, 3D, …) that
372
+ * must be retrievable by anyone joining the doc, even late. Opinionated
373
+ * but bare — see BlobStore.
374
+ */
375
+ Object.defineProperty(this, "blobs", {
376
+ enumerable: true,
377
+ configurable: true,
378
+ writable: true,
379
+ value: void 0
380
+ });
381
+ Object.defineProperty(this, "requestResolvers", {
382
+ enumerable: true,
383
+ configurable: true,
384
+ writable: true,
385
+ value: []
386
+ });
387
+ this.hostInformation = initMessage.hostInfo;
388
+ this.appId = initMessage.appId ?? '';
389
+ this.state = initMessage.state ?? {};
390
+ // Mirror the first of `shareTargets` onto the deprecated singular `shareTarget`
391
+ // so older Vitres (which only read `shareTarget`) still get the primary target.
392
+ // New hosts prefer `shareTargets` and ignore the mirrored singular.
393
+ this.options = {
394
+ ...options,
395
+ shareTarget: options.shareTarget ??
396
+ (options.shareTargets?.length ? options.shareTargets[0] : undefined),
397
+ };
398
+ this.postMessage({
399
+ type: 'connectorInitialized',
400
+ options: this.options,
401
+ });
402
+ // Older Vitres reject unknown message types and fail the whole parse,
403
+ // so never emit `crdt*` toward a host below the supported version. The
404
+ // channel still constructs and works locally; emission is just dropped
405
+ // (graceful degradation — onSynced never fires on old hosts, by design).
406
+ const crdtSupported = isMinVersion(this.hostInformation.version, MIN_CRDT_HOST_VERSION);
407
+ this.crdt = new CrdtChannel((message, transfer) => {
408
+ // No cast: `ConnectorApiMessagesOut` already includes the four `crdt*`
409
+ // arms (Connector.Model.ts), so the union narrows naturally and TS
410
+ // will flag any drift between the two definitions.
411
+ if (!crdtSupported)
412
+ return;
413
+ this.postMessage(message, transfer);
414
+ });
415
+ this.crdt.onSynced(() => this.onYjsSynced?.());
416
+ this.crdt.onUpdate((update) => this.onYjsUpdate?.(update));
417
+ this.blobs = new BlobStore(this.crdt);
418
+ }
419
+ resolveRequest(msg) {
420
+ this.requestResolvers = this.requestResolvers.filter((rr) => !rr.isHandled(msg));
421
+ }
422
+ raiseMessage(msg) {
423
+ this.resolveRequest(msg);
424
+ switch (msg.type) {
425
+ case 'privacyChanged':
426
+ this.hostInformation = {
427
+ ...this.hostInformation,
428
+ device: { ...this.hostInformation.device, privacy: msg.privacy },
429
+ };
430
+ this.onPrivacyChanged?.(msg.privacy);
431
+ break;
432
+ case 'deviceJoined':
433
+ this.hostInformation = {
434
+ ...this.hostInformation,
435
+ devicesInSpace: [
436
+ ...this.hostInformation.devicesInSpace.filter((d) => d.id !== msg.device.id),
437
+ msg.device,
438
+ ],
439
+ };
440
+ this.onDeviceJoined?.(msg.device);
441
+ break;
442
+ case 'deviceLeft':
443
+ this.hostInformation = {
444
+ ...this.hostInformation,
445
+ devicesInSpace: this.hostInformation.devicesInSpace.filter((d) => d.id !== msg.deviceId),
446
+ };
447
+ this.onDeviceLeft?.(msg.deviceId);
448
+ break;
449
+ case 'deviceMessageReceived':
450
+ this.onDeviceMessageReceived?.(msg);
451
+ break;
452
+ case 'menuClicked':
453
+ this.onMenuClicked?.(msg.menuId, msg.tag, msg.isChecked);
454
+ break;
455
+ case 'fieldUpdated':
456
+ this.onFieldUpdated?.(msg.field);
457
+ break;
458
+ case 'frameConnectorLoading':
459
+ this.onFrameConnectorLoading?.(msg.options);
460
+ break;
461
+ case 'shareDataReceived':
462
+ this.onShareDataReceived?.(msg.data);
463
+ break;
464
+ case 'fileShareDataReceived':
465
+ this.onShareFileReceived?.(msg.data);
466
+ break;
467
+ case 'frameLoaded':
468
+ this.openedFrames.push(msg);
469
+ this.onFrameLoaded?.(msg.frameConnectorId);
470
+ break;
471
+ case 'frameConnectorLoaded':
472
+ {
473
+ const idx = this.openedFrames.findIndex((f) => f.frameConnectorId === msg.frameConnectorId);
474
+ if (idx >= 0) {
475
+ this.openedFrames[idx] = msg;
476
+ }
477
+ this.onFrameConnectorLoaded?.(msg.frameConnectorId);
478
+ }
479
+ break;
480
+ case 'frameUnloaded':
481
+ {
482
+ const idx = this.openedFrames.findIndex((f) => f.frameConnectorId === msg.frameConnectorId);
483
+ if (idx >= 0) {
484
+ this.openedFrames.splice(idx, 1);
485
+ }
486
+ this.onFrameUnloaded?.(msg.frameConnectorId);
487
+ }
488
+ break;
489
+ case 'localConnectorMessageReceived':
490
+ this.onLocalConnectorMessageReceived?.(msg.data, msg.from, msg.fileData);
491
+ break;
492
+ case 'extensionMessage':
493
+ this.onExtensionMessage?.(msg);
494
+ this.onAppMessage?.(msg);
495
+ this.onEmbedMessage?.(msg);
496
+ break;
497
+ case 'appMessage':
498
+ this.onAppMessage?.(msg);
499
+ this.onEmbedMessage?.(msg);
500
+ break;
501
+ case 'knockKnockReceived':
502
+ this.onKnockKnockReceived?.(msg);
503
+ break;
504
+ case 'pendingDevicesConnectionRequested':
505
+ this.onPendingDevicesConnectionRequested?.(msg.pendingDevices);
506
+ break;
507
+ case 'settingsUpdated':
508
+ this.hostInformation = {
509
+ ...this.hostInformation,
510
+ settings: msg.settings,
511
+ };
512
+ this.onSettingsUpdated?.(msg.settings);
513
+ break;
514
+ case 'vitreSettingsUpdated':
515
+ this.hostInformation = {
516
+ ...this.hostInformation,
517
+ space: msg.currentSpace,
518
+ vitreSettings: msg,
519
+ device: {
520
+ ...this.hostInformation.device,
521
+ name: msg.name ?? this.hostInformation.device.name,
522
+ color: msg.color,
523
+ },
524
+ };
525
+ this.onVitreSettingsUpdated?.(msg);
526
+ break;
527
+ case 'notificationButtonClicked':
528
+ this.onNotificationButtonClicked?.(msg);
529
+ break;
530
+ case 'notificationDismissed':
531
+ this.onNotificationDismissed?.(msg.id);
532
+ break;
533
+ case 'devicePrivacyChanged':
534
+ this.hostInformation = {
535
+ ...this.hostInformation,
536
+ devicesInSpace: [
537
+ ...this.hostInformation.devicesInSpace.filter((d) => d.id !== msg.device.id),
538
+ msg.device,
539
+ ],
540
+ };
541
+ this.onDevicePrivacyChanged?.(msg.device);
542
+ break;
543
+ case 'frameZIndexChanged':
544
+ {
545
+ const idx = this.openedFrames.findIndex((f) => f.frameConnectorId === msg.frameConnectorId);
546
+ if (idx >= 0) {
547
+ this.openedFrames[idx] = msg;
548
+ }
549
+ this.onFrameZIndexChanged?.(msg);
550
+ }
551
+ break;
552
+ case 'deviceFrameLoaded':
553
+ this.onDeviceFrameLoaded?.(msg);
554
+ break;
555
+ case 'deviceFrameUnloaded':
556
+ this.onDeviceFrameUnloaded?.(msg);
557
+ break;
558
+ case 'deviceFrameConnectorLoaded':
559
+ this.onDeviceFrameConnectorLoaded?.(msg);
560
+ break;
561
+ case 'voiceActionDetected':
562
+ this.onVoiceActionDetected?.(msg);
563
+ break;
564
+ case 'deviceFullscreenUpdated':
565
+ this.onDeviceFullscreenUpdated?.(msg);
566
+ break;
567
+ case 'framePositionUpdated':
568
+ this.onFramePositionUpdated?.(msg);
569
+ break;
570
+ case 'deviceScalingUpdated':
571
+ if (msg.deviceId === this.hostInformation.device.id) {
572
+ this.hostInformation.device.sendingScaling = msg.sendingScaling;
573
+ this.hostInformation.device.orientation = msg.orientation;
574
+ this.hostInformation.device.orientationBy = msg.orientationBy;
575
+ }
576
+ this.hostInformation.devicesInSpace =
577
+ this.hostInformation.devicesInSpace.map((d) => d.id === msg.deviceId
578
+ ? {
579
+ ...d,
580
+ sendingScaling: msg.sendingScaling,
581
+ orientation: msg.orientation,
582
+ orientationBy: msg.orientationBy,
583
+ }
584
+ : d);
585
+ this.onDeviceScalingUpdated?.(msg);
586
+ break;
587
+ case 'connectionCodeUpdated':
588
+ this.hostInformation = {
589
+ ...this.hostInformation,
590
+ companionCode: msg.companionCode,
591
+ };
592
+ this.onConnectionCodeUpdated?.(msg.companionCode);
593
+ break;
594
+ case 'stateReplaced':
595
+ this._onStateReplaced(msg);
596
+ break;
597
+ case 'externalMessageReceived':
598
+ this._onExternalMessageReceived(msg);
599
+ break;
600
+ case 'appTokenReceived':
601
+ // Handled by requestResolvers (postRequest pattern)
602
+ break;
603
+ case 'mediaDevicesChanged':
604
+ this.hostInformation = {
605
+ ...this.hostInformation,
606
+ vitreSettings: {
607
+ ...this.hostInformation.vitreSettings,
608
+ availableMediaDevices: msg.devices,
609
+ },
610
+ };
611
+ this.onMediaDevicesChanged?.(msg.devices);
612
+ break;
613
+ case 'crdtUpdate':
614
+ case 'crdtSyncComplete':
615
+ case 'crdtRequestSync':
616
+ case 'crdtAwarenessUpdate':
617
+ case 'crdtSubdocUpdate':
618
+ case 'crdtSubdocSyncComplete':
619
+ case 'crdtSubdocTransferProgress':
620
+ case 'crdtSubdocRequestSync':
621
+ this.crdt.handleMessage(msg);
622
+ break;
623
+ case 'frameOwnerChanged':
624
+ this.onFrameOwnerChanged?.(msg.frameConnectorId, msg.owner);
625
+ break;
626
+ case 'messageFromCompanionConnector':
627
+ this.onMessageFromCompanionConnector?.(msg.fromCompanionId, msg.message, msg.fileData);
628
+ break;
629
+ case 'messageFromCompanionFrame':
630
+ this.onMessageFromCompanionFrame?.(msg.fromCompanionId, msg.frameConnectorId, msg.message, msg.fileData);
631
+ break;
632
+ case 'frameMenuClickedOnCompanion':
633
+ this.onFrameMenuClickedOnCompanion?.(msg.frameConnectorId, msg.fromCompanionId, msg.menuId, msg.isChecked, msg.tag);
634
+ break;
635
+ }
636
+ this.onMessageReceived?.(msg);
637
+ }
638
+ _onStateReplaced(msg) {
639
+ const oldState = this.state;
640
+ this.state = msg.state;
641
+ this.onStateReplaced?.(this.state, oldState, msg.replacedBy, msg.delta);
642
+ }
643
+ _onExternalMessageReceived(msg) {
644
+ if (this.onExternalMessageReceived) {
645
+ const result = this.onExternalMessageReceived(msg);
646
+ // If handler returns a value (sync or Promise), automatically send response
647
+ if (result !== undefined && result !== null) {
648
+ const sendResponse = (response) => {
649
+ this.postMessage({
650
+ type: 'externalMessageResponse',
651
+ requestId: msg.requestId,
652
+ response,
653
+ });
654
+ };
655
+ if (result instanceof Promise || (result && typeof result.then === 'function')) {
656
+ ;
657
+ result.then(sendResponse).catch(() => {
658
+ sendResponse(null);
659
+ });
660
+ }
661
+ else {
662
+ sendResponse(result);
663
+ }
664
+ }
665
+ }
666
+ }
667
+ async requestAppToken() {
668
+ const requestId = uuid();
669
+ const token = await this.postRequest({ type: 'requestAppToken', requestId }, (msg, resolve, reject) => {
670
+ if (msg.type === 'appTokenReceived' && msg.requestId === requestId) {
671
+ const tokenMsg = msg;
672
+ if (tokenMsg.token) {
673
+ resolve(tokenMsg.token);
674
+ }
675
+ else {
676
+ reject(tokenMsg.error ?? 'Failed to get app token');
677
+ }
678
+ }
679
+ });
680
+ this.appToken = token;
681
+ return token;
682
+ }
683
+ /**
684
+ * Run JavaScript inside a (cross-origin) child iframe this app embeds in its
685
+ * frame.html, and resolve with the JSON-parsed return value.
686
+ *
687
+ * The iframe must carry a `name` attribute (e.g. `<iframe name="my-target">`)
688
+ * matching `frameName`. `code` runs as a function body — use `return <expr>` to
689
+ * produce a value (any JSON-serializable value round-trips; `undefined` → `null`).
690
+ *
691
+ * Requires the `injectScriptIntoFrame` app authorization and the native (CEF)
692
+ * host (rejects on a web host). The host also restricts the target to this app's
693
+ * own frame subtree.
694
+ */
695
+ async executeInFrame(frameName, code) {
696
+ const requestId = uuid();
697
+ const json = await this.postRequest({ type: 'executeInFrame', requestId, frameName, code }, (msg, resolve, reject) => {
698
+ if (msg.type === 'executeInFrameResult' &&
699
+ msg.requestId === requestId) {
700
+ const resultMsg = msg;
701
+ if (resultMsg.error) {
702
+ reject(resultMsg.error);
703
+ }
704
+ else {
705
+ resolve(resultMsg.result);
706
+ }
707
+ }
708
+ });
709
+ return (json === undefined ? undefined : JSON.parse(json));
710
+ }
711
+ startAppTokenRefresh(intervalMs = 3600000) {
712
+ this.stopAppTokenRefresh();
713
+ // Request initial token
714
+ this.requestAppToken().catch(() => { });
715
+ // Refresh periodically
716
+ this.appTokenRefreshTimer = setInterval(async () => {
717
+ try {
718
+ const token = await this.requestAppToken();
719
+ this.onAppTokenRefreshed?.(token);
720
+ }
721
+ catch (_error) {
722
+ // Will retry on next interval
723
+ }
724
+ }, intervalMs);
725
+ }
726
+ stopAppTokenRefresh() {
727
+ if (this.appTokenRefreshTimer) {
728
+ clearInterval(this.appTokenRefreshTimer);
729
+ this.appTokenRefreshTimer = null;
730
+ }
731
+ }
732
+ /** Release the resources owned by this connector. Stops the app-token
733
+ * refresh timer and tears the CRDT channel down (unbinds doc/awareness
734
+ * listeners, destroys the default Y.Doc + Awareness). Safe to call
735
+ * multiple times. */
736
+ destroy() {
737
+ this.stopAppTokenRefresh();
738
+ this.crdt.destroy();
739
+ }
740
+ updateState(updates, forceApplyLocally = true) {
741
+ updates.forEach((update) => {
742
+ //Compat fix, add value for remove action
743
+ if (update.action === 'remove') {
744
+ ;
745
+ update.value = null;
746
+ }
747
+ });
748
+ this.postMessage({
749
+ type: 'updateState',
750
+ updates,
751
+ });
752
+ if (forceApplyLocally) {
753
+ updates.forEach((update) => {
754
+ if (update.action === 'add') {
755
+ this.state[update.key] = update.value;
756
+ }
757
+ else {
758
+ delete this.state[update.key];
759
+ }
760
+ });
761
+ }
762
+ }
763
+ async postRequest(data, handler, transfer) {
764
+ return await new Promise((resolve, reject) => {
765
+ let isHandled = false;
766
+ const handleAndResolve = (data) => {
767
+ isHandled = true;
768
+ resolve(data);
769
+ };
770
+ const handleAndReject = (error) => {
771
+ isHandled = true;
772
+ reject(error);
773
+ };
774
+ const resolver = {
775
+ isHandled: (msg) => {
776
+ try {
777
+ handler(msg, handleAndResolve, handleAndReject);
778
+ }
779
+ catch (error) {
780
+ handleAndReject(error);
781
+ }
782
+ return isHandled;
783
+ },
784
+ };
785
+ this.requestResolvers.push(resolver);
786
+ this.postMessage(data, transfer);
787
+ });
788
+ }
789
+ async requestStats() {
790
+ const requestId = uuid();
791
+ return await this.postRequest({ type: 'getStats', requestId }, (msg, resolve, _reject) => {
792
+ if (msg.type === 'statsResponse' && msg.requestId === requestId) {
793
+ resolve(msg);
794
+ }
795
+ });
796
+ }
797
+ async requestEnumerateDevices() {
798
+ const requestId = uuid();
799
+ return await this.postRequest({ type: 'enumerateMediaDevices', requestId }, async (msg, resolve, _reject) => {
800
+ if (msg.type === 'enumerateMediaDevicesCompleted' &&
801
+ msg.requestId === requestId) {
802
+ const localDevices = await navigator.mediaDevices.enumerateDevices();
803
+ const cleanName = (name) => {
804
+ if (!name)
805
+ return name;
806
+ return name.replace(/\s*\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/gi, '');
807
+ };
808
+ const mappedDevices = msg.devices.map((d) => {
809
+ const localDevice = localDevices.find((ld) => cleanName(ld.label) === cleanName(d.label) &&
810
+ ld.kind === d.kind);
811
+ if (localDevice) {
812
+ return {
813
+ ...d,
814
+ deviceId: localDevice.deviceId,
815
+ groupId: localDevice.groupId,
816
+ vitreId: d.deviceId,
817
+ vitreGroupId: d.groupId,
818
+ };
819
+ }
820
+ return d;
821
+ });
822
+ resolve(mappedDevices);
823
+ }
824
+ });
825
+ }
826
+ async requestOpenStream(streamId, constraints) {
827
+ const requestId = uuid();
828
+ return await this.postRequest({ type: 'openStream', requestId, streamId, constraints }, (msg, resolve, reject) => {
829
+ if (msg.type === 'openStreamCompleted' && msg.requestId === requestId) {
830
+ if (msg.error != null || msg.tracks == null) {
831
+ reject(msg.error ?? 'openStream failed');
832
+ }
833
+ else {
834
+ resolve(msg.tracks);
835
+ }
836
+ }
837
+ });
838
+ }
839
+ async convertConstraintsToVitreConstraints(constraints) {
840
+ const vitreDevices = await this.requestEnumerateDevices();
841
+ const videoConstraint = (typeof constraints.video === 'object' &&
842
+ constraints.video);
843
+ const audioConstraint = (typeof constraints.audio === 'object' &&
844
+ constraints.audio);
845
+ const videoDeviceId = videoConstraint?.deviceId;
846
+ const audioDeviceId = audioConstraint?.deviceId;
847
+ const mappedVideoDevice = vitreDevices.find((d) => d.deviceId === videoDeviceId && d.kind === 'videoinput');
848
+ const mappedVideoDeviceId = mappedVideoDevice?.vitreId ?? mappedVideoDevice?.deviceId;
849
+ const mappedAudioDevice = vitreDevices.find((d) => d.deviceId === audioDeviceId && d.kind === 'audioinput');
850
+ const mappedAudioDeviceId = mappedAudioDevice?.vitreId ?? mappedAudioDevice?.deviceId;
851
+ let mappedConstraint = videoDeviceId
852
+ ? {
853
+ ...constraints,
854
+ video: { ...videoConstraint, deviceId: mappedVideoDeviceId },
855
+ }
856
+ : constraints;
857
+ mappedConstraint = audioDeviceId
858
+ ? {
859
+ ...mappedConstraint,
860
+ audio: { ...audioConstraint, deviceId: mappedAudioDeviceId },
861
+ }
862
+ : mappedConstraint;
863
+ return mappedConstraint;
864
+ }
865
+ async requestOpenStreamFrame(openStreamFrame) {
866
+ const requestId = uuid();
867
+ const constraints = openStreamFrame.constraints
868
+ ? await this.convertConstraintsToVitreConstraints(openStreamFrame.constraints)
869
+ : undefined;
870
+ return await this.postRequest({ type: 'openStreamFrame', requestId, ...openStreamFrame, constraints }, (msg, resolve, reject) => {
871
+ if (msg.type === 'openStreamFrameCompleted' &&
872
+ msg.requestId === requestId) {
873
+ if (msg.error != null || msg.tracks == null) {
874
+ reject(msg.error ?? 'openStream failed');
875
+ }
876
+ else {
877
+ resolve(msg.tracks);
878
+ }
879
+ }
880
+ });
881
+ }
882
+ /**
883
+ * Whether {@link shareStream} is available in this runtime. Requires the
884
+ * MediaStreamTrack Insertable Streams API (Chromium-only) and the app being
885
+ * served same-site as the Vitre host (so the transferred stream survives the
886
+ * iframe boundary zero-copy). Apps should feature-detect before offering a
887
+ * share action.
888
+ */
889
+ canShareStream() {
890
+ return typeof MediaStreamTrackProcessor !== 'undefined';
891
+ }
892
+ toShareTracks(stream) {
893
+ const tracks = [];
894
+ const transfer = [];
895
+ for (const track of stream.getTracks()) {
896
+ const { readable } = new MediaStreamTrackProcessor({ track });
897
+ tracks.push({
898
+ kind: track.kind,
899
+ readable,
900
+ settings: track.getSettings(),
901
+ });
902
+ transfer.push(readable);
903
+ }
904
+ return { tracks, transfer };
905
+ }
906
+ /**
907
+ * Share a camera/microphone (or any) `MediaStream` the app controls TO the
908
+ * Vitre, which forwards it to the other peers in the space like a regular
909
+ * shared stream. The stream is handed over zero-copy (no re-encode) via the
910
+ * breakout box; the app keeps ownership of its tracks and can stop them
911
+ * independently.
912
+ *
913
+ * Returns a `sharedStreamId` to pass to {@link replaceShareStream} /
914
+ * {@link stopShareStream}. Throws if {@link canShareStream} is false.
915
+ */
916
+ async shareStream(stream, options) {
917
+ if (!this.canShareStream()) {
918
+ throw new Error('shareStream is not supported in this runtime (requires Chromium MediaStreamTrackProcessor and same-site hosting)');
919
+ }
920
+ const sharedStreamId = uuid();
921
+ const requestId = uuid();
922
+ const { tracks, transfer } = this.toShareTracks(stream);
923
+ await this.postRequest({ type: 'shareStream', requestId, sharedStreamId, options, tracks }, (msg, resolve, reject) => {
924
+ if (msg.type === 'shareStreamCompleted' && msg.requestId === requestId) {
925
+ if (msg.error != null)
926
+ reject(msg.error);
927
+ else
928
+ resolve(undefined);
929
+ }
930
+ }, transfer);
931
+ return sharedStreamId;
932
+ }
933
+ /**
934
+ * Swap the source of an open share WITHOUT closing it (e.g. switch camera,
935
+ * or camera→screen). Peers keep receiving on the same slot with no
936
+ * renegotiation blip. `sharedStreamId` is the value returned by
937
+ * {@link shareStream}.
938
+ */
939
+ async replaceShareStream(sharedStreamId, streamOrTrack) {
940
+ if (!this.canShareStream()) {
941
+ throw new Error('replaceShareStream is not supported in this runtime');
942
+ }
943
+ const stream = streamOrTrack instanceof MediaStream
944
+ ? streamOrTrack
945
+ : new MediaStream([streamOrTrack]);
946
+ const requestId = uuid();
947
+ const { tracks, transfer } = this.toShareTracks(stream);
948
+ await this.postRequest({ type: 'replaceShareStream', requestId, sharedStreamId, tracks }, (msg, resolve, reject) => {
949
+ if (msg.type === 'shareStreamCompleted' && msg.requestId === requestId) {
950
+ if (msg.error != null)
951
+ reject(msg.error);
952
+ else
953
+ resolve(undefined);
954
+ }
955
+ }, transfer);
956
+ }
957
+ /** Stop an app share. `sharedStreamId` is the value returned by {@link shareStream}. */
958
+ stopShareStream(sharedStreamId) {
959
+ this.postMessage({ type: 'stopShareStream', sharedStreamId });
960
+ }
961
+ getFrame(frameConnectorId) {
962
+ try {
963
+ const frameId = `${this.appId}|${frameConnectorId}`;
964
+ return window.parent.frames[frameId];
965
+ }
966
+ catch (_error) {
967
+ return null;
968
+ }
969
+ }
970
+ getFrameConnector(frameConnector) {
971
+ const frame = this.getFrame(frameConnector);
972
+ return frame?.frameConnector;
973
+ }
974
+ async openFrame(frameOptions) {
975
+ return await this.postRequest({
976
+ type: 'openFrame',
977
+ options: frameOptions,
978
+ }, (msg, resolve, _reject) => {
979
+ if (msg.type === 'frameConnectorLoaded' &&
980
+ msg.frameConnectorId === frameOptions.frameConnectorId) {
981
+ resolve(msg);
982
+ }
983
+ });
984
+ }
985
+ async openLocalFrame(frameOptions) {
986
+ return await this.postRequest({
987
+ type: 'openLocalFrame',
988
+ options: frameOptions,
989
+ }, (msg, resolve, _reject) => {
990
+ if (msg.type === 'frameConnectorLoaded' &&
991
+ msg.frameConnectorId === frameOptions.frameConnectorId) {
992
+ resolve(msg);
993
+ }
994
+ });
995
+ }
996
+ sendMessageTo(message) {
997
+ this.postMessage({ type: 'sendMessageTo', ...message });
998
+ }
999
+ sendMessageToAll(message) {
1000
+ this.postMessage({
1001
+ type: 'sendMessageToAll',
1002
+ ...message,
1003
+ });
1004
+ }
1005
+ sendKnockKnock(message) {
1006
+ this.postMessage({ type: 'sendKnockKnock', ...message });
1007
+ }
1008
+ sendToLocalFrame(frameConnectorId, data, fileData) {
1009
+ this.postMessage({
1010
+ type: 'sendToLocalFrame',
1011
+ frameConnectorId,
1012
+ data,
1013
+ fileData,
1014
+ });
1015
+ }
1016
+ setMenu(menu) {
1017
+ this.postMessage({
1018
+ type: 'setRootMenu',
1019
+ menu,
1020
+ });
1021
+ }
1022
+ /**
1023
+ * @deprecated Use sendAppMessage on vitre v18
1024
+ */
1025
+ sendExtensionMessage(data, target, fileData) {
1026
+ this.postMessage({
1027
+ type: 'extensionMessage',
1028
+ data,
1029
+ target,
1030
+ fileData,
1031
+ });
1032
+ }
1033
+ /** @deprecated Use sendMessageToEmbed */
1034
+ sendAppMessage(data, target, fileData) {
1035
+ this.postMessage({
1036
+ type: 'appMessage',
1037
+ data,
1038
+ target,
1039
+ fileData,
1040
+ });
1041
+ }
1042
+ sendMessageToEmbed(data, target, fileData) {
1043
+ this.postMessage({
1044
+ type: 'appMessage',
1045
+ data,
1046
+ target,
1047
+ fileData,
1048
+ });
1049
+ }
1050
+ async requestVitreSettings() {
1051
+ return await this.postRequest({ type: 'getVitreSettings' }, (msg, resolve, _reject) => {
1052
+ if (msg.type === 'vitreSettingsResponse') {
1053
+ resolve(msg);
1054
+ }
1055
+ });
1056
+ }
1057
+ setVitreSettings(setters) {
1058
+ this.postMessage({ type: 'setVitreSettings', ...setters });
1059
+ }
1060
+ /**
1061
+ * Share a URL/data with the host, which routes it to a matching app.
1062
+ * @param owner Optional device id (`HostInformation.devicesInSpace[].id`) to
1063
+ * attribute the resulting shared content to. The owner drives the languette
1064
+ * colour/info and the content appears already-owned on every vitre. When
1065
+ * omitted the share is owned by the opener (default).
1066
+ */
1067
+ shareData(url, targetAppId, owner) {
1068
+ this.postMessage({
1069
+ type: 'shareData',
1070
+ url,
1071
+ targetAppId,
1072
+ owner,
1073
+ });
1074
+ }
1075
+ /**
1076
+ * Share a file with the host, which routes it to a matching app.
1077
+ * @param owner Optional device id (`HostInformation.devicesInSpace[].id`) to
1078
+ * attribute the resulting shared content to. See {@link shareData}.
1079
+ */
1080
+ shareFile(fileData, targetAppId, owner) {
1081
+ this.postMessage({
1082
+ type: 'shareFile',
1083
+ fileData,
1084
+ targetAppId,
1085
+ owner,
1086
+ });
1087
+ }
1088
+ saveSettings(settings) {
1089
+ this.postMessage({
1090
+ type: 'saveSettings',
1091
+ settings,
1092
+ });
1093
+ }
1094
+ changeTeamSpace(space) {
1095
+ this.postMessage({
1096
+ type: 'changeTeamSpace',
1097
+ space,
1098
+ });
1099
+ }
1100
+ changeTeamSpaceGuest(space, teamDomain) {
1101
+ this.postMessage({
1102
+ type: 'changeTeamSpaceGuest',
1103
+ space,
1104
+ teamDomain,
1105
+ });
1106
+ }
1107
+ showNotification(notification) {
1108
+ this.postMessage({
1109
+ ...notification,
1110
+ type: 'showNotification',
1111
+ });
1112
+ }
1113
+ hideNotification(notificationId) {
1114
+ this.postMessage({
1115
+ id: notificationId,
1116
+ type: 'hideNotification',
1117
+ });
1118
+ }
1119
+ changePrivacy(privacy) {
1120
+ this.postMessage({
1121
+ type: 'changePrivacy',
1122
+ privacy,
1123
+ });
1124
+ }
1125
+ trackEvent(name, properties) {
1126
+ this.postMessage({
1127
+ type: 'trackEvent',
1128
+ name,
1129
+ properties,
1130
+ });
1131
+ }
1132
+ startTrackEvent(name) {
1133
+ this.postMessage({
1134
+ type: 'startTrackEvent',
1135
+ name,
1136
+ });
1137
+ }
1138
+ stopTrackEvent(name, properties) {
1139
+ this.postMessage({
1140
+ type: 'stopTrackEvent',
1141
+ name,
1142
+ properties,
1143
+ });
1144
+ }
1145
+ setSettingsSchema(schema) {
1146
+ this.options = {
1147
+ ...this.options,
1148
+ settingsSchema: schema.schema,
1149
+ settingsSchemaUI: schema.schemaUI,
1150
+ };
1151
+ this.postMessage({
1152
+ type: 'setSettingsSchema',
1153
+ ...schema,
1154
+ });
1155
+ }
1156
+ /**
1157
+ * Update the app's share target at any time. The new share target replaces
1158
+ * the one provided at initialization (ConnectorOptions.shareTarget) and is
1159
+ * applied immediately by the host. Can be called repeatedly.
1160
+ *
1161
+ * @deprecated Use `setShareTargets` to advertise one or more share targets.
1162
+ */
1163
+ setShareTarget(shareTarget) {
1164
+ this.options = {
1165
+ ...this.options,
1166
+ shareTarget,
1167
+ shareTargets: [shareTarget],
1168
+ };
1169
+ this.postMessage({
1170
+ type: 'setShareTarget',
1171
+ shareTarget,
1172
+ });
1173
+ }
1174
+ /**
1175
+ * Update the app's share targets at any time. The new array replaces the ones
1176
+ * provided at initialization (ConnectorOptions.shareTargets) and is applied
1177
+ * immediately by the host. Can be called repeatedly.
1178
+ */
1179
+ setShareTargets(shareTargets) {
1180
+ this.options = {
1181
+ ...this.options,
1182
+ shareTargets,
1183
+ // Mirror the first target onto the deprecated singular for older Vitres.
1184
+ shareTarget: shareTargets[0],
1185
+ };
1186
+ // Emit the legacy singular first so older Vitres (which only handle
1187
+ // `setShareTarget`) still get the primary target at runtime, then the full
1188
+ // array which new hosts apply (and which supersedes the singular there).
1189
+ if (shareTargets[0]) {
1190
+ this.postMessage({
1191
+ type: 'setShareTarget',
1192
+ shareTarget: shareTargets[0],
1193
+ });
1194
+ }
1195
+ this.postMessage({
1196
+ type: 'setShareTargets',
1197
+ shareTargets,
1198
+ });
1199
+ }
1200
+ setVoiceActions(actions) {
1201
+ this.postMessage({
1202
+ type: 'setVoiceActions',
1203
+ actions,
1204
+ });
1205
+ }
1206
+ setFramePosition(frameConnectorId, position) {
1207
+ this.postMessage({
1208
+ type: 'setFramePosition',
1209
+ frameConnectorId,
1210
+ position,
1211
+ });
1212
+ }
1213
+ closeFrame(frameConnectorId) {
1214
+ this.postMessage({
1215
+ type: 'closeFrame',
1216
+ frameConnectorId,
1217
+ });
1218
+ }
1219
+ /**
1220
+ * Reassign the owner of an already-opened shared frame. `owner` is a
1221
+ * device id from `HostInformation.devicesInSpace[].id`. The new owner
1222
+ * drives the languette colour, and when it is a Vitre it takes over
1223
+ * hosting the frame so it survives the opener disconnecting.
1224
+ */
1225
+ setFrameOwner(frameConnectorId, owner) {
1226
+ this.postMessage({
1227
+ type: 'setFrameOwner',
1228
+ frameConnectorId,
1229
+ owner,
1230
+ });
1231
+ }
1232
+ /**
1233
+ * Update the visual style of an already-open frame's shared content at any
1234
+ * time — the same surface styling and companion icon that
1235
+ * `OpenFrameOptions` sets at open time, but applied live. Only the fields you
1236
+ * pass change; omitted fields keep their current value. Pass an empty string
1237
+ * to clear an override back to the host default (e.g. `{ background: '' }`).
1238
+ * The host re-renders the surface on this Vitre, on peer Vitres / tableaux
1239
+ * showing the frame, and re-propagates the icon to connected companions.
1240
+ */
1241
+ setChromeStyle(frameConnectorId, style) {
1242
+ this.postMessage({
1243
+ type: 'setChromeStyle',
1244
+ frameConnectorId,
1245
+ ...style,
1246
+ });
1247
+ }
1248
+ setReducedAudioMode(enabled) {
1249
+ this.postMessage({
1250
+ type: 'setReducedAudioMode',
1251
+ enabled,
1252
+ });
1253
+ }
1254
+ setFrameSize(frameId, size) {
1255
+ this.postMessage({
1256
+ type: 'setFrameSize',
1257
+ frameId,
1258
+ size,
1259
+ });
1260
+ }
1261
+ sendToSerialPort(serialPort) {
1262
+ this.postMessage({
1263
+ type: 'sendToSerialPort',
1264
+ ...serialPort,
1265
+ });
1266
+ }
1267
+ /// Request access to a serial port. Resolves with the granted port name
1268
+ /// (empty string if denied or cancelled).
1269
+ /// - `{ port }` given: the host pre-grants that port and resolves with it,
1270
+ /// so a following `navigator.serial.requestPort()` resolves to it with no
1271
+ /// picker.
1272
+ /// - no argument (or `{}`): the host shows its port-picker and resolves with
1273
+ /// the port the user chose (also pre-granted).
1274
+ /// Honoured only when the app holds the WebSerial authorization.
1275
+ async requestSerialPortAccess(request) {
1276
+ const requestId = uuid();
1277
+ return await this.postRequest({ type: 'requestSerialPortAccess', requestId, port: request?.port }, (msg, resolve, reject) => {
1278
+ if (msg.type === 'serialPortAccessResult' &&
1279
+ msg.requestId === requestId) {
1280
+ if (msg.port) {
1281
+ resolve(msg.port);
1282
+ }
1283
+ else {
1284
+ reject(msg.reason ?? 'cancelled');
1285
+ }
1286
+ }
1287
+ });
1288
+ }
1289
+ /// Send an opaque message to the companion-side `CompanionConnector`
1290
+ /// for the same `appId`. `target` selects one or all companions
1291
+ /// currently connected to this Vitre — `{ kind: 'all' }` broadcasts to
1292
+ /// every connected companion, `{ kind: 'one', companionId }` addresses a
1293
+ /// single one. The message is forwarded unchanged; the receiving side
1294
+ /// gets it as `onMessageFromVitreConnector`.
1295
+ sendMessageToCompanionConnector(target, message, fileData) {
1296
+ this.postMessage({
1297
+ type: 'sendMessageToCompanionConnector',
1298
+ target,
1299
+ message,
1300
+ fileData,
1301
+ });
1302
+ }
1303
+ }
1304
+ export async function initializeConnector(init, createConnector) {
1305
+ return await new Promise((resolve) => {
1306
+ const channel = new MessageChannel();
1307
+ let mainConnector = null;
1308
+ const messageHandler = (createPostMessage) => (e) => {
1309
+ switch (e.data.type) {
1310
+ case 'initialize':
1311
+ if (mainConnector == null) {
1312
+ const initializeMsg = e.data;
1313
+ const options = init(initializeMsg.hostInfo);
1314
+ mainConnector = new (createConnector ?? Connector)(createPostMessage(initializeMsg.hostInfo.origin), initializeMsg, options);
1315
+ const w = window;
1316
+ w.mainConnector = mainConnector;
1317
+ resolve(mainConnector);
1318
+ }
1319
+ break;
1320
+ default:
1321
+ mainConnector?.raiseMessage(e.data);
1322
+ break;
1323
+ }
1324
+ };
1325
+ channel.port1.onmessage = messageHandler((_origin) => (message, transfer) => {
1326
+ channel.port1.postMessage(message, transfer ?? []);
1327
+ });
1328
+ window.parent.postMessage({
1329
+ type: 'connectorInitializationRequest',
1330
+ version: apiVersion,
1331
+ }, '*', [channel.port2]);
1332
+ window.addEventListener('message', messageHandler((origin) => (message, transfer) => {
1333
+ window.parent.postMessage(message, origin, transfer);
1334
+ }), false);
1335
+ });
1336
+ }
1337
+ //# sourceMappingURL=Connector.js.map