@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.
- package/LICENSE +21 -0
- package/README.md +121 -0
- package/dist/Common/AiChannel.d.ts +59 -0
- package/dist/Common/AiChannel.js +97 -0
- package/dist/Common/AiChannel.js.map +1 -0
- package/dist/Common/BlobStore.d.ts +44 -0
- package/dist/Common/BlobStore.js +186 -0
- package/dist/Common/BlobStore.js.map +1 -0
- package/dist/Common/Common.Model.d.ts +1020 -0
- package/dist/Common/Common.Model.js +21 -0
- package/dist/Common/Common.Model.js.map +1 -0
- package/dist/Common/CrdtChannel.d.ts +198 -0
- package/dist/Common/CrdtChannel.js +659 -0
- package/dist/Common/CrdtChannel.js.map +1 -0
- package/dist/Common/Version.d.ts +21 -0
- package/dist/Common/Version.js +62 -0
- package/dist/Common/Version.js.map +1 -0
- package/dist/Common/index.d.ts +6 -0
- package/dist/Common/index.js +32 -0
- package/dist/Common/index.js.map +1 -0
- package/dist/CompanionConnector/CompanionConnector.Model.d.ts +85 -0
- package/dist/CompanionConnector/CompanionConnector.Model.js +17 -0
- package/dist/CompanionConnector/CompanionConnector.Model.js.map +1 -0
- package/dist/CompanionConnector/CompanionConnector.d.ts +28 -0
- package/dist/CompanionConnector/CompanionConnector.js +385 -0
- package/dist/CompanionConnector/CompanionConnector.js.map +1 -0
- package/dist/CompanionConnector/index.d.ts +2 -0
- package/dist/CompanionConnector/index.js +3 -0
- package/dist/CompanionConnector/index.js.map +1 -0
- package/dist/CompanionFrame/CompanionFrame.d.ts +103 -0
- package/dist/CompanionFrame/CompanionFrame.js +100 -0
- package/dist/CompanionFrame/CompanionFrame.js.map +1 -0
- package/dist/CompanionFrame/index.d.ts +1 -0
- package/dist/CompanionFrame/index.js +2 -0
- package/dist/CompanionFrame/index.js.map +1 -0
- package/dist/Connector/Connector.Model.d.ts +567 -0
- package/dist/Connector/Connector.Model.js +2 -0
- package/dist/Connector/Connector.Model.js.map +1 -0
- package/dist/Connector/Connector.d.ts +227 -0
- package/dist/Connector/Connector.js +1337 -0
- package/dist/Connector/Connector.js.map +1 -0
- package/dist/Connector/index.d.ts +2 -0
- package/dist/Connector/index.js +3 -0
- package/dist/Connector/index.js.map +1 -0
- package/dist/Frame/Frame.Model.d.ts +533 -0
- package/dist/Frame/Frame.Model.js +2 -0
- package/dist/Frame/Frame.Model.js.map +1 -0
- package/dist/Frame/Frame.d.ts +309 -0
- package/dist/Frame/Frame.js +1408 -0
- package/dist/Frame/Frame.js.map +1 -0
- package/dist/Frame/SyncAdapter.d.ts +75 -0
- package/dist/Frame/SyncAdapter.js +134 -0
- package/dist/Frame/SyncAdapter.js.map +1 -0
- package/dist/Frame/index.d.ts +3 -0
- package/dist/Frame/index.js +4 -0
- package/dist/Frame/index.js.map +1 -0
- package/dist/MediaLink/MediaLink.d.ts +178 -0
- package/dist/MediaLink/MediaLink.js +1432 -0
- package/dist/MediaLink/MediaLink.js.map +1 -0
- package/dist/MediaLink/index.d.ts +1 -0
- package/dist/MediaLink/index.js +2 -0
- package/dist/MediaLink/index.js.map +1 -0
- package/dist/Native/index.d.ts +170 -0
- package/dist/Native/index.js +19 -0
- package/dist/Native/index.js.map +1 -0
- package/dist/Version.d.ts +1 -0
- package/dist/Version.js +2 -0
- package/dist/Version.js.map +1 -0
- package/package.json +76 -0
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import { apiVersion } from '../Version.js';
|
|
2
|
+
/// Runtime instance handed to a companion connector once the host has
|
|
3
|
+
/// finished the `initialize` handshake. The shape is intentionally much
|
|
4
|
+
/// smaller than the Vitre `Connector` — anything not in this class doesn't
|
|
5
|
+
/// apply on the companion.
|
|
6
|
+
export class CompanionConnector {
|
|
7
|
+
constructor(postMessage, initMessage, options) {
|
|
8
|
+
Object.defineProperty(this, "postMessage", {
|
|
9
|
+
enumerable: true,
|
|
10
|
+
configurable: true,
|
|
11
|
+
writable: true,
|
|
12
|
+
value: postMessage
|
|
13
|
+
});
|
|
14
|
+
/// Identity of the Vitre this companion connector is hosted against
|
|
15
|
+
/// (the host). Read-only — the host pushes updates by reinitializing
|
|
16
|
+
/// the connector if needed.
|
|
17
|
+
Object.defineProperty(this, "hostInformation", {
|
|
18
|
+
enumerable: true,
|
|
19
|
+
configurable: true,
|
|
20
|
+
writable: true,
|
|
21
|
+
value: void 0
|
|
22
|
+
});
|
|
23
|
+
/// This companion's own identity and runtime context (name, user,
|
|
24
|
+
/// language, origin, version). Distinct from `hostInformation` (Vitre).
|
|
25
|
+
Object.defineProperty(this, "companionInformation", {
|
|
26
|
+
enumerable: true,
|
|
27
|
+
configurable: true,
|
|
28
|
+
writable: true,
|
|
29
|
+
value: void 0
|
|
30
|
+
});
|
|
31
|
+
Object.defineProperty(this, "appId", {
|
|
32
|
+
enumerable: true,
|
|
33
|
+
configurable: true,
|
|
34
|
+
writable: true,
|
|
35
|
+
value: void 0
|
|
36
|
+
});
|
|
37
|
+
Object.defineProperty(this, "options", {
|
|
38
|
+
enumerable: true,
|
|
39
|
+
configurable: true,
|
|
40
|
+
writable: true,
|
|
41
|
+
value: void 0
|
|
42
|
+
});
|
|
43
|
+
// Callbacks — host → connector events. All optional.
|
|
44
|
+
Object.defineProperty(this, "onMenuClicked", {
|
|
45
|
+
enumerable: true,
|
|
46
|
+
configurable: true,
|
|
47
|
+
writable: true,
|
|
48
|
+
value: void 0
|
|
49
|
+
});
|
|
50
|
+
Object.defineProperty(this, "onFrameLoaded", {
|
|
51
|
+
enumerable: true,
|
|
52
|
+
configurable: true,
|
|
53
|
+
writable: true,
|
|
54
|
+
value: void 0
|
|
55
|
+
});
|
|
56
|
+
Object.defineProperty(this, "onFrameUnloaded", {
|
|
57
|
+
enumerable: true,
|
|
58
|
+
configurable: true,
|
|
59
|
+
writable: true,
|
|
60
|
+
value: void 0
|
|
61
|
+
});
|
|
62
|
+
/// Called when a shared frame's owner was (re)assigned (at open time or
|
|
63
|
+
/// post-hoc, including by another device). `owner` is the new owner's
|
|
64
|
+
/// device id (`HostInformation.devicesInSpace[].id`). Mirrors the Vitre
|
|
65
|
+
/// `Connector.onFrameOwnerChanged`.
|
|
66
|
+
Object.defineProperty(this, "onFrameOwnerChanged", {
|
|
67
|
+
enumerable: true,
|
|
68
|
+
configurable: true,
|
|
69
|
+
writable: true,
|
|
70
|
+
value: void 0
|
|
71
|
+
});
|
|
72
|
+
/// Called when the matching Vitre `Connector` (same `appId`) sent a
|
|
73
|
+
/// message via `sendMessageToCompanionConnector`. The companion side
|
|
74
|
+
/// does not know which Vitre user sent the message — it is always
|
|
75
|
+
/// "the" Vitre connector for that app.
|
|
76
|
+
Object.defineProperty(this, "onMessageFromVitreConnector", {
|
|
77
|
+
enumerable: true,
|
|
78
|
+
configurable: true,
|
|
79
|
+
writable: true,
|
|
80
|
+
value: void 0
|
|
81
|
+
});
|
|
82
|
+
Object.defineProperty(this, "onMessageReceived", {
|
|
83
|
+
enumerable: true,
|
|
84
|
+
configurable: true,
|
|
85
|
+
writable: true,
|
|
86
|
+
value: void 0
|
|
87
|
+
});
|
|
88
|
+
this.hostInformation = initMessage.hostInfo;
|
|
89
|
+
this.companionInformation = initMessage.companionInfo;
|
|
90
|
+
// `appId` is optional — a host may legitimately omit it for a generic
|
|
91
|
+
// connector — but message routing keys on it, so warn when the empty
|
|
92
|
+
// fallback is hit to surface a misconfigured host.
|
|
93
|
+
if (initMessage.appId == null) {
|
|
94
|
+
console.warn('[CompanionConnector] initialize message has no appId; ' +
|
|
95
|
+
'falling back to an empty string — Vitre-connector message ' +
|
|
96
|
+
'routing will not match');
|
|
97
|
+
}
|
|
98
|
+
this.appId = initMessage.appId ?? '';
|
|
99
|
+
this.options = options;
|
|
100
|
+
this.postMessage({
|
|
101
|
+
type: 'connectorInitialized',
|
|
102
|
+
options,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
/// Handler called by `initializeCompanionConnector` for every inbound
|
|
106
|
+
/// message after the initial `initialize`. Exposed for testing and for
|
|
107
|
+
/// hosts that drive the connector through a side channel.
|
|
108
|
+
raiseMessage(msg) {
|
|
109
|
+
switch (msg.type) {
|
|
110
|
+
case 'menuClicked':
|
|
111
|
+
this.onMenuClicked?.(msg.menuId, msg.tag, msg.isChecked);
|
|
112
|
+
break;
|
|
113
|
+
case 'frameLoaded':
|
|
114
|
+
this.onFrameLoaded?.(msg.frameConnectorId);
|
|
115
|
+
break;
|
|
116
|
+
case 'frameUnloaded':
|
|
117
|
+
this.onFrameUnloaded?.(msg.frameConnectorId);
|
|
118
|
+
break;
|
|
119
|
+
case 'frameOwnerChanged':
|
|
120
|
+
this.onFrameOwnerChanged?.(msg.frameConnectorId, msg.owner);
|
|
121
|
+
break;
|
|
122
|
+
case 'messageFromVitreConnector':
|
|
123
|
+
this.onMessageFromVitreConnector?.(msg.message, msg.fileData);
|
|
124
|
+
break;
|
|
125
|
+
// `initialize` is handled by the bootstrap, not here. Return early
|
|
126
|
+
// so the public `onMessageReceived` callback is NOT invoked with it
|
|
127
|
+
// — the SDK documents `initialize` as not delivered through this
|
|
128
|
+
// handler, and falling through would break that contract.
|
|
129
|
+
case 'initialize':
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
this.onMessageReceived?.(msg);
|
|
133
|
+
}
|
|
134
|
+
/// Publish this companion connector's menu for the app.
|
|
135
|
+
///
|
|
136
|
+
/// By default (`mode: 'replace'`, or no options) the menu fully replaces
|
|
137
|
+
/// what the Vitre-side `Connector` published for this app on the
|
|
138
|
+
/// companion. Pass `{ mode: 'append' }` to instead *add* these entries
|
|
139
|
+
/// after the Vitre menu without hiding it — useful for contributing
|
|
140
|
+
/// companion-only entries on top of a Vitre-managed menu.
|
|
141
|
+
setMenu(menu, options) {
|
|
142
|
+
this.postMessage({ type: 'setRootMenu', menu, mode: options?.mode });
|
|
143
|
+
}
|
|
144
|
+
openFrame(options) {
|
|
145
|
+
this.postMessage({ type: 'openFrame', options });
|
|
146
|
+
}
|
|
147
|
+
closeFrame(frameConnectorId) {
|
|
148
|
+
this.postMessage({ type: 'closeFrame', frameConnectorId });
|
|
149
|
+
}
|
|
150
|
+
/// Reassign the owner of an already-opened shared frame. `owner` is a
|
|
151
|
+
/// device id from `HostInformation.devicesInSpace[].id`. Drives the
|
|
152
|
+
/// languette colour and, when the owner is a Vitre, hosting transfer so
|
|
153
|
+
/// the frame survives the opener disconnecting.
|
|
154
|
+
setFrameOwner(frameConnectorId, owner) {
|
|
155
|
+
this.postMessage({ type: 'setFrameOwner', frameConnectorId, owner });
|
|
156
|
+
}
|
|
157
|
+
/// Open (or focus) the paired frame full-page on this companion. The
|
|
158
|
+
/// host treats this as a navigation event: any current SubPage
|
|
159
|
+
/// (camera-share, another frame, etc.) is closed in favour of the new
|
|
160
|
+
/// frame, mirroring the behaviour when a Vitre-driven open triggers
|
|
161
|
+
/// `autoOpen` on the main page. If the Vitre side is reachable the
|
|
162
|
+
/// host also announces the open to it so a paired Vitre frame mounts.
|
|
163
|
+
///
|
|
164
|
+
/// `frameConnectorId` MUST match the paired Vitre frame's id so both
|
|
165
|
+
/// sides bind to the same frame (per-frame messages + yjs subdoc relay
|
|
166
|
+
/// rely on this).
|
|
167
|
+
openCompanionFrame(frameConnectorId, options) {
|
|
168
|
+
this.postMessage({
|
|
169
|
+
type: 'openCompanionFrame',
|
|
170
|
+
frameConnectorId,
|
|
171
|
+
options,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
/// Send an opaque message to the matching Vitre-side `Connector`. The
|
|
175
|
+
/// payload is forwarded unchanged. There is no targeted addressing —
|
|
176
|
+
/// the message goes to "the" Vitre connector for this app.
|
|
177
|
+
sendMessageToVitreConnector(message, fileData) {
|
|
178
|
+
this.postMessage({
|
|
179
|
+
type: 'sendMessageToVitreConnector',
|
|
180
|
+
message,
|
|
181
|
+
fileData,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/// Hard cap on the pre-`initialize` queue. A host that floods messages
|
|
186
|
+
/// before/while `initialize` is in flight (or one that never sends it)
|
|
187
|
+
/// must not grow this buffer without bound. On overflow we drop the
|
|
188
|
+
/// oldest queued message and warn once.
|
|
189
|
+
const MAX_PENDING_MESSAGES = 200;
|
|
190
|
+
/// Client-side bail-out: if `initialize` never arrives (host crash,
|
|
191
|
+
/// protocol mismatch, dropped postMessage) the outer Promise rejects
|
|
192
|
+
/// after this delay instead of dangling forever.
|
|
193
|
+
const INITIALIZE_TIMEOUT_MS = 30000;
|
|
194
|
+
export async function initializeCompanionConnector(buildOptions, createConnector) {
|
|
195
|
+
return await new Promise((resolve, reject) => {
|
|
196
|
+
const channel = new MessageChannel();
|
|
197
|
+
let connector = null;
|
|
198
|
+
// Set synchronously the moment the first `initialize` arrives so a
|
|
199
|
+
// second one delivered between the await and the assignment below
|
|
200
|
+
// is ignored instead of constructing a second instance.
|
|
201
|
+
let initializing = false;
|
|
202
|
+
// Trusted origin learned from the first initialize message. Until
|
|
203
|
+
// it is set, the window listener only accepts messages whose
|
|
204
|
+
// `source === window.parent`. After it is set, the channel port is
|
|
205
|
+
// the only ingress and the window listener is detached.
|
|
206
|
+
let trustedOrigin = null;
|
|
207
|
+
// Whether overflow on `pendingMessages` has already been warned about,
|
|
208
|
+
// so a flood produces a single warning rather than one per drop.
|
|
209
|
+
let pendingOverflowWarned = false;
|
|
210
|
+
// Messages received before `connector` is constructed are queued
|
|
211
|
+
// here and flushed in arrival order once construction finishes.
|
|
212
|
+
const pendingMessages = [];
|
|
213
|
+
// Best-effort guess of the parent origin so we don't transfer the
|
|
214
|
+
// MessagePort with `targetOrigin: '*'`. `document.referrer` is the
|
|
215
|
+
// URL of the page that loaded this iframe (the parent in our setup
|
|
216
|
+
// since CompanionConnector iframes are always direct children of
|
|
217
|
+
// the companion host). Falls back to '*' only if the referrer is
|
|
218
|
+
// empty (Referrer-Policy: no-referrer or sandbox).
|
|
219
|
+
const parentOriginGuess = (() => {
|
|
220
|
+
try {
|
|
221
|
+
if (document.referrer)
|
|
222
|
+
return new URL(document.referrer).origin;
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
// ignore — referrer wasn't a valid URL
|
|
226
|
+
}
|
|
227
|
+
return '*';
|
|
228
|
+
})();
|
|
229
|
+
// Detach the spoofable surface only: the window listener and the
|
|
230
|
+
// no-initialize timeout. Used on the SUCCESS path, where `channel.port1`
|
|
231
|
+
// MUST stay open with its `onmessage` handler installed — it is the
|
|
232
|
+
// connector's live ingress (host → connector events) and the egress
|
|
233
|
+
// captured by the `postMessage` closure (connector → host). Closing it
|
|
234
|
+
// here would silently sever every subsequent `setMenu` / `openFrame` /
|
|
235
|
+
// `closeFrame` / `sendMessageToVitreConnector` and inbound
|
|
236
|
+
// `menuClicked` / `frameLoaded` / `messageFromVitreConnector`.
|
|
237
|
+
const cleanupListeners = () => {
|
|
238
|
+
window.removeEventListener('message', windowListener, false);
|
|
239
|
+
if (initializeTimer != null) {
|
|
240
|
+
clearTimeout(initializeTimer);
|
|
241
|
+
initializeTimer = null;
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
// Full teardown: also tear down the channel port. Used on the timeout /
|
|
245
|
+
// failure / reject paths only, where no connector was constructed (or the
|
|
246
|
+
// outer Promise has already rejected), so the port has no live consumer
|
|
247
|
+
// and must not dangle.
|
|
248
|
+
const cleanup = () => {
|
|
249
|
+
cleanupListeners();
|
|
250
|
+
channel.port1.onmessage = null;
|
|
251
|
+
channel.port1.close();
|
|
252
|
+
};
|
|
253
|
+
const handleMessage = async (e, createPostMessage, fromWindow) => {
|
|
254
|
+
// Guard against malformed inbound payloads (null/undefined/primitive
|
|
255
|
+
// `e.data`) before touching `.type`, so a single bad postMessage
|
|
256
|
+
// can't crash the switch / surface as an unhandled rejection.
|
|
257
|
+
if (!e.data || typeof e.data !== 'object')
|
|
258
|
+
return;
|
|
259
|
+
// Origin / source validation for messages arriving via the window
|
|
260
|
+
// listener. The channel port is implicitly trusted (only the host
|
|
261
|
+
// has the matching port2). The `e.source === window.parent` guard
|
|
262
|
+
// stays active for the lifetime of the window listener — during the
|
|
263
|
+
// `await buildOptions` window the listener is still attached, so the
|
|
264
|
+
// source check (which a forging same-origin frame cannot satisfy)
|
|
265
|
+
// must keep applying alongside the origin check.
|
|
266
|
+
if (fromWindow) {
|
|
267
|
+
if (e.source !== window.parent)
|
|
268
|
+
return;
|
|
269
|
+
if (trustedOrigin != null && e.origin !== trustedOrigin)
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
switch (e.data.type) {
|
|
273
|
+
case 'initialize':
|
|
274
|
+
if (initializing || connector != null) {
|
|
275
|
+
console.warn('[CompanionConnector] ignoring duplicate initialize message');
|
|
276
|
+
break;
|
|
277
|
+
}
|
|
278
|
+
initializing = true;
|
|
279
|
+
try {
|
|
280
|
+
const initMsg = e.data;
|
|
281
|
+
// Trust the browser-asserted origin (`e.origin`), not the
|
|
282
|
+
// payload-supplied `companionInfo.origin` which the sender
|
|
283
|
+
// controls and could mis-declare. The origin posting these
|
|
284
|
+
// messages is the companion runtime, so the companion-scoped
|
|
285
|
+
// `companionInfo.origin` is the relevant claim (the Vitre
|
|
286
|
+
// `hostInfo` has no origin). On the channel-port path
|
|
287
|
+
// `e.origin` is empty/meaningless, so fall back to the payload.
|
|
288
|
+
const browserOrigin = fromWindow ? e.origin : '';
|
|
289
|
+
if (fromWindow &&
|
|
290
|
+
browserOrigin &&
|
|
291
|
+
initMsg.companionInfo.origin &&
|
|
292
|
+
initMsg.companionInfo.origin !== browserOrigin) {
|
|
293
|
+
console.warn('[CompanionConnector] companionInfo.origin does not match ' +
|
|
294
|
+
'the browser-asserted parent origin; trusting the latter', {
|
|
295
|
+
claimed: initMsg.companionInfo.origin,
|
|
296
|
+
actual: browserOrigin,
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
trustedOrigin = browserOrigin || initMsg.companionInfo.origin;
|
|
300
|
+
const options = await buildOptions(initMsg.hostInfo);
|
|
301
|
+
connector = new (createConnector ?? CompanionConnector)(createPostMessage(trustedOrigin), initMsg, options);
|
|
302
|
+
// Non-enumerable so it doesn't show up in iteration / JSON of
|
|
303
|
+
// `window`, while keeping parity with the Vitre `Connector`
|
|
304
|
+
// which sets a `mainConnector` global for the same reason
|
|
305
|
+
// (host-side debugging hook).
|
|
306
|
+
Object.defineProperty(window, 'companionConnector', {
|
|
307
|
+
value: connector,
|
|
308
|
+
enumerable: false,
|
|
309
|
+
configurable: true,
|
|
310
|
+
writable: true,
|
|
311
|
+
});
|
|
312
|
+
for (const queued of pendingMessages) {
|
|
313
|
+
connector.raiseMessage(queued);
|
|
314
|
+
}
|
|
315
|
+
pendingMessages.length = 0;
|
|
316
|
+
// Once the MessageChannel is established and the connector is
|
|
317
|
+
// built, drop the window listener and the timeout — port1 is
|
|
318
|
+
// the only legitimate ingress from here on, and detaching
|
|
319
|
+
// removes the spoofable surface. Keep port1 OPEN: it is the
|
|
320
|
+
// connector's live ingress/egress for the rest of its lifetime.
|
|
321
|
+
cleanupListeners();
|
|
322
|
+
resolve(connector);
|
|
323
|
+
}
|
|
324
|
+
catch (err) {
|
|
325
|
+
// Initialization failed. Reject the outer Promise so the caller
|
|
326
|
+
// learns about it (instead of dangling as an unhandled
|
|
327
|
+
// rejection), and tear everything down. Retries are NOT
|
|
328
|
+
// supported: the outer Promise has already settled, so a later
|
|
329
|
+
// `initialize` could only wire up `window.companionConnector`
|
|
330
|
+
// while the awaited handle stays rejected — a silent
|
|
331
|
+
// inconsistent state. Keeping `initializing` true makes any
|
|
332
|
+
// subsequent `initialize` ignored as a duplicate, and `cleanup()`
|
|
333
|
+
// detaches the listener, port, and timer.
|
|
334
|
+
console.error('[CompanionConnector] initialize failed', err);
|
|
335
|
+
cleanup();
|
|
336
|
+
reject(err);
|
|
337
|
+
}
|
|
338
|
+
break;
|
|
339
|
+
default:
|
|
340
|
+
if (connector != null) {
|
|
341
|
+
connector.raiseMessage(e.data);
|
|
342
|
+
}
|
|
343
|
+
else {
|
|
344
|
+
// Cap the pre-init queue: drop the oldest on overflow so a
|
|
345
|
+
// misbehaving host can't grow it without bound. Warn once.
|
|
346
|
+
if (pendingMessages.length >= MAX_PENDING_MESSAGES) {
|
|
347
|
+
pendingMessages.shift();
|
|
348
|
+
if (!pendingOverflowWarned) {
|
|
349
|
+
pendingOverflowWarned = true;
|
|
350
|
+
console.warn('[CompanionConnector] pending-message queue exceeded ' +
|
|
351
|
+
`${MAX_PENDING_MESSAGES} before initialize; dropping oldest`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
pendingMessages.push(e.data);
|
|
355
|
+
}
|
|
356
|
+
break;
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
channel.port1.onmessage = (e) => void handleMessage(e, (_origin) => (message, transfer) => {
|
|
360
|
+
channel.port1.postMessage(message, transfer ?? []);
|
|
361
|
+
}, false).catch((err) => console.error('[CompanionConnector]', err));
|
|
362
|
+
const windowListener = (e) => void handleMessage(e, (origin) => (message, transfer) => {
|
|
363
|
+
window.parent.postMessage(message, origin, transfer);
|
|
364
|
+
}, true).catch((err) => console.error('[CompanionConnector]', err));
|
|
365
|
+
window.addEventListener('message', windowListener, false);
|
|
366
|
+
// Bail out if the host never sends `initialize` (crash, protocol
|
|
367
|
+
// mismatch, dropped message). Detach everything and reject so the
|
|
368
|
+
// caller doesn't await forever.
|
|
369
|
+
let initializeTimer = setTimeout(() => {
|
|
370
|
+
initializeTimer = null;
|
|
371
|
+
if (connector != null || initializing)
|
|
372
|
+
return;
|
|
373
|
+
cleanup();
|
|
374
|
+
const err = new Error(`[CompanionConnector] no initialize received within ` +
|
|
375
|
+
`${INITIALIZE_TIMEOUT_MS}ms`);
|
|
376
|
+
console.warn(err.message);
|
|
377
|
+
reject(err);
|
|
378
|
+
}, INITIALIZE_TIMEOUT_MS);
|
|
379
|
+
window.parent.postMessage({
|
|
380
|
+
type: 'companionConnectorInitializationRequest',
|
|
381
|
+
version: apiVersion,
|
|
382
|
+
}, parentOriginGuess, [channel.port2]);
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
//# sourceMappingURL=CompanionConnector.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CompanionConnector.js","sourceRoot":"","sources":["../../CompanionConnector/CompanionConnector.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAW1C,sEAAsE;AACtE,wEAAwE;AACxE,2EAA2E;AAC3E,2BAA2B;AAC3B,MAAM,OAAO,kBAAkB;IA8B7B,YACmB,WAGR,EACT,WAAyC,EACzC,OAAkC;QALlC;;;;mBAAiB,WAAW;WAGnB;QAjCX,oEAAoE;QACpE,qEAAqE;QACrE,4BAA4B;QACrB;;;;;WAAyC;QAChD,kEAAkE;QAClE,wEAAwE;QACjE;;;;;WAA0C;QAC1C;;;;;WAAa;QACb;;;;;WAAkC;QAEzC,qDAAqD;QAC9C;;;;;WAAsE;QACtE;;;;;WAAkD;QAClD;;;;;WAAoD;QAC3D,wEAAwE;QACxE,sEAAsE;QACtE,wEAAwE;QACxE,oCAAoC;QAC7B;;;;;WAAuE;QAC9E,oEAAoE;QACpE,qEAAqE;QACrE,kEAAkE;QAClE,uCAAuC;QAChC;;;;;WAGE;QACF;;;;;WAAkE;QAUvE,IAAI,CAAC,eAAe,GAAG,WAAW,CAAC,QAAQ,CAAA;QAC3C,IAAI,CAAC,oBAAoB,GAAG,WAAW,CAAC,aAAa,CAAA;QACrD,sEAAsE;QACtE,qEAAqE;QACrE,mDAAmD;QACnD,IAAI,WAAW,CAAC,KAAK,IAAI,IAAI,EAAE,CAAC;YAC9B,OAAO,CAAC,IAAI,CACV,wDAAwD;gBACtD,4DAA4D;gBAC5D,wBAAwB,CAC3B,CAAA;QACH,CAAC;QACD,IAAI,CAAC,KAAK,GAAG,WAAW,CAAC,KAAK,IAAI,EAAE,CAAA;QACpC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,WAAW,CAAC;YACf,IAAI,EAAE,sBAAsB;Y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AO,EAAE,QAAyB,EAAE,EAAE;YACzD,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAA;QACtD,CAAC,EACD,IAAI,CACL,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,sBAAsB,EAAE,GAAG,CAAC,CAAC,CAAA;QAE9D,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,cAAc,EAAE,KAAK,CAAC,CAAA;QAEzD,iEAAiE;QACjE,kEAAkE;QAClE,gCAAgC;QAChC,IAAI,eAAe,GAAyC,UAAU,CACpE,GAAG,EAAE;YACH,eAAe,GAAG,IAAI,CAAA;YACtB,IAAI,SAAS,IAAI,IAAI,IAAI,YAAY;gBAAE,OAAM;YAC7C,OAAO,EAAE,CAAA;YACT,MAAM,GAAG,GAAG,IAAI,KAAK,CACnB,qDAAqD;gBACnD,GAAG,qBAAqB,IAAI,CAC/B,CAAA;YACD,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;YACzB,MAAM,CAAC,GAAG,CAAC,CAAA;QACb,CAAC,EACD,qBAAqB,CACtB,CAAA;QAED,MAAM,CAAC,MAAM,CAAC,WAAW,CACvB;YACE,IAAI,EAAE,yCAAyC;YAC/C,OAAO,EAAE,UAAU;SACpB,EACD,iBAAiB,EACjB,CAAC,OAAO,CAAC,KAAK,CAAC,CAChB,CAAA;IACH,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import type { FileData, OpenFrameOptions } from '../Common/index.js'\nimport type { RootMenuEntry } from '../Connector/Connector.Model.js'\nimport { apiVersion } from '../Version.js'\nimport type {\n CompanionConnectorApiMessagesIn,\n CompanionConnectorApiMessagesOut,\n CompanionConnectorOptions,\n CompanionHostInformation,\n CompanionInformation,\n CompanionInitializeConnector,\n SetMenuOptions,\n} from './CompanionConnector.Model.js'\n\n/// Runtime instance handed to a companion connector once the host has\n/// finished the `initialize` handshake. The shape is intentionally much\n/// smaller than the Vitre `Connector` — anything not in this class doesn't\n/// apply on the companion.\nexport class CompanionConnector {\n /// Identity of the Vitre this companion connector is hosted against\n /// (the host). Read-only — the host pushes updates by reinitializing\n /// the connector if needed.\n public hostInformation: CompanionHostInformation\n /// This companion's own identity and runtime context (name, user,\n /// language, origin, version). Distinct from `hostInformation` (Vitre).\n public companionInformation: CompanionInformation\n public appId: string\n public options: CompanionConnectorOptions\n\n // Callbacks — host → connector events. All optional.\n public onMenuClicked?: (menuId: string, tag: any, isChecked: boolean) => void\n public onFrameLoaded?: (frameConnectorId: string) => void\n public onFrameUnloaded?: (frameConnectorId: string) => void\n /// Called when a shared frame's owner was (re)assigned (at open time or\n /// post-hoc, including by another device). `owner` is the new owner's\n /// device id (`HostInformation.devicesInSpace[].id`). Mirrors the Vitre\n /// `Connector.onFrameOwnerChanged`.\n public onFrameOwnerChanged?: (frameConnectorId: string, owner: string) => void\n /// Called when the matching Vitre `Connector` (same `appId`) sent a\n /// message via `sendMessageToCompanionConnector`. The companion side\n /// does not know which Vitre user sent the message — it is always\n /// \"the\" Vitre connector for that app.\n public onMessageFromVitreConnector?: (\n message: string,\n fileData?: FileData,\n ) => void\n public onMessageReceived?: (msg: CompanionConnectorApiMessagesIn) => void\n\n constructor(\n private readonly postMessage: (\n message: CompanionConnectorApiMessagesOut,\n transfer?: Transferable[],\n ) => void,\n initMessage: CompanionInitializeConnector,\n options: CompanionConnectorOptions,\n ) {\n this.hostInformation = initMessage.hostInfo\n this.companionInformation = initMessage.companionInfo\n // `appId` is optional — a host may legitimately omit it for a generic\n // connector — but message routing keys on it, so warn when the empty\n // fallback is hit to surface a misconfigured host.\n if (initMessage.appId == null) {\n console.warn(\n '[CompanionConnector] initialize message has no appId; ' +\n 'falling back to an empty string — Vitre-connector message ' +\n 'routing will not match',\n )\n }\n this.appId = initMessage.appId ?? ''\n this.options = options\n this.postMessage({\n type: 'connectorInitialized',\n options,\n })\n }\n\n /// Handler called by `initializeCompanionConnector` for every inbound\n /// message after the initial `initialize`. Exposed for testing and for\n /// hosts that drive the connector through a side channel.\n raiseMessage(msg: CompanionConnectorApiMessagesIn) {\n switch (msg.type) {\n case 'menuClicked':\n this.onMenuClicked?.(msg.menuId, msg.tag, msg.isChecked)\n break\n case 'frameLoaded':\n this.onFrameLoaded?.(msg.frameConnectorId)\n break\n case 'frameUnloaded':\n this.onFrameUnloaded?.(msg.frameConnectorId)\n break\n case 'frameOwnerChanged':\n this.onFrameOwnerChanged?.(msg.frameConnectorId, msg.owner)\n break\n case 'messageFromVitreConnector':\n this.onMessageFromVitreConnector?.(msg.message, msg.fileData)\n break\n // `initialize` is handled by the bootstrap, not here. Return early\n // so the public `onMessageReceived` callback is NOT invoked with it\n // — the SDK documents `initialize` as not delivered through this\n // handler, and falling through would break that contract.\n case 'initialize':\n return\n }\n this.onMessageReceived?.(msg)\n }\n\n /// Publish this companion connector's menu for the app.\n ///\n /// By default (`mode: 'replace'`, or no options) the menu fully replaces\n /// what the Vitre-side `Connector` published for this app on the\n /// companion. Pass `{ mode: 'append' }` to instead *add* these entries\n /// after the Vitre menu without hiding it — useful for contributing\n /// companion-only entries on top of a Vitre-managed menu.\n public setMenu(menu: RootMenuEntry[], options?: SetMenuOptions) {\n this.postMessage({ type: 'setRootMenu', menu, mode: options?.mode })\n }\n\n public openFrame(options: OpenFrameOptions) {\n this.postMessage({ type: 'openFrame', options })\n }\n\n public closeFrame(frameConnectorId: string) {\n this.postMessage({ type: 'closeFrame', frameConnectorId })\n }\n\n /// Reassign the owner of an already-opened shared frame. `owner` is a\n /// device id from `HostInformation.devicesInSpace[].id`. Drives the\n /// languette colour and, when the owner is a Vitre, hosting transfer so\n /// the frame survives the opener disconnecting.\n public setFrameOwner(frameConnectorId: string, owner: string) {\n this.postMessage({ type: 'setFrameOwner', frameConnectorId, owner })\n }\n\n /// Open (or focus) the paired frame full-page on this companion. The\n /// host treats this as a navigation event: any current SubPage\n /// (camera-share, another frame, etc.) is closed in favour of the new\n /// frame, mirroring the behaviour when a Vitre-driven open triggers\n /// `autoOpen` on the main page. If the Vitre side is reachable the\n /// host also announces the open to it so a paired Vitre frame mounts.\n ///\n /// `frameConnectorId` MUST match the paired Vitre frame's id so both\n /// sides bind to the same frame (per-frame messages + yjs subdoc relay\n /// rely on this).\n public openCompanionFrame(\n frameConnectorId: string,\n options: Omit<OpenFrameOptions, 'frameConnectorId'>,\n ) {\n this.postMessage({\n type: 'openCompanionFrame',\n frameConnectorId,\n options,\n })\n }\n\n /// Send an opaque message to the matching Vitre-side `Connector`. The\n /// payload is forwarded unchanged. There is no targeted addressing —\n /// the message goes to \"the\" Vitre connector for this app.\n public sendMessageToVitreConnector(message: string, fileData?: FileData) {\n this.postMessage({\n type: 'sendMessageToVitreConnector',\n message,\n fileData,\n })\n }\n}\n\ntype PostMessageOut = (\n message: CompanionConnectorApiMessagesOut,\n transfer?: Transferable[],\n) => void\n\n/// Hard cap on the pre-`initialize` queue. A host that floods messages\n/// before/while `initialize` is in flight (or one that never sends it)\n/// must not grow this buffer without bound. On overflow we drop the\n/// oldest queued message and warn once.\nconst MAX_PENDING_MESSAGES = 200\n\n/// Client-side bail-out: if `initialize` never arrives (host crash,\n/// protocol mismatch, dropped postMessage) the outer Promise rejects\n/// after this delay instead of dangling forever.\nconst INITIALIZE_TIMEOUT_MS = 30_000\n\n/// Bootstrap a companion connector. Mirrors `initializeConnector` from\n/// `../Connector/Connector.ts`: posts a request to the parent window,\n/// waits for the host's `initialize`, then resolves with a ready instance.\n///\n/// `buildOptions` is invoked once when the host pushes `initialize`. It\n/// returns the connector's declared name, optional icon, and optional\n/// initial menu. The returned options are echoed back to the host inside\n/// `connectorInitialized`.\n///\n/// Two overloads: when `createConnector` is supplied the resolved\n/// instance is the caller's `T extends CompanionConnector`; when it is\n/// omitted the resolved instance is a plain `CompanionConnector`. This\n/// keeps the return type sound — the omitted-factory path genuinely\n/// builds a base `CompanionConnector`, never a `T`.\nexport async function initializeCompanionConnector<\n T extends CompanionConnector,\n>(\n buildOptions: (\n host: CompanionHostInformation,\n ) => CompanionConnectorOptions | Promise<CompanionConnectorOptions>,\n createConnector: new (\n postMessage: PostMessageOut,\n initMessage: CompanionInitializeConnector,\n options: CompanionConnectorOptions,\n ) => T,\n): Promise<T>\nexport async function initializeCompanionConnector(\n buildOptions: (\n host: CompanionHostInformation,\n ) => CompanionConnectorOptions | Promise<CompanionConnectorOptions>,\n): Promise<CompanionConnector>\nexport async function initializeCompanionConnector<\n T extends CompanionConnector,\n>(\n buildOptions: (\n host: CompanionHostInformation,\n ) => CompanionConnectorOptions | Promise<CompanionConnectorOptions>,\n createConnector?: new (\n postMessage: PostMessageOut,\n initMessage: CompanionInitializeConnector,\n options: CompanionConnectorOptions,\n ) => T,\n): Promise<T | CompanionConnector> {\n return await new Promise<T | CompanionConnector>((resolve, reject) => {\n const channel = new MessageChannel()\n let connector: T | CompanionConnector | null = null\n // Set synchronously the moment the first `initialize` arrives so a\n // second one delivered between the await and the assignment below\n // is ignored instead of constructing a second instance.\n let initializing = false\n // Trusted origin learned from the first initialize message. Until\n // it is set, the window listener only accepts messages whose\n // `source === window.parent`. After it is set, the channel port is\n // the only ingress and the window listener is detached.\n let trustedOrigin: string | null = null\n // Whether overflow on `pendingMessages` has already been warned about,\n // so a flood produces a single warning rather than one per drop.\n let pendingOverflowWarned = false\n // Messages received before `connector` is constructed are queued\n // here and flushed in arrival order once construction finishes.\n const pendingMessages: CompanionConnectorApiMessagesIn[] = []\n\n // Best-effort guess of the parent origin so we don't transfer the\n // MessagePort with `targetOrigin: '*'`. `document.referrer` is the\n // URL of the page that loaded this iframe (the parent in our setup\n // since CompanionConnector iframes are always direct children of\n // the companion host). Falls back to '*' only if the referrer is\n // empty (Referrer-Policy: no-referrer or sandbox).\n const parentOriginGuess = (() => {\n try {\n if (document.referrer) return new URL(document.referrer).origin\n } catch {\n // ignore — referrer wasn't a valid URL\n }\n return '*'\n })()\n\n // Detach the spoofable surface only: the window listener and the\n // no-initialize timeout. Used on the SUCCESS path, where `channel.port1`\n // MUST stay open with its `onmessage` handler installed — it is the\n // connector's live ingress (host → connector events) and the egress\n // captured by the `postMessage` closure (connector → host). Closing it\n // here would silently sever every subsequent `setMenu` / `openFrame` /\n // `closeFrame` / `sendMessageToVitreConnector` and inbound\n // `menuClicked` / `frameLoaded` / `messageFromVitreConnector`.\n const cleanupListeners = () => {\n window.removeEventListener('message', windowListener, false)\n if (initializeTimer != null) {\n clearTimeout(initializeTimer)\n initializeTimer = null\n }\n }\n\n // Full teardown: also tear down the channel port. Used on the timeout /\n // failure / reject paths only, where no connector was constructed (or the\n // outer Promise has already rejected), so the port has no live consumer\n // and must not dangle.\n const cleanup = () => {\n cleanupListeners()\n channel.port1.onmessage = null\n channel.port1.close()\n }\n\n const handleMessage = async (\n e: MessageEvent<CompanionConnectorApiMessagesIn>,\n createPostMessage: (origin: string) => PostMessageOut,\n fromWindow: boolean,\n ) => {\n // Guard against malformed inbound payloads (null/undefined/primitive\n // `e.data`) before touching `.type`, so a single bad postMessage\n // can't crash the switch / surface as an unhandled rejection.\n if (!e.data || typeof e.data !== 'object') return\n\n // Origin / source validation for messages arriving via the window\n // listener. The channel port is implicitly trusted (only the host\n // has the matching port2). The `e.source === window.parent` guard\n // stays active for the lifetime of the window listener — during the\n // `await buildOptions` window the listener is still attached, so the\n // source check (which a forging same-origin frame cannot satisfy)\n // must keep applying alongside the origin check.\n if (fromWindow) {\n if (e.source !== window.parent) return\n if (trustedOrigin != null && e.origin !== trustedOrigin) return\n }\n\n switch (e.data.type) {\n case 'initialize':\n if (initializing || connector != null) {\n console.warn(\n '[CompanionConnector] ignoring duplicate initialize message',\n )\n break\n }\n initializing = true\n try {\n const initMsg = e.data\n // Trust the browser-asserted origin (`e.origin`), not the\n // payload-supplied `companionInfo.origin` which the sender\n // controls and could mis-declare. The origin posting these\n // messages is the companion runtime, so the companion-scoped\n // `companionInfo.origin` is the relevant claim (the Vitre\n // `hostInfo` has no origin). On the channel-port path\n // `e.origin` is empty/meaningless, so fall back to the payload.\n const browserOrigin = fromWindow ? e.origin : ''\n if (\n fromWindow &&\n browserOrigin &&\n initMsg.companionInfo.origin &&\n initMsg.companionInfo.origin !== browserOrigin\n ) {\n console.warn(\n '[CompanionConnector] companionInfo.origin does not match ' +\n 'the browser-asserted parent origin; trusting the latter',\n {\n claimed: initMsg.companionInfo.origin,\n actual: browserOrigin,\n },\n )\n }\n trustedOrigin = browserOrigin || initMsg.companionInfo.origin\n const options = await buildOptions(initMsg.hostInfo)\n connector = new (createConnector ?? CompanionConnector)(\n createPostMessage(trustedOrigin),\n initMsg,\n options,\n )\n // Non-enumerable so it doesn't show up in iteration / JSON of\n // `window`, while keeping parity with the Vitre `Connector`\n // which sets a `mainConnector` global for the same reason\n // (host-side debugging hook).\n Object.defineProperty(window, 'companionConnector', {\n value: connector,\n enumerable: false,\n configurable: true,\n writable: true,\n })\n for (const queued of pendingMessages) {\n connector.raiseMessage(queued)\n }\n pendingMessages.length = 0\n // Once the MessageChannel is established and the connector is\n // built, drop the window listener and the timeout — port1 is\n // the only legitimate ingress from here on, and detaching\n // removes the spoofable surface. Keep port1 OPEN: it is the\n // connector's live ingress/egress for the rest of its lifetime.\n cleanupListeners()\n resolve(connector)\n } catch (err) {\n // Initialization failed. Reject the outer Promise so the caller\n // learns about it (instead of dangling as an unhandled\n // rejection), and tear everything down. Retries are NOT\n // supported: the outer Promise has already settled, so a later\n // `initialize` could only wire up `window.companionConnector`\n // while the awaited handle stays rejected — a silent\n // inconsistent state. Keeping `initializing` true makes any\n // subsequent `initialize` ignored as a duplicate, and `cleanup()`\n // detaches the listener, port, and timer.\n console.error('[CompanionConnector] initialize failed', err)\n cleanup()\n reject(err)\n }\n break\n default:\n if (connector != null) {\n connector.raiseMessage(e.data)\n } else {\n // Cap the pre-init queue: drop the oldest on overflow so a\n // misbehaving host can't grow it without bound. Warn once.\n if (pendingMessages.length >= MAX_PENDING_MESSAGES) {\n pendingMessages.shift()\n if (!pendingOverflowWarned) {\n pendingOverflowWarned = true\n console.warn(\n '[CompanionConnector] pending-message queue exceeded ' +\n `${MAX_PENDING_MESSAGES} before initialize; dropping oldest`,\n )\n }\n }\n pendingMessages.push(e.data)\n }\n break\n }\n }\n\n channel.port1.onmessage = (e) =>\n void handleMessage(\n e,\n (_origin: string) => (message, transfer?: Transferable[]) => {\n channel.port1.postMessage(message, transfer ?? [])\n },\n false,\n ).catch((err) => console.error('[CompanionConnector]', err))\n\n const windowListener = (e: MessageEvent<CompanionConnectorApiMessagesIn>) =>\n void handleMessage(\n e,\n (origin: string) => (message, transfer?: Transferable[]) => {\n window.parent.postMessage(message, origin, transfer)\n },\n true,\n ).catch((err) => console.error('[CompanionConnector]', err))\n\n window.addEventListener('message', windowListener, false)\n\n // Bail out if the host never sends `initialize` (crash, protocol\n // mismatch, dropped message). Detach everything and reject so the\n // caller doesn't await forever.\n let initializeTimer: ReturnType<typeof setTimeout> | null = setTimeout(\n () => {\n initializeTimer = null\n if (connector != null || initializing) return\n cleanup()\n const err = new Error(\n `[CompanionConnector] no initialize received within ` +\n `${INITIALIZE_TIMEOUT_MS}ms`,\n )\n console.warn(err.message)\n reject(err)\n },\n INITIALIZE_TIMEOUT_MS,\n )\n\n window.parent.postMessage(\n {\n type: 'companionConnectorInitializationRequest',\n version: apiVersion,\n },\n parentOriginGuess,\n [channel.port2],\n )\n })\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../CompanionConnector/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAA;AACvC,cAAc,+BAA+B,CAAA","sourcesContent":["export * from './CompanionConnector.js'\nexport * from './CompanionConnector.Model.js'\n"]}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { Frame } from '../Frame/Frame.js';
|
|
2
|
+
import type { InitFrameOptions, ViewOptions } from '../Frame/Frame.Model.js';
|
|
3
|
+
import type { Device, FileData, HostInformation } from '../Common/index.js';
|
|
4
|
+
/**
|
|
5
|
+
* Runtime class for a frame iframe loaded by the la Vitre **companion**.
|
|
6
|
+
* Extends the shared `Frame` runtime (same wire, same lifecycle) with the two
|
|
7
|
+
* send methods that ONLY make sense — and are ONLY decoded by the host — on the
|
|
8
|
+
* companion side:
|
|
9
|
+
*
|
|
10
|
+
* - `sendMessageToVitreConnector` → host message `sendToVitreConnector`, which
|
|
11
|
+
* the companion host relays to the app's Vitre-side main `Connector`
|
|
12
|
+
* (`onMessageFromCompanionFrame`).
|
|
13
|
+
* - `closeOnCompanion` → host message `closeOnCompanion` (local companion
|
|
14
|
+
* close; the Vitre keeps its own frame).
|
|
15
|
+
*
|
|
16
|
+
* Both live HERE, not on `Frame`: the Vitre host does NOT decode those message
|
|
17
|
+
* types, so calling them from a Vitre frame produced a "case type not found"
|
|
18
|
+
* parse error on the Vitre. Keeping them off `Frame` makes that misuse a
|
|
19
|
+
* compile error. A Vitre frame that needs to reach its own connector uses
|
|
20
|
+
* `sendToLocalMainConnector` instead.
|
|
21
|
+
*/
|
|
22
|
+
declare class CompanionFrameImpl extends Frame {
|
|
23
|
+
/**
|
|
24
|
+
* Send a message straight to this app's Vitre-side main `Connector` — even
|
|
25
|
+
* when there is NO paired Vitre frame (a local companion frame). The Vitre
|
|
26
|
+
* connector receives it on `onMessageFromCompanionFrame(fromCompanionId,
|
|
27
|
+
* frameConnectorId, message, fileData)`, `frameConnectorId` set to this
|
|
28
|
+
* frame's id so the app can tell which companion frame spoke. Frame-side
|
|
29
|
+
* counterpart of `CompanionConnector.sendMessageToVitreConnector` (which has
|
|
30
|
+
* no frame id).
|
|
31
|
+
*/
|
|
32
|
+
sendMessageToVitreConnector(message: string, fileData?: FileData): void;
|
|
33
|
+
/**
|
|
34
|
+
* Close the iframe locally on the companion and remove this companion from
|
|
35
|
+
* the per-frame `framePresence` on the Vitre. The Vitre keeps its own frame
|
|
36
|
+
* open (`openFrame` re-shows the same frame); use `close()` to close globally.
|
|
37
|
+
* See `FrameApiMessagesOut`'s `closeOnCompanion` arm doc for the rationale.
|
|
38
|
+
*/
|
|
39
|
+
closeOnCompanion(): void;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* SDK surface intended for apps running inside a frame iframe loaded by the
|
|
43
|
+
* la Vitre **companion** (not by a Vitre). Mirrors the `Connector` /
|
|
44
|
+
* `CompanionConnector` split: a companion frame talks to its paired Vitre frame
|
|
45
|
+
* and to its own host, but has no notion of other Vitres in the space — so the
|
|
46
|
+
* broadcast-style send methods (`sendMessageTo`, `sendMessageToAll`,
|
|
47
|
+
* `sendKnockKnock`) and the Vitre-only side effects (`setVitreSettings`,
|
|
48
|
+
* `setShareTarget`, the device-event callbacks) are deliberately not exposed.
|
|
49
|
+
* Conversely, the companion-only `sendMessageToVitreConnector` /
|
|
50
|
+
* `closeOnCompanion` (see {@link CompanionFrameImpl}) are exposed HERE and
|
|
51
|
+
* nowhere else — in particular NOT on the Vitre `Frame`.
|
|
52
|
+
*
|
|
53
|
+
* `crdt` flows through the la Vitre Yjs transport identical to the Vitre side —
|
|
54
|
+
* the same Y.Doc and Awareness end up in sync on the Vitre frame, on other
|
|
55
|
+
* companions of the same `(appId, frameId)` presence set, and on this
|
|
56
|
+
* companion. Apps using carbone or any other Y-doc-backed library can keep
|
|
57
|
+
* using `createVitreSyncAdapter(frame)` unchanged — the adapter only touches
|
|
58
|
+
* `frame.crdt`.
|
|
59
|
+
*/
|
|
60
|
+
export type CompanionFrame = Pick<CompanionFrameImpl, 'id' | 'appId' | 'options' | 'initOptions' | 'initiator' | 'hostInformation' | 'companionInformation' | 'state' | 'crdt' | 'blobs' | 'yjsDoc' | 'isFullscreen' | 'isBorderless' | 'position' | 'zIndex' | 'setFullscreen' | 'setWindowed' | 'setMenu' | 'sendToVitreFrame' | 'sendMessageToVitreConnector' | 'canShareStream' | 'shareStream' | 'replaceShareStream' | 'stopShareStream' | 'attachStream' | 'detachStream' | 'getIceServers' | 'onSharedStream' | 'onSharedStreamRemoved' | 'close' | 'closeOnCompanion' | 'onLocalConnectorMessageReceived' | 'onMessageReceived' | 'onMenuClicked' | 'onFieldUpdated' | 'onFullscreenChanged' | 'onBorderlessChanged' | 'onYjsSynced' | 'onYjsUpdate'>;
|
|
61
|
+
/**
|
|
62
|
+
* Mirror of `initializeFrame` for the companion side. Same wire-level
|
|
63
|
+
* handshake (`connectorInitializationRequest` posted with a MessageChannel
|
|
64
|
+
* `port2` transferred to the parent) — the companion host's behaviour is
|
|
65
|
+
* identical to the Vitre's at that protocol point (see
|
|
66
|
+
* `lavitre-companion/.../CompanionApps.State.fs:postFrameInit`). It instantiates
|
|
67
|
+
* the companion runtime subclass `CompanionFrameImpl`, so the returned
|
|
68
|
+
* `CompanionFrame` carries the companion-only send methods; existing helpers
|
|
69
|
+
* like `createVitreSyncAdapter` keep working (they only touch `frame.crdt`).
|
|
70
|
+
*
|
|
71
|
+
* Usage:
|
|
72
|
+
* const frame = await initializeCompanionFrame((host, initiator, opts) => ({
|
|
73
|
+
* name: 'My App',
|
|
74
|
+
* allowFullscreen: true,
|
|
75
|
+
* }))
|
|
76
|
+
* frame.sendToVitreFrame({ kind: 'hello', from: 'companion' })
|
|
77
|
+
* frame.closeOnCompanion()
|
|
78
|
+
*/
|
|
79
|
+
export declare function initializeCompanionFrame(init: (info: HostInformation, initiator: Device, options: InitFrameOptions, state?: Record<string, any>) => ViewOptions): Promise<CompanionFrame>;
|
|
80
|
+
/**
|
|
81
|
+
* Convenience guard for apps that ship a single `frame.tsx` entry but want to
|
|
82
|
+
* branch behaviour based on context. Reads the dedicated
|
|
83
|
+
* `hostInformation.isCompanion` flag set by `lavitre-companion`
|
|
84
|
+
* (CompanionApps.State.fs:buildVitreLikeHostInformation). Old hosts that
|
|
85
|
+
* predate the flag omit it, in which case we conservatively return `false` and
|
|
86
|
+
* the caller behaves as on a Vitre — the safer default since the Vitre surface
|
|
87
|
+
* is the superset.
|
|
88
|
+
*
|
|
89
|
+
* Note: to USE the companion-only send methods (`sendMessageToVitreConnector`,
|
|
90
|
+
* `closeOnCompanion`) you need a `CompanionFrame` from `initializeCompanionFrame`
|
|
91
|
+
* (ship a dedicated companion entry). This guard only narrows behaviour/UX, not
|
|
92
|
+
* the static type — a value from `initializeFrame` stays a Vitre `Frame`.
|
|
93
|
+
*
|
|
94
|
+
* Usage:
|
|
95
|
+
* const frame = await initializeFrame(init)
|
|
96
|
+
* if (isCompanionFrame(frame.hostInformation)) {
|
|
97
|
+
* // Apply companion-only UX (e.g. a "Leave this frame" button)
|
|
98
|
+
* } else {
|
|
99
|
+
* // Vitre surface: sendMessageTo / sendKnockKnock / setVitreSettings / …
|
|
100
|
+
* }
|
|
101
|
+
*/
|
|
102
|
+
export declare function isCompanionFrame(hostInformation: HostInformation): boolean;
|
|
103
|
+
export {};
|