@lynx-js/devtool-connector 0.9.5 → 0.13.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.
Files changed (49) hide show
  1. package/LICENSE +1 -1
  2. package/dist/346.js +635 -0
  3. package/dist/390.js +262 -35
  4. package/dist/556.js +9 -4
  5. package/dist/61.js +3432 -0
  6. package/dist/63.js +112 -30
  7. package/dist/712.js +28 -2
  8. package/dist/872.js +552 -122
  9. package/dist/962.js +25 -17
  10. package/dist/client-discovery-errors.d.ts +1 -0
  11. package/dist/client-id.d.ts +9 -2
  12. package/dist/command/client.d.ts +28 -0
  13. package/dist/command/contract.d.ts +255 -0
  14. package/dist/command/core.d.ts +32 -0
  15. package/dist/command/index.d.ts +20 -0
  16. package/dist/command/index.js +224 -0
  17. package/dist/command/query.d.ts +5 -0
  18. package/dist/command/reactlynx/controller.d.ts +71 -0
  19. package/dist/command/reactlynx/model.d.ts +48 -0
  20. package/dist/command/reactlynx/protocol.d.ts +40 -0
  21. package/dist/command/reactlynx/session.d.ts +43 -0
  22. package/dist/command/reactlynx/types.d.ts +73 -0
  23. package/dist/command/ref-actions.d.ts +17 -0
  24. package/dist/command/result.d.ts +29 -0
  25. package/dist/command/screenshot-annotation.d.ts +22 -0
  26. package/dist/command/screenshot.d.ts +28 -0
  27. package/dist/command/snapshot.d.ts +79 -0
  28. package/dist/command/targets.d.ts +15 -0
  29. package/dist/daemon/device-connection.d.ts +3 -1
  30. package/dist/daemon/entry.js +11 -0
  31. package/dist/daemon/index.d.ts +1 -0
  32. package/dist/daemon/index.js +3 -0
  33. package/dist/daemon/manager.d.ts +11 -9
  34. package/dist/daemon/protocol.d.ts +24 -3
  35. package/dist/daemon/server.d.ts +1 -0
  36. package/dist/index.d.ts +6 -2
  37. package/dist/index.js +2 -454
  38. package/dist/streams/customized.d.ts +2 -1
  39. package/dist/transport/android.d.ts +1 -1
  40. package/dist/transport/desktop.d.ts +1 -1
  41. package/dist/transport/index.js +2 -2
  42. package/dist/transport/ios.d.ts +1 -1
  43. package/dist/transport/transport.d.ts +7 -1
  44. package/dist/transport/ws-stream.d.ts +9 -0
  45. package/dist/types.d.ts +35 -0
  46. package/package.json +10 -2
  47. package/dist/187.js +0 -272
  48. package/dist/43.js +0 -20
  49. package/dist/677.js +0 -19
package/dist/index.js CHANGED
@@ -1,454 +1,2 @@
1
- import { randomInt } from "node:crypto";
2
- import { ReadableStream } from "node:stream/web";
3
- import { CDPOutputTransformStream, GlobalSwitchRequestTransformStream, CustomizedResponseTransformStream, AppResponseTransformStream, CDPRequestTransformStream, CustomizedRequestTransformStream, SessionGuardTransformStream, FilterTransformStream, InspectStream, CustomizedClientIdTransformStream, CDPResponseTransformStream } from "./712.js";
4
- import { DaemonTransport } from "./556.js";
5
- import { isListSessionResponse, isGetGlobalSwitchResponse, isHeadlessPrepareResponse, isInitializeResponse, isSetGlobalSwitchResponse } from "./677.js";
6
- import { ClientId } from "./43.js";
7
- import { node_createDebug } from "./187.js";
8
- function _ts_add_disposable_resource(env, value, async) {
9
- if (null != value) {
10
- if ("object" != typeof value && "function" != typeof value) throw new TypeError("Object expected.");
11
- var dispose, inner;
12
- if (async) {
13
- if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
14
- dispose = value[Symbol.asyncDispose];
15
- }
16
- if (void 0 === dispose) {
17
- if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
18
- dispose = value[Symbol.dispose];
19
- if (async) inner = dispose;
20
- }
21
- if ("function" != typeof dispose) throw new TypeError("Object not disposable.");
22
- if (inner) dispose = function() {
23
- try {
24
- inner.call(this);
25
- } catch (e) {
26
- return Promise.reject(e);
27
- }
28
- };
29
- env.stack.push({
30
- value: value,
31
- dispose: dispose,
32
- async: async
33
- });
34
- } else if (async) env.stack.push({
35
- async: true
36
- });
37
- return value;
38
- }
39
- function src_ts_dispose_resources(env) {
40
- var _SuppressedError = "function" == typeof SuppressedError ? SuppressedError : function(error, suppressed, message) {
41
- var e = new Error(message);
42
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
43
- };
44
- return (src_ts_dispose_resources = function(env) {
45
- function fail(e) {
46
- env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
47
- env.hasError = true;
48
- }
49
- var r, s = 0;
50
- function next() {
51
- while(r = env.stack.pop())try {
52
- if (!r.async && 1 === s) return s = 0, env.stack.push(r), Promise.resolve().then(next);
53
- if (r.dispose) {
54
- var result = r.dispose.call(r.value);
55
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
56
- fail(e);
57
- return next();
58
- });
59
- } else s |= 1;
60
- } catch (e) {
61
- fail(e);
62
- }
63
- if (1 === s) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
64
- if (env.hasError) throw env.error;
65
- }
66
- return next();
67
- })(env);
68
- }
69
- const debug = node_createDebug('devtool-mcp-server:connector');
70
- function hasClientList(transport) {
71
- return 'function' == typeof transport.listClients;
72
- }
73
- class Connector {
74
- #transports;
75
- #daemonTransports;
76
- constructor(transports){
77
- this.#transports = transports;
78
- this.#daemonTransports = transports.filter((t)=>t instanceof DaemonTransport);
79
- }
80
- async listClients() {
81
- const daemonClientResults = await Promise.allSettled(this.#daemonTransports.map(async (transport)=>{
82
- const clients = await transport.listClients();
83
- await Promise.allSettled(clients.flatMap(({ id })=>this.#setupClient(transport, id)));
84
- return clients;
85
- }));
86
- const fulfilledDaemonClientResults = daemonClientResults.filter((r)=>'fulfilled' === r.status);
87
- const daemonClients = fulfilledDaemonClientResults.flatMap((r)=>r.value);
88
- if (fulfilledDaemonClientResults.length > 0) {
89
- debug('Using clients from daemon transport: %o', daemonClients);
90
- return daemonClients;
91
- }
92
- const transportDevices = await Promise.allSettled(this.#transports.filter((t)=>!(t instanceof DaemonTransport)).map(async (transport)=>({
93
- transport,
94
- devices: await transport.listDevices()
95
- })));
96
- for (const result of transportDevices)if ('rejected' === result.status) debug('listClients: listDevices failed on one transport: %O', result.reason);
97
- const results = await Promise.allSettled(transportDevices.filter((r)=>'fulfilled' === r.status).map((r)=>r.value).flatMap(({ transport, devices })=>devices.flatMap(({ id })=>this.#listClientsForDevice(transport, id))));
98
- return results.filter((r)=>'fulfilled' === r.status).flatMap((r)=>r.value);
99
- }
100
- async listDevices() {
101
- const results = await Promise.allSettled(this.#transports.map((t)=>t.listDevices()));
102
- return results.filter((result)=>'fulfilled' === result.status).flatMap(({ value })=>value);
103
- }
104
- async listAvailableApps(deviceId) {
105
- const transport = await this.#findTransportWithDeviceId(deviceId);
106
- return await transport.listAvailableApps(deviceId);
107
- }
108
- async openApp(deviceId, packageName, options) {
109
- const transport = await this.#findTransportWithDeviceId(deviceId);
110
- await transport.openApp(deviceId, packageName, options);
111
- const signal = AbortSignal.any([
112
- options?.signal,
113
- AbortSignal.timeout(60000)
114
- ].filter((i)=>void 0 !== i));
115
- const { setTimeout } = await import("node:timers/promises");
116
- while(!signal.aborted){
117
- try {
118
- const clients = hasClientList(transport) ? (await transport.listClients()).filter(({ id })=>ClientId.deserialize(id)?.deviceId === deviceId) : await this.#listClientsForDevice(transport, deviceId);
119
- if (clients.some(({ info })=>info.AppProcessName === packageName || info.bundleId === packageName || info.bundleName === packageName)) break;
120
- } catch (err) {
121
- debug(`openApp ${deviceId} ${packageName} client not found %o`, err);
122
- }
123
- await setTimeout(1000);
124
- }
125
- }
126
- async sendMessage(clientId, message, pipeline = {
127
- input: [],
128
- output: []
129
- }) {
130
- return this.#sendMessage(clientId, message, pipeline);
131
- }
132
- async sendMessageNoReply(clientId, message) {
133
- const { deviceId, port } = this.#resolveClientId(clientId);
134
- const transport = await this.#findTransportWithDeviceId(deviceId);
135
- const signal = AbortSignal.timeout(5000);
136
- const conn = await transport.connect({
137
- deviceId,
138
- port,
139
- signal
140
- });
141
- try {
142
- const inputStream = [
143
- new CustomizedClientIdTransformStream(port),
144
- new InspectStream((msg)=>debug(`sendMessageNoReply ${deviceId}:${port} send %o`, JSON.stringify(msg)))
145
- ].reduce((stream, transform)=>stream.pipeThrough(transform), ReadableStream.from([
146
- message
147
- ]));
148
- await inputStream.pipeTo(conn.writable, {
149
- preventClose: true
150
- });
151
- } finally{
152
- await conn[Symbol.asyncDispose]();
153
- }
154
- }
155
- async sendAppMessage(clientId, method, params) {
156
- const id = randomInt(10000, 50000);
157
- return await this.#sendMessage(clientId, {
158
- method,
159
- params: {
160
- ...params
161
- }
162
- }, {
163
- input: [
164
- new CustomizedRequestTransformStream({
165
- type: 'App',
166
- sessionId: -1,
167
- messageBuilder: (message)=>({
168
- id,
169
- ...message
170
- })
171
- })
172
- ],
173
- output: [
174
- new CustomizedResponseTransformStream('App', id),
175
- new AppResponseTransformStream(method)
176
- ]
177
- });
178
- }
179
- async sendCDPMessage(clientId, sessionId, method, params, isMainThread = false) {
180
- const id = randomInt(10000, 50000);
181
- const SUPPORTED_DOMAIN = [
182
- 'Debugger',
183
- 'Runtime',
184
- 'HeapProfiler',
185
- 'Profiler'
186
- ];
187
- if (isMainThread && !SUPPORTED_DOMAIN.some((domain)=>method.startsWith(domain + '.'))) throw new Error(`Method ${method} is not supported for main thread. Supported domains: ${SUPPORTED_DOMAIN.join(', ')}`);
188
- return await this.#sendMessage(clientId, {
189
- method,
190
- params,
191
- sessionId: isMainThread ? 'Main' : void 0
192
- }, {
193
- input: [
194
- new CDPRequestTransformStream(sessionId, id)
195
- ],
196
- output: [
197
- new CDPResponseTransformStream(id),
198
- new CDPOutputTransformStream()
199
- ]
200
- });
201
- }
202
- async sendListSessionMessage(clientId) {
203
- return await this.#sendListSessionMessage(clientId);
204
- }
205
- async prepareHeadless(clientId) {
206
- const { data: { data: state } } = await this.#sendMessage(clientId, {
207
- event: 'Customized',
208
- data: {
209
- type: 'HeadlessPrepare',
210
- data: {}
211
- }
212
- }, {
213
- input: [],
214
- output: [
215
- new FilterTransformStream(isHeadlessPrepareResponse)
216
- ]
217
- });
218
- return state;
219
- }
220
- async waitForHeadlessReady(clientId, options = {}) {
221
- const timeoutMs = options.timeoutMs ?? 300000;
222
- const pollIntervalMs = options.pollIntervalMs ?? 1000;
223
- const { setTimeout: delay } = await import("node:timers/promises");
224
- const deadline = Date.now() + timeoutMs;
225
- let lastError;
226
- for(;;){
227
- const state = await this.prepareHeadless(clientId);
228
- if ('ready' === state.status) return;
229
- if ('error' === state.status) lastError = state.message ?? 'unknown error';
230
- if (Date.now() >= deadline) throw new Error(void 0 !== lastError ? `Failed to prepare headless runtime: ${lastError}` : `Timed out preparing headless runtime after ${timeoutMs}ms`);
231
- await delay(pollIntervalMs);
232
- }
233
- }
234
- async #sendListSessionMessage(clientId) {
235
- const { data: { data: sessions } } = await this.#sendMessage(clientId, {
236
- event: 'Customized',
237
- data: {
238
- type: 'ListSession',
239
- data: {}
240
- }
241
- }, {
242
- input: [],
243
- output: [
244
- new FilterTransformStream(isListSessionResponse)
245
- ]
246
- });
247
- return sessions.map((session)=>({
248
- ...session,
249
- type: '' === session.type ? 'lynx' : session.type
250
- }));
251
- }
252
- async getGlobalSwitch(clientId, key) {
253
- const { data: { data: { message } } } = await this.#sendMessage(clientId, {
254
- key
255
- }, {
256
- input: [
257
- new GlobalSwitchRequestTransformStream('GetGlobalSwitch')
258
- ],
259
- output: [
260
- new FilterTransformStream(isGetGlobalSwitchResponse)
261
- ]
262
- });
263
- if ('object' == typeof message) return message?.global_value === 'true' || message?.global_value === true;
264
- return 'true' === message || true === message;
265
- }
266
- async setGlobalSwitch(clientId, key, value) {
267
- await this.#sendMessage(clientId, {
268
- key,
269
- value
270
- }, {
271
- input: [
272
- new GlobalSwitchRequestTransformStream('SetGlobalSwitch')
273
- ],
274
- output: [
275
- new FilterTransformStream(isSetGlobalSwitchResponse)
276
- ]
277
- });
278
- }
279
- async sendStream(clientId, inputStream, { signal, pipeline } = {}) {
280
- const { deviceId, port } = this.#resolveClientId(clientId);
281
- const transport = await this.#findTransportWithDeviceId(deviceId);
282
- return await this.#connect(transport, {
283
- deviceId,
284
- port,
285
- signal
286
- }, inputStream, pipeline ?? {
287
- input: [],
288
- output: []
289
- });
290
- }
291
- async sendCDPStream(clientId, sessionId, inputStream, { signal } = {}) {
292
- return await this.sendStream(clientId, inputStream, {
293
- signal,
294
- pipeline: {
295
- input: [
296
- new CDPRequestTransformStream(sessionId)
297
- ],
298
- output: [
299
- new SessionGuardTransformStream(sessionId),
300
- new CDPResponseTransformStream()
301
- ]
302
- }
303
- });
304
- }
305
- #resolveClientId(clientId) {
306
- const parsed = ClientId.deserialize(clientId);
307
- if (!parsed) throw new Error(`Invalid clientId: ${clientId}`);
308
- return parsed;
309
- }
310
- async #findTransportWithDeviceId(deviceId) {
311
- const daemonTransport = await this.#findTransportWithDeviceIdInPool(this.#daemonTransports, deviceId);
312
- if (daemonTransport) return daemonTransport;
313
- const transport = await this.#findTransportWithDeviceIdInPool(this.#transports.filter((t)=>!(t instanceof DaemonTransport)), deviceId);
314
- if (transport) return transport;
315
- throw new Error(`Device with id: ${deviceId} not found`);
316
- }
317
- async #findTransportWithDeviceIdInPool(transports, deviceId) {
318
- return await Promise.any(transports.map(async (transport)=>{
319
- const devices = await transport.listDevices();
320
- if (devices.some(({ id })=>id === deviceId)) return transport;
321
- throw new Error('Not found in this transport');
322
- })).catch(()=>null);
323
- }
324
- async #connect(transport, options, inputStream, pipeline) {
325
- const { deviceId, port } = options;
326
- const conn = await transport.connect(options);
327
- const inputAbortController = new AbortController();
328
- const inputClosed = [
329
- ...pipeline.input,
330
- new CustomizedClientIdTransformStream(port),
331
- new InspectStream((msg)=>debug(`connect ${deviceId}:${port} input stream send %o`, JSON.stringify(msg)))
332
- ].reduce((stream, transform)=>stream.pipeThrough(transform), inputStream).pipeTo(conn.writable, {
333
- preventClose: true,
334
- signal: inputAbortController.signal
335
- }).catch((err)=>{
336
- if (err?.name !== 'AbortError') debug(`connect ${deviceId}:${port} input stream err %O`, err);
337
- });
338
- const outputStream = [
339
- new InspectStream((msg)=>debug(`connect ${deviceId}:${port} output stream receive %O`, msg)),
340
- ...pipeline.output
341
- ].reduce((stream, transform)=>stream.pipeThrough(transform, {
342
- preventCancel: true
343
- }), conn.readable);
344
- return Object.assign(outputStream, {
345
- inputClosed,
346
- async [Symbol.asyncDispose] () {
347
- debug(`connect ${deviceId}:${port} close connection`);
348
- inputAbortController.abort();
349
- await inputClosed.catch(()=>{});
350
- return conn[Symbol.asyncDispose]();
351
- }
352
- });
353
- }
354
- async #sendMessage(clientId, input, pipeline = {
355
- input: [],
356
- output: []
357
- }) {
358
- const { deviceId, port } = this.#resolveClientId(clientId);
359
- const transport = await this.#findTransportWithDeviceId(deviceId);
360
- const signal = AbortSignal.timeout(10000);
361
- return this.#sendMessageWithTransport(transport, {
362
- deviceId,
363
- port,
364
- signal
365
- }, input, pipeline);
366
- }
367
- async #sendMessageWithTransport(transport, options, input, pipeline) {
368
- const env = {
369
- stack: [],
370
- error: void 0,
371
- hasError: false
372
- };
373
- try {
374
- const outputStream = _ts_add_disposable_resource(env, await this.#connect(transport, options, ReadableStream.from([
375
- input
376
- ]), pipeline), true);
377
- for await (const response of outputStream){
378
- await outputStream.inputClosed;
379
- return response;
380
- }
381
- await outputStream.inputClosed;
382
- const clientId = ClientId.serialize(options.deviceId, options.port);
383
- throw new Error(`No response found for clientId: ${clientId}`);
384
- } catch (e) {
385
- env.error = e;
386
- env.hasError = true;
387
- } finally{
388
- const result = src_ts_dispose_resources(env);
389
- if (result) await result;
390
- }
391
- }
392
- async #listClientsForDevice(transport, deviceId) {
393
- const MIN_PORT = 8901;
394
- const PORTS = Array.from({
395
- length: 10
396
- }, (_, i)=>MIN_PORT + i);
397
- const signal = AbortSignal.timeout(5000);
398
- const results = await Promise.allSettled(PORTS.map(async (port)=>{
399
- const { data: { info } } = await this.#sendMessageWithTransport(transport, {
400
- deviceId,
401
- port,
402
- signal
403
- }, {
404
- event: 'Initialize',
405
- data: port
406
- }, {
407
- input: [],
408
- output: [
409
- new FilterTransformStream(isInitializeResponse)
410
- ]
411
- });
412
- const clientId = ClientId.serialize(deviceId, port);
413
- await this.#setupClient(transport, clientId);
414
- return {
415
- id: clientId,
416
- info,
417
- port
418
- };
419
- }));
420
- return results.filter((result)=>'fulfilled' === result.status).map((result)=>result.value);
421
- }
422
- async #setupClient(transport, clientId) {
423
- const { deviceId, port } = this.#resolveClientId(clientId);
424
- for (const input of [
425
- {
426
- key: 'enable_devtool',
427
- value: true
428
- },
429
- {
430
- key: 'enable_quickjs_debug',
431
- value: true
432
- }
433
- ])try {
434
- await this.#sendMessageWithTransport(transport, {
435
- deviceId,
436
- port,
437
- signal: AbortSignal.timeout(3000)
438
- }, input, {
439
- input: [
440
- new GlobalSwitchRequestTransformStream('SetGlobalSwitch')
441
- ],
442
- output: [
443
- new FilterTransformStream(isSetGlobalSwitchResponse)
444
- ]
445
- });
446
- } catch (err) {
447
- debug(`setupClient ${deviceId}:${port} ${input.key} failed %O`, err);
448
- }
449
- }
450
- }
451
- export { CDPOutputTransformStream, CDPRequestTransformStream, CDPResponseTransformStream } from "./712.js";
452
- export { ClientId } from "./43.js";
453
- export { isCustomizedResponseWithType, isGetGlobalSwitchResponse, isHeadlessPrepareResponse, isInitializeResponse, isListSessionResponse, isSetGlobalSwitchResponse } from "./677.js";
454
- export { Connector };
1
+ export { CDPOutputTransformStream, CDPRequestTransformStream, CDPResponseTransformStream, createCorrelatedFilter, isCustomizedResponseWithType, isGetGlobalSwitchResponse, isHeadlessPrepareResponse, isInitializeResponse, isListSessionResponse, isSetGlobalSwitchResponse } from "./712.js";
2
+ export { ClientId, Connector } from "./346.js";
@@ -1,7 +1,8 @@
1
1
  import { TransformStream } from 'node:stream/web';
2
+ import type { ClientTarget } from '../client-id.ts';
2
3
  import { type AppResponseMessage, type CustomizedResponseMap, type CustomizedResponseMessageMap, type Response } from '../types.ts';
3
4
  export declare class CustomizedClientIdTransformStream extends TransformStream {
4
- constructor(clientId: number);
5
+ constructor(clientId: ClientTarget);
5
6
  }
6
7
  export declare class CustomizedRequestTransformStream<T = unknown> extends TransformStream<T, unknown> {
7
8
  constructor(options: {
@@ -1,6 +1,6 @@
1
1
  import type { SocketConnectOpts } from 'node:net';
2
2
  import { AdbServerClient } from '@yume-chan/adb';
3
- import type { App, Connection, Device, OpenAppOptions, Transport, TransportConnectOptions } from './transport.ts';
3
+ import { type App, type Connection, type Device, type OpenAppOptions, type Transport, type TransportConnectOptions } from './transport.ts';
4
4
  export declare class AndroidTransport implements Transport {
5
5
  #private;
6
6
  protected readonly client: AdbServerClient;
@@ -1,4 +1,4 @@
1
- import type { App, Connection, Device, Transport, TransportConnectOptions } from './transport.ts';
1
+ import { type App, type Connection, type Device, type Transport, type TransportConnectOptions } from './transport.ts';
2
2
  export declare class DesktopTransport implements Transport {
3
3
  #private;
4
4
  connect<TInput = unknown, TOutput = unknown>(options: TransportConnectOptions): Promise<Connection<TOutput, TInput>>;
@@ -1,3 +1,3 @@
1
- export { AndroidTransport, DesktopTransport, MessageToPeertalkTransformStream, PeertalkToMessageTransformStream, Usbmux, connectWithPeertalk, createMessageConnection, iOSTransport, peertalkCodecFactory } from "../962.js";
1
+ export { AndroidTransport, DesktopTransport, MessageToPeertalkTransformStream, PeertalkToMessageTransformStream, Usbmux, connectWithPeertalk, createMessageConnection, iOSTransport, peertalkCodecFactory, requireNumericPort } from "../962.js";
2
2
  export { DaemonTransport } from "../556.js";
3
- export { WsWebSocketStream, wsStreams } from "../63.js";
3
+ export { WsWebSocketStream, createWebSocketReadable, wsStreams } from "../63.js";
@@ -1,5 +1,5 @@
1
1
  import type { NetConnectOpts } from 'node:net';
2
- import type { App, Connection, Device, OpenAppOptions, Transport, TransportConnectOptions } from './transport.ts';
2
+ import { type App, type Connection, type Device, type OpenAppOptions, type Transport, type TransportConnectOptions } from './transport.ts';
3
3
  export declare class iOSTransport implements Transport {
4
4
  #private;
5
5
  constructor(options?: NetConnectOpts);
@@ -1,10 +1,16 @@
1
1
  import type { ReadableStream, WritableStream } from 'node:stream/web';
2
+ import type { ClientTarget } from '../client-id.ts';
2
3
  import type { AppInfo } from '../types.ts';
3
4
  export interface TransportConnectOptions {
4
5
  deviceId: string;
5
- port: number;
6
+ port: ClientTarget;
6
7
  signal?: AbortSignal | undefined;
7
8
  }
9
+ /**
10
+ * Narrow a {@link ClientTarget} to the numeric debug-router port required by
11
+ * port-forwarding transports.
12
+ */
13
+ export declare function requireNumericPort(port: ClientTarget): number;
8
14
  export interface OpenAppOptions {
9
15
  signal?: AbortSignal;
10
16
  withDataCleared?: boolean | undefined;
@@ -1,4 +1,13 @@
1
1
  import { ReadableStream, WritableStream } from 'node:stream/web';
2
+ import { WebSocket } from 'ws';
3
+ /**
4
+ * Wraps a `ws` WebSocket into a `ReadableStream<string>` of text frames.
5
+ *
6
+ * The stream applies backpressure by pausing the socket once the queue is
7
+ * full, reaches EOF on an orderly close, and errors with a
8
+ * `code`/`reason`-carrying `Error` on an abnormal close.
9
+ */
10
+ export declare function createWebSocketReadable(ws: WebSocket): ReadableStream<string>;
2
11
  /**
3
12
  * A lightweight wrapper around the `ws` WebSocket that exposes a
4
13
  * `WebSocketStream`-compatible interface (opened / closed / close).
package/dist/types.d.ts CHANGED
@@ -5,6 +5,16 @@ type Event<E extends string, D> = {
5
5
  type CustomizedEvent<TType extends string, TData> = Event<'Customized', {
6
6
  type: TType;
7
7
  data: TData;
8
+ /**
9
+ * Optional request-response correlation id.
10
+ *
11
+ * When a request carries an `id`, the response echoes it back so the caller
12
+ * can match which response belongs to which request — similar to how CDP
13
+ * uses `id`.
14
+ *
15
+ * @see https://github.com/lynx-family/debug-router/issues/162
16
+ */
17
+ id?: number;
8
18
  }>;
9
19
  export type AppInfo = {
10
20
  App: string;
@@ -13,6 +23,7 @@ export type AppInfo = {
13
23
  AppProcessName?: string;
14
24
  /** iOS only */
15
25
  bundleId?: string;
26
+ /** OpenHarmony only */
16
27
  bundleName?: string;
17
28
  debugRouterId: string;
18
29
  debugRouterVersion: string;
@@ -163,6 +174,30 @@ export type Response = InitializeResponse | ListSessionResponse | AppResponse |
163
174
  export declare function isInitializeResponse(response: Response): response is InitializeResponse;
164
175
  export declare function isHeadlessPrepareResponse(response: Response): response is HeadlessPrepareResponse;
165
176
  export declare function isListSessionResponse(response: Response): response is ListSessionResponse;
177
+ /**
178
+ * Create a type guard that accepts a Customized response only when its `id`
179
+ * correlates with the given request `id`.
180
+ *
181
+ * Correlation rules (matching CDP id semantics):
182
+ * 1. Response has NO `id` field → accept (old SDK that doesn't support id yet)
183
+ * 2. Response `id` matches our request `id` → accept (our response)
184
+ * 3. Response `id` is -1 → reject (response to a request without id from another old client)
185
+ * 4. Response `id` is a different positive number → reject (response to another client's request)
186
+ *
187
+ * @param baseFilter - A type guard to check the response type (e.g. isListSessionResponse)
188
+ * @param requestId - The id we sent in the request
189
+ *
190
+ * @example
191
+ * ```ts
192
+ * // For ListSession:
193
+ * new FilterTransformStream(createCorrelatedFilter(isListSessionResponse, id))
194
+ * // For GetGlobalSwitch (future):
195
+ * new FilterTransformStream(createCorrelatedFilter(isGetGlobalSwitchResponse, id))
196
+ * ```
197
+ *
198
+ * @see https://github.com/lynx-family/debug-router/issues/162
199
+ */
200
+ export declare function createCorrelatedFilter<T extends Response>(baseFilter: (response: Response) => response is T, requestId: number): (response: Response) => response is T;
166
201
  export declare function isGetGlobalSwitchResponse(response: Response): response is GetGlobalSwitchResponse;
167
202
  export declare function isSetGlobalSwitchResponse(response: Response): response is SetGlobalSwitchResponse;
168
203
  export declare function isCustomizedResponseWithType<T extends keyof CustomizedResponseMap>(response: Response, type: T): response is CustomizedResponseMap[T];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lynx-js/devtool-connector",
3
- "version": "0.9.5",
3
+ "version": "0.13.1",
4
4
  "repository": {
5
5
  "url": "https://github.com/lynx-community/skills"
6
6
  },
@@ -30,6 +30,11 @@
30
30
  "import": "./dist/streams/index.js",
31
31
  "default": "./dist/streams/index.js"
32
32
  },
33
+ "./command": {
34
+ "types": "./dist/command/index.d.ts",
35
+ "import": "./dist/command/index.js",
36
+ "default": "./dist/command/index.js"
37
+ },
33
38
  "./package.json": "./package.json"
34
39
  },
35
40
  "main": "./dist/index.js",
@@ -40,16 +45,19 @@
40
45
  "public"
41
46
  ],
42
47
  "dependencies": {
48
+ "jpeg-js": "^0.4.4",
49
+ "obug": "^2.1.3",
50
+ "semver": "^7.7.3",
43
51
  "ws": "^8.21.0"
44
52
  },
45
53
  "devDependencies": {
46
54
  "@rslib/core": "0.23.0",
47
55
  "@types/node": "^24.13.2",
56
+ "@types/semver": "^7.7.1",
48
57
  "@types/ws": "^8.18.1",
49
58
  "@yume-chan/adb": "^2.6.0",
50
59
  "@yume-chan/adb-server-node-tcp": "^2.5.2",
51
60
  "@yume-chan/stream-extra": "^2.6.1",
52
- "obug": "^2.1.3",
53
61
  "plist": "^5.0.0",
54
62
  "rsbuild-plugin-publint": "^1.0.0",
55
63
  "typescript": "^5.9.3"