electron-cast 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.md +85 -2
- package/dist/client/cast-client.d.ts +92 -0
- package/dist/client/cast-client.js +427 -0
- package/dist/client/cast-client.js.map +1 -0
- package/dist/client/errors.d.ts +17 -0
- package/dist/client/errors.js +30 -0
- package/dist/client/errors.js.map +1 -0
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.js +5 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/namespaces.d.ts +9 -0
- package/dist/client/namespaces.js +10 -0
- package/dist/client/namespaces.js.map +1 -0
- package/dist/client/types.d.ts +27 -0
- package/dist/client/types.js +2 -0
- package/dist/client/types.js.map +1 -0
- package/dist/discovery/cast-discovery.d.ts +84 -0
- package/dist/discovery/cast-discovery.js +234 -0
- package/dist/discovery/cast-discovery.js.map +1 -0
- package/dist/discovery/device-cache.d.ts +40 -0
- package/dist/discovery/device-cache.js +212 -0
- package/dist/discovery/device-cache.js.map +1 -0
- package/dist/discovery/dns-packet.d.ts +70 -0
- package/dist/discovery/dns-packet.js +244 -0
- package/dist/discovery/dns-packet.js.map +1 -0
- package/dist/discovery/index.d.ts +4 -0
- package/dist/discovery/index.js +5 -0
- package/dist/discovery/index.js.map +1 -0
- package/dist/discovery/udp-socket.d.ts +12 -0
- package/dist/discovery/udp-socket.js +105 -0
- package/dist/discovery/udp-socket.js.map +1 -0
- package/dist/electron/main.d.ts +51 -0
- package/dist/electron/main.js +79 -0
- package/dist/electron/main.js.map +1 -0
- package/dist/electron/preload.d.ts +22 -0
- package/dist/electron/preload.js +36 -0
- package/dist/electron/preload.js.map +1 -0
- package/dist/electron/session-service.d.ts +125 -0
- package/dist/electron/session-service.js +661 -0
- package/dist/electron/session-service.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/polyfill/bridge-types.d.ts +82 -0
- package/dist/polyfill/bridge-types.js +2 -0
- package/dist/polyfill/bridge-types.js.map +1 -0
- package/dist/polyfill/install.d.ts +12 -0
- package/dist/polyfill/install.js +546 -0
- package/dist/polyfill/install.js.map +1 -0
- package/dist/protocol/cast-message.d.ts +20 -0
- package/dist/protocol/cast-message.js +166 -0
- package/dist/protocol/cast-message.js.map +1 -0
- package/dist/protocol/errors.d.ts +4 -0
- package/dist/protocol/errors.js +8 -0
- package/dist/protocol/errors.js.map +1 -0
- package/dist/protocol/framing.d.ts +18 -0
- package/dist/protocol/framing.js +95 -0
- package/dist/protocol/framing.js.map +1 -0
- package/dist/protocol/index.d.ts +3 -0
- package/dist/protocol/index.js +4 -0
- package/dist/protocol/index.js.map +1 -0
- package/package.json +60 -4
- package/src/client/cast-client.ts +483 -0
- package/src/client/errors.ts +32 -0
- package/src/client/index.ts +4 -0
- package/src/client/namespaces.ts +10 -0
- package/src/client/types.ts +27 -0
- package/src/discovery/cast-discovery.ts +265 -0
- package/src/discovery/device-cache.ts +231 -0
- package/src/discovery/dns-packet.ts +262 -0
- package/src/discovery/index.ts +4 -0
- package/src/discovery/udp-socket.ts +121 -0
- package/src/electron/main.ts +113 -0
- package/src/electron/preload.ts +57 -0
- package/src/electron/session-service.ts +715 -0
- package/src/index.ts +8 -0
- package/src/polyfill/bridge-types.ts +26 -0
- package/src/polyfill/install.ts +576 -0
- package/src/protocol/cast-message.ts +176 -0
- package/src/protocol/errors.ts +7 -0
- package/src/protocol/framing.ts +97 -0
- package/src/protocol/index.ts +3 -0
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
import tls from "node:tls";
|
|
4
|
+
import type { TLSSocket } from "node:tls";
|
|
5
|
+
import { decodeCastMessage, encodeCastMessage, frame, FrameDecoder, PayloadType } from "../protocol/index.ts";
|
|
6
|
+
import type { CastMessage } from "../protocol/index.ts";
|
|
7
|
+
import { NS, PLATFORM_RECEIVER_ID } from "./namespaces.ts";
|
|
8
|
+
import { CastConnectionError, CastRequestError, CastTimeoutError } from "./errors.ts";
|
|
9
|
+
import type { ReceiverApplication, ReceiverStatus, ReceiverVolume } from "./types.ts";
|
|
10
|
+
|
|
11
|
+
/** Options for {@link CastClient}. */
|
|
12
|
+
export interface CastClientOptions {
|
|
13
|
+
host: string;
|
|
14
|
+
port?: number;
|
|
15
|
+
senderId?: string;
|
|
16
|
+
connectTimeoutMs?: number;
|
|
17
|
+
requestTimeoutMs?: number;
|
|
18
|
+
launchTimeoutMs?: number;
|
|
19
|
+
heartbeatIntervalMs?: number;
|
|
20
|
+
heartbeatTimeoutMs?: number;
|
|
21
|
+
tls?: Omit<tls.ConnectionOptions, "host" | "port">;
|
|
22
|
+
connectPayload?: Record<string, unknown>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Events emitted by {@link CastClient}. */
|
|
26
|
+
export interface CastClientEvents {
|
|
27
|
+
message: [msg: { namespace: string; sourceId: string; destinationId: string; data: string | Buffer }];
|
|
28
|
+
receiverStatus: [status: ReceiverStatus];
|
|
29
|
+
transportClosed: [transportId: string];
|
|
30
|
+
close: [error?: Error];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface PendingRequest {
|
|
34
|
+
namespace: string;
|
|
35
|
+
destinationId: string;
|
|
36
|
+
timer: NodeJS.Timeout;
|
|
37
|
+
resolve: (value: unknown) => void;
|
|
38
|
+
reject: (err: unknown) => void;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface LaunchWaiter {
|
|
42
|
+
appId: string;
|
|
43
|
+
requestId: number;
|
|
44
|
+
timer: NodeJS.Timeout;
|
|
45
|
+
resolve: (app: ReceiverApplication) => void;
|
|
46
|
+
reject: (err: unknown) => void;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
type ClientState = "idle" | "connecting" | "connected" | "closed";
|
|
50
|
+
|
|
51
|
+
const ERROR_REPLY_TYPES = new Set(["INVALID_REQUEST", "LOAD_FAILED", "LOAD_CANCELLED", "INVALID_PLAYER_STATE"]);
|
|
52
|
+
|
|
53
|
+
function isErrorResponse(type: string): boolean {
|
|
54
|
+
return ERROR_REPLY_TYPES.has(type) || type.endsWith("_ERROR");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function buildMessage(sourceId: string, namespace: string, destinationId: string, payload: string | Uint8Array | object): CastMessage {
|
|
58
|
+
const msg: CastMessage = {
|
|
59
|
+
protocolVersion: 0,
|
|
60
|
+
sourceId,
|
|
61
|
+
destinationId,
|
|
62
|
+
namespace,
|
|
63
|
+
payloadType: payload instanceof Uint8Array ? PayloadType.BINARY : PayloadType.STRING,
|
|
64
|
+
};
|
|
65
|
+
if (typeof payload === "string") msg.payloadUtf8 = payload;
|
|
66
|
+
else if (payload instanceof Uint8Array) msg.payloadBinary = Buffer.from(payload);
|
|
67
|
+
else msg.payloadUtf8 = JSON.stringify(payload);
|
|
68
|
+
return msg;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** A single-use Cast v2 client: one TLS connection to one receiver. */
|
|
72
|
+
export class CastClient extends EventEmitter<CastClientEvents> {
|
|
73
|
+
/** The sender id this client uses as its sourceId. */
|
|
74
|
+
readonly senderId: string;
|
|
75
|
+
|
|
76
|
+
private readonly options: CastClientOptions;
|
|
77
|
+
private socket: TLSSocket | null = null;
|
|
78
|
+
private decoder = new FrameDecoder();
|
|
79
|
+
private state: ClientState = "idle";
|
|
80
|
+
private nextRequestId = 1;
|
|
81
|
+
private pending = new Map<number, PendingRequest>();
|
|
82
|
+
private launchWaiters: LaunchWaiter[] = [];
|
|
83
|
+
private transports = new Set<string>();
|
|
84
|
+
private heartbeatTimer: NodeJS.Timeout | null = null;
|
|
85
|
+
private livenessTimer: NodeJS.Timeout | null = null;
|
|
86
|
+
private connectTimer: NodeJS.Timeout | null = null;
|
|
87
|
+
|
|
88
|
+
constructor(options: CastClientOptions) {
|
|
89
|
+
super();
|
|
90
|
+
this.options = options;
|
|
91
|
+
this.senderId = options.senderId ?? "sender-" + randomBytes(4).toString("hex");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** True while connected to the receiver. */
|
|
95
|
+
get connected(): boolean {
|
|
96
|
+
return this.state === "connected";
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Open the TLS connection and send CONNECT to the platform receiver. */
|
|
100
|
+
connect(): Promise<void> {
|
|
101
|
+
if (this.state !== "idle") {
|
|
102
|
+
return Promise.reject(new CastConnectionError(`cannot connect: client is ${this.state}`));
|
|
103
|
+
}
|
|
104
|
+
this.state = "connecting";
|
|
105
|
+
const host = this.options.host;
|
|
106
|
+
const port = this.options.port ?? 8009;
|
|
107
|
+
const socket = tls.connect({ host, port, rejectUnauthorized: false, ...this.options.tls });
|
|
108
|
+
this.socket = socket;
|
|
109
|
+
|
|
110
|
+
return new Promise<void>((resolve, reject) => {
|
|
111
|
+
let settled = false;
|
|
112
|
+
const settle = (err?: Error) => {
|
|
113
|
+
if (settled) return;
|
|
114
|
+
settled = true;
|
|
115
|
+
if (this.connectTimer !== null) {
|
|
116
|
+
clearTimeout(this.connectTimer);
|
|
117
|
+
this.connectTimer = null;
|
|
118
|
+
}
|
|
119
|
+
if (err === undefined) {
|
|
120
|
+
this.state = "connected";
|
|
121
|
+
this.startHeartbeat();
|
|
122
|
+
this.write(buildMessage(this.senderId, NS.CONNECTION, PLATFORM_RECEIVER_ID, { type: "CONNECT", ...this.options.connectPayload }));
|
|
123
|
+
resolve();
|
|
124
|
+
} else {
|
|
125
|
+
this.state = "closed";
|
|
126
|
+
this.socket = null;
|
|
127
|
+
socket.destroy();
|
|
128
|
+
reject(err);
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const connectTimeoutMs = this.options.connectTimeoutMs ?? 10000;
|
|
133
|
+
this.connectTimer = setTimeout(() => {
|
|
134
|
+
settle(new CastTimeoutError(`TLS handshake did not complete within ${connectTimeoutMs} ms`));
|
|
135
|
+
}, connectTimeoutMs);
|
|
136
|
+
|
|
137
|
+
socket.on("secureConnect", () => {
|
|
138
|
+
socket.on("data", (chunk: Buffer) => this.onData(chunk));
|
|
139
|
+
settle();
|
|
140
|
+
});
|
|
141
|
+
socket.on("error", (err: Error) => {
|
|
142
|
+
if (this.state === "connecting") {
|
|
143
|
+
settle(new CastConnectionError(`failed to connect to ${host}:${port}: ${err.message}`, { cause: err }));
|
|
144
|
+
} else if (this.state === "connected") {
|
|
145
|
+
this.fail(new CastConnectionError(`socket error: ${err.message}`, { cause: err }));
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
socket.on("close", () => {
|
|
149
|
+
if (this.state === "connecting") {
|
|
150
|
+
settle(new CastConnectionError("connection closed during TLS handshake"));
|
|
151
|
+
} else if (this.state === "connected") {
|
|
152
|
+
this.fail(new CastConnectionError("connection closed by remote end"));
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Close gracefully: goodbye CLOSE messages, then end the socket. Idempotent. */
|
|
159
|
+
close(): void {
|
|
160
|
+
if (this.state !== "connected") return;
|
|
161
|
+
this.state = "closed";
|
|
162
|
+
this.stopTimers();
|
|
163
|
+
for (const id of [...this.transports]) {
|
|
164
|
+
this.sendJson(NS.CONNECTION, id, { type: "CLOSE" });
|
|
165
|
+
}
|
|
166
|
+
this.transports.clear();
|
|
167
|
+
this.sendJson(NS.CONNECTION, PLATFORM_RECEIVER_ID, { type: "CLOSE" });
|
|
168
|
+
const socket = this.socket;
|
|
169
|
+
this.socket = null;
|
|
170
|
+
if (socket !== null) socket.end();
|
|
171
|
+
const err = new CastConnectionError("client closed");
|
|
172
|
+
this.rejectAllPending(err);
|
|
173
|
+
this.rejectAllLaunches(err);
|
|
174
|
+
this.emit("close");
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Send a raw message; throws {@link CastConnectionError} when not connected. */
|
|
178
|
+
send(namespace: string, destinationId: string, payload: string | Uint8Array | object): void {
|
|
179
|
+
if (this.state !== "connected") throw new CastConnectionError("not connected");
|
|
180
|
+
this.write(buildMessage(this.senderId, namespace, destinationId, payload));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Send a request and wait for the matching reply. */
|
|
184
|
+
request<T = Record<string, unknown>>(
|
|
185
|
+
namespace: string,
|
|
186
|
+
destinationId: string,
|
|
187
|
+
payload: Record<string, unknown>,
|
|
188
|
+
options?: { timeoutMs?: number },
|
|
189
|
+
): Promise<T> {
|
|
190
|
+
if (this.state !== "connected") {
|
|
191
|
+
return Promise.reject(new CastConnectionError("not connected"));
|
|
192
|
+
}
|
|
193
|
+
const requestId = this.nextRequestId++;
|
|
194
|
+
const timeoutMs = options?.timeoutMs ?? this.options.requestTimeoutMs ?? 10000;
|
|
195
|
+
return new Promise<T>((resolve, reject) => {
|
|
196
|
+
const entry: PendingRequest = {
|
|
197
|
+
namespace,
|
|
198
|
+
destinationId,
|
|
199
|
+
timer: setTimeout(() => {
|
|
200
|
+
this.pending.delete(requestId);
|
|
201
|
+
reject(new CastTimeoutError(`request ${requestId} on ${namespace} timed out after ${timeoutMs} ms`));
|
|
202
|
+
}, timeoutMs),
|
|
203
|
+
resolve: resolve as (value: unknown) => void,
|
|
204
|
+
reject,
|
|
205
|
+
};
|
|
206
|
+
this.pending.set(requestId, entry);
|
|
207
|
+
this.write(buildMessage(this.senderId, namespace, destinationId, { ...payload, requestId }));
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Ask the receiver for its current status. */
|
|
212
|
+
getStatus(): Promise<ReceiverStatus> {
|
|
213
|
+
return this.request<Record<string, unknown>>(NS.RECEIVER, PLATFORM_RECEIVER_ID, { type: "GET_STATUS" }).then((reply) =>
|
|
214
|
+
this.normalizeStatus(reply.status),
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Launch an app and wait until it appears in a RECEIVER_STATUS. */
|
|
219
|
+
launch(appId: string): Promise<ReceiverApplication> {
|
|
220
|
+
if (this.state !== "connected") {
|
|
221
|
+
return Promise.reject(new CastConnectionError("not connected"));
|
|
222
|
+
}
|
|
223
|
+
const requestId = this.nextRequestId++;
|
|
224
|
+
const timeoutMs = this.options.launchTimeoutMs ?? 30000;
|
|
225
|
+
return new Promise<ReceiverApplication>((resolve, reject) => {
|
|
226
|
+
const waiter: LaunchWaiter = {
|
|
227
|
+
appId,
|
|
228
|
+
requestId,
|
|
229
|
+
timer: setTimeout(() => {
|
|
230
|
+
this.removeLaunchWaiter(waiter);
|
|
231
|
+
reject(new CastTimeoutError(`launch of ${appId} timed out after ${timeoutMs} ms`));
|
|
232
|
+
}, timeoutMs),
|
|
233
|
+
resolve,
|
|
234
|
+
reject,
|
|
235
|
+
};
|
|
236
|
+
this.launchWaiters.push(waiter);
|
|
237
|
+
this.write(buildMessage(this.senderId, NS.RECEIVER, PLATFORM_RECEIVER_ID, { type: "LAUNCH", appId, requestId }));
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Stop a session; resolves with the new status. */
|
|
242
|
+
stop(sessionId: string): Promise<ReceiverStatus> {
|
|
243
|
+
return this.request<Record<string, unknown>>(NS.RECEIVER, PLATFORM_RECEIVER_ID, { type: "STOP", sessionId }).then((reply) =>
|
|
244
|
+
this.normalizeStatus(reply.status),
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Set the volume by level or muted flag; resolves with the new status. */
|
|
249
|
+
setVolume(volume: { level: number } | { muted: boolean }): Promise<ReceiverStatus> {
|
|
250
|
+
return this.request<Record<string, unknown>>(NS.RECEIVER, PLATFORM_RECEIVER_ID, { type: "SET_VOLUME", volume }).then((reply) =>
|
|
251
|
+
this.normalizeStatus(reply.status),
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Ask which of the given app ids are available on the receiver. */
|
|
256
|
+
async getAppAvailability(appIds: string[]): Promise<Record<string, boolean>> {
|
|
257
|
+
const reply = await this.request<Record<string, unknown>>(NS.RECEIVER, PLATFORM_RECEIVER_ID, {
|
|
258
|
+
type: "GET_APP_AVAILABILITY",
|
|
259
|
+
appId: appIds,
|
|
260
|
+
});
|
|
261
|
+
const availability = (reply.availability ?? {}) as Record<string, unknown>;
|
|
262
|
+
const out: Record<string, boolean> = {};
|
|
263
|
+
for (const id of appIds) out[id] = availability[id] === "APP_AVAILABLE";
|
|
264
|
+
return out;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Open a virtual connection to a transport (idempotent). */
|
|
268
|
+
connectTransport(transportId: string): void {
|
|
269
|
+
if (this.state !== "connected") return;
|
|
270
|
+
if (this.transports.has(transportId)) return;
|
|
271
|
+
this.transports.add(transportId);
|
|
272
|
+
this.sendJson(NS.CONNECTION, transportId, { type: "CONNECT", ...this.options.connectPayload });
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Close a virtual connection to a transport. */
|
|
276
|
+
closeTransport(transportId: string): void {
|
|
277
|
+
if (this.state !== "connected") return;
|
|
278
|
+
this.transports.delete(transportId);
|
|
279
|
+
this.sendJson(NS.CONNECTION, transportId, { type: "CLOSE" });
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
private onData(chunk: Buffer): void {
|
|
283
|
+
if (this.state !== "connected") return;
|
|
284
|
+
this.resetLiveness();
|
|
285
|
+
let bodies: Buffer[];
|
|
286
|
+
try {
|
|
287
|
+
bodies = this.decoder.push(chunk);
|
|
288
|
+
} catch (err) {
|
|
289
|
+
this.fail(new CastConnectionError(`protocol error: ${describe(err)}`, { cause: err instanceof Error ? err : undefined }));
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
for (const body of bodies) {
|
|
293
|
+
let msg: CastMessage;
|
|
294
|
+
try {
|
|
295
|
+
msg = decodeCastMessage(body);
|
|
296
|
+
} catch (err) {
|
|
297
|
+
this.fail(new CastConnectionError(`protocol error: ${describe(err)}`, { cause: err instanceof Error ? err : undefined }));
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
this.handleMessage(msg);
|
|
301
|
+
if (this.state !== "connected") return;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
private handleMessage(msg: CastMessage): void {
|
|
306
|
+
if (msg.namespace === NS.HEARTBEAT) {
|
|
307
|
+
if (this.jsonType(msg) === "PING") this.sendJson(NS.HEARTBEAT, msg.sourceId, { type: "PONG" });
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (msg.namespace === NS.CONNECTION) {
|
|
311
|
+
if (this.jsonType(msg) === "CLOSE") {
|
|
312
|
+
if (msg.sourceId === PLATFORM_RECEIVER_ID) {
|
|
313
|
+
this.fail(new CastConnectionError("closed by receiver"));
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
if (this.transports.delete(msg.sourceId)) this.emit("transportClosed", msg.sourceId);
|
|
317
|
+
}
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const data: string | Buffer =
|
|
322
|
+
msg.payloadType === PayloadType.STRING ? (msg.payloadUtf8 ?? "") : (msg.payloadBinary ?? Buffer.alloc(0));
|
|
323
|
+
this.emit("message", { namespace: msg.namespace, sourceId: msg.sourceId, destinationId: msg.destinationId, data });
|
|
324
|
+
|
|
325
|
+
if (msg.payloadType !== PayloadType.STRING || msg.payloadUtf8 === undefined) return;
|
|
326
|
+
let reply: Record<string, unknown> | undefined;
|
|
327
|
+
try {
|
|
328
|
+
const parsed: unknown = JSON.parse(msg.payloadUtf8);
|
|
329
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) reply = parsed as Record<string, unknown>;
|
|
330
|
+
} catch {
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if (reply === undefined) return;
|
|
334
|
+
|
|
335
|
+
this.matchPending(msg, reply);
|
|
336
|
+
if (msg.namespace !== NS.RECEIVER) return;
|
|
337
|
+
const type = typeof reply.type === "string" ? reply.type : "";
|
|
338
|
+
if (type === "RECEIVER_STATUS") {
|
|
339
|
+
const status = this.normalizeStatus(reply.status);
|
|
340
|
+
this.emit("receiverStatus", status);
|
|
341
|
+
this.settleLaunches(status);
|
|
342
|
+
} else if (type === "LAUNCH_ERROR" || type === "INVALID_REQUEST") {
|
|
343
|
+
this.rejectLaunches(reply);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
private matchPending(msg: CastMessage, reply: Record<string, unknown>): void {
|
|
348
|
+
const requestId = reply.requestId;
|
|
349
|
+
if (typeof requestId !== "number") return;
|
|
350
|
+
const entry = this.pending.get(requestId);
|
|
351
|
+
if (entry === undefined) return;
|
|
352
|
+
if (entry.namespace !== msg.namespace || entry.destinationId !== msg.sourceId) return;
|
|
353
|
+
this.pending.delete(requestId);
|
|
354
|
+
clearTimeout(entry.timer);
|
|
355
|
+
const type = typeof reply.type === "string" ? reply.type : "";
|
|
356
|
+
if (isErrorResponse(type)) entry.reject(new CastRequestError(reply));
|
|
357
|
+
else entry.resolve(reply);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
private settleLaunches(status: ReceiverStatus): void {
|
|
361
|
+
for (const waiter of [...this.launchWaiters]) {
|
|
362
|
+
const app = status.applications.find((a) => a.appId === waiter.appId);
|
|
363
|
+
if (app !== undefined) {
|
|
364
|
+
this.removeLaunchWaiter(waiter);
|
|
365
|
+
waiter.resolve(app);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
private rejectLaunches(reply: Record<string, unknown>): void {
|
|
371
|
+
const requestId = reply.requestId;
|
|
372
|
+
if (typeof requestId !== "number") return;
|
|
373
|
+
for (const waiter of [...this.launchWaiters]) {
|
|
374
|
+
if (waiter.requestId !== requestId) continue;
|
|
375
|
+
this.removeLaunchWaiter(waiter);
|
|
376
|
+
waiter.reject(new CastRequestError(reply));
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
private removeLaunchWaiter(waiter: LaunchWaiter): void {
|
|
381
|
+
const i = this.launchWaiters.indexOf(waiter);
|
|
382
|
+
if (i !== -1) this.launchWaiters.splice(i, 1);
|
|
383
|
+
clearTimeout(waiter.timer);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
private normalizeStatus(status: unknown): ReceiverStatus {
|
|
387
|
+
const s = (status !== null && typeof status === "object" ? status : {}) as Record<string, unknown>;
|
|
388
|
+
return {
|
|
389
|
+
...s,
|
|
390
|
+
applications: Array.isArray(s.applications) ? (s.applications as ReceiverApplication[]) : [],
|
|
391
|
+
volume: s.volume !== null && typeof s.volume === "object" ? (s.volume as ReceiverVolume) : {},
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
private jsonType(msg: CastMessage): string | undefined {
|
|
396
|
+
if (msg.payloadType !== PayloadType.STRING || msg.payloadUtf8 === undefined) return undefined;
|
|
397
|
+
try {
|
|
398
|
+
const parsed: unknown = JSON.parse(msg.payloadUtf8);
|
|
399
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
400
|
+
const t = (parsed as Record<string, unknown>).type;
|
|
401
|
+
if (typeof t === "string") return t;
|
|
402
|
+
}
|
|
403
|
+
} catch {
|
|
404
|
+
return undefined;
|
|
405
|
+
}
|
|
406
|
+
return undefined;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
private startHeartbeat(): void {
|
|
410
|
+
this.stopTimers();
|
|
411
|
+
this.heartbeatTimer = setInterval(() => {
|
|
412
|
+
this.sendJson(NS.HEARTBEAT, PLATFORM_RECEIVER_ID, { type: "PING" });
|
|
413
|
+
}, this.options.heartbeatIntervalMs ?? 5000);
|
|
414
|
+
this.resetLiveness();
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
private resetLiveness(): void {
|
|
418
|
+
if (this.livenessTimer !== null) clearTimeout(this.livenessTimer);
|
|
419
|
+
const timeoutMs = this.options.heartbeatTimeoutMs ?? 10000;
|
|
420
|
+
this.livenessTimer = setTimeout(() => {
|
|
421
|
+
this.fail(new CastConnectionError(`no traffic from receiver for ${timeoutMs} ms (heartbeat timeout)`));
|
|
422
|
+
}, timeoutMs);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
private stopTimers(): void {
|
|
426
|
+
if (this.heartbeatTimer !== null) {
|
|
427
|
+
clearInterval(this.heartbeatTimer);
|
|
428
|
+
this.heartbeatTimer = null;
|
|
429
|
+
}
|
|
430
|
+
if (this.livenessTimer !== null) {
|
|
431
|
+
clearTimeout(this.livenessTimer);
|
|
432
|
+
this.livenessTimer = null;
|
|
433
|
+
}
|
|
434
|
+
if (this.connectTimer !== null) {
|
|
435
|
+
clearTimeout(this.connectTimer);
|
|
436
|
+
this.connectTimer = null;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** Fail the client: destroy the socket, reject pending work, emit close once. */
|
|
441
|
+
private fail(err: CastConnectionError): void {
|
|
442
|
+
if (this.state !== "connected") return;
|
|
443
|
+
this.state = "closed";
|
|
444
|
+
this.stopTimers();
|
|
445
|
+
const socket = this.socket;
|
|
446
|
+
this.socket = null;
|
|
447
|
+
if (socket !== null) socket.destroy();
|
|
448
|
+
this.rejectAllPending(err);
|
|
449
|
+
this.rejectAllLaunches(err);
|
|
450
|
+
this.emit("close", err);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
private rejectAllPending(err: Error): void {
|
|
454
|
+
for (const entry of this.pending.values()) {
|
|
455
|
+
clearTimeout(entry.timer);
|
|
456
|
+
entry.reject(err);
|
|
457
|
+
}
|
|
458
|
+
this.pending.clear();
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
private rejectAllLaunches(err: Error): void {
|
|
462
|
+
for (const waiter of this.launchWaiters) {
|
|
463
|
+
clearTimeout(waiter.timer);
|
|
464
|
+
waiter.reject(err);
|
|
465
|
+
}
|
|
466
|
+
this.launchWaiters = [];
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
private sendJson(namespace: string, destinationId: string, payload: Record<string, unknown>): void {
|
|
470
|
+
this.write(buildMessage(this.senderId, namespace, destinationId, payload));
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
private write(msg: CastMessage): void {
|
|
474
|
+
const socket = this.socket;
|
|
475
|
+
if (socket !== null) socket.write(frame(encodeCastMessage(msg)));
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function describe(err: unknown): string {
|
|
480
|
+
return err instanceof Error ? err.message : String(err);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** The connection to the receiver could not be established or was lost. */
|
|
2
|
+
export class CastConnectionError extends Error {
|
|
3
|
+
constructor(message: string, options?: { cause?: unknown }) {
|
|
4
|
+
super(message, options);
|
|
5
|
+
this.name = "CastConnectionError";
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** A connect, request or launch did not finish within its time limit. */
|
|
10
|
+
export class CastTimeoutError extends Error {
|
|
11
|
+
constructor(message: string) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "CastTimeoutError";
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The receiver answered a request with an error reply. */
|
|
18
|
+
export class CastRequestError extends Error {
|
|
19
|
+
readonly type: string;
|
|
20
|
+
readonly reason: string | undefined;
|
|
21
|
+
readonly response: Record<string, unknown>;
|
|
22
|
+
|
|
23
|
+
constructor(response: Record<string, unknown>) {
|
|
24
|
+
const type = typeof response.type === "string" ? response.type : "UNKNOWN";
|
|
25
|
+
const reason = typeof response.reason === "string" ? response.reason : undefined;
|
|
26
|
+
super(reason === undefined ? type : `${type}: ${reason}`);
|
|
27
|
+
this.name = "CastRequestError";
|
|
28
|
+
this.type = type;
|
|
29
|
+
this.reason = reason;
|
|
30
|
+
this.response = response;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Well-known Cast v2 namespace urns. */
|
|
2
|
+
export const NS = {
|
|
3
|
+
CONNECTION: "urn:x-cast:com.google.cast.tp.connection",
|
|
4
|
+
HEARTBEAT: "urn:x-cast:com.google.cast.tp.heartbeat",
|
|
5
|
+
RECEIVER: "urn:x-cast:com.google.cast.receiver",
|
|
6
|
+
DEVICE_AUTH: "urn:x-cast:com.google.cast.tp.deviceauth",
|
|
7
|
+
} as const;
|
|
8
|
+
|
|
9
|
+
/** Destination id of the platform receiver (the device itself). */
|
|
10
|
+
export const PLATFORM_RECEIVER_ID = "receiver-0";
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** An application running on the receiver, as reported in RECEIVER_STATUS. */
|
|
2
|
+
export interface ReceiverApplication {
|
|
3
|
+
appId: string;
|
|
4
|
+
displayName: string;
|
|
5
|
+
sessionId: string;
|
|
6
|
+
transportId: string;
|
|
7
|
+
statusText?: string;
|
|
8
|
+
namespaces: { name: string }[];
|
|
9
|
+
isIdleScreen?: boolean;
|
|
10
|
+
iconUrl?: string;
|
|
11
|
+
[key: string]: unknown;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Volume state of the receiver. */
|
|
15
|
+
export interface ReceiverVolume {
|
|
16
|
+
level?: number;
|
|
17
|
+
muted?: boolean;
|
|
18
|
+
controlType?: string;
|
|
19
|
+
stepInterval?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Normalized receiver status (the `status` field of RECEIVER_STATUS). */
|
|
23
|
+
export interface ReceiverStatus {
|
|
24
|
+
applications: ReceiverApplication[];
|
|
25
|
+
volume: ReceiverVolume;
|
|
26
|
+
[key: string]: unknown;
|
|
27
|
+
}
|