@lynx-js/devtool-connector 0.1.1 → 0.9.5

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 (47) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +1 -1
  3. package/README.md +152 -0
  4. package/dist/187.js +272 -0
  5. package/dist/390.js +102 -0
  6. package/dist/43.js +20 -0
  7. package/dist/556.js +253 -0
  8. package/dist/63.js +93 -0
  9. package/dist/677.js +19 -0
  10. package/dist/712.js +180 -0
  11. package/dist/872.js +771 -0
  12. package/dist/962.js +12150 -0
  13. package/dist/client-id.d.ts +7 -0
  14. package/dist/daemon/device-connection.d.ts +36 -0
  15. package/dist/daemon/entry.d.ts +1 -0
  16. package/dist/daemon/entry.js +46 -0
  17. package/dist/daemon/index.d.ts +1 -0
  18. package/dist/daemon/index.js +1 -0
  19. package/dist/daemon/manager.d.ts +14 -0
  20. package/dist/daemon/protocol.d.ts +73 -0
  21. package/dist/daemon/server.d.ts +14 -0
  22. package/dist/daemon/static-server.d.ts +5 -0
  23. package/dist/daemon/tarball-cache.d.ts +16 -0
  24. package/dist/daemon/version.d.ts +1 -0
  25. package/dist/index.d.ts +47 -19
  26. package/dist/index.js +188 -349
  27. package/dist/rslib-runtime.js +0 -20
  28. package/dist/streams/cdp.d.ts +2 -4
  29. package/dist/streams/customized.d.ts +5 -4
  30. package/dist/streams/index.d.ts +3 -0
  31. package/dist/streams/index.js +1 -0
  32. package/dist/streams/utils.d.ts +11 -0
  33. package/dist/transport/android.d.ts +4 -3
  34. package/dist/transport/base.d.ts +9 -0
  35. package/dist/transport/daemon.d.ts +20 -0
  36. package/dist/transport/desktop.d.ts +4 -3
  37. package/dist/transport/index.d.ts +5 -0
  38. package/dist/transport/index.js +3 -11253
  39. package/dist/transport/ios.d.ts +3 -4
  40. package/dist/transport/transport.d.ts +7 -5
  41. package/dist/transport/usbmux.d.ts +49 -0
  42. package/dist/transport/ws-stream.d.ts +28 -0
  43. package/dist/types.d.ts +73 -19
  44. package/package.json +33 -15
  45. package/public/inspector-wrapper.html +539 -0
  46. package/dist/844.js +0 -632
  47. /package/dist/{streams → transport}/peertalk.d.ts +0 -0
package/dist/872.js ADDED
@@ -0,0 +1,771 @@
1
+ import node_http from "node:http";
2
+ import { setTimeout as promises_setTimeout } from "node:timers/promises";
3
+ import { WebSocketServer } from "ws";
4
+ import node_fs from "node:fs";
5
+ import node_path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import node_zlib from "node:zlib";
8
+ import { isCustomizedMessage, DAEMON_VERSION_PATH, DAEMON_INSPECTOR_PATH, isListClientsRequest, DAEMON_SHUTDOWN_PATH, isPingEvent, isRegisterEvent, isControlRequest, node_createDebug, DAEMON_WS_PATH } from "./187.js";
9
+ import { isInitializeResponse } from "./677.js";
10
+ import { ClientId } from "./43.js";
11
+ const debug = node_createDebug('devtool-mcp-server:daemon:device-connection');
12
+ class DeviceConnection {
13
+ key;
14
+ deviceId;
15
+ port;
16
+ #conn = null;
17
+ #writer = null;
18
+ #subscribers = new Map();
19
+ #transport;
20
+ #options;
21
+ #disposed = false;
22
+ #readLoopPromise = null;
23
+ appInfo = null;
24
+ constructor(transport, options){
25
+ this.#transport = transport;
26
+ this.#options = options;
27
+ this.deviceId = options.deviceId;
28
+ this.port = options.port;
29
+ this.key = `${options.deviceId}:${options.port}`;
30
+ }
31
+ async connect() {
32
+ debug('connecting to %s', this.key);
33
+ if (this.#disposed) throw new Error(`DeviceConnection ${this.key} was disposed before connect started`);
34
+ const conn = await this.#transport.connect(this.#options);
35
+ if (this.#disposed) {
36
+ await conn[Symbol.asyncDispose]();
37
+ throw new Error(`DeviceConnection ${this.key} was disposed before connect completed`);
38
+ }
39
+ this.#conn = conn;
40
+ this.#writer = this.#conn.writable.getWriter();
41
+ this.#readLoopPromise = this.#readLoop();
42
+ debug('connected to %s', this.key);
43
+ }
44
+ addSubscriber(subscriber) {
45
+ this.#subscribers.set(subscriber.id, subscriber);
46
+ debug('subscriber %d added to %s (total: %d)', subscriber.id, this.key, this.#subscribers.size);
47
+ }
48
+ removeSubscriber(id) {
49
+ this.#subscribers.delete(id);
50
+ debug('subscriber %d removed from %s (total: %d)', id, this.key, this.#subscribers.size);
51
+ }
52
+ get subscriberCount() {
53
+ return this.#subscribers.size;
54
+ }
55
+ get isDisposed() {
56
+ return this.#disposed;
57
+ }
58
+ get isPersistent() {
59
+ return true === this.#transport.persistent;
60
+ }
61
+ async send(message) {
62
+ if (!this.#writer) throw new Error(`DeviceConnection ${this.key} is not connected`);
63
+ try {
64
+ await this.#writer.write(message);
65
+ } catch (err) {
66
+ debug('send to %s failed: %O', this.key, err);
67
+ throw err;
68
+ }
69
+ }
70
+ async dispose() {
71
+ if (this.#disposed) return;
72
+ this.#disposed = true;
73
+ debug('disposing device connection %s', this.key);
74
+ try {
75
+ this.#writer?.releaseLock();
76
+ } catch {}
77
+ try {
78
+ await this.#conn?.[Symbol.asyncDispose]();
79
+ } catch (err) {
80
+ debug('error disposing connection %s: %O', this.key, err);
81
+ }
82
+ await this.#readLoopPromise;
83
+ this.#subscribers.clear();
84
+ }
85
+ async #readLoop() {
86
+ if (!this.#conn) return;
87
+ try {
88
+ for await (const message of this.#conn.readable){
89
+ if (null === this.appInfo) {
90
+ const response = message;
91
+ if (isInitializeResponse(response)) {
92
+ this.appInfo = response.data.info;
93
+ debug('captured appInfo for %s: %O', this.key, this.appInfo);
94
+ continue;
95
+ }
96
+ }
97
+ this.#broadcast(message);
98
+ }
99
+ } catch (err) {
100
+ if (!this.#disposed) debug('read loop error on %s: %O', this.key, err);
101
+ }
102
+ if (!this.#disposed) {
103
+ debug('device connection %s closed by remote', this.key);
104
+ this.#disposed = true;
105
+ this.#closeAllSubscribers();
106
+ }
107
+ }
108
+ #closeAllSubscribers() {
109
+ for (const [, subscriber] of this.#subscribers)try {
110
+ subscriber.close();
111
+ } catch (err) {
112
+ debug('failed to close subscriber %d: %O', subscriber.id, err);
113
+ }
114
+ }
115
+ #broadcast(message) {
116
+ for (const [, subscriber] of this.#subscribers)try {
117
+ subscriber.send(message);
118
+ } catch (err) {
119
+ debug('failed to send to subscriber %d: %O', subscriber.id, err);
120
+ }
121
+ }
122
+ }
123
+ const tarball_cache_debug = node_createDebug('devtool-mcp-server:daemon:tarball-cache');
124
+ const TAR_FILTER_PREFIX = '';
125
+ class TarballCache {
126
+ #files = new Map();
127
+ #pending = new Map();
128
+ #done = false;
129
+ #error = null;
130
+ #loading = null;
131
+ get(filePath) {
132
+ return this.#files.get(filePath);
133
+ }
134
+ get isDone() {
135
+ return this.#done;
136
+ }
137
+ waitFor(filePath) {
138
+ const existing = this.#files.get(filePath);
139
+ if (existing) return Promise.resolve(existing);
140
+ if (this.#error) return Promise.reject(this.#error);
141
+ if (this.#done) return Promise.resolve(null);
142
+ return new Promise((resolve, reject)=>{
143
+ let waiters = this.#pending.get(filePath);
144
+ if (!waiters) {
145
+ waiters = [];
146
+ this.#pending.set(filePath, waiters);
147
+ }
148
+ waiters.push({
149
+ resolve,
150
+ reject
151
+ });
152
+ });
153
+ }
154
+ start(url) {
155
+ if (this.#loading) return;
156
+ this.#loading = this.#load(url);
157
+ }
158
+ async #load(url) {
159
+ try {
160
+ const response = await fetch(url);
161
+ if (!response.ok) throw new Error(`Failed to fetch tarball: ${response.status}`);
162
+ if (!response.body) throw new Error('No response body');
163
+ const gunzip = node_zlib.createGunzip();
164
+ const { Readable } = await import("node:stream");
165
+ Readable.fromWeb(response.body).pipe(gunzip);
166
+ let buf = Buffer.alloc(0);
167
+ for await (const chunk of gunzip){
168
+ buf = Buffer.concat([
169
+ buf,
170
+ chunk
171
+ ]);
172
+ buf = this.#consumeTar(buf);
173
+ }
174
+ this.#consumeTar(buf);
175
+ } catch (err) {
176
+ this.#error = err instanceof Error ? err : new Error(String(err));
177
+ tarball_cache_debug('tarball stream error: %O', this.#error);
178
+ } finally{
179
+ this.#done = true;
180
+ for (const [, waiters] of this.#pending)for (const { resolve, reject } of waiters)if (this.#error) reject(this.#error);
181
+ else resolve(null);
182
+ this.#pending.clear();
183
+ tarball_cache_debug('tarball cache done: %d files', this.#files.size);
184
+ }
185
+ }
186
+ #consumeTar(buf) {
187
+ while(buf.length >= 512){
188
+ const header = buf.subarray(0, 512);
189
+ if (header.every((b)=>0 === b)) {
190
+ buf = buf.subarray(512);
191
+ continue;
192
+ }
193
+ const rawName = header.subarray(0, 100).toString('utf-8').replace(/\0.*$/, '');
194
+ const prefix = header.subarray(345, 500).toString('utf-8').replace(/\0.*$/, '');
195
+ const name = prefix ? `${prefix}/${rawName}` : rawName;
196
+ const sizeStr = header.subarray(124, 136).toString('utf-8').replace(/\0.*$/, '').trim();
197
+ const size = parseInt(sizeStr, 8) || 0;
198
+ const typeFlag = header[156];
199
+ const paddedSize = 512 * Math.ceil(size / 512);
200
+ if (buf.length < 512 + paddedSize) break;
201
+ if ((48 === typeFlag || 0 === typeFlag) && name.startsWith(TAR_FILTER_PREFIX)) {
202
+ const fileData = buf.subarray(512, 512 + size);
203
+ const ext = node_path.extname(name).toLowerCase();
204
+ if ('.map' !== ext) {
205
+ const gzipped = node_zlib.gzipSync(fileData, {
206
+ level: node_zlib.constants.Z_BEST_SPEED
207
+ });
208
+ const entry = {
209
+ gzipped,
210
+ rawSize: size
211
+ };
212
+ this.#files.set(name, entry);
213
+ const waiters = this.#pending.get(name);
214
+ if (waiters) {
215
+ this.#pending.delete(name);
216
+ for (const { resolve } of waiters)resolve(entry);
217
+ }
218
+ }
219
+ }
220
+ buf = buf.subarray(512 + paddedSize);
221
+ }
222
+ return buf;
223
+ }
224
+ }
225
+ const static_server_debug = node_createDebug('devtool-mcp-server:daemon:static-server');
226
+ const DEVTOOL_FRONTEND_TARBALL_URL = 'https://github.com/lynx-family/lynx-devtool/releases/download/devtools-frontend-lynx-7/devtool.frontend.lynx_1.0.1779085629.tar.gz';
227
+ const DEVTOOL_FRONTEND_PATH_PREFIX = '/devtool-frontend/';
228
+ const MIME_TYPES = {
229
+ '.html': 'text/html; charset=utf-8',
230
+ '.js': "application/javascript; charset=utf-8",
231
+ '.css': 'text/css; charset=utf-8',
232
+ '.json': 'application/json; charset=utf-8',
233
+ '.png': 'image/png',
234
+ '.jpg': 'image/jpeg',
235
+ '.svg': 'image/svg+xml',
236
+ '.woff2': 'font/woff2',
237
+ '.woff': 'font/woff',
238
+ '.ttf': 'font/ttf'
239
+ };
240
+ class StaticServer {
241
+ #frontendCache = null;
242
+ tryHandle(req, res) {
243
+ if ('GET' !== req.method) return false;
244
+ const pathname = new URL(req.url ?? '/', 'http://127.0.0.1').pathname;
245
+ if (pathname === DAEMON_INSPECTOR_PATH) {
246
+ this.#serveInspectorWrapper(res);
247
+ return true;
248
+ }
249
+ if (pathname.startsWith(DEVTOOL_FRONTEND_PATH_PREFIX)) {
250
+ this.#serveFrontendRes(req, res, pathname);
251
+ return true;
252
+ }
253
+ return false;
254
+ }
255
+ #serveInspectorWrapper(res) {
256
+ const base = node_path.dirname(fileURLToPath(import.meta.url));
257
+ const primary = node_path.resolve(base, '../../public');
258
+ const secondary = node_path.resolve(base, '../public');
259
+ const candidates = [
260
+ primary,
261
+ secondary
262
+ ];
263
+ const filePath = candidates.map((d)=>node_path.join(d, 'inspector-wrapper.html')).find((f)=>node_fs.existsSync(f)) ?? node_path.join(primary, 'inspector-wrapper.html');
264
+ node_fs.readFile(filePath, 'utf-8', (err, content)=>{
265
+ if (err) {
266
+ res.writeHead(404);
267
+ res.end('Not found');
268
+ return;
269
+ }
270
+ res.writeHead(200, {
271
+ 'content-type': 'text/html; charset=utf-8',
272
+ 'content-length': Buffer.byteLength(content),
273
+ 'cache-control': 'no-store'
274
+ });
275
+ res.end(content);
276
+ });
277
+ }
278
+ async #serveFrontendRes(req, res, pathname) {
279
+ try {
280
+ if (!this.#frontendCache) {
281
+ this.#frontendCache = new TarballCache();
282
+ this.#frontendCache.start(DEVTOOL_FRONTEND_TARBALL_URL);
283
+ }
284
+ const relativePath = pathname.slice(DEVTOOL_FRONTEND_PATH_PREFIX.length);
285
+ if (relativePath.includes('..')) {
286
+ res.writeHead(404);
287
+ res.end('Not found');
288
+ return;
289
+ }
290
+ const ext = node_path.extname(relativePath).toLowerCase();
291
+ if ('.map' === ext) {
292
+ res.writeHead(404);
293
+ res.end('Not found');
294
+ return;
295
+ }
296
+ const entry = this.#frontendCache.get(relativePath) ?? await this.#frontendCache.waitFor(relativePath);
297
+ if (!entry) {
298
+ res.writeHead(404);
299
+ res.end('Not found');
300
+ return;
301
+ }
302
+ const contentType = MIME_TYPES[ext] ?? 'application/octet-stream';
303
+ const acceptGzip = req.headers['accept-encoding']?.includes('gzip');
304
+ if (acceptGzip) {
305
+ res.writeHead(200, {
306
+ 'content-type': contentType,
307
+ 'content-encoding': 'gzip',
308
+ 'content-length': entry.gzipped.length,
309
+ 'cache-control': 'public, max-age=31536000, immutable'
310
+ });
311
+ res.end(entry.gzipped);
312
+ } else {
313
+ const raw = node_zlib.gunzipSync(entry.gzipped);
314
+ res.writeHead(200, {
315
+ 'content-type': contentType,
316
+ 'content-length': raw.length,
317
+ 'cache-control': 'public, max-age=31536000, immutable'
318
+ });
319
+ res.end(raw);
320
+ }
321
+ } catch (err) {
322
+ static_server_debug('failed to serve frontend file: %O', err);
323
+ res.writeHead(502);
324
+ res.end('Failed to load resource');
325
+ }
326
+ }
327
+ }
328
+ var package_namespaceObject = {
329
+ rE: "0.9.5"
330
+ };
331
+ const CONNECTOR_VERSION = package_namespaceObject.rE;
332
+ const server_debug = node_createDebug('devtool-mcp-server:daemon:server');
333
+ const IDLE_TIMEOUT_MS = 300000;
334
+ const DEVICE_CONN_GRACE_MS = 10000;
335
+ const DEVICE_DISCOVERY_TIMEOUT_MS = 2500;
336
+ const DEVICE_CONN_SETUP_TIMEOUT_MS = 5000;
337
+ const DEVICE_CONN_DISPOSE_TIMEOUT_MS = 1000;
338
+ class DevtoolDaemon {
339
+ #httpServer;
340
+ #wss = null;
341
+ #transports;
342
+ #deviceConnections = new Map();
343
+ #pendingDeviceConnections = new Map();
344
+ #deviceConnectionCleanupTimers = new Map();
345
+ #wsClients = new Map();
346
+ #nextClientId = 0;
347
+ #idleTimer = null;
348
+ #closed = false;
349
+ #onIdle;
350
+ #onShutdown;
351
+ #staticServer = new StaticServer();
352
+ constructor(transports, options){
353
+ this.#transports = transports;
354
+ this.#onIdle = options?.onIdle;
355
+ this.#onShutdown = options?.onShutdown;
356
+ this.#httpServer = node_http.createServer((req, res)=>{
357
+ if ('GET' === req.method && this.#isVersionRequest(req.url)) return void this.#sendJson(res, 200, {
358
+ version: CONNECTOR_VERSION
359
+ });
360
+ if (this.#staticServer.tryHandle(req, res)) return;
361
+ if ('POST' === req.method && this.#isShutdownRequest(req.url)) return void this.#sendJson(res, 202, {
362
+ ok: true
363
+ }, ()=>{
364
+ this.close().catch((err)=>{
365
+ server_debug('failed to close daemon after shutdown request: %O', err);
366
+ }).finally(()=>{
367
+ this.#onShutdown?.();
368
+ });
369
+ });
370
+ res.writeHead(404);
371
+ res.end();
372
+ });
373
+ }
374
+ async start(port) {
375
+ const wss = new WebSocketServer({
376
+ noServer: true
377
+ });
378
+ this.#wss = wss;
379
+ this.#httpServer.on('upgrade', (request, socket, head)=>{
380
+ if (!request.url?.startsWith(DAEMON_WS_PATH)) return void socket.destroy();
381
+ wss.handleUpgrade(request, socket, head, (ws)=>{
382
+ this.#handleConnection(ws);
383
+ });
384
+ });
385
+ return new Promise((resolve, reject)=>{
386
+ this.#httpServer.once('error', reject);
387
+ this.#httpServer.listen(port, '127.0.0.1', ()=>{
388
+ this.#httpServer.removeListener('error', reject);
389
+ this.#resetIdleTimer();
390
+ const address = this.#httpServer.address();
391
+ server_debug('daemon listening on ws://127.0.0.1:%d%s', address.port, DAEMON_WS_PATH);
392
+ resolve(address.port);
393
+ });
394
+ });
395
+ }
396
+ async close() {
397
+ if (this.#closed) return;
398
+ this.#closed = true;
399
+ this.#clearIdleTimer();
400
+ for (const [, client] of this.#wsClients)client.close();
401
+ this.#wsClients.clear();
402
+ for (const [, conn] of this.#deviceConnections)await conn.dispose();
403
+ this.#deviceConnections.clear();
404
+ for (const [, timer] of this.#deviceConnectionCleanupTimers)clearTimeout(timer);
405
+ this.#deviceConnectionCleanupTimers.clear();
406
+ for (const transport of this.#transports)await transport.close();
407
+ this.#wss?.close();
408
+ return new Promise((resolve)=>{
409
+ this.#httpServer.close(()=>resolve());
410
+ });
411
+ }
412
+ #isVersionRequest(url) {
413
+ return new URL(url ?? '/', 'http://127.0.0.1').pathname === DAEMON_VERSION_PATH;
414
+ }
415
+ #isShutdownRequest(url) {
416
+ return new URL(url ?? '/', 'http://127.0.0.1').pathname === DAEMON_SHUTDOWN_PATH;
417
+ }
418
+ #sendJson(res, statusCode, data, callback) {
419
+ const body = JSON.stringify(data);
420
+ res.writeHead(statusCode, {
421
+ 'content-type': 'application/json; charset=utf-8',
422
+ 'content-length': Buffer.byteLength(body),
423
+ 'cache-control': 'no-store'
424
+ });
425
+ res.end(body, callback);
426
+ }
427
+ #handleConnection(ws) {
428
+ const clientId = ++this.#nextClientId;
429
+ server_debug('new ws client %d', clientId);
430
+ this.#clearIdleTimer();
431
+ const session = {
432
+ id: clientId,
433
+ subscriptions: new Set(),
434
+ send (message) {
435
+ if (1 === ws.readyState) ws.send(JSON.stringify(message));
436
+ },
437
+ close () {
438
+ ws.close(1001, 'device disconnected');
439
+ }
440
+ };
441
+ session.send({
442
+ event: 'Initialize',
443
+ data: clientId
444
+ });
445
+ ws.on('message', (raw)=>{
446
+ try {
447
+ const msg = JSON.parse(String(raw));
448
+ this.#handleMessage(session, msg);
449
+ } catch (err) {
450
+ server_debug('failed to parse message from client %d: %O', clientId, err);
451
+ }
452
+ });
453
+ ws.on('close', ()=>{
454
+ server_debug('ws client %d disconnected', clientId);
455
+ this.#wsClients.delete(clientId);
456
+ for (const key of session.subscriptions){
457
+ const deviceConn = this.#deviceConnections.get(key);
458
+ if (deviceConn) {
459
+ deviceConn.removeSubscriber(clientId);
460
+ if (0 === deviceConn.subscriberCount) this.#scheduleDeviceConnectionCleanup(key);
461
+ }
462
+ }
463
+ session.subscriptions.clear();
464
+ this.#resetIdleTimer();
465
+ });
466
+ ws.on('error', (err)=>{
467
+ server_debug('ws client %d error: %O', clientId, err);
468
+ });
469
+ }
470
+ #handleMessage(session, msg) {
471
+ if (isRegisterEvent(msg)) {
472
+ this.#wsClients.set(session.id, session);
473
+ server_debug('client %d registered', session.id);
474
+ return;
475
+ }
476
+ if (isListClientsRequest(msg)) return void this.#sendClientList(session);
477
+ if (isPingEvent(msg)) return void session.send({
478
+ event: 'Pong'
479
+ });
480
+ if (isControlRequest(msg)) return void this.#handleControlRequest(session, msg);
481
+ if (isCustomizedMessage(msg)) return void this.#handleCustomizedMessage(session, msg);
482
+ server_debug('unknown message from client %d: %O', session.id, msg);
483
+ }
484
+ async #handleCustomizedMessage(session, msg) {
485
+ const targetPort = msg.to ?? msg.data?.data?.client_id;
486
+ if ('number' != typeof targetPort) return void server_debug('cannot determine target port from message: %O', msg);
487
+ for (const key of session.subscriptions){
488
+ const deviceConn = this.#deviceConnections.get(key);
489
+ if (deviceConn && deviceConn.port === targetPort) {
490
+ try {
491
+ await deviceConn.send({
492
+ ...msg,
493
+ data: {
494
+ ...msg.data,
495
+ sender: targetPort
496
+ }
497
+ });
498
+ } catch (err) {
499
+ server_debug('failed to forward message to %s: %O', key, err);
500
+ }
501
+ return;
502
+ }
503
+ }
504
+ server_debug('no matching device connection for client %d, port %d', session.id, targetPort);
505
+ }
506
+ async #handleControlRequest(session, req) {
507
+ const { id, method, params } = req.data;
508
+ try {
509
+ let result;
510
+ switch(method){
511
+ case 'listClients':
512
+ result = await this.#discoverClients();
513
+ break;
514
+ case 'listDevices':
515
+ {
516
+ const devices = [];
517
+ const allResults = await Promise.allSettled(this.#transports.map((t)=>t.listDevices()));
518
+ for (const r of allResults)if ('fulfilled' === r.status) devices.push(...r.value);
519
+ result = devices;
520
+ break;
521
+ }
522
+ case 'listAvailableApps':
523
+ {
524
+ const deviceId = params?.deviceId;
525
+ if (!deviceId) throw new Error('deviceId is required');
526
+ const transport = await this.#findTransportWithDeviceId(deviceId);
527
+ result = await transport.listAvailableApps(deviceId);
528
+ break;
529
+ }
530
+ case 'openApp':
531
+ {
532
+ const p = params ?? {};
533
+ if (!p.deviceId || !p.packageName) throw new Error('deviceId and packageName are required');
534
+ const transport = await this.#findTransportWithDeviceId(p.deviceId);
535
+ await transport.openApp(p.deviceId, p.packageName, {
536
+ withDataCleared: p.withDataCleared
537
+ });
538
+ result = null;
539
+ break;
540
+ }
541
+ case 'subscribe':
542
+ {
543
+ const s = params ?? {};
544
+ if (!s.deviceId || void 0 === s.port) throw new Error('deviceId and port are required');
545
+ const transport = await this.#findTransportWithDeviceId(s.deviceId);
546
+ const conn = await this.#getOrCreateDeviceConnection(transport, s.deviceId, s.port);
547
+ conn.addSubscriber(session);
548
+ session.subscriptions.add(conn.key);
549
+ result = null;
550
+ break;
551
+ }
552
+ default:
553
+ throw new Error(`Unknown control method: ${method}`);
554
+ }
555
+ session.send({
556
+ event: 'ControlResponse',
557
+ data: {
558
+ id,
559
+ result
560
+ }
561
+ });
562
+ } catch (err) {
563
+ const message = err instanceof Error ? err.message : String(err);
564
+ session.send({
565
+ event: 'ControlResponse',
566
+ data: {
567
+ id,
568
+ error: message
569
+ }
570
+ });
571
+ }
572
+ }
573
+ async #sendClientList(session) {
574
+ try {
575
+ const clients = await this.#discoverClients();
576
+ session.send({
577
+ event: 'ClientList',
578
+ data: clients
579
+ });
580
+ } catch (err) {
581
+ server_debug('failed to send client list: %O', err);
582
+ session.send({
583
+ event: 'ClientList',
584
+ data: []
585
+ });
586
+ }
587
+ }
588
+ async #discoverClients() {
589
+ const entries = [];
590
+ const clientListTransports = this.#transports.filter((t)=>'function' == typeof t.listClients);
591
+ const clientListResults = await Promise.allSettled(clientListTransports.map((t)=>t.listClients()));
592
+ for (const r of clientListResults)if ('fulfilled' === r.status) for (const { id, info } of r.value)entries.push({
593
+ id,
594
+ info,
595
+ type: 'runtime'
596
+ });
597
+ for (const [, conn] of this.#deviceConnections)if (conn.appInfo && !conn.isDisposed) {
598
+ const id = ClientId.serialize(conn.deviceId, conn.port);
599
+ if (entries.some((e)=>e.id === id)) continue;
600
+ entries.push({
601
+ id,
602
+ info: conn.appInfo,
603
+ type: 'runtime'
604
+ });
605
+ }
606
+ const allDevices = [];
607
+ const transportResults = await Promise.allSettled(this.#transports.filter((transport)=>'function' != typeof transport.listClients).map(async (transport)=>({
608
+ transport,
609
+ devices: await transport.listDevices()
610
+ })));
611
+ for (const r of transportResults)if ('fulfilled' === r.status) allDevices.push(r.value);
612
+ const MIN_PORT = 8901;
613
+ const PORTS = Array.from({
614
+ length: 10
615
+ }, (_, i)=>MIN_PORT + i);
616
+ const existingKeys = new Set(this.#deviceConnections.keys());
617
+ const probeResults = await Promise.allSettled(allDevices.flatMap(({ transport, devices })=>devices.flatMap((device)=>PORTS.filter((port)=>!existingKeys.has(`${device.id}:${port}`)).map(async (port)=>{
618
+ const conn = await this.#getOrCreateDeviceConnection(transport, device.id, port);
619
+ const deadline = Date.now() + DEVICE_DISCOVERY_TIMEOUT_MS;
620
+ while(!conn.appInfo && !conn.isDisposed && Date.now() < deadline)await new Promise((resolve)=>setTimeout(resolve, 100));
621
+ return conn;
622
+ }))));
623
+ for (const r of probeResults)if ('fulfilled' === r.status) {
624
+ const conn = r.value;
625
+ if (conn.appInfo && !conn.isDisposed) {
626
+ const clientId = ClientId.serialize(conn.deviceId, conn.port);
627
+ if (!entries.some((e)=>e.id === clientId)) entries.push({
628
+ id: clientId,
629
+ info: conn.appInfo,
630
+ type: 'runtime'
631
+ });
632
+ }
633
+ }
634
+ return entries;
635
+ }
636
+ async #getOrCreateDeviceConnection(transport, deviceId, port) {
637
+ const key = `${deviceId}:${port}`;
638
+ const existing = this.#deviceConnections.get(key);
639
+ if (existing && !existing.isDisposed) {
640
+ this.#clearDeviceConnectionCleanup(key);
641
+ return existing;
642
+ }
643
+ const pending = this.#pendingDeviceConnections.get(key);
644
+ if (pending) return await pending;
645
+ const connectionPromise = (async ()=>{
646
+ const setupAbortController = new AbortController();
647
+ const setupTimeout = setTimeout(()=>{
648
+ setupAbortController.abort(createDeviceConnectionSetupTimeoutError(key));
649
+ }, DEVICE_CONN_SETUP_TIMEOUT_MS);
650
+ const conn = new DeviceConnection(transport, {
651
+ deviceId,
652
+ port,
653
+ signal: setupAbortController.signal
654
+ });
655
+ const connectPromise = conn.connect();
656
+ try {
657
+ await withAbortSignal(connectPromise, setupAbortController.signal);
658
+ await withAbortSignal(conn.send({
659
+ event: 'Initialize',
660
+ data: port
661
+ }), setupAbortController.signal);
662
+ this.#deviceConnections.set(key, conn);
663
+ return conn;
664
+ } catch (err) {
665
+ server_debug('failed to connect to %s: %O', key, err);
666
+ this.#deviceConnections.delete(key);
667
+ await this.#disposeDeviceConnectionBestEffort(key, conn);
668
+ throw err;
669
+ } finally{
670
+ clearTimeout(setupTimeout);
671
+ this.#pendingDeviceConnections.delete(key);
672
+ }
673
+ })();
674
+ this.#pendingDeviceConnections.set(key, connectionPromise);
675
+ return await connectionPromise;
676
+ }
677
+ async #disposeDeviceConnectionBestEffort(key, conn) {
678
+ const timeoutAbortController = new AbortController();
679
+ const disposePromise = conn.dispose().catch((err)=>{
680
+ server_debug('failed to dispose device connection %s after setup failure: %O', key, err);
681
+ });
682
+ const timeoutPromise = promises_setTimeout(DEVICE_CONN_DISPOSE_TIMEOUT_MS, void 0, {
683
+ signal: timeoutAbortController.signal
684
+ }).then(()=>{
685
+ throw new Error(`Timed out disposing failed device connection ${key}`);
686
+ });
687
+ try {
688
+ await Promise.race([
689
+ disposePromise,
690
+ timeoutPromise
691
+ ]);
692
+ } catch (err) {
693
+ server_debug('best-effort dispose for %s did not complete: %O', key, err);
694
+ } finally{
695
+ timeoutAbortController.abort();
696
+ }
697
+ }
698
+ #scheduleDeviceConnectionCleanup(key) {
699
+ const conn = this.#deviceConnections.get(key);
700
+ if (conn?.isPersistent) {
701
+ this.#clearDeviceConnectionCleanup(key);
702
+ server_debug('skipping cleanup for persistent connection %s', key);
703
+ return;
704
+ }
705
+ server_debug('scheduling cleanup for %s in %dms', key, DEVICE_CONN_GRACE_MS);
706
+ this.#clearDeviceConnectionCleanup(key);
707
+ const timer = setTimeout(()=>{
708
+ this.#deviceConnectionCleanupTimers.delete(key);
709
+ const conn = this.#deviceConnections.get(key);
710
+ if (conn && 0 === conn.subscriberCount) {
711
+ server_debug('disposing idle device connection %s', key);
712
+ this.#deviceConnections.delete(key);
713
+ conn.dispose();
714
+ }
715
+ }, DEVICE_CONN_GRACE_MS);
716
+ this.#deviceConnectionCleanupTimers.set(key, timer);
717
+ }
718
+ #clearDeviceConnectionCleanup(key) {
719
+ const timer = this.#deviceConnectionCleanupTimers.get(key);
720
+ if (!timer) return;
721
+ clearTimeout(timer);
722
+ this.#deviceConnectionCleanupTimers.delete(key);
723
+ }
724
+ async #findTransportWithDeviceId(deviceId) {
725
+ for (const transport of this.#transports)try {
726
+ const devices = await transport.listDevices();
727
+ if (devices.some(({ id })=>id === deviceId)) return transport;
728
+ } catch {}
729
+ throw new Error(`Device with id: ${deviceId} not found`);
730
+ }
731
+ #resetIdleTimer() {
732
+ this.#clearIdleTimer();
733
+ if (0 === this.#wsClients.size && !this.#closed) {
734
+ server_debug('no clients connected, starting idle timer (%dms)', IDLE_TIMEOUT_MS);
735
+ this.#idleTimer = setTimeout(()=>{
736
+ if (0 === this.#wsClients.size) {
737
+ server_debug('idle timeout reached, shutting down daemon');
738
+ this.#onIdle?.();
739
+ }
740
+ }, IDLE_TIMEOUT_MS);
741
+ }
742
+ }
743
+ #clearIdleTimer() {
744
+ if (this.#idleTimer) {
745
+ clearTimeout(this.#idleTimer);
746
+ this.#idleTimer = null;
747
+ }
748
+ }
749
+ }
750
+ function createDeviceConnectionSetupTimeoutError(key) {
751
+ return new Error(`Timed out setting up device connection ${key} after ${DEVICE_CONN_SETUP_TIMEOUT_MS}ms`);
752
+ }
753
+ async function withAbortSignal(promise, signal) {
754
+ signal.throwIfAborted();
755
+ return await new Promise((resolve, reject)=>{
756
+ const abortHandler = ()=>{
757
+ reject(signal.reason ?? new Error('The operation was aborted'));
758
+ };
759
+ signal.addEventListener('abort', abortHandler, {
760
+ once: true
761
+ });
762
+ promise.then((value)=>{
763
+ signal.removeEventListener('abort', abortHandler);
764
+ resolve(value);
765
+ }, (error)=>{
766
+ signal.removeEventListener('abort', abortHandler);
767
+ reject(error);
768
+ });
769
+ });
770
+ }
771
+ export { DevtoolDaemon };