@open-wa/screencaster 5.0.0-alpha.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.
@@ -0,0 +1,107 @@
1
+ import { IScreencastCDPSession, IScreencastPage, ScreencastOptions } from "./types.mjs";
2
+ import { Context } from "hono";
3
+
4
+ //#region src/server.d.ts
5
+ /**
6
+ * Hono's upgradeWebSocket helper signature.
7
+ * We accept this as a parameter to avoid importing any runtime-specific adapter.
8
+ */
9
+ type UpgradeWebSocket = (handler: (c: Context) => HonoWSHandlers | Promise<HonoWSHandlers>) => (c: Context) => Response | Promise<Response>;
10
+ interface HonoWSHandlers {
11
+ onOpen?: (evt: unknown, ws: HonoWSContext) => void;
12
+ onMessage?: (evt: {
13
+ data: unknown;
14
+ }, ws: HonoWSContext) => void;
15
+ onClose?: (evt: unknown, ws: HonoWSContext) => void;
16
+ onError?: (evt: unknown, ws: HonoWSContext) => void;
17
+ }
18
+ interface HonoWSContext {
19
+ send(data: string | ArrayBuffer | Uint8Array): void;
20
+ close(code?: number, reason?: string): void;
21
+ readyState: number;
22
+ }
23
+ /**
24
+ * ScreencastManager owns the CDP session lifecycle and frame distribution.
25
+ * It is page-agnostic at construction — call setPage() once the browser is ready.
26
+ */
27
+ declare class ScreencastManager {
28
+ private page;
29
+ private cdpSession;
30
+ private clients;
31
+ private isScreencasting;
32
+ private currentOptions;
33
+ private viewport;
34
+ private cdpLock;
35
+ private frameHandler;
36
+ private navigationHandler;
37
+ private pageNavigationHandler;
38
+ private destroyed;
39
+ /**
40
+ * Bind a CDP-capable page. Can be called multiple times
41
+ * (e.g., when the session restarts).
42
+ */
43
+ setPage(page: IScreencastPage): Promise<void>;
44
+ /**
45
+ * Unbind the current page (session ended, browser closed).
46
+ */
47
+ clearPage(): Promise<void>;
48
+ /**
49
+ * Whether a page is currently bound.
50
+ */
51
+ get isBound(): boolean;
52
+ /**
53
+ * Number of connected viewers.
54
+ */
55
+ get clientCount(): number;
56
+ addClient(ws: HonoWSContext): void;
57
+ removeClient(ws: HonoWSContext): void;
58
+ handleMessage(ws: HonoWSContext, raw: unknown): Promise<void>;
59
+ private startScreencast;
60
+ private stopScreencast;
61
+ private executeInLock;
62
+ private setupFrameListener;
63
+ private sendNavState;
64
+ private getPageUrl;
65
+ private handleMouse;
66
+ private handleKey;
67
+ private handleScroll;
68
+ private handleNavigate;
69
+ private handleGoBack;
70
+ private handleGoForward;
71
+ private handleResize;
72
+ private broadcast;
73
+ private sendTo;
74
+ private logError;
75
+ private teardownCDP;
76
+ destroy(): Promise<void>;
77
+ }
78
+ /**
79
+ * Creates a Hono route handler for the screencast WebSocket endpoint.
80
+ *
81
+ * @param upgradeWebSocket - The `upgradeWebSocket` helper from a Hono WebSocket adapter
82
+ * (e.g., `@hono/node-ws`, `hono/bun`, `hono/deno`).
83
+ * @param manager - A `ScreencastManager` instance that handles CDP orchestration.
84
+ * @returns A Hono handler function — register it with `app.get('/screencast', handler)`.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * // Node.js
89
+ * import { createNodeWebSocket } from '@hono/node-ws';
90
+ * const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
91
+ * const manager = new ScreencastManager();
92
+ * app.get('/screencast', createScreencastRoute(upgradeWebSocket, manager));
93
+ * // After server.listen():
94
+ * injectWebSocket(server);
95
+ *
96
+ * // Bun
97
+ * import { createBunWebSocket } from 'hono/bun';
98
+ * const { upgradeWebSocket, websocket } = createBunWebSocket();
99
+ * const manager = new ScreencastManager();
100
+ * app.get('/screencast', createScreencastRoute(upgradeWebSocket, manager));
101
+ * export default { fetch: app.fetch, websocket };
102
+ * ```
103
+ */
104
+ declare function createScreencastRoute(upgradeWebSocket: UpgradeWebSocket, manager: ScreencastManager): (c: Context) => Response | Promise<Response>;
105
+ //#endregion
106
+ export { type IScreencastCDPSession, type IScreencastPage, ScreencastManager, type ScreencastOptions, createScreencastRoute };
107
+ //# sourceMappingURL=server.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";;;;;AA+ByF;;;KA8BpF,gBAAA,IACD,OAAA,GAAU,CAAA,EAAG,OAAA,KAAY,cAAA,GAAiB,OAAA,CAAQ,cAAA,OAChD,CAAA,EAAG,OAAA,KAAY,QAAA,GAAW,OAAA,CAAQ,QAAA;AAAA,UAE9B,cAAA;EACN,MAAA,IAAU,GAAA,WAAc,EAAA,EAAI,aAAA;EAC5B,SAAA,IAAa,GAAA;IAAO,IAAA;EAAA,GAAiB,EAAA,EAAI,aAAA;EACzC,OAAA,IAAW,GAAA,WAAc,EAAA,EAAI,aAAA;EAC7B,OAAA,IAAW,GAAA,WAAc,EAAA,EAAI,aAAA;AAAA;AAAA,UAGvB,aAAA;EACN,IAAA,CAAK,IAAA,WAAe,WAAA,GAAc,UAAA;EAClC,KAAA,CAAM,IAAA,WAAe,MAAA;EACrB,UAAA;AAAA;;;;;cAcS,iBAAA;EAAA,QACD,IAAA;EAAA,QACA,UAAA;EAAA,QACA,OAAA;EAAA,QACA,eAAA;EAAA,QACA,cAAA;EAAA,QACA,QAAA;EAAA,QACA,OAAA;EAAA,QACA,YAAA;EAAA,QACA,iBAAA;EAAA,QACA,qBAAA;EAAA,QACA,SAAA;EA/BkC;;;;EAqCpC,OAAA,CAAQ,IAAA,EAAM,eAAA,GAAkB,OAAA;EAxCd;;;EAuElB,SAAA,CAAA,GAAa,OAAA;EAtEsB;;;EAAA,IAiFrC,OAAA,CAAA;EAhFyB;;;EAAA,IAwFzB,WAAA,CAAA;EAMJ,SAAA,CAAU,EAAA,EAAI,aAAA;EAsCd,YAAA,CAAa,EAAA,EAAI,aAAA;EAaX,aAAA,CAAc,EAAA,EAAI,aAAA,EAAe,GAAA,YAAe,OAAA;EAAA,QA4FxC,eAAA;EAAA,QAiCA,cAAA;EAAA,QAcA,aAAA;EAAA,QAQN,kBAAA;EAAA,QAmKM,YAAA;EAAA,QAgCA,UAAA;EAAA,QAeA,WAAA;EAAA,QAuBA,SAAA;EAAA,QAkCA,YAAA;EAAA,QAeA,cAAA;EAAA,QAMA,YAAA;EAAA,QAcA,eAAA;EAAA,QAcA,YAAA;EAAA,QAsCN,SAAA;EAAA,QAuBA,MAAA;EAAA,QASA,QAAA;EAAA,QAIM,WAAA;EAoCR,OAAA,CAAA,GAAW,OAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA4CL,qBAAA,CACZ,gBAAA,EAAkB,gBAAA,EAClB,OAAA,EAAS,iBAAA,IAAiB,CAAA,EAjwBrB,OAAA,KAAY,QAAA,GAAW,OAAA,CAAQ,QAAA"}
@@ -0,0 +1,588 @@
1
+ import { DEFAULT_SCREENCAST_OPTIONS, SPECIAL_KEYS } from "./types.mjs";
2
+ //#region src/server.ts
3
+ const TAG = "[SC:server]";
4
+ let _frameCount = 0;
5
+ let _lastFrameLogTime = 0;
6
+ function ts() {
7
+ return Date.now().toString();
8
+ }
9
+ function dbg(...args) {
10
+ if (process.env.DEBUG_SCREENCAST) console.log(ts(), TAG, ...args);
11
+ }
12
+ function dbgWarn(...args) {
13
+ if (process.env.DEBUG_SCREENCAST) console.warn(ts(), TAG, ...args);
14
+ }
15
+ function dbgErr(...args) {
16
+ if (process.env.DEBUG_SCREENCAST) console.error(ts(), TAG, ...args);
17
+ }
18
+ /**
19
+ * ScreencastManager owns the CDP session lifecycle and frame distribution.
20
+ * It is page-agnostic at construction — call setPage() once the browser is ready.
21
+ */
22
+ var ScreencastManager = class {
23
+ page = null;
24
+ cdpSession = null;
25
+ clients = /* @__PURE__ */ new Set();
26
+ isScreencasting = false;
27
+ currentOptions = { ...DEFAULT_SCREENCAST_OPTIONS };
28
+ viewport = {
29
+ width: 1280,
30
+ height: 720
31
+ };
32
+ cdpLock = Promise.resolve();
33
+ frameHandler = null;
34
+ navigationHandler = null;
35
+ pageNavigationHandler = null;
36
+ destroyed = false;
37
+ /**
38
+ * Bind a CDP-capable page. Can be called multiple times
39
+ * (e.g., when the session restarts).
40
+ */
41
+ async setPage(page) {
42
+ dbg("setPage() called, page.isClosed():", page.isClosed());
43
+ await this.executeInLock(() => this.teardownCDP());
44
+ this.page = page;
45
+ dbg("setPage() — calling page.cdp() to create CDP session...");
46
+ this.cdpSession = await page.cdp();
47
+ dbg("setPage() — CDP session obtained:", !!this.cdpSession);
48
+ dbg("setPage() — CDP session type:", typeof this.cdpSession);
49
+ dbg("setPage() — CDP session keys:", this.cdpSession ? Object.keys(this.cdpSession).slice(0, 15) : "null");
50
+ this.setupFrameListener();
51
+ dbg("setPage() — clients waiting:", this.clients.size);
52
+ if (this.clients.size > 0) {
53
+ dbg("setPage() — auto-starting screencast for waiting clients");
54
+ await this.executeInLock(() => this.startScreencast());
55
+ }
56
+ dbg("setPage() — broadcasting ready:true");
57
+ this.broadcast({
58
+ type: "ready",
59
+ bound: true
60
+ });
61
+ }
62
+ /**
63
+ * Unbind the current page (session ended, browser closed).
64
+ */
65
+ async clearPage() {
66
+ dbg("clearPage() called");
67
+ await this.executeInLock(() => this.teardownCDP());
68
+ this.page = null;
69
+ this.cdpSession = null;
70
+ this.broadcast({
71
+ type: "ready",
72
+ bound: false
73
+ });
74
+ }
75
+ /**
76
+ * Whether a page is currently bound.
77
+ */
78
+ get isBound() {
79
+ return this.page !== null && !this.page.isClosed();
80
+ }
81
+ /**
82
+ * Number of connected viewers.
83
+ */
84
+ get clientCount() {
85
+ return this.clients.size;
86
+ }
87
+ addClient(ws) {
88
+ this.clients.add(ws);
89
+ dbg("addClient() — total clients:", this.clients.size, "| isBound:", this.isBound, "| isScreencasting:", this.isScreencasting, "| ws.readyState:", ws.readyState);
90
+ const rawWs = ws.raw;
91
+ if (rawWs && typeof rawWs.on === "function") {
92
+ rawWs.on("close", (code, reason) => {
93
+ dbg("RAW_WS:close — code:", code, "| reason:", reason?.toString(), "| rawWs.readyState:", rawWs.readyState);
94
+ });
95
+ rawWs.on("error", (err) => {
96
+ dbgErr("RAW_WS:error —", err.message);
97
+ });
98
+ const socket = rawWs._socket;
99
+ if (socket) {
100
+ socket.once("close", (hadError) => {
101
+ dbg("TCP_SOCKET:close — hadError:", hadError);
102
+ });
103
+ socket.once("error", (err) => {
104
+ dbgErr("TCP_SOCKET:error —", err.message);
105
+ });
106
+ }
107
+ }
108
+ this.sendTo(ws, {
109
+ type: "ready",
110
+ bound: this.isBound
111
+ });
112
+ if (this.isBound && !this.isScreencasting) {
113
+ dbg("addClient() — auto-starting screencast (first client with bound page)");
114
+ this.executeInLock(() => this.startScreencast()).catch(this.logError);
115
+ this.executeInLock(() => this.sendNavState()).catch(this.logError);
116
+ } else dbg("addClient() — NOT auto-starting. isBound:", this.isBound, "isScreencasting:", this.isScreencasting);
117
+ }
118
+ removeClient(ws) {
119
+ this.clients.delete(ws);
120
+ dbg("removeClient() — total clients:", this.clients.size, "| isScreencasting:", this.isScreencasting);
121
+ if (this.clients.size === 0 && this.isScreencasting) {
122
+ dbg("removeClient() — no clients left, stopping screencast");
123
+ this.stopScreencast().catch(this.logError);
124
+ }
125
+ }
126
+ async handleMessage(ws, raw) {
127
+ let msg;
128
+ try {
129
+ msg = JSON.parse(typeof raw === "string" ? raw : String(raw));
130
+ } catch {
131
+ dbgWarn("handleMessage() — invalid JSON from client:", typeof raw === "string" ? raw.slice(0, 100) : typeof raw);
132
+ this.sendTo(ws, {
133
+ type: "error",
134
+ message: "Invalid JSON"
135
+ });
136
+ return;
137
+ }
138
+ if (msg.type !== "mouse" && msg.type !== "ack") dbg("handleMessage():", msg.type, JSON.stringify(msg).slice(0, 200));
139
+ try {
140
+ switch (msg.type) {
141
+ case "start":
142
+ if (msg.options) {
143
+ this.currentOptions = {
144
+ ...DEFAULT_SCREENCAST_OPTIONS,
145
+ ...msg.options
146
+ };
147
+ dbg("handleMessage(start) — options updated:", JSON.stringify(this.currentOptions));
148
+ }
149
+ dbg("handleMessage(start) — isBound:", this.isBound, "| isScreencasting:", this.isScreencasting);
150
+ if (this.isBound) await this.executeInLock(async () => {
151
+ await this.startScreencast();
152
+ await this.sendNavState();
153
+ });
154
+ else dbgWarn("handleMessage(start) — page not bound, cannot start");
155
+ break;
156
+ case "stop":
157
+ dbg("handleMessage(stop)");
158
+ await this.executeInLock(() => this.stopScreencast());
159
+ this.sendTo(ws, { type: "stopped" });
160
+ break;
161
+ case "ack":
162
+ dbg("handleMessage(ack) — no-op (server-side ACK), sessionId:", msg.sessionId);
163
+ break;
164
+ case "mouse":
165
+ await this.executeInLock(() => this.handleMouse(msg));
166
+ break;
167
+ case "key":
168
+ dbg("handleMessage(key):", msg.action, msg.key, msg.code);
169
+ await this.executeInLock(() => this.handleKey(msg));
170
+ break;
171
+ case "scroll":
172
+ await this.executeInLock(() => this.handleScroll(msg));
173
+ break;
174
+ case "navigate":
175
+ dbg("handleMessage(navigate):", msg.url);
176
+ await this.executeInLock(() => this.handleNavigate(msg.url));
177
+ break;
178
+ case "go-back":
179
+ dbg("handleMessage(go-back)");
180
+ await this.executeInLock(() => this.handleGoBack());
181
+ break;
182
+ case "go-forward":
183
+ dbg("handleMessage(go-forward)");
184
+ await this.executeInLock(() => this.handleGoForward());
185
+ break;
186
+ case "resize":
187
+ dbg("handleMessage(resize):", msg.width, "x", msg.height);
188
+ await this.executeInLock(() => this.handleResize(msg.width, msg.height));
189
+ break;
190
+ default: dbgWarn("handleMessage() — unknown message type:", msg.type);
191
+ }
192
+ } catch (err) {
193
+ dbgErr("handleMessage() — error processing", msg.type, ":", err instanceof Error ? err.message : err);
194
+ this.sendTo(ws, {
195
+ type: "error",
196
+ message: err instanceof Error ? err.message : "Unknown error"
197
+ });
198
+ }
199
+ }
200
+ async startScreencast() {
201
+ dbg("startScreencast() — cdpSession:", !!this.cdpSession, "| isScreencasting:", this.isScreencasting, "| destroyed:", this.destroyed);
202
+ if (!this.cdpSession || this.isScreencasting || this.destroyed) {
203
+ dbg("startScreencast() — SKIPPING (guard failed)");
204
+ return;
205
+ }
206
+ this.isScreencasting = true;
207
+ try {
208
+ const params = {
209
+ format: this.currentOptions.format,
210
+ quality: this.currentOptions.quality,
211
+ maxWidth: this.currentOptions.maxWidth,
212
+ maxHeight: this.currentOptions.maxHeight,
213
+ everyNthFrame: this.currentOptions.everyNthFrame
214
+ };
215
+ dbg("startScreencast() — sending Page.startScreencast with params:", JSON.stringify(params));
216
+ await this.cdpSession.send("Page.startScreencast", params);
217
+ _frameCount = 0;
218
+ _lastFrameLogTime = Date.now();
219
+ dbg("startScreencast() — ✅ SUCCESS, screencast is now running");
220
+ } catch (err) {
221
+ this.isScreencasting = false;
222
+ dbgErr("startScreencast() — ❌ FAILED:", err instanceof Error ? err.message : err);
223
+ dbgErr("startScreencast() — full error:", err);
224
+ this.logError(err);
225
+ }
226
+ }
227
+ async stopScreencast() {
228
+ dbg("stopScreencast() — cdpSession:", !!this.cdpSession, "| isScreencasting:", this.isScreencasting);
229
+ if (!this.cdpSession || !this.isScreencasting) return;
230
+ try {
231
+ await this.cdpSession.send("Page.stopScreencast");
232
+ dbg("stopScreencast() — ✅ stopped");
233
+ } catch (err) {
234
+ dbgWarn("stopScreencast() — error (session may be closed):", err instanceof Error ? err.message : err);
235
+ }
236
+ this.isScreencasting = false;
237
+ }
238
+ async executeInLock(fn) {
239
+ const next = this.cdpLock.then(fn);
240
+ this.cdpLock = next.then(() => {}).catch(() => {});
241
+ return next;
242
+ }
243
+ setupFrameListener() {
244
+ dbg("setupFrameListener() — cdpSession:", !!this.cdpSession);
245
+ if (!this.cdpSession) return;
246
+ const rawSession = this.cdpSession;
247
+ dbg("setupFrameListener() — rawSession.on:", typeof rawSession.on, "| rawSession.off:", typeof rawSession.off);
248
+ if (typeof rawSession.on !== "function") {
249
+ dbgErr("setupFrameListener() — ❌ CDP session does NOT support .on() event subscriptions!");
250
+ dbgErr("setupFrameListener() — session prototype chain:", Object.getPrototypeOf(this.cdpSession)?.constructor?.name);
251
+ console.warn("[screencaster] CDP session does not support event subscriptions");
252
+ return;
253
+ }
254
+ if (this.frameHandler && typeof rawSession.off === "function") {
255
+ dbg("setupFrameListener() — cleaning up previous frame handler");
256
+ rawSession.off("Page.screencastFrame", this.frameHandler);
257
+ }
258
+ dbg("setupFrameListener() — registering Page.screencastFrame handler");
259
+ const session = this.cdpSession;
260
+ this.frameHandler = ((...args) => {
261
+ _frameCount++;
262
+ const now = Date.now();
263
+ const { data, sessionId, metadata } = args[0];
264
+ if (_frameCount <= 5 || _frameCount % 30 === 0 || now - _lastFrameLogTime > 5e3) {
265
+ dbg(`📦 FRAME #${_frameCount} | sessionId: ${sessionId} | dataLen: ${data?.length ?? "null"} | hasMetadata: ${!!metadata} | clients: ${this.clients.size}`);
266
+ if (metadata) dbg(` metadata: ${metadata.deviceWidth}x${metadata.deviceHeight} | pageScale: ${metadata.pageScaleFactor} | offsetTop: ${metadata.offsetTop}`);
267
+ _lastFrameLogTime = now;
268
+ }
269
+ if (metadata) this.viewport = {
270
+ width: metadata.deviceWidth || this.viewport.width,
271
+ height: metadata.deviceHeight || this.viewport.height
272
+ };
273
+ const frame = {
274
+ type: "frame",
275
+ data,
276
+ sessionId,
277
+ metadata: metadata || {
278
+ width: this.viewport.width,
279
+ height: this.viewport.height,
280
+ timestamp: Date.now(),
281
+ offsetTop: 0,
282
+ pageScaleFactor: 1,
283
+ deviceWidth: this.viewport.width,
284
+ deviceHeight: this.viewport.height
285
+ }
286
+ };
287
+ this.broadcast(frame);
288
+ session.send("Page.screencastFrameAck", { sessionId }).catch(() => {});
289
+ if (_frameCount <= 3) dbg(` → ACK sent server-side for sessionId: ${sessionId}`);
290
+ });
291
+ rawSession.on("Page.screencastFrame", this.frameHandler);
292
+ dbg("setupFrameListener() — ✅ Page.screencastFrame handler registered");
293
+ dbg("setupFrameListener() — registering Page.frameNavigated handler (CDP)");
294
+ if (this.navigationHandler && typeof rawSession.off === "function") {
295
+ dbg("setupFrameListener() — cleaning up previous CDP navigation handler");
296
+ rawSession.off("Page.frameNavigated", this.navigationHandler);
297
+ }
298
+ this.navigationHandler = (async (...navArgs) => {
299
+ const frame = navArgs[0];
300
+ const isMainFrame = frame.frame && !frame.frame.parentId;
301
+ dbg("CDP:Page.frameNavigated fired | isMainFrame:", isMainFrame, "| url:", frame.frame?.url?.slice(0, 80));
302
+ if (isMainFrame) {
303
+ dbg("CDP:Page.frameNavigated — main frame navigation detected, resetting screencast");
304
+ this.isScreencasting = false;
305
+ await this.sendNavState();
306
+ if (this.clients.size > 0) {
307
+ dbg("CDP:Page.frameNavigated — restarting screencast for", this.clients.size, "clients");
308
+ await this.startScreencast();
309
+ }
310
+ }
311
+ });
312
+ rawSession.on("Page.frameNavigated", this.navigationHandler);
313
+ if (this.page && typeof this.page.on === "function") {
314
+ if (this.pageNavigationHandler && typeof this.page.off === "function") {
315
+ dbg("setupFrameListener() — cleaning up previous page-level navigation handler");
316
+ this.page.off("framenavigated", this.pageNavigationHandler);
317
+ }
318
+ this.pageNavigationHandler = async (_frame) => {
319
+ dbg("PAGE:framenavigated fired (high-level) — isScreencasting:", this.isScreencasting);
320
+ if (!this.isScreencasting && this.clients.size > 0) {
321
+ dbg("PAGE:framenavigated — screencast not running, restarting for", this.clients.size, "clients");
322
+ await this.sendNavState();
323
+ await this.startScreencast();
324
+ } else dbg("PAGE:framenavigated — screencast already running or no clients, no action needed");
325
+ };
326
+ this.page.on("framenavigated", this.pageNavigationHandler);
327
+ dbg("setupFrameListener() — ✅ page-level framenavigated listener registered");
328
+ } else dbgWarn("setupFrameListener() — page does not support .on() events, skipping page-level navigation listener");
329
+ dbg("setupFrameListener() — sending Page.enable");
330
+ this.cdpSession.send("Page.enable").catch((err) => {
331
+ dbgErr("setupFrameListener() — Page.enable failed:", err instanceof Error ? err.message : err);
332
+ this.logError(err);
333
+ });
334
+ dbg("setupFrameListener() — ✅ setup complete");
335
+ }
336
+ async sendNavState() {
337
+ dbg("sendNavState() — cdpSession:", !!this.cdpSession);
338
+ if (!this.cdpSession) return;
339
+ try {
340
+ const history = await this.cdpSession.send("Page.getNavigationHistory");
341
+ if (!history) {
342
+ dbgWarn("sendNavState() — getNavigationHistory returned null/undefined");
343
+ return;
344
+ }
345
+ const { currentIndex, entries } = history;
346
+ const url = this.page?.isClosed() ? "" : await this.getPageUrl();
347
+ const nav = {
348
+ type: "nav-state",
349
+ url,
350
+ canGoBack: currentIndex > 0,
351
+ canGoForward: currentIndex < entries.length - 1
352
+ };
353
+ dbg("sendNavState() — broadcasting:", JSON.stringify({
354
+ url: url.slice(0, 60),
355
+ canGoBack: nav.canGoBack,
356
+ canGoForward: nav.canGoForward,
357
+ entries: entries.length
358
+ }));
359
+ this.broadcast(nav);
360
+ } catch (err) {
361
+ dbgWarn("sendNavState() — error:", err instanceof Error ? err.message : err);
362
+ }
363
+ }
364
+ async getPageUrl() {
365
+ if (!this.cdpSession) return "";
366
+ try {
367
+ return (await this.cdpSession.send("Runtime.evaluate", { expression: "window.location.href" }))?.result?.value || "";
368
+ } catch {
369
+ return "";
370
+ }
371
+ }
372
+ async handleMouse(msg) {
373
+ if (!this.cdpSession) return;
374
+ const x = msg.x * this.viewport.width;
375
+ const y = msg.y * this.viewport.height;
376
+ const cdpButton = msg.button === "right" ? "right" : msg.button === "middle" ? "middle" : "left";
377
+ const cdpType = msg.action === "move" ? "mouseMoved" : msg.action === "down" ? "mousePressed" : "mouseReleased";
378
+ await this.cdpSession.send("Input.dispatchMouseEvent", {
379
+ type: cdpType,
380
+ x,
381
+ y,
382
+ button: cdpButton,
383
+ clickCount: msg.action === "down" ? 1 : 0
384
+ });
385
+ }
386
+ async handleKey(msg) {
387
+ if (!this.cdpSession) return;
388
+ const modifiers = msg.modifiers || 0;
389
+ const type = msg.action === "down" ? "keyDown" : "keyUp";
390
+ if (msg.action === "down" && msg.key.length === 1 && !SPECIAL_KEYS.has(msg.key)) {
391
+ await this.cdpSession.send("Input.dispatchKeyEvent", {
392
+ type: "keyDown",
393
+ key: msg.key,
394
+ code: msg.code,
395
+ modifiers,
396
+ windowsVirtualKeyCode: msg.key.charCodeAt(0),
397
+ nativeVirtualKeyCode: msg.key.charCodeAt(0)
398
+ });
399
+ await this.cdpSession.send("Input.dispatchKeyEvent", {
400
+ type: "char",
401
+ text: msg.key,
402
+ key: msg.key,
403
+ code: msg.code,
404
+ modifiers
405
+ });
406
+ } else await this.cdpSession.send("Input.dispatchKeyEvent", {
407
+ type,
408
+ key: msg.key,
409
+ code: msg.code,
410
+ modifiers
411
+ });
412
+ }
413
+ async handleScroll(msg) {
414
+ if (!this.cdpSession) return;
415
+ const x = msg.x * this.viewport.width;
416
+ const y = msg.y * this.viewport.height;
417
+ await this.cdpSession.send("Input.dispatchMouseEvent", {
418
+ type: "mouseWheel",
419
+ x,
420
+ y,
421
+ deltaX: msg.deltaX,
422
+ deltaY: msg.deltaY
423
+ });
424
+ }
425
+ async handleNavigate(url) {
426
+ if (!this.cdpSession) return;
427
+ await this.cdpSession.send("Page.navigate", { url });
428
+ }
429
+ async handleGoBack() {
430
+ if (!this.cdpSession) return;
431
+ const history = await this.cdpSession.send("Page.getNavigationHistory");
432
+ if (history && history.currentIndex > 0) {
433
+ const entry = history.entries[history.currentIndex - 1];
434
+ await this.cdpSession.send("Page.navigateToHistoryEntry", { entryId: entry.id });
435
+ }
436
+ }
437
+ async handleGoForward() {
438
+ if (!this.cdpSession) return;
439
+ const history = await this.cdpSession.send("Page.getNavigationHistory");
440
+ if (history && history.currentIndex < history.entries.length - 1) {
441
+ const entry = history.entries[history.currentIndex + 1];
442
+ await this.cdpSession.send("Page.navigateToHistoryEntry", { entryId: entry.id });
443
+ }
444
+ }
445
+ async handleResize(width, height) {
446
+ if (!this.cdpSession) return;
447
+ try {
448
+ const w = Math.floor(width);
449
+ const h = Math.floor(height);
450
+ dbg("handleResize() — updating viewport and stopping screencast | new size:", w, "x", h);
451
+ this.currentOptions.maxWidth = w;
452
+ this.currentOptions.maxHeight = h;
453
+ this.viewport = {
454
+ width: w,
455
+ height: h
456
+ };
457
+ await this.cdpSession.send("Emulation.setDeviceMetricsOverride", {
458
+ width: w,
459
+ height: h,
460
+ deviceScaleFactor: 1,
461
+ mobile: false,
462
+ screenOrientation: {
463
+ angle: 0,
464
+ type: "portraitPrimary"
465
+ }
466
+ });
467
+ if (this.isScreencasting) {
468
+ dbg("handleResize() — restarting screencast");
469
+ await this.stopScreencast();
470
+ await this.startScreencast();
471
+ }
472
+ } catch (err) {
473
+ dbgErr("handleResize() — error:", err instanceof Error ? err.message : err);
474
+ this.logError(err);
475
+ }
476
+ }
477
+ broadcast(msg) {
478
+ const payload = JSON.stringify(msg);
479
+ let sent = 0;
480
+ let skipped = 0;
481
+ for (const ws of this.clients) if (ws.readyState === 1) try {
482
+ ws.send(payload);
483
+ sent++;
484
+ } catch (err) {
485
+ dbgErr("broadcast() — send failed for a client:", err instanceof Error ? err.message : err);
486
+ skipped++;
487
+ }
488
+ else skipped++;
489
+ if (msg.type !== "frame") dbg(`broadcast(${msg.type}) — sent: ${sent}, skipped: ${skipped}, total: ${this.clients.size}`);
490
+ }
491
+ sendTo(ws, msg) {
492
+ dbg(`sendTo(${msg.type}) — ws.readyState: ${ws.readyState}`);
493
+ if (ws.readyState === 1) ws.send(JSON.stringify(msg));
494
+ else dbgWarn(`sendTo(${msg.type}) — ws not OPEN (readyState: ${ws.readyState}), dropping`);
495
+ }
496
+ logError = (err) => {
497
+ dbgErr("logError:", err instanceof Error ? err.stack || err.message : err);
498
+ };
499
+ async teardownCDP() {
500
+ dbg("teardownCDP() — isScreencasting:", this.isScreencasting, "| hasFrameHandler:", !!this.frameHandler, "| hasNavHandler:", !!this.navigationHandler, "| hasPageNavHandler:", !!this.pageNavigationHandler, "| hasCdpSession:", !!this.cdpSession);
501
+ if (this.isScreencasting) await this.stopScreencast();
502
+ if (this.cdpSession) {
503
+ const rawSession = this.cdpSession;
504
+ if (typeof rawSession.off === "function") {
505
+ if (this.frameHandler) {
506
+ dbg("teardownCDP() — removing Page.screencastFrame handler");
507
+ rawSession.off("Page.screencastFrame", this.frameHandler);
508
+ }
509
+ if (this.navigationHandler) {
510
+ dbg("teardownCDP() — removing Page.frameNavigated handler");
511
+ rawSession.off("Page.frameNavigated", this.navigationHandler);
512
+ }
513
+ }
514
+ }
515
+ this.frameHandler = null;
516
+ this.navigationHandler = null;
517
+ if (this.pageNavigationHandler && this.page && typeof this.page.off === "function") {
518
+ dbg("teardownCDP() — removing page-level framenavigated handler");
519
+ this.page.off("framenavigated", this.pageNavigationHandler);
520
+ }
521
+ this.pageNavigationHandler = null;
522
+ dbg("teardownCDP() — ✅ complete");
523
+ }
524
+ async destroy() {
525
+ dbg("destroy() called, clients:", this.clients.size);
526
+ this.destroyed = true;
527
+ await this.executeInLock(() => this.teardownCDP());
528
+ for (const ws of this.clients) ws.close(1001, "Server shutting down");
529
+ this.clients.clear();
530
+ this.page = null;
531
+ this.cdpSession = null;
532
+ dbg("destroy() — ✅ complete");
533
+ }
534
+ };
535
+ /**
536
+ * Creates a Hono route handler for the screencast WebSocket endpoint.
537
+ *
538
+ * @param upgradeWebSocket - The `upgradeWebSocket` helper from a Hono WebSocket adapter
539
+ * (e.g., `@hono/node-ws`, `hono/bun`, `hono/deno`).
540
+ * @param manager - A `ScreencastManager` instance that handles CDP orchestration.
541
+ * @returns A Hono handler function — register it with `app.get('/screencast', handler)`.
542
+ *
543
+ * @example
544
+ * ```ts
545
+ * // Node.js
546
+ * import { createNodeWebSocket } from '@hono/node-ws';
547
+ * const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
548
+ * const manager = new ScreencastManager();
549
+ * app.get('/screencast', createScreencastRoute(upgradeWebSocket, manager));
550
+ * // After server.listen():
551
+ * injectWebSocket(server);
552
+ *
553
+ * // Bun
554
+ * import { createBunWebSocket } from 'hono/bun';
555
+ * const { upgradeWebSocket, websocket } = createBunWebSocket();
556
+ * const manager = new ScreencastManager();
557
+ * app.get('/screencast', createScreencastRoute(upgradeWebSocket, manager));
558
+ * export default { fetch: app.fetch, websocket };
559
+ * ```
560
+ */
561
+ function createScreencastRoute(upgradeWebSocket, manager) {
562
+ dbg("createScreencastRoute() — route factory invoked");
563
+ return upgradeWebSocket((_c) => ({
564
+ onOpen(_evt, ws) {
565
+ dbg("WS:onOpen — new connection, ws.readyState:", ws.readyState);
566
+ manager.addClient(ws);
567
+ },
568
+ onMessage(evt, ws) {
569
+ manager.handleMessage(ws, evt.data).catch((err) => {
570
+ dbgErr("WS:onMessage — unhandled error:", err);
571
+ });
572
+ },
573
+ onClose(evt, ws) {
574
+ const closeEvt = evt;
575
+ dbg("WS:onClose — connection closed | code:", closeEvt.code, "| reason:", closeEvt.reason, "| wasClean:", closeEvt.wasClean, "| ws.readyState:", ws.readyState);
576
+ manager.removeClient(ws);
577
+ },
578
+ onError(evt, ws) {
579
+ const errEvt = evt;
580
+ dbgErr("WS:onError — connection error | message:", errEvt.message, "| error:", errEvt.error);
581
+ manager.removeClient(ws);
582
+ }
583
+ }));
584
+ }
585
+ //#endregion
586
+ export { ScreencastManager, createScreencastRoute };
587
+
588
+ //# sourceMappingURL=server.mjs.map