electron-cast 0.1.1 → 0.3.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/CHANGELOG.md +24 -0
- package/README.md +49 -14
- package/dist/electron/main.d.ts +15 -2
- package/dist/electron/main.js +200 -14
- package/dist/electron/main.js.map +1 -1
- package/dist/electron/preload.d.ts +13 -1
- package/dist/electron/preload.js +50 -1
- package/dist/electron/preload.js.map +1 -1
- package/dist/electron/presentation-envelope.d.ts +60 -0
- package/dist/electron/presentation-envelope.js +296 -0
- package/dist/electron/presentation-envelope.js.map +1 -0
- package/dist/electron/presentation-handler.d.ts +100 -0
- package/dist/electron/presentation-handler.js +487 -0
- package/dist/electron/presentation-handler.js.map +1 -0
- package/dist/electron/session-service.js +2 -0
- package/dist/electron/session-service.js.map +1 -1
- package/dist/polyfill/bridge-types.d.ts +4 -0
- package/dist/polyfill/install.js +1044 -24
- package/dist/polyfill/install.js.map +1 -1
- package/dist/polyfill/presentation-standin.d.ts +13 -0
- package/dist/polyfill/presentation-standin.js +275 -0
- package/dist/polyfill/presentation-standin.js.map +1 -0
- package/package.json +4 -3
- package/src/electron/main.ts +197 -14
- package/src/electron/preload.ts +59 -1
- package/src/electron/presentation-envelope.ts +311 -0
- package/src/electron/presentation-handler.ts +518 -0
- package/src/electron/session-service.ts +2 -0
- package/src/polyfill/bridge-types.ts +4 -1
- package/src/polyfill/install.ts +1055 -20
- package/src/polyfill/presentation-standin.ts +271 -0
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
// Main-process presentation handler: plays the part of Chrome's Media Router for Google's clank.js Cast
|
|
2
|
+
// sender. The page talks to it in Chromium's private JSON envelope over a connection; the handler drives
|
|
3
|
+
// CastSessionService through service.handle(sender, method, params) and translates with the codec in
|
|
4
|
+
// presentation-envelope.ts.
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import type { BridgeEvent, InitializeResult, SessionSnapshot } from "../polyfill/bridge-types.ts";
|
|
7
|
+
import type { CastSessionService } from "./session-service.ts";
|
|
8
|
+
import {
|
|
9
|
+
MEDIA_NAMESPACE,
|
|
10
|
+
envelope,
|
|
11
|
+
isMediaRequest,
|
|
12
|
+
parseEnvelope,
|
|
13
|
+
parsePresentationUrl,
|
|
14
|
+
receiverLabel,
|
|
15
|
+
receiverMediaType,
|
|
16
|
+
toMediaEntry,
|
|
17
|
+
toReceiver,
|
|
18
|
+
toSession,
|
|
19
|
+
} from "./presentation-envelope.ts";
|
|
20
|
+
import type { ParsedEnvelope } from "./presentation-envelope.ts";
|
|
21
|
+
|
|
22
|
+
export interface PresentationRequestInfo { urls: string[]; origin: string; senderId: number }
|
|
23
|
+
|
|
24
|
+
export interface PresentationConnectionHandle {
|
|
25
|
+
readonly id: string;
|
|
26
|
+
readonly url: string;
|
|
27
|
+
/** Page -> handler: one JSON envelope string. Ignored once the connection is closed. */
|
|
28
|
+
send(message: string): void;
|
|
29
|
+
/** The page closed the connection: leaveSession, then onclose("closed"). */
|
|
30
|
+
close(): void;
|
|
31
|
+
/** The page terminated the connection: stopSession, then onclose("terminated"). */
|
|
32
|
+
terminate(): void;
|
|
33
|
+
/** Handler -> page. While null, messages are queued; assigning a function flushes the queue in order. */
|
|
34
|
+
onmessage: ((message: string) => void) | null;
|
|
35
|
+
/** Called once, when the connection closes for any reason. */
|
|
36
|
+
onclose: ((reason: "closed" | "terminated") => void) | null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** An error thrown by the handler; `name` is a DOMException name the page can map onto. */
|
|
40
|
+
export class PresentationError extends Error {
|
|
41
|
+
constructor(name: string, message: string) {
|
|
42
|
+
super(message);
|
|
43
|
+
this.name = name;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A live getAvailability watch of one sender. */
|
|
48
|
+
interface Watch { onchange: (value: boolean) => void }
|
|
49
|
+
|
|
50
|
+
/** Per-sender handler state: its connections keyed by clientId, and its availability watches. */
|
|
51
|
+
interface SenderState {
|
|
52
|
+
conns: Map<string, Conn>;
|
|
53
|
+
watches: Map<number, Watch>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The pending-media table is bounded like Chromium's (kMaxPendingMediaRequests, best known value). */
|
|
57
|
+
const MAX_PENDING_MEDIA = 100;
|
|
58
|
+
/** Request ids wrap back to 1 past this value. */
|
|
59
|
+
const REQUEST_ID_MAX = 2 ** 31;
|
|
60
|
+
const CAST_SESSION_PREFIX = "cast-session_";
|
|
61
|
+
|
|
62
|
+
/** One presentation connection between the handler and a page. */
|
|
63
|
+
class Conn implements PresentationConnectionHandle {
|
|
64
|
+
readonly id: string;
|
|
65
|
+
readonly url: string;
|
|
66
|
+
readonly senderId: number;
|
|
67
|
+
readonly origin: string;
|
|
68
|
+
readonly clientId: string;
|
|
69
|
+
/** Media request ids handed out to the receiver, mapped back to the page's sequence numbers. */
|
|
70
|
+
readonly pendingMedia = new Map<number, number>();
|
|
71
|
+
sessionId: string | null;
|
|
72
|
+
/** The latest session snapshot seen for this connection (namespaces, receiver). */
|
|
73
|
+
snapshot: SessionSnapshot | null;
|
|
74
|
+
onclose: ((reason: "closed" | "terminated") => void) | null = null;
|
|
75
|
+
private readonly owner: CastPresentationHandler;
|
|
76
|
+
private queue: string[] = [];
|
|
77
|
+
private msgHandler: ((message: string) => void) | null = null;
|
|
78
|
+
private isClosed = false;
|
|
79
|
+
|
|
80
|
+
constructor(
|
|
81
|
+
owner: CastPresentationHandler,
|
|
82
|
+
id: string,
|
|
83
|
+
url: string,
|
|
84
|
+
senderId: number,
|
|
85
|
+
origin: string,
|
|
86
|
+
clientId: string,
|
|
87
|
+
sessionId: string | null,
|
|
88
|
+
snapshot: SessionSnapshot | null,
|
|
89
|
+
) {
|
|
90
|
+
this.owner = owner;
|
|
91
|
+
this.id = id;
|
|
92
|
+
this.url = url;
|
|
93
|
+
this.senderId = senderId;
|
|
94
|
+
this.origin = origin;
|
|
95
|
+
this.clientId = clientId;
|
|
96
|
+
this.sessionId = sessionId;
|
|
97
|
+
this.snapshot = snapshot;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
get onmessage(): ((message: string) => void) | null {
|
|
101
|
+
return this.msgHandler;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
set onmessage(fn: ((message: string) => void) | null) {
|
|
105
|
+
this.msgHandler = fn;
|
|
106
|
+
if (fn !== null && !this.isClosed) {
|
|
107
|
+
const queued = this.queue;
|
|
108
|
+
this.queue = [];
|
|
109
|
+
for (const message of queued) fn(message);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
get closed(): boolean {
|
|
114
|
+
return this.isClosed;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
send(message: string): void {
|
|
118
|
+
if (this.isClosed) return;
|
|
119
|
+
this.owner.dispatch(this, message);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
close(): void {
|
|
123
|
+
this.owner.pageClosed(this);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
terminate(): void {
|
|
127
|
+
this.owner.pageTerminated(this);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Handler -> page: deliver directly, or queue until onmessage is assigned. */
|
|
131
|
+
deliver(message: string): void {
|
|
132
|
+
if (this.isClosed) return;
|
|
133
|
+
if (this.msgHandler !== null) this.msgHandler(message);
|
|
134
|
+
else this.queue.push(message);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Close once: no more sends or deliveries, the queue is dropped, onclose fires. */
|
|
138
|
+
end(reason: "closed" | "terminated"): void {
|
|
139
|
+
if (this.isClosed) return;
|
|
140
|
+
this.isClosed = true;
|
|
141
|
+
this.queue.length = 0;
|
|
142
|
+
const cb = this.onclose;
|
|
143
|
+
if (cb !== null) cb(reason);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Drives CastSessionService on behalf of pages speaking the presentation envelope. */
|
|
148
|
+
export class CastPresentationHandler {
|
|
149
|
+
private readonly service: Pick<CastSessionService, "handle">;
|
|
150
|
+
private readonly token: string;
|
|
151
|
+
private readonly senders = new Map<number, SenderState>();
|
|
152
|
+
private nextRequestId: number;
|
|
153
|
+
private watchSeq = 0;
|
|
154
|
+
|
|
155
|
+
constructor(opts: { service: Pick<CastSessionService, "handle">; token?: string }) {
|
|
156
|
+
this.service = opts.service;
|
|
157
|
+
this.token = opts.token ?? randomBytes(16).toString("hex");
|
|
158
|
+
this.nextRequestId = 1 + Math.floor(Math.random() * (2 ** 30 - 1));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Is the app available on some receiver? Resolves false for unparseable URLs and failed calls. */
|
|
162
|
+
async getAvailability(req: PresentationRequestInfo & { onchange(value: boolean): void; signal: AbortSignal }): Promise<boolean> {
|
|
163
|
+
const parsed = parsePresentationUrl((req.urls[0] ?? ""));
|
|
164
|
+
if (parsed === null) return false;
|
|
165
|
+
const state = this.senderState(req.senderId);
|
|
166
|
+
const watchId = ++this.watchSeq;
|
|
167
|
+
state.watches.set(watchId, { onchange: req.onchange });
|
|
168
|
+
const signal = req.signal;
|
|
169
|
+
if (signal.aborted) {
|
|
170
|
+
state.watches.delete(watchId);
|
|
171
|
+
} else {
|
|
172
|
+
signal.addEventListener("abort", () => {
|
|
173
|
+
state.watches.delete(watchId);
|
|
174
|
+
}, { once: true });
|
|
175
|
+
}
|
|
176
|
+
const res = await this.service.handle(this.senderOf(req.senderId, req.origin), "initialize", {
|
|
177
|
+
appId: parsed.appId,
|
|
178
|
+
capabilities: parsed.capabilities,
|
|
179
|
+
autoJoinPolicy: "page_scoped",
|
|
180
|
+
});
|
|
181
|
+
if (!res.ok) return false;
|
|
182
|
+
return (res.value as InitializeResult).available;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Launches the app and resolves with a connection carrying receiver_action then new_session. */
|
|
186
|
+
async startPresentation(req: PresentationRequestInfo): Promise<PresentationConnectionHandle> {
|
|
187
|
+
const parsed = parsePresentationUrl((req.urls[0] ?? ""));
|
|
188
|
+
if (parsed === null) throw new PresentationError("NotSupportedError", `Unsupported presentation URL: ${(req.urls[0] ?? "")}`);
|
|
189
|
+
const sender = this.senderOf(req.senderId, req.origin);
|
|
190
|
+
const res = await this.service.handle(sender, "requestSession", {
|
|
191
|
+
appId: parsed.appId,
|
|
192
|
+
capabilities: [],
|
|
193
|
+
timeoutMs: parsed.launchTimeout ?? 60000,
|
|
194
|
+
});
|
|
195
|
+
if (!res.ok) {
|
|
196
|
+
if (res.code === "cancel") throw new PresentationError("AbortError", res.description ?? "The user cancelled the request");
|
|
197
|
+
if (res.code === "receiver_unavailable") throw new PresentationError("NotFoundError", res.description ?? "No receivers are available");
|
|
198
|
+
throw new PresentationError("OperationError", res.description ?? res.code);
|
|
199
|
+
}
|
|
200
|
+
const s = res.value as SessionSnapshot;
|
|
201
|
+
const clientId = parsed.clientId ?? randomBytes(16).toString("hex");
|
|
202
|
+
const state = this.senderState(req.senderId);
|
|
203
|
+
const previous = state.conns.get(clientId);
|
|
204
|
+
if (previous !== undefined) {
|
|
205
|
+
state.conns.delete(clientId);
|
|
206
|
+
previous.end("closed");
|
|
207
|
+
}
|
|
208
|
+
const conn = new Conn(this, `${CAST_SESSION_PREFIX}${s.sessionId}`, (req.urls[0] ?? ""), req.senderId, req.origin, clientId, s.sessionId, s);
|
|
209
|
+
state.conns.set(clientId, conn);
|
|
210
|
+
const label = receiverLabel(s.receiver.label, this.token);
|
|
211
|
+
conn.deliver(envelope("receiver_action", { receiver: toReceiver(s.receiver, label), action: "cast" }, clientId));
|
|
212
|
+
conn.deliver(envelope("new_session", toSession(s, label), clientId));
|
|
213
|
+
if (s.namespaces.some((n) => n.name === MEDIA_NAMESPACE)) {
|
|
214
|
+
// Like Chromium, the request id is not recorded: the reply arrives as an unsolicited MEDIA_STATUS.
|
|
215
|
+
void this.service.handle(sender, "sendMessage", {
|
|
216
|
+
sessionId: s.sessionId,
|
|
217
|
+
namespace: MEDIA_NAMESPACE,
|
|
218
|
+
message: JSON.stringify({ type: "GET_STATUS", requestId: this.freshRequestId() }),
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
return conn;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Rejoins an existing session; the connection carries new_session only. */
|
|
225
|
+
async reconnectPresentation(req: PresentationRequestInfo & { presentationId: string }): Promise<PresentationConnectionHandle> {
|
|
226
|
+
const parsed = parsePresentationUrl((req.urls[0] ?? ""));
|
|
227
|
+
if (parsed === null) throw new PresentationError("NotSupportedError", `Unsupported presentation URL: ${(req.urls[0] ?? "")}`);
|
|
228
|
+
const sender = this.senderOf(req.senderId, req.origin);
|
|
229
|
+
const presentationId = req.presentationId;
|
|
230
|
+
let snapshot: SessionSnapshot;
|
|
231
|
+
if (presentationId === "auto-join") {
|
|
232
|
+
const res = await this.service.handle(sender, "initialize", {
|
|
233
|
+
appId: parsed.appId,
|
|
234
|
+
capabilities: [],
|
|
235
|
+
autoJoinPolicy: parsed.autoJoinPolicy,
|
|
236
|
+
});
|
|
237
|
+
if (!res.ok) throw new PresentationError("NotFoundError", res.description ?? "No matching route");
|
|
238
|
+
const sessions = (res.value as InitializeResult).sessions;
|
|
239
|
+
if (sessions.length === 0) throw new PresentationError("NotFoundError", "No matching route");
|
|
240
|
+
snapshot = sessions[0]!;
|
|
241
|
+
} else if (presentationId.startsWith(CAST_SESSION_PREFIX)) {
|
|
242
|
+
const sessionId = presentationId.slice(CAST_SESSION_PREFIX.length);
|
|
243
|
+
const res = await this.service.handle(sender, "joinSession", { sessionId });
|
|
244
|
+
if (!res.ok) throw new PresentationError("NotFoundError", res.description ?? "No matching route");
|
|
245
|
+
const s = res.value as SessionSnapshot;
|
|
246
|
+
if (s.appId !== parsed.appId) {
|
|
247
|
+
void this.service.handle(sender, "leaveSession", { sessionId: s.sessionId });
|
|
248
|
+
throw new PresentationError("NotFoundError", "The session's app does not match the request URL");
|
|
249
|
+
}
|
|
250
|
+
snapshot = s;
|
|
251
|
+
} else {
|
|
252
|
+
throw new PresentationError("NotFoundError", `Unknown presentation id: ${presentationId}`);
|
|
253
|
+
}
|
|
254
|
+
const clientId = parsed.clientId ?? randomBytes(16).toString("hex");
|
|
255
|
+
const state = this.senderState(req.senderId);
|
|
256
|
+
const previous = state.conns.get(clientId);
|
|
257
|
+
if (previous !== undefined) {
|
|
258
|
+
state.conns.delete(clientId);
|
|
259
|
+
previous.end("closed");
|
|
260
|
+
}
|
|
261
|
+
const conn = new Conn(this, presentationId, (req.urls[0] ?? ""), req.senderId, req.origin, clientId, snapshot.sessionId, snapshot);
|
|
262
|
+
state.conns.set(clientId, conn);
|
|
263
|
+
const label = receiverLabel(snapshot.receiver.label, this.token);
|
|
264
|
+
conn.deliver(envelope("new_session", toSession(snapshot, label), clientId));
|
|
265
|
+
return conn;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** A service event for one of our senders (wired to the service's emit option). */
|
|
269
|
+
onServiceEvent(senderId: number, event: BridgeEvent): void {
|
|
270
|
+
const state = this.senders.get(senderId);
|
|
271
|
+
if (state === undefined) return;
|
|
272
|
+
switch (event.type) {
|
|
273
|
+
case "receiverAvailability": {
|
|
274
|
+
for (const watch of state.watches.values()) watch.onchange(event.available);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
case "sessionUpdated": {
|
|
278
|
+
for (const conn of [...state.conns.values()]) {
|
|
279
|
+
if (conn.closed || conn.sessionId !== event.session.sessionId) continue;
|
|
280
|
+
conn.snapshot = event.session;
|
|
281
|
+
const label = receiverLabel(event.session.receiver.label, this.token);
|
|
282
|
+
conn.deliver(envelope("update_session", toSession(event.session, label), conn.clientId));
|
|
283
|
+
}
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
case "receiverAction": {
|
|
287
|
+
for (const conn of [...state.conns.values()]) {
|
|
288
|
+
if (conn.closed || conn.sessionId !== event.sessionId) continue;
|
|
289
|
+
const snap = conn.snapshot;
|
|
290
|
+
if (snap === null) continue;
|
|
291
|
+
const label = receiverLabel(snap.receiver.label, this.token);
|
|
292
|
+
conn.deliver(envelope("receiver_action", { receiver: toReceiver(snap.receiver, label), action: "stop" }, conn.clientId));
|
|
293
|
+
}
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
case "sessionEnded": {
|
|
297
|
+
for (const conn of [...state.conns.values()]) {
|
|
298
|
+
if (conn.closed || conn.sessionId !== event.sessionId) continue;
|
|
299
|
+
this.endSession(conn, event.status);
|
|
300
|
+
}
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
case "message": {
|
|
304
|
+
for (const conn of [...state.conns.values()]) {
|
|
305
|
+
if (conn.closed || conn.sessionId !== event.sessionId) continue;
|
|
306
|
+
if (event.namespace === MEDIA_NAMESPACE) this.deliverMediaReply(conn, event.message);
|
|
307
|
+
else conn.deliver(envelope("app_message", {
|
|
308
|
+
sessionId: event.sessionId,
|
|
309
|
+
namespaceName: event.namespace,
|
|
310
|
+
message: event.message,
|
|
311
|
+
}, conn.clientId));
|
|
312
|
+
}
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** The sender went away: close its connections (no messages, no service calls) and drop its watches. */
|
|
319
|
+
senderGone(senderId: number): void {
|
|
320
|
+
const state = this.senders.get(senderId);
|
|
321
|
+
if (state === undefined) return;
|
|
322
|
+
this.senders.delete(senderId);
|
|
323
|
+
for (const conn of state.conns.values()) conn.end("closed");
|
|
324
|
+
state.watches.clear();
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** The next fresh media request id: incremented per use, wrapping back to 1 past 2^31. */
|
|
328
|
+
private freshRequestId(): number {
|
|
329
|
+
const id = this.nextRequestId;
|
|
330
|
+
this.nextRequestId = id >= REQUEST_ID_MAX ? 1 : id + 1;
|
|
331
|
+
return id;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
private senderOf(senderId: number, origin: string): { id: number; origin: string } {
|
|
335
|
+
return { id: senderId, origin };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
private senderState(senderId: number): SenderState {
|
|
339
|
+
let state = this.senders.get(senderId);
|
|
340
|
+
if (state === undefined) {
|
|
341
|
+
state = { conns: new Map(), watches: new Map() };
|
|
342
|
+
this.senders.set(senderId, state);
|
|
343
|
+
}
|
|
344
|
+
return state;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** End a connection the way a receiver-ended session does: a final message, then onclose. */
|
|
348
|
+
private endSession(conn: Conn, status: "stopped" | "disconnected"): void {
|
|
349
|
+
if (conn.closed) return;
|
|
350
|
+
const type = status === "stopped" ? "remove_session" : "disconnect_session";
|
|
351
|
+
const reason = status === "stopped" ? "terminated" : "closed";
|
|
352
|
+
if (conn.sessionId !== null) conn.deliver(envelope(type, conn.sessionId, conn.clientId));
|
|
353
|
+
conn.end(reason);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** A media-namespace reply from the receiver, mapped back onto the page's sequence numbers. */
|
|
357
|
+
private deliverMediaReply(conn: Conn, raw: string): void {
|
|
358
|
+
let data: unknown;
|
|
359
|
+
try {
|
|
360
|
+
data = JSON.parse(raw);
|
|
361
|
+
} catch {
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
if (typeof data !== "object" || data === null || Array.isArray(data)) return;
|
|
365
|
+
const payload = data as Record<string, unknown>;
|
|
366
|
+
if (Array.isArray(payload.status)) {
|
|
367
|
+
payload.status = payload.status.map((entry) => toMediaEntry(entry as Record<string, unknown>, conn.sessionId as string));
|
|
368
|
+
}
|
|
369
|
+
let sequenceNumber: number | undefined;
|
|
370
|
+
const requestId = payload.requestId;
|
|
371
|
+
if (typeof requestId === "number") {
|
|
372
|
+
sequenceNumber = conn.pendingMedia.get(requestId);
|
|
373
|
+
if (sequenceNumber !== undefined) conn.pendingMedia.delete(requestId);
|
|
374
|
+
}
|
|
375
|
+
// A payload without a status array is only forwarded when it answers a pending request.
|
|
376
|
+
if (!Array.isArray(payload.status) && sequenceNumber === undefined) return;
|
|
377
|
+
conn.deliver(envelope("v2_message", payload, conn.clientId, sequenceNumber));
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** One inbound envelope from the page (already checked that the connection is open). */
|
|
381
|
+
/** @internal Called by Conn. */
|
|
382
|
+
dispatch(conn: Conn, raw: string): void {
|
|
383
|
+
const env = parseEnvelope(raw);
|
|
384
|
+
if (env === null) return;
|
|
385
|
+
if (env.clientId !== conn.clientId) return;
|
|
386
|
+
switch (env.type) {
|
|
387
|
+
case "client_connect":
|
|
388
|
+
return;
|
|
389
|
+
case "app_message":
|
|
390
|
+
void this.handleAppMessage(conn, env);
|
|
391
|
+
return;
|
|
392
|
+
case "v2_message":
|
|
393
|
+
void this.handleV2Message(conn, env);
|
|
394
|
+
return;
|
|
395
|
+
case "leave_session":
|
|
396
|
+
void this.handleLeave(conn, env);
|
|
397
|
+
return;
|
|
398
|
+
default:
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
private async handleAppMessage(conn: Conn, env: ParsedEnvelope): Promise<void> {
|
|
404
|
+
const m = env.message as { sessionId: string; namespaceName: string; message: unknown };
|
|
405
|
+
if (conn.sessionId === null || m.sessionId !== conn.sessionId) return;
|
|
406
|
+
const snap = conn.snapshot;
|
|
407
|
+
if (snap === null || !snap.namespaces.some((n) => n.name === m.namespaceName)) {
|
|
408
|
+
conn.deliver(envelope("error", {
|
|
409
|
+
code: "invalid_parameter",
|
|
410
|
+
description: `Invalid namespace: ${m.namespaceName}`,
|
|
411
|
+
details: null,
|
|
412
|
+
}, conn.clientId, env.sequenceNumber));
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
const payload = typeof m.message === "string" ? m.message : JSON.stringify(m.message);
|
|
416
|
+
const res = await this.service.handle(this.senderOf(conn.senderId, conn.origin), "sendMessage", {
|
|
417
|
+
sessionId: m.sessionId,
|
|
418
|
+
namespace: m.namespaceName,
|
|
419
|
+
message: payload,
|
|
420
|
+
});
|
|
421
|
+
if (res.ok) {
|
|
422
|
+
conn.deliver(envelope("app_message", null, conn.clientId, env.sequenceNumber));
|
|
423
|
+
} else {
|
|
424
|
+
conn.deliver(envelope("error", { code: res.code, description: res.description ?? null, details: null }, conn.clientId, env.sequenceNumber));
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
private async handleV2Message(conn: Conn, env: ParsedEnvelope): Promise<void> {
|
|
429
|
+
const m = env.message as Record<string, unknown>;
|
|
430
|
+
if (conn.sessionId === null || m.sessionId !== conn.sessionId) return;
|
|
431
|
+
const type = m.type as string;
|
|
432
|
+
const seq = env.sequenceNumber;
|
|
433
|
+
const sender = this.senderOf(conn.senderId, conn.origin);
|
|
434
|
+
if (type === "SET_VOLUME") {
|
|
435
|
+
const volume = m.volume as { level?: unknown; muted?: unknown } | null | undefined;
|
|
436
|
+
let failed: { code: string; description?: string } | null = null;
|
|
437
|
+
if (volume !== null && typeof volume === "object") {
|
|
438
|
+
if (typeof volume.level === "number") {
|
|
439
|
+
const r = await this.service.handle(sender, "setReceiverVolume", { sessionId: m.sessionId as string, level: volume.level });
|
|
440
|
+
if (!r.ok) failed = r;
|
|
441
|
+
}
|
|
442
|
+
if (failed === null && typeof volume.muted === "boolean") {
|
|
443
|
+
const r = await this.service.handle(sender, "setReceiverMuted", { sessionId: m.sessionId as string, muted: volume.muted });
|
|
444
|
+
if (!r.ok) failed = r;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
if (failed !== null) {
|
|
448
|
+
conn.deliver(envelope("error", { code: failed.code, description: failed.description ?? null, details: null }, conn.clientId, seq));
|
|
449
|
+
} else {
|
|
450
|
+
conn.deliver(envelope("v2_message", null, conn.clientId, seq));
|
|
451
|
+
}
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
if (type === "STOP") {
|
|
455
|
+
const res = await this.service.handle(sender, "stopSession", { sessionId: m.sessionId as string });
|
|
456
|
+
if (!res.ok) {
|
|
457
|
+
conn.deliver(envelope("error", { code: res.code, description: res.description ?? null, details: null }, conn.clientId, seq));
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
conn.deliver(envelope("v2_message", null, conn.clientId, seq));
|
|
461
|
+
// The service does not tell the caller its own stop ended the session; push it here.
|
|
462
|
+
this.endSession(conn, "stopped");
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
if (isMediaRequest(type)) {
|
|
466
|
+
const requestId = this.freshRequestId();
|
|
467
|
+
const body: Record<string, unknown> = { ...m, type: receiverMediaType(type), requestId };
|
|
468
|
+
if (typeof seq === "number") {
|
|
469
|
+
conn.pendingMedia.set(requestId, seq);
|
|
470
|
+
while (conn.pendingMedia.size > MAX_PENDING_MEDIA) {
|
|
471
|
+
const oldest = conn.pendingMedia.keys().next().value;
|
|
472
|
+
if (oldest === undefined) break;
|
|
473
|
+
conn.pendingMedia.delete(oldest);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
const res = await this.service.handle(sender, "sendMessage", {
|
|
477
|
+
sessionId: m.sessionId as string,
|
|
478
|
+
namespace: MEDIA_NAMESPACE,
|
|
479
|
+
message: JSON.stringify(body),
|
|
480
|
+
});
|
|
481
|
+
if (!res.ok) {
|
|
482
|
+
conn.pendingMedia.delete(requestId);
|
|
483
|
+
conn.deliver(envelope("error", { code: res.code, description: res.description ?? null, details: null }, conn.clientId, seq));
|
|
484
|
+
}
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
// Anything else: ignore.
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
private async handleLeave(conn: Conn, env: ParsedEnvelope): Promise<void> {
|
|
491
|
+
// Acknowledge before doing the work, like Chromium.
|
|
492
|
+
conn.deliver(envelope("leave_session", null, conn.clientId, env.sequenceNumber));
|
|
493
|
+
// Leave only this connection's own session, whatever id the page named.
|
|
494
|
+
const sessionId = conn.sessionId;
|
|
495
|
+
if (sessionId !== null) {
|
|
496
|
+
await this.service.handle(this.senderOf(conn.senderId, conn.origin), "leaveSession", { sessionId });
|
|
497
|
+
}
|
|
498
|
+
conn.end("closed");
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** @internal Called by Conn. */
|
|
502
|
+
pageClosed(conn: Conn): void {
|
|
503
|
+
if (conn.closed) return;
|
|
504
|
+
if (conn.sessionId !== null) {
|
|
505
|
+
void this.service.handle(this.senderOf(conn.senderId, conn.origin), "leaveSession", { sessionId: conn.sessionId });
|
|
506
|
+
}
|
|
507
|
+
conn.end("closed");
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** @internal Called by Conn. */
|
|
511
|
+
pageTerminated(conn: Conn): void {
|
|
512
|
+
if (conn.closed) return;
|
|
513
|
+
if (conn.sessionId !== null) {
|
|
514
|
+
void this.service.handle(this.senderOf(conn.senderId, conn.origin), "stopSession", { sessionId: conn.sessionId });
|
|
515
|
+
}
|
|
516
|
+
conn.end("terminated");
|
|
517
|
+
}
|
|
518
|
+
}
|
|
@@ -350,6 +350,8 @@ export class CastSessionService {
|
|
|
350
350
|
if (choice === "stop") {
|
|
351
351
|
const rec = request.session !== undefined ? this.sessions.get(request.session.sessionId) : undefined;
|
|
352
352
|
if (rec === undefined) return bad("cancel");
|
|
353
|
+
// Like Chrome, tell the caller's receiver action listeners about the stop before the session ends.
|
|
354
|
+
this.emitTo(sender.id, { type: "receiverAction", sessionId: rec.app.sessionId, action: "stop" });
|
|
353
355
|
const stopped = await this.stopSessionRecord(rec, sender.id, true);
|
|
354
356
|
return stopped.ok ? bad("cancel") : stopped;
|
|
355
357
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
export type BridgeResult<T = unknown> =
|
|
1
|
+
export type BridgeResult<T = unknown> =
|
|
2
|
+
| { ok: true; value: T }
|
|
3
|
+
| { ok: false; code: string; description?: string };
|
|
2
4
|
export type BridgeMethod = "initialize" | "requestSession" | "joinSession" | "sendMessage" | "stopSession"
|
|
3
5
|
| "leaveSession" | "setReceiverVolume" | "setReceiverMuted";
|
|
4
6
|
export interface CastBridge {
|
|
@@ -20,6 +22,7 @@ export type BridgeEvent =
|
|
|
20
22
|
| { type: "receiverAvailability"; available: boolean }
|
|
21
23
|
| { type: "sessionUpdated"; session: SessionSnapshot }
|
|
22
24
|
| { type: "sessionEnded"; sessionId: string; status: "stopped" | "disconnected" }
|
|
25
|
+
| { type: "receiverAction"; sessionId: string; action: "stop" }
|
|
23
26
|
| { type: "message"; sessionId: string; namespace: string; message: string };
|
|
24
27
|
export interface InitializeParams { appId: string; capabilities: string[]; autoJoinPolicy: string }
|
|
25
28
|
export interface InitializeResult { available: boolean; sessions: SessionSnapshot[] }
|