electron-cast 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +123 -14
  3. package/dist/cjs/client/auth/build-time.d.ts +7 -0
  4. package/dist/cjs/client/auth/build-time.js +11 -0
  5. package/dist/cjs/client/auth/build-time.js.map +1 -0
  6. package/dist/cjs/client/auth/cast-auth.d.ts +44 -0
  7. package/dist/cjs/client/auth/cast-auth.js +145 -0
  8. package/dist/cjs/client/auth/cast-auth.js.map +1 -0
  9. package/dist/cjs/client/auth/cast-cert-validator.d.ts +34 -0
  10. package/dist/cjs/client/auth/cast-cert-validator.js +89 -0
  11. package/dist/cjs/client/auth/cast-cert-validator.js.map +1 -0
  12. package/dist/cjs/client/auth/crl.d.ts +45 -0
  13. package/dist/cjs/client/auth/crl.js +227 -0
  14. package/dist/cjs/client/auth/crl.js.map +1 -0
  15. package/dist/cjs/client/auth/der.d.ts +62 -0
  16. package/dist/cjs/client/auth/der.js +208 -0
  17. package/dist/cjs/client/auth/der.js.map +1 -0
  18. package/dist/cjs/client/auth/names.d.ts +52 -0
  19. package/dist/cjs/client/auth/names.js +447 -0
  20. package/dist/cjs/client/auth/names.js.map +1 -0
  21. package/dist/cjs/client/auth/path-validator.d.ts +29 -0
  22. package/dist/cjs/client/auth/path-validator.js +421 -0
  23. package/dist/cjs/client/auth/path-validator.js.map +1 -0
  24. package/dist/cjs/client/auth/trust-data.d.ts +24 -0
  25. package/dist/cjs/client/auth/trust-data.js +97 -0
  26. package/dist/cjs/client/auth/trust-data.js.map +1 -0
  27. package/dist/cjs/client/auth/x509.d.ts +109 -0
  28. package/dist/cjs/client/auth/x509.js +442 -0
  29. package/dist/cjs/client/auth/x509.js.map +1 -0
  30. package/dist/cjs/client/cast-client.d.ts +111 -0
  31. package/dist/cjs/client/cast-client.js +505 -0
  32. package/dist/cjs/client/cast-client.js.map +1 -0
  33. package/dist/cjs/client/errors.d.ts +28 -0
  34. package/dist/cjs/client/errors.js +50 -0
  35. package/dist/cjs/client/errors.js.map +1 -0
  36. package/dist/cjs/client/index.d.ts +6 -0
  37. package/dist/cjs/client/index.js +21 -0
  38. package/dist/cjs/client/index.js.map +1 -0
  39. package/dist/cjs/client/namespaces.d.ts +9 -0
  40. package/dist/cjs/client/namespaces.js +13 -0
  41. package/dist/cjs/client/namespaces.js.map +1 -0
  42. package/dist/cjs/client/types.d.ts +27 -0
  43. package/dist/cjs/client/types.js +3 -0
  44. package/dist/cjs/client/types.js.map +1 -0
  45. package/dist/cjs/discovery/cast-discovery.d.ts +103 -0
  46. package/dist/cjs/discovery/cast-discovery.js +323 -0
  47. package/dist/cjs/discovery/cast-discovery.js.map +1 -0
  48. package/dist/cjs/discovery/device-cache.d.ts +45 -0
  49. package/dist/cjs/discovery/device-cache.js +240 -0
  50. package/dist/cjs/discovery/device-cache.js.map +1 -0
  51. package/dist/cjs/discovery/dns-packet.d.ts +70 -0
  52. package/dist/cjs/discovery/dns-packet.js +251 -0
  53. package/dist/cjs/discovery/dns-packet.js.map +1 -0
  54. package/dist/cjs/discovery/index.d.ts +4 -0
  55. package/dist/cjs/discovery/index.js +21 -0
  56. package/dist/cjs/discovery/index.js.map +1 -0
  57. package/dist/cjs/discovery/udp-socket.d.ts +16 -0
  58. package/dist/cjs/discovery/udp-socket.js +163 -0
  59. package/dist/cjs/discovery/udp-socket.js.map +1 -0
  60. package/dist/cjs/electron/main.d.ts +86 -0
  61. package/dist/cjs/electron/main.js +408 -0
  62. package/dist/cjs/electron/main.js.map +1 -0
  63. package/dist/cjs/electron/manager-api.d.ts +132 -0
  64. package/dist/cjs/electron/manager-api.js +207 -0
  65. package/dist/cjs/electron/manager-api.js.map +1 -0
  66. package/dist/cjs/electron/preload.d.ts +39 -0
  67. package/dist/cjs/electron/preload.js +96 -0
  68. package/dist/cjs/electron/preload.js.map +1 -0
  69. package/dist/cjs/electron/presentation-envelope.d.ts +60 -0
  70. package/dist/cjs/electron/presentation-envelope.js +318 -0
  71. package/dist/cjs/electron/presentation-envelope.js.map +1 -0
  72. package/dist/cjs/electron/presentation-handler.d.ts +100 -0
  73. package/dist/cjs/electron/presentation-handler.js +499 -0
  74. package/dist/cjs/electron/presentation-handler.js.map +1 -0
  75. package/dist/cjs/electron/session-service.d.ts +174 -0
  76. package/dist/cjs/electron/session-service.js +891 -0
  77. package/dist/cjs/electron/session-service.js.map +1 -0
  78. package/dist/cjs/index.d.ts +8 -0
  79. package/dist/cjs/index.js +26 -0
  80. package/dist/cjs/index.js.map +1 -0
  81. package/dist/cjs/package.json +1 -0
  82. package/dist/cjs/polyfill/bridge-types.d.ts +86 -0
  83. package/dist/cjs/polyfill/bridge-types.js +3 -0
  84. package/dist/cjs/polyfill/bridge-types.js.map +1 -0
  85. package/dist/cjs/polyfill/install.d.ts +12 -0
  86. package/dist/cjs/polyfill/install.js +1569 -0
  87. package/dist/cjs/polyfill/install.js.map +1 -0
  88. package/dist/cjs/polyfill/presentation-standin.d.ts +13 -0
  89. package/dist/cjs/polyfill/presentation-standin.js +279 -0
  90. package/dist/cjs/polyfill/presentation-standin.js.map +1 -0
  91. package/dist/cjs/protocol/cast-message.d.ts +20 -0
  92. package/dist/cjs/protocol/cast-message.js +171 -0
  93. package/dist/cjs/protocol/cast-message.js.map +1 -0
  94. package/dist/cjs/protocol/device-auth.d.ts +61 -0
  95. package/dist/cjs/protocol/device-auth.js +113 -0
  96. package/dist/cjs/protocol/device-auth.js.map +1 -0
  97. package/dist/cjs/protocol/errors.d.ts +4 -0
  98. package/dist/cjs/protocol/errors.js +12 -0
  99. package/dist/cjs/protocol/errors.js.map +1 -0
  100. package/dist/cjs/protocol/framing.d.ts +18 -0
  101. package/dist/cjs/protocol/framing.js +100 -0
  102. package/dist/cjs/protocol/framing.js.map +1 -0
  103. package/dist/cjs/protocol/index.d.ts +4 -0
  104. package/dist/cjs/protocol/index.js +21 -0
  105. package/dist/cjs/protocol/index.js.map +1 -0
  106. package/dist/cjs/protocol/proto-wire.d.ts +11 -0
  107. package/dist/cjs/protocol/proto-wire.js +64 -0
  108. package/dist/cjs/protocol/proto-wire.js.map +1 -0
  109. package/dist/client/auth/build-time.d.ts +7 -0
  110. package/dist/client/auth/build-time.js +8 -0
  111. package/dist/client/auth/build-time.js.map +1 -0
  112. package/dist/client/auth/cast-auth.d.ts +44 -0
  113. package/dist/client/auth/cast-auth.js +141 -0
  114. package/dist/client/auth/cast-auth.js.map +1 -0
  115. package/dist/client/auth/cast-cert-validator.d.ts +34 -0
  116. package/dist/client/auth/cast-cert-validator.js +86 -0
  117. package/dist/client/auth/cast-cert-validator.js.map +1 -0
  118. package/dist/client/auth/crl.d.ts +45 -0
  119. package/dist/client/auth/crl.js +221 -0
  120. package/dist/client/auth/crl.js.map +1 -0
  121. package/dist/client/auth/der.d.ts +62 -0
  122. package/dist/client/auth/der.js +196 -0
  123. package/dist/client/auth/der.js.map +1 -0
  124. package/dist/client/auth/names.d.ts +52 -0
  125. package/dist/client/auth/names.js +438 -0
  126. package/dist/client/auth/names.js.map +1 -0
  127. package/dist/client/auth/path-validator.d.ts +29 -0
  128. package/dist/client/auth/path-validator.js +417 -0
  129. package/dist/client/auth/path-validator.js.map +1 -0
  130. package/dist/client/auth/trust-data.d.ts +24 -0
  131. package/dist/client/auth/trust-data.js +94 -0
  132. package/dist/client/auth/trust-data.js.map +1 -0
  133. package/dist/client/auth/x509.d.ts +109 -0
  134. package/dist/client/auth/x509.js +430 -0
  135. package/dist/client/auth/x509.js.map +1 -0
  136. package/dist/client/cast-client.d.ts +20 -1
  137. package/dist/client/cast-client.js +74 -3
  138. package/dist/client/cast-client.js.map +1 -1
  139. package/dist/client/errors.d.ts +11 -0
  140. package/dist/client/errors.js +13 -0
  141. package/dist/client/errors.js.map +1 -1
  142. package/dist/client/index.d.ts +2 -0
  143. package/dist/discovery/cast-discovery.d.ts +21 -2
  144. package/dist/discovery/cast-discovery.js +94 -14
  145. package/dist/discovery/cast-discovery.js.map +1 -1
  146. package/dist/discovery/device-cache.d.ts +6 -1
  147. package/dist/discovery/device-cache.js +31 -7
  148. package/dist/discovery/device-cache.js.map +1 -1
  149. package/dist/discovery/udp-socket.d.ts +5 -1
  150. package/dist/discovery/udp-socket.js +56 -5
  151. package/dist/discovery/udp-socket.js.map +1 -1
  152. package/dist/electron/main.d.ts +26 -4
  153. package/dist/electron/main.js +191 -54
  154. package/dist/electron/main.js.map +1 -1
  155. package/dist/electron/manager-api.d.ts +132 -0
  156. package/dist/electron/manager-api.js +198 -0
  157. package/dist/electron/manager-api.js.map +1 -0
  158. package/dist/electron/preload.d.ts +5 -0
  159. package/dist/electron/preload.js +9 -1
  160. package/dist/electron/preload.js.map +1 -1
  161. package/dist/electron/presentation-envelope.js +7 -1
  162. package/dist/electron/presentation-envelope.js.map +1 -1
  163. package/dist/electron/presentation-handler.js +16 -9
  164. package/dist/electron/presentation-handler.js.map +1 -1
  165. package/dist/electron/session-service.d.ts +42 -1
  166. package/dist/electron/session-service.js +226 -23
  167. package/dist/electron/session-service.js.map +1 -1
  168. package/dist/polyfill/presentation-standin.js +3 -2
  169. package/dist/polyfill/presentation-standin.js.map +1 -1
  170. package/dist/protocol/device-auth.d.ts +61 -0
  171. package/dist/protocol/device-auth.js +106 -0
  172. package/dist/protocol/device-auth.js.map +1 -0
  173. package/dist/protocol/index.d.ts +1 -0
  174. package/dist/protocol/index.js +1 -0
  175. package/dist/protocol/index.js.map +1 -1
  176. package/dist/protocol/proto-wire.d.ts +11 -0
  177. package/dist/protocol/proto-wire.js +60 -0
  178. package/dist/protocol/proto-wire.js.map +1 -0
  179. package/package.json +47 -12
  180. package/src/client/auth/build-time.ts +7 -0
  181. package/src/client/auth/cast-auth.ts +184 -0
  182. package/src/client/auth/cast-cert-validator.ts +133 -0
  183. package/src/client/auth/crl.ts +228 -0
  184. package/src/client/auth/der.ts +193 -0
  185. package/src/client/auth/names.ts +411 -0
  186. package/src/client/auth/path-validator.ts +449 -0
  187. package/src/client/auth/trust-data.ts +95 -0
  188. package/src/client/auth/x509.ts +488 -0
  189. package/src/client/cast-client.ts +85 -3
  190. package/src/client/errors.ts +29 -0
  191. package/src/client/index.ts +2 -0
  192. package/src/discovery/cast-discovery.ts +104 -19
  193. package/src/discovery/device-cache.ts +38 -8
  194. package/src/discovery/udp-socket.ts +63 -4
  195. package/src/electron/main.ts +218 -59
  196. package/src/electron/manager-api.ts +312 -0
  197. package/src/electron/preload.ts +15 -1
  198. package/src/electron/presentation-envelope.ts +7 -1
  199. package/src/electron/presentation-handler.ts +16 -10
  200. package/src/electron/session-service.ts +230 -26
  201. package/src/polyfill/presentation-standin.ts +3 -2
  202. package/src/protocol/device-auth.ts +126 -0
  203. package/src/protocol/index.ts +1 -0
  204. package/src/protocol/proto-wire.ts +55 -0
@@ -3,24 +3,53 @@ import type { CastDevice } from "../discovery/index.ts";
3
3
  import { CastDiscovery } from "../discovery/index.ts";
4
4
  import { CastClient } from "../client/index.ts";
5
5
  import { CastPresentationHandler, type PresentationConnectionHandle } from "./presentation-handler.ts";
6
+ import { createManagerApi, createSinksObservers, type CastManagerApi, type DevicePickerContext } from "./manager-api.ts";
7
+ import type { BridgeMethod } from "../polyfill/bridge-types.ts";
8
+
9
+ /**
10
+ * The methods a page may call over IPC: the bridge's own. The service also handles methods that only main calls
11
+ * (joinRunningSession, from the presentation handler), which a page must not reach directly.
12
+ */
13
+ const PAGE_METHODS: ReadonlySet<string> = new Set<BridgeMethod>([
14
+ "initialize", "requestSession", "joinSession", "sendMessage", "stopSession",
15
+ "leaveSession", "setReceiverVolume", "setReceiverMuted",
16
+ ]);
6
17
 
7
18
  export type { CastRequestInfo, DeviceChoice } from "./session-service.ts";
8
19
  export type { CastDevice } from "../discovery/index.ts";
20
+ export { MediaRouteError } from "./manager-api.ts";
21
+ export type {
22
+ CastManagerApi, DevicePickerContext, MediaRoute, MediaRouteController, MediaRoutesObserver, MediaSink, MediaSinksObserver,
23
+ MediaSinksQuery, SinkIconType,
24
+ } from "./manager-api.ts";
9
25
 
10
26
  /** The subset of an Electron `WebFrameMain` the manager needs. */
11
- export interface FrameLike { url: string; origin?: string }
27
+ export interface FrameLike {
28
+ url: string;
29
+ origin?: string;
30
+ /** Browser-global and constant for the frame's lifetime, across navigations; identifies a subframe. */
31
+ frameTreeNodeId?: number;
32
+ /** Null or absent on a main frame. */
33
+ parent?: unknown;
34
+ processId?: number;
35
+ routingId?: number;
36
+ /** Reaches only this frame (and needs the preload to run there: `nodeIntegrationInSubFrames`). */
37
+ send?(channel: string, ...args: any[]): void;
38
+ }
12
39
  /** The subset of an Electron `WebContents` the manager needs. */
13
40
  export interface WebContentsLike {
14
41
  readonly id: number;
15
42
  send(channel: string, ...args: any[]): void;
16
43
  isDestroyed(): boolean;
44
+ /** The frame tree; consulted to find a subframe's current frame and to notice frames that were removed. */
45
+ readonly mainFrame?: { readonly framesInSubtree: readonly FrameLike[] };
17
46
  once(event: "destroyed", listener: () => void): unknown;
18
- on(event: "did-navigate", listener: (...args: any[]) => void): unknown;
47
+ on(event: "did-navigate" | "did-frame-navigate", listener: (...args: any[]) => void): unknown;
19
48
  }
20
49
  /** The subset of an Electron `IpcMainInvokeEvent` the manager needs. */
21
50
  export interface IpcMainInvokeEventLike { sender: WebContentsLike; senderFrame: FrameLike | null }
22
51
  /** The subset of an Electron `IpcMainEvent` the manager needs. */
23
- export interface IpcMainEventLike { sender: WebContentsLike }
52
+ export interface IpcMainEventLike { sender: WebContentsLike; senderFrame?: FrameLike | null }
24
53
  /** The subset of an Electron `IpcMain` the manager needs (`on`/`removeListener` unless `presentation: false`). */
25
54
  export interface IpcMainLike {
26
55
  handle(channel: string, listener: (event: IpcMainInvokeEventLike, ...args: any[]) => unknown): void;
@@ -31,7 +60,8 @@ export interface IpcMainLike {
31
60
  /** Dependencies of {@link createCastManager}; the Electron objects are passed in, never imported. */
32
61
  export interface CastManagerOptions {
33
62
  ipcMain: IpcMainLike;
34
- selectDevice(devices: CastDevice[], request: CastRequestInfo): Promise<DeviceChoice>;
63
+ /** `picker` (optional to declare) streams device changes while the picker is open; see {@link DevicePickerContext}. */
64
+ selectDevice(devices: CastDevice[], request: CastRequestInfo, picker: DevicePickerContext): Promise<DeviceChoice>;
35
65
  allowOrigin?(origin: string): boolean;
36
66
  discovery?: DeviceSource & { start(): Promise<void>; stop(): void }; // default new CastDiscovery()
37
67
  createClient?(device: CastDevice): CastClientLike; // default new CastClient({ host, port })
@@ -42,16 +72,25 @@ export interface CastManagerOptions {
42
72
  * the preload's `mode: "chromecast"`.
43
73
  */
44
74
  presentation?: boolean;
75
+ /**
76
+ * Verify each device is a genuine Google-certified Cast device when connecting, as Chrome does (CastClient's
77
+ * `verifyDevice`). Default true; false allows uncertified receivers. Ignored when `createClient` is given.
78
+ */
79
+ verifyDevices?: boolean;
45
80
  }
46
- /** The main-process cast manager. */
47
- export interface CastManager {
81
+ /** The main-process cast manager; the observers, routes and route control come from {@link CastManagerApi}. */
82
+ export interface CastManager extends CastManagerApi {
48
83
  start(): Promise<void>;
49
84
  devices(): CastDevice[];
50
85
  dispose(): Promise<void>;
51
86
  }
52
87
 
53
- /** Availability watches kept per webContents; the page never releases one, so the oldest are dropped. */
88
+ /** Availability watches kept per frame; the page never releases one, so the oldest are dropped. */
54
89
  const MAX_WATCHES_PER_PAGE = 32;
90
+ /** Sender ids of subframes start here, far above any webContents id (a main frame's sender id is its webContents id). */
91
+ const SUBFRAME_ID_BASE = 2 ** 30;
92
+ /** How often removed iframes (which Electron does not announce) are noticed and their sessions released. */
93
+ const FRAME_SWEEP_MS = 5000;
55
94
  /** Largest page-to-receiver message accepted (Cast messages are capped at 64 KiB on the wire). */
56
95
  const MAX_MESSAGE_CHARS = 1 << 20;
57
96
 
@@ -78,9 +117,97 @@ export function createCastManager(options: CastManagerOptions): CastManager {
78
117
  throw new TypeError("presentation mode needs ipcMain.on and ipcMain.removeListener");
79
118
  }
80
119
  const discovery = options.discovery ?? new CastDiscovery();
81
- const createClient = options.createClient ?? ((d: CastDevice) => new CastClient({ host: d.host, port: d.port }));
82
- const contents = new Map<number, WebContentsLike>();
120
+ const createClient = options.createClient ?? ((d: CastDevice) => new CastClient({ host: d.host, port: d.port, verifyDevice: options.verifyDevices !== false }));
121
+ /**
122
+ * A sender is one frame. A main frame's sender id is its webContents id; a subframe gets an id of its own, kept for
123
+ * the frame's lifetime (across its navigations, so a reloaded iframe can rejoin its session). The frame is looked up
124
+ * in the frame tree on every use, never held, because navigating can swap the frame object.
125
+ */
126
+ interface SenderEntry { wc: WebContentsLike; frameTreeNodeId: number | null }
127
+ const senders = new Map<number, SenderEntry>();
128
+ const subframeIds = new Map<number, number>(); // frameTreeNodeId -> sender id
129
+ const watched = new Set<number>(); // webContents ids
130
+ let nextSubframeId = SUBFRAME_ID_BASE;
131
+ let sweepTimer: ReturnType<typeof setInterval> | undefined;
83
132
  let handler: CastPresentationHandler | undefined;
133
+
134
+ const findFrame = (wc: WebContentsLike, frameTreeNodeId: number): FrameLike | undefined => {
135
+ try {
136
+ return wc.mainFrame?.framesInSubtree.find((f) => f.frameTreeNodeId === frameTreeNodeId);
137
+ } catch {
138
+ return undefined; // the webContents is gone
139
+ }
140
+ };
141
+ const isMainFrame = (frame: FrameLike): boolean => frame.parent === undefined || frame.parent === null;
142
+ /**
143
+ * The sender id of an IPC event's frame, without registering it; undefined when it is not a known sender. An event
144
+ * with no `senderFrame` property at all is the main frame's; a null one is a frame that is already gone.
145
+ */
146
+ const senderIdOf = (wc: WebContentsLike, frame: FrameLike | null | undefined): number | undefined => {
147
+ if (frame === undefined) return wc.id;
148
+ if (frame === null) return undefined;
149
+ if (isMainFrame(frame)) return wc.id;
150
+ return typeof frame.frameTreeNodeId === "number" ? subframeIds.get(frame.frameTreeNodeId) : undefined;
151
+ };
152
+ /** The sender id of an IPC event's frame, registering a subframe (and watching its webContents) on first use. */
153
+ const registerSender = (wc: WebContentsLike, frame: FrameLike): number | null => {
154
+ if (isMainFrame(frame)) {
155
+ watch(wc);
156
+ if (!senders.has(wc.id)) senders.set(wc.id, { wc, frameTreeNodeId: null });
157
+ return wc.id;
158
+ }
159
+ const node = frame.frameTreeNodeId;
160
+ if (typeof node !== "number") return null;
161
+ watch(wc);
162
+ let id = subframeIds.get(node);
163
+ if (id === undefined) {
164
+ id = nextSubframeId++;
165
+ subframeIds.set(node, id);
166
+ senders.set(id, { wc, frameTreeNodeId: node });
167
+ sweepTimer ??= setInterval(sweepFrames, FRAME_SWEEP_MS);
168
+ sweepTimer.unref?.();
169
+ }
170
+ return id;
171
+ };
172
+ /** Forget a subframe sender for good: its connections, watches and sessions end. */
173
+ const dropSubframe = (id: number): void => {
174
+ const entry = senders.get(id);
175
+ if (entry === undefined || entry.frameTreeNodeId === null) return;
176
+ presentation?.senderGone(id);
177
+ senders.delete(id);
178
+ subframeIds.delete(entry.frameTreeNodeId);
179
+ service.senderGone(id);
180
+ if (subframeIds.size === 0 && sweepTimer !== undefined) {
181
+ clearInterval(sweepTimer);
182
+ sweepTimer = undefined;
183
+ }
184
+ };
185
+ /** Drop subframe senders whose frame was removed (Electron announces neither an iframe's removal nor its page's). */
186
+ function sweepFrames(): void {
187
+ for (const [id, entry] of [...senders]) {
188
+ if (entry.frameTreeNodeId === null) continue;
189
+ if (entry.wc.isDestroyed() || findFrame(entry.wc, entry.frameTreeNodeId) === undefined) dropSubframe(id);
190
+ }
191
+ }
192
+ /** Send to the one frame that owns the sender; a frame that is gone ends the sender. */
193
+ const deliver = (senderId: number, ch: string, payload: unknown): void => {
194
+ const entry = senders.get(senderId);
195
+ if (entry === undefined || entry.wc.isDestroyed()) return;
196
+ try {
197
+ if (entry.frameTreeNodeId === null) {
198
+ entry.wc.send(ch, payload);
199
+ return;
200
+ }
201
+ const frame = findFrame(entry.wc, entry.frameTreeNodeId);
202
+ if (frame?.send === undefined) {
203
+ queueMicrotask(() => dropSubframe(senderId)); // not inside the service's own emit
204
+ return;
205
+ }
206
+ frame.send(ch, payload);
207
+ } catch {
208
+ // the webContents or frame was destroyed between the check and the send
209
+ }
210
+ };
84
211
  const service = new CastSessionService({
85
212
  devices: discovery,
86
213
  createClient,
@@ -92,39 +219,56 @@ export function createCastManager(options: CastManagerOptions): CastManager {
92
219
  } catch (err) {
93
220
  console.error("electron-cast: presentation handler failed on a service event", err);
94
221
  }
95
- const wc = contents.get(senderId);
96
- if (wc === undefined || wc.isDestroyed()) return;
97
- try {
98
- wc.send(`${channel}:event`, event);
99
- } catch {
100
- // the webContents was destroyed between the check and the send
101
- }
222
+ deliver(senderId, `${channel}:event`, event);
102
223
  },
103
224
  });
104
225
 
105
- /** Record a webContents on first use and watch it once. */
106
- const watch = (wc: WebContentsLike): void => {
107
- if (contents.has(wc.id)) return;
108
- contents.set(wc.id, wc);
226
+ /** Watch a webContents once: its destruction and its navigations end or park its senders. */
227
+ function watch(wc: WebContentsLike): void {
228
+ if (watched.has(wc.id)) return;
229
+ watched.add(wc.id);
230
+ const subframes = (): number[] =>
231
+ [...senders].filter(([, e]) => e.wc === wc && e.frameTreeNodeId !== null).map(([id]) => id);
109
232
  wc.once("destroyed", () => {
233
+ watched.delete(wc.id);
234
+ for (const id of subframes()) dropSubframe(id);
110
235
  presentation?.senderGone(wc.id);
111
- contents.delete(wc.id);
236
+ senders.delete(wc.id);
112
237
  service.senderGone(wc.id);
113
238
  });
114
239
  // A navigation ends the page's connections, but its sessions stay open (parked) so the next page can rejoin them
115
240
  wc.on("did-navigate", () => {
116
241
  presentation?.senderGone(wc.id);
117
242
  service.senderNavigated(wc.id);
243
+ for (const id of subframes()) dropSubframe(id); // the page's iframes went with it
118
244
  });
119
- };
245
+ // An iframe that navigates on its own is treated the same way (the main frame is handled above).
246
+ wc.on("did-frame-navigate", (_event, _url, _code, _text, mainFrame, processId, routingId) => {
247
+ if (mainFrame === true) return;
248
+ const frame = wc.mainFrame?.framesInSubtree.find((f) => f.processId === processId && f.routingId === routingId);
249
+ const id = typeof frame?.frameTreeNodeId === "number" ? subframeIds.get(frame.frameTreeNodeId) : undefined;
250
+ if (id !== undefined) {
251
+ presentation?.senderGone(id);
252
+ service.senderNavigated(id);
253
+ }
254
+ sweepFrames();
255
+ });
256
+ }
120
257
 
121
258
  options.ipcMain.handle(`${channel}:call`, (event, method, params) => {
122
259
  const origin = originOf(event.senderFrame);
123
- if (origin === null) {
260
+ if (origin === null || event.senderFrame === null) {
124
261
  return Promise.resolve({ ok: false, code: "extension_missing", description: "No sender frame" });
125
262
  }
126
- watch(event.sender);
127
- return service.handle({ id: event.sender.id, origin }, method, params);
263
+ // mode "chromecast" is main-frame only; iframes are served in presentation mode, as in Chrome
264
+ if (!isMainFrame(event.senderFrame)) {
265
+ return Promise.resolve({ ok: false, code: "extension_missing", description: "chrome.cast is not available in iframes; use presentation mode" });
266
+ }
267
+ if (typeof method !== "string" || !PAGE_METHODS.has(method)) {
268
+ return Promise.resolve({ ok: false, code: "invalid_parameter", description: `unknown method: ${String(method)}` });
269
+ }
270
+ const id = registerSender(event.sender, event.senderFrame)!;
271
+ return service.handle({ id, origin }, method, params);
128
272
  });
129
273
 
130
274
  /** Presentation mode: IPC for the page's stand-in Presentation API, answered by a CastPresentationHandler. */
@@ -134,16 +278,10 @@ export function createCastManager(options: CastManagerOptions): CastManager {
134
278
  const off = ipc.removeListener!.bind(ipc);
135
279
  const h = new CastPresentationHandler({ service });
136
280
  handler = h;
137
- const connections = new Map<string, { conn: PresentationConnectionHandle | null; wcId: number }>();
138
- const watches = new Map<string, { ac: AbortController; wcId: number }>();
139
- const sendTo = (wcId: number, payload: unknown): void => {
140
- const wc = contents.get(wcId);
141
- if (wc === undefined || wc.isDestroyed()) return;
142
- try {
143
- wc.send(`${channel}:presentation:event`, payload);
144
- } catch {
145
- // destroyed between the check and the send
146
- }
281
+ const connections = new Map<string, { conn: PresentationConnectionHandle | null; sid: number }>();
282
+ const watches = new Map<string, { ac: AbortController; sid: number }>();
283
+ const sendTo = (sid: number, payload: unknown): void => {
284
+ deliver(sid, `${channel}:presentation:event`, payload);
147
285
  };
148
286
  const invalid = (description: string) => ({ ok: false, code: "InvalidAccessError", description });
149
287
  const isId = (v: unknown): v is string => typeof v === "string" && v !== "" && v.length <= 256;
@@ -151,9 +289,9 @@ export function createCastManager(options: CastManagerOptions): CastManager {
151
289
  Array.isArray(v) && v.length > 0 && v.length <= 16 && v.every((u) => typeof u === "string");
152
290
 
153
291
  /** Finish a start/reconnect: register the connection and route its traffic to the page. */
154
- const open = async (wcId: number, connectionId: string, opening: () => Promise<PresentationConnectionHandle>) => {
292
+ const open = async (sid: number, connectionId: string, opening: () => Promise<PresentationConnectionHandle>) => {
155
293
  if (connections.has(connectionId)) return invalid("connectionId in use");
156
- const slot: { conn: PresentationConnectionHandle | null; wcId: number } = { conn: null, wcId };
294
+ const slot: { conn: PresentationConnectionHandle | null; sid: number } = { conn: null, sid };
157
295
  connections.set(connectionId, slot); // reserved while the picker or join is pending
158
296
  let conn: PresentationConnectionHandle;
159
297
  try {
@@ -164,25 +302,25 @@ export function createCastManager(options: CastManagerOptions): CastManager {
164
302
  const name = typeof e?.name === "string" && e.name !== "" && e.name !== "Error" ? e.name : "OperationError";
165
303
  return { ok: false, code: name, description: typeof e?.message === "string" ? e.message : String(err) };
166
304
  }
167
- if (!contents.has(wcId) || connections.get(connectionId) !== slot) {
305
+ if (!senders.has(sid) || connections.get(connectionId) !== slot) {
168
306
  conn.close();
169
307
  return { ok: false, code: "AbortError", description: "The page went away" };
170
308
  }
171
309
  slot.conn = conn;
172
310
  conn.onclose = (state) => {
173
311
  if (connections.get(connectionId) === slot) connections.delete(connectionId);
174
- sendTo(wcId, { type: "statechange", connectionId, state });
312
+ sendTo(sid, { type: "statechange", connectionId, state });
175
313
  };
176
314
  // The stand-in registered this connectionId before calling, so it buffers anything sent before the reply.
177
- conn.onmessage = (data) => sendTo(wcId, { type: "message", connectionId, data });
315
+ conn.onmessage = (data) => sendTo(sid, { type: "message", connectionId, data });
178
316
  return { ok: true, value: { id: conn.id, url: conn.url } };
179
317
  };
180
318
 
181
319
  ipc.handle(`${channel}:presentation`, async (event, method, params) => {
182
320
  const origin = originOf(event.senderFrame);
183
- if (origin === null) return { ok: false, code: "NotAllowedError", description: "No sender frame" };
184
- watch(event.sender);
185
- const wcId = event.sender.id;
321
+ if (origin === null || event.senderFrame === null) return { ok: false, code: "NotAllowedError", description: "No sender frame" };
322
+ const sid = registerSender(event.sender, event.senderFrame);
323
+ if (sid === null) return { ok: false, code: "NotAllowedError", description: "Unidentifiable sender frame" };
186
324
  const p = (typeof params === "object" && params !== null ? params : {}) as Record<string, unknown>;
187
325
  try {
188
326
  switch (method) {
@@ -190,28 +328,28 @@ export function createCastManager(options: CastManagerOptions): CastManager {
190
328
  if (!isId(p.watchId) || !isUrls(p.urls)) return invalid("getAvailability expects { watchId, urls }");
191
329
  const watchId = p.watchId;
192
330
  const old = watches.get(watchId);
193
- if (old !== undefined && old.wcId !== wcId) return invalid("watchId in use");
331
+ if (old !== undefined && old.sid !== sid) return invalid("watchId in use");
194
332
  old?.ac.abort();
195
333
  watches.delete(watchId);
196
- const mine = [...watches].filter(([, w]) => w.wcId === wcId);
334
+ const mine = [...watches].filter(([, w]) => w.sid === sid);
197
335
  for (const [id, w] of mine.slice(0, Math.max(0, mine.length - (MAX_WATCHES_PER_PAGE - 1)))) {
198
336
  w.ac.abort();
199
337
  watches.delete(id);
200
338
  }
201
339
  const ac = new AbortController();
202
- watches.set(watchId, { ac, wcId });
340
+ watches.set(watchId, { ac, sid });
203
341
  const available = await h.getAvailability({
204
342
  urls: p.urls,
205
343
  origin,
206
- senderId: wcId,
344
+ senderId: sid,
207
345
  signal: ac.signal,
208
- onchange: (value) => sendTo(wcId, { type: "availability", watchId, value }),
346
+ onchange: (value) => sendTo(sid, { type: "availability", watchId, value }),
209
347
  });
210
348
  return { ok: true, value: { available } };
211
349
  }
212
350
  case "stopWatching": {
213
351
  const w = isId(p.watchId) ? watches.get(p.watchId) : undefined;
214
- if (w !== undefined && w.wcId === wcId) {
352
+ if (w !== undefined && w.sid === sid) {
215
353
  w.ac.abort();
216
354
  watches.delete(p.watchId as string);
217
355
  }
@@ -219,9 +357,13 @@ export function createCastManager(options: CastManagerOptions): CastManager {
219
357
  }
220
358
  case "start":
221
359
  if (!isId(p.connectionId) || !isUrls(p.urls)) return invalid("start expects { connectionId, urls }");
360
+ // PresentationServiceImpl::StartPresentation: PRESENTATION_REQUEST_CANCELLED, which the page sees as AbortError
361
+ if (p.hasGesture !== true) {
362
+ return { ok: false, code: "AbortError", description: "PresentationRequest::start() requires user gesture." };
363
+ }
222
364
  {
223
365
  const urls = p.urls;
224
- return await open(wcId, p.connectionId, () => h.startPresentation({ urls, origin, senderId: wcId }));
366
+ return await open(sid, p.connectionId, () => h.startPresentation({ urls, origin, senderId: sid }));
225
367
  }
226
368
  case "reconnect":
227
369
  if (!isId(p.connectionId) || !isUrls(p.urls) || !isId(p.presentationId)) {
@@ -229,13 +371,13 @@ export function createCastManager(options: CastManagerOptions): CastManager {
229
371
  }
230
372
  {
231
373
  const { urls, presentationId } = p;
232
- return await open(wcId, p.connectionId,
233
- () => h.reconnectPresentation({ urls, origin, senderId: wcId, presentationId }));
374
+ return await open(sid, p.connectionId,
375
+ () => h.reconnectPresentation({ urls, origin, senderId: sid, presentationId }));
234
376
  }
235
377
  case "close":
236
378
  case "terminate": {
237
379
  const c = isId(p.connectionId) ? connections.get(p.connectionId) : undefined;
238
- if (c !== undefined && c.wcId === wcId && c.conn !== null) {
380
+ if (c !== undefined && c.sid === sid && c.conn !== null) {
239
381
  if (method === "close") c.conn.close();
240
382
  else c.conn.terminate();
241
383
  }
@@ -252,7 +394,7 @@ export function createCastManager(options: CastManagerOptions): CastManager {
252
394
  const onSend = (event: IpcMainEventLike, connectionId: unknown, data: unknown): void => {
253
395
  if (typeof connectionId !== "string" || typeof data !== "string") return;
254
396
  const c = connections.get(connectionId);
255
- if (c === undefined || c.wcId !== event.sender.id || c.conn === null) return;
397
+ if (c === undefined || c.sid !== senderIdOf(event.sender, event.senderFrame) || c.conn === null) return;
256
398
  if (data.length > MAX_MESSAGE_CHARS) return;
257
399
  c.conn.send(data);
258
400
  };
@@ -260,11 +402,11 @@ export function createCastManager(options: CastManagerOptions): CastManager {
260
402
 
261
403
  return {
262
404
  /** Close the page's connections and watches before the service drops it. */
263
- senderGone(wcId: number): void {
264
- h.senderGone(wcId);
265
- for (const [id, c] of connections) if (c.wcId === wcId) connections.delete(id);
405
+ senderGone(sid: number): void {
406
+ h.senderGone(sid);
407
+ for (const [id, c] of connections) if (c.sid === sid) connections.delete(id);
266
408
  for (const [id, w] of watches) {
267
- if (w.wcId !== wcId) continue;
409
+ if (w.sid !== sid) continue;
268
410
  w.ac.abort();
269
411
  watches.delete(id);
270
412
  }
@@ -280,18 +422,35 @@ export function createCastManager(options: CastManagerOptions): CastManager {
280
422
  };
281
423
  const presentation = options.presentation !== false ? setUpPresentation() : undefined;
282
424
 
425
+ // The service knows frames by sender id (an iframe has a synthetic one); the API speaks of windows, so a route's
426
+ // pages are reported as `webContents.id`s, once each however many of its frames hold the route.
427
+ const windowIds = (ids: number[]): number[] => [...new Set(ids.map((id) => senders.get(id)?.wc.id ?? id))];
428
+ const api = createManagerApi(createSinksObservers(discovery), {
429
+ mediaRoutes: () =>
430
+ service.mediaRoutes().map((r) => ({ ...r, members: windowIds(r.members), parkedSenders: windowIds(r.parkedSenders) })),
431
+ observeSessions: (l) => service.observeSessions(l),
432
+ terminateSession: (id) => service.terminateSession(id),
433
+ setSessionVolume: (id, v) => service.setSessionVolume(id, v),
434
+ detachSession: (id) => service.detachSession(id),
435
+ });
283
436
  let disposed = false;
284
437
  return {
438
+ ...api,
285
439
  start: () => discovery.start(),
286
440
  devices: () => discovery.devices(),
287
441
  async dispose() {
288
442
  if (disposed) return;
289
443
  disposed = true;
444
+ api.dispose();
290
445
  options.ipcMain.removeHandler(`${channel}:call`);
291
446
  presentation?.dispose();
292
447
  discovery.stop();
293
448
  await service.dispose();
294
- contents.clear();
449
+ senders.clear();
450
+ subframeIds.clear();
451
+ watched.clear();
452
+ if (sweepTimer !== undefined) clearInterval(sweepTimer);
453
+ sweepTimer = undefined;
295
454
  },
296
455
  };
297
456
  }