electron-cast 0.2.0 → 0.3.1

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.
@@ -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
+ }
@@ -89,6 +89,11 @@ interface SessionRecord {
89
89
  origin: string;
90
90
  appId: string;
91
91
  members: Set<number>;
92
+ /**
93
+ * Senders whose page navigated away (a reload, say) while a member. Like Chrome's Media Router, the session outlives
94
+ * the page: it stays open on the device so the sender's next page can rejoin it. Parked senders get no events.
95
+ */
96
+ parked: Set<number>;
92
97
  lastVolume: ReceiverVolume;
93
98
  lastSnapshot: SessionSnapshot | null;
94
99
  /** Set while a stopSession is in flight; onClientStatus skips this sender when it ends the session. */
@@ -276,14 +281,32 @@ export class CastSessionService {
276
281
 
277
282
  /** Detach a sender that went away: cancel its pending request, leave its sessions, drop its bookkeeping. */
278
283
  senderGone(senderId: number): void {
284
+ this.forgetSender(senderId);
285
+ for (const rec of [...this.sessions.values()]) {
286
+ if (!rec.members.has(senderId) && !rec.parked.has(senderId)) continue;
287
+ this.leave(rec, senderId);
288
+ }
289
+ }
290
+
291
+ /**
292
+ * The sender's page navigated (a reload or a new page): cancel its pending request and drop its bookkeeping, but
293
+ * keep its sessions open on the device, parked, so the next page can rejoin them (auto-join or joinSession) as it
294
+ * would in Chrome. A parked session ends as usual if the receiver app stops or the device drops; senderGone ends
295
+ * the sender's share of it for good.
296
+ */
297
+ senderNavigated(senderId: number): void {
298
+ this.forgetSender(senderId);
299
+ for (const rec of this.sessions.values()) {
300
+ if (!rec.members.delete(senderId)) continue;
301
+ rec.parked.add(senderId);
302
+ }
303
+ }
304
+
305
+ private forgetSender(senderId: number): void {
279
306
  const pending = this.pendingRequests.get(senderId);
280
307
  if (pending !== undefined) pending.cancelled.value = true;
281
308
  this.pendingRequests.delete(senderId);
282
309
  this.senders.delete(senderId);
283
- for (const rec of [...this.sessions.values()]) {
284
- if (!rec.members.has(senderId)) continue;
285
- this.leave(rec, senderId);
286
- }
287
310
  }
288
311
 
289
312
  /** Unsubscribe, close every client and clear all state. */
@@ -310,11 +333,12 @@ export class CastSessionService {
310
333
  const joined: SessionSnapshot[] = [];
311
334
  for (const rec of this.sessions.values()) {
312
335
  if (rec.appId !== p.appId || rec.origin !== sender.origin) continue;
313
- if (p.autoJoinPolicy === "origin_scoped") {
336
+ // tab_and_origin_scoped: this sender (the same tab) is a member, or was one before its page navigated
337
+ const sameTab = rec.members.has(sender.id) || rec.parked.has(sender.id);
338
+ if (p.autoJoinPolicy === "origin_scoped" || (p.autoJoinPolicy === "tab_and_origin_scoped" && sameTab)) {
339
+ rec.parked.delete(sender.id);
314
340
  rec.members.add(sender.id);
315
341
  joined.push(this.snapshotOf(rec));
316
- } else if (p.autoJoinPolicy === "tab_and_origin_scoped" && rec.members.has(sender.id)) {
317
- joined.push(this.snapshotOf(rec));
318
342
  }
319
343
  }
320
344
  return good({ available, sessions: joined });
@@ -387,6 +411,7 @@ export class CastSessionService {
387
411
  if (p === null) return bad("invalid_parameter");
388
412
  const rec = this.sessions.get(p.sessionId);
389
413
  if (rec === undefined || rec.origin !== sender.origin) return bad("session_error");
414
+ rec.parked.delete(sender.id);
390
415
  rec.members.add(sender.id);
391
416
  return good(this.snapshotOf(rec));
392
417
  }
@@ -559,6 +584,7 @@ export class CastSessionService {
559
584
  origin: sender.origin,
560
585
  appId,
561
586
  members: new Set([sender.id]),
587
+ parked: new Set(),
562
588
  lastVolume: status.volume,
563
589
  lastSnapshot: null,
564
590
  };
@@ -576,7 +602,8 @@ export class CastSessionService {
576
602
  /** Remove a sender from a session; when it was the last one, tear the session down. */
577
603
  private leave(rec: SessionRecord, senderId: number): void {
578
604
  rec.members.delete(senderId);
579
- if (rec.members.size === 0) {
605
+ rec.parked.delete(senderId);
606
+ if (rec.members.size === 0 && rec.parked.size === 0) {
580
607
  rec.client.closeTransport(rec.app.transportId);
581
608
  this.sessions.delete(rec.app.sessionId);
582
609
  this.cleanupIdle(rec.device.id, rec.client);