@lynx-js/devtool-connector 0.1.1 → 0.9.4

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 +7 -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 +12151 -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/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @lynx-js/devtool-connector
2
+
3
+ ## 0.9.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 6f4df9d: Add the Lynx DevTool packages: `@lynx-js/devtool-connector` (device transport layer with background daemon), `@lynx-js/devtool-mcp-server` (MCP server exposing DOM/CSS/Runtime/Performance and more tools), and an updated `@lynx-js/skill-lynx-devtool` skill with screenshot, console, heap snapshot, recorder, and ReactLynx inspection commands.
package/LICENSE CHANGED
@@ -199,4 +199,4 @@
199
199
  distributed under the License is distributed on an "AS IS" BASIS,
200
200
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
201
  See the License for the specific language governing permissions and
202
- limitations under the License.
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # @lynx-js/devtool-connector
2
+
3
+ `@lynx-js/devtool-connector` provides low-level connectivity for Lynx DevTool. It unifies transport layers for Android / iOS / Desktop, and exposes stable request APIs (such as `CDP`, `App`, and `ListSession`).
4
+
5
+ It can be used as a TypeScript library in higher-level services like `devtool-mcp-server`.
6
+
7
+ ## Requirements
8
+
9
+ - Node.js >= 18.19
10
+ - At least one available device channel:
11
+ - Android: ADB (default `127.0.0.1:5037`)
12
+ - iOS: usbmuxd
13
+ - Desktop: local `127.0.0.1` port
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ pnpm add @lynx-js/devtool-connector
19
+ ```
20
+
21
+ ## Library usage
22
+
23
+ ### 1) Initialize Connector
24
+
25
+ ```ts
26
+ import { Connector } from "@lynx-js/devtool-connector";
27
+ import { DaemonTransport } from "@lynx-js/devtool-connector/transport";
28
+
29
+ const transports = [
30
+ new DaemonTransport(),
31
+ ];
32
+
33
+ const connector = new Connector(transports);
34
+ ```
35
+
36
+ Use `DaemonTransport` as the default transport. It automatically manages a local daemon process and reuses stable device connections, so it should be the primary path for client discovery and follow-up requests.
37
+
38
+ Add other transports only when you need fallback behavior for environments where the daemon is unavailable or cannot discover a target client. When fallback transports are present, `Connector` tries daemon-backed clients first, then the remaining direct platform transports.
39
+
40
+ Fallback example:
41
+
42
+ ```ts
43
+ import { Connector } from "@lynx-js/devtool-connector";
44
+ import {
45
+ AndroidTransport,
46
+ DaemonTransport,
47
+ DesktopTransport,
48
+ iOSTransport,
49
+ } from "@lynx-js/devtool-connector/transport";
50
+
51
+ const connector = new Connector([
52
+ new DaemonTransport(),
53
+ new AndroidTransport(),
54
+ new iOSTransport(),
55
+ new DesktopTransport(),
56
+ ]);
57
+ ```
58
+
59
+ ### 2) List devices, clients, and sessions
60
+
61
+ ```ts
62
+ const devices = await connector.listDevices();
63
+ const clients = await connector.listClients();
64
+
65
+ if (clients.length === 0) {
66
+ throw new Error("No available clients found");
67
+ }
68
+
69
+ const clientId = clients[0].id;
70
+ const sessions = await connector.sendListSessionMessage(clientId);
71
+ ```
72
+
73
+ ### 3) Send CDP / App requests
74
+
75
+ ```ts
76
+ const sessionId = sessions[0]?.session_id;
77
+ if (!sessionId) {
78
+ throw new Error("No session found");
79
+ }
80
+
81
+ const dom = await connector.sendCDPMessage(
82
+ clientId,
83
+ sessionId,
84
+ "DOM.getDocument",
85
+ { depth: -1 },
86
+ );
87
+
88
+ const mainThreadEval = await connector.sendCDPMessage(
89
+ clientId,
90
+ sessionId,
91
+ "Runtime.evaluate",
92
+ { expression: "2 + 2" },
93
+ // isMainThread
94
+ true,
95
+ );
96
+
97
+ await connector.sendAppMessage(clientId, "App.openPage", {
98
+ url: "https://lynxjs.org",
99
+ });
100
+ ```
101
+
102
+ Pass `true` as the optional `isMainThread` argument to target the main-thread VM. Main-thread CDP requests currently support only `Debugger.*`, `Runtime.*`, `HeapProfiler.*`, and `Profiler.*` methods.
103
+
104
+ ### 4) Streaming APIs (advanced)
105
+
106
+ The connector also supports streaming send/receive:
107
+
108
+ - `sendCDPStream(...)`
109
+ - `sendStream(...)` (custom pipeline)
110
+
111
+ These APIs are useful for subscription-style logs, continuous requests, or protocol debugging.
112
+
113
+ When you finish consuming the returned stream, make sure to close it (dispose the output stream) to release the underlying connection.
114
+
115
+ Example: consume CDP events with `for await...of`
116
+
117
+ ```ts
118
+ import { ReadableStream } from "node:stream/web";
119
+
120
+ await using outputStream = await connector.sendCDPStream(
121
+ clientId,
122
+ sessionId,
123
+ ReadableStream.from([
124
+ { method: "Runtime.enable" },
125
+ ]),
126
+ );
127
+
128
+ for await (const message of outputStream) {
129
+ // `sendCDPStream` yields CDP events, e.g. { method: "Runtime.consoleAPICalled", params: ... }
130
+ console.log(message.method, message.params);
131
+ break;
132
+ }
133
+ ```
134
+
135
+ ## Exported entry points
136
+
137
+ - `@lynx-js/devtool-connector`: `Connector`, `ClientId`, and protocol transform streams
138
+ - `@lynx-js/devtool-connector/transport`: platform transport implementations and type definitions
139
+ - `@lynx-js/devtool-connector/test-with-client`: helper for integration tests with real clients
140
+
141
+ ## Debugging
142
+
143
+ Use the `debug` namespace to inspect connection/protocol send-receive details while running code that imports this package:
144
+
145
+ ```bash
146
+ DEBUG=devtool-mcp-server:connector* node ./your-script.mjs
147
+ ```
148
+
149
+ ## Known limitations
150
+
151
+ - USB-based iOS transport (`iOSTransport`) still does not implement `listAvailableApps` / `openApp`.
152
+ - `listClients()` has snapshot semantics: each call re-scans ports and re-validates clients via handshake.
package/dist/187.js ADDED
@@ -0,0 +1,272 @@
1
+ import { isatty } from "node:tty";
2
+ import { formatWithOptions, inspect } from "node:util";
3
+ function coerce(value) {
4
+ if (value instanceof Error) return value.stack || value.message;
5
+ return value;
6
+ }
7
+ function selectColor(colors, namespace) {
8
+ let hash = 0;
9
+ for(let i = 0; i < namespace.length; i++){
10
+ hash = (hash << 5) - hash + namespace.charCodeAt(i);
11
+ hash |= 0;
12
+ }
13
+ return colors[Math.abs(hash) % colors.length];
14
+ }
15
+ function matchesTemplate(search, template) {
16
+ let searchIndex = 0;
17
+ let templateIndex = 0;
18
+ let starIndex = -1;
19
+ let matchIndex = 0;
20
+ while(searchIndex < search.length)if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || "*" === template[templateIndex])) if ("*" === template[templateIndex]) {
21
+ starIndex = templateIndex;
22
+ matchIndex = searchIndex;
23
+ templateIndex++;
24
+ } else {
25
+ searchIndex++;
26
+ templateIndex++;
27
+ }
28
+ else {
29
+ if (-1 === starIndex) return false;
30
+ templateIndex = starIndex + 1;
31
+ matchIndex++;
32
+ searchIndex = matchIndex;
33
+ }
34
+ while(templateIndex < template.length && "*" === template[templateIndex])templateIndex++;
35
+ return templateIndex === template.length;
36
+ }
37
+ function humanize(value) {
38
+ if (value >= 1e3) return `${(value / 1e3).toFixed(1)}s`;
39
+ return `${value}ms`;
40
+ }
41
+ let globalNamespaces = "";
42
+ function createDebug(namespace, options) {
43
+ let prevTime;
44
+ let enableOverride;
45
+ let namespacesCache;
46
+ let enabledCache;
47
+ const debug = (...args)=>{
48
+ if (!debug.enabled) return;
49
+ const curr = Date.now();
50
+ const diff = curr - (prevTime || curr);
51
+ prevTime = curr;
52
+ args[0] = coerce(args[0]);
53
+ if ("string" != typeof args[0]) args.unshift("%O");
54
+ let index = 0;
55
+ args[0] = args[0].replace(/%([a-z%])/gi, (match, format)=>{
56
+ if ("%%" === match) return "%";
57
+ index++;
58
+ const formatter = options.formatters[format];
59
+ if ("function" == typeof formatter) {
60
+ const value = args[index];
61
+ match = formatter.call(debug, value);
62
+ args.splice(index, 1);
63
+ index--;
64
+ }
65
+ return match;
66
+ });
67
+ options.formatArgs.call(debug, diff, args);
68
+ debug.log(...args);
69
+ };
70
+ debug.extend = function(namespace, delimiter = ":") {
71
+ return createDebug(this.namespace + delimiter + namespace, {
72
+ useColors: this.useColors,
73
+ color: this.color,
74
+ formatArgs: this.formatArgs,
75
+ formatters: this.formatters,
76
+ inspectOpts: this.inspectOpts,
77
+ log: this.log,
78
+ humanize: this.humanize
79
+ });
80
+ };
81
+ Object.assign(debug, options);
82
+ debug.namespace = namespace;
83
+ Object.defineProperty(debug, "enabled", {
84
+ enumerable: true,
85
+ configurable: false,
86
+ get: ()=>{
87
+ if (null != enableOverride) return enableOverride;
88
+ if (namespacesCache !== globalNamespaces) {
89
+ namespacesCache = globalNamespaces;
90
+ enabledCache = enabled(namespace);
91
+ }
92
+ return enabledCache;
93
+ },
94
+ set: (v)=>{
95
+ enableOverride = v;
96
+ }
97
+ });
98
+ return debug;
99
+ }
100
+ let names = [];
101
+ let skips = [];
102
+ function enable(namespaces) {
103
+ globalNamespaces = namespaces;
104
+ names = [];
105
+ skips = [];
106
+ const split = globalNamespaces.trim().replace(/\s+/g, ",").split(",").filter(Boolean);
107
+ for (const ns of split)if ("-" === ns[0]) skips.push(ns.slice(1));
108
+ else names.push(ns);
109
+ }
110
+ function enabled(name) {
111
+ for (const skip of skips)if (matchesTemplate(name, skip)) return false;
112
+ for (const ns of names)if (matchesTemplate(name, ns)) return true;
113
+ return false;
114
+ }
115
+ const node_colors = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
116
+ 20,
117
+ 21,
118
+ 26,
119
+ 27,
120
+ 32,
121
+ 33,
122
+ 38,
123
+ 39,
124
+ 40,
125
+ 41,
126
+ 42,
127
+ 43,
128
+ 44,
129
+ 45,
130
+ 56,
131
+ 57,
132
+ 62,
133
+ 63,
134
+ 68,
135
+ 69,
136
+ 74,
137
+ 75,
138
+ 76,
139
+ 77,
140
+ 78,
141
+ 79,
142
+ 80,
143
+ 81,
144
+ 92,
145
+ 93,
146
+ 98,
147
+ 99,
148
+ 112,
149
+ 113,
150
+ 128,
151
+ 129,
152
+ 134,
153
+ 135,
154
+ 148,
155
+ 149,
156
+ 160,
157
+ 161,
158
+ 162,
159
+ 163,
160
+ 164,
161
+ 165,
162
+ 166,
163
+ 167,
164
+ 168,
165
+ 169,
166
+ 170,
167
+ 171,
168
+ 172,
169
+ 173,
170
+ 178,
171
+ 179,
172
+ 184,
173
+ 185,
174
+ 196,
175
+ 197,
176
+ 198,
177
+ 199,
178
+ 200,
179
+ 201,
180
+ 202,
181
+ 203,
182
+ 204,
183
+ 205,
184
+ 206,
185
+ 207,
186
+ 208,
187
+ 209,
188
+ 214,
189
+ 215,
190
+ 220,
191
+ 221
192
+ ] : [
193
+ 6,
194
+ 2,
195
+ 3,
196
+ 4,
197
+ 5,
198
+ 1
199
+ ];
200
+ const inspectOpts = Object.keys(process.env).filter((key)=>/^debug_/i.test(key)).reduce((obj, key)=>{
201
+ const prop = key.slice(6).toLowerCase().replace(/_([a-z])/g, (_, k)=>k.toUpperCase());
202
+ let value = process.env[key];
203
+ const lowerCase = "string" == typeof value && value.toLowerCase();
204
+ value = "null" === value ? null : "yes" === lowerCase || "on" === lowerCase || "true" === lowerCase || "enabled" === lowerCase ? true : "no" === lowerCase || "off" === lowerCase || "false" === lowerCase || "disabled" === lowerCase ? false : Number(value);
205
+ obj[prop] = value;
206
+ return obj;
207
+ }, Object.create(null));
208
+ function node_useColors() {
209
+ return "colors" in inspectOpts ? Boolean(inspectOpts.colors) : isatty(process.stderr.fd);
210
+ }
211
+ function getDate() {
212
+ if (inspectOpts.hideDate) return "";
213
+ return `${/* @__PURE__ */ new Date().toISOString()} `;
214
+ }
215
+ function formatArgs(diff, args) {
216
+ const { namespace: name, useColors } = this;
217
+ if (useColors) {
218
+ const c = this.color;
219
+ const colorCode = `\u001B[3${c < 8 ? c : `8;5;${c}`}`;
220
+ const prefix = ` ${colorCode};1m${name} \u001B[0m`;
221
+ args[0] = prefix + args[0].split("\n").join(`\n${prefix}`);
222
+ args.push(`${colorCode}m+${this.humanize(diff)}\u001B[0m`);
223
+ } else args[0] = `${getDate()}${name} ${args[0]}`;
224
+ }
225
+ function log(...args) {
226
+ process.stderr.write(`${formatWithOptions(this.inspectOpts, ...args)}\n`);
227
+ }
228
+ const defaultOptions = {
229
+ useColors: node_useColors(),
230
+ formatArgs: formatArgs,
231
+ formatters: {
232
+ o (v) {
233
+ this.inspectOpts.colors = this.useColors;
234
+ return inspect(v, this.inspectOpts).split("\n").map((str)=>str.trim()).join(" ");
235
+ },
236
+ O (v) {
237
+ this.inspectOpts.colors = this.useColors;
238
+ return inspect(v, this.inspectOpts);
239
+ }
240
+ },
241
+ inspectOpts: inspectOpts,
242
+ log: log,
243
+ humanize: humanize
244
+ };
245
+ function node_createDebug(namespace, options) {
246
+ var _ref;
247
+ const color = null != (_ref = options && options.color) ? _ref : selectColor(node_colors, namespace);
248
+ return createDebug(namespace, Object.assign(defaultOptions, {
249
+ color
250
+ }, options));
251
+ }
252
+ enable(process.env.DEBUG || "");
253
+ function isCustomizedMessage(msg) {
254
+ return 'object' == typeof msg && null !== msg && 'Customized' === msg.event;
255
+ }
256
+ function isControlRequest(msg) {
257
+ return 'object' == typeof msg && null !== msg && 'Control' === msg.event;
258
+ }
259
+ function isListClientsRequest(msg) {
260
+ return 'object' == typeof msg && null !== msg && 'ListClients' === msg.event;
261
+ }
262
+ function isPingEvent(msg) {
263
+ return 'object' == typeof msg && null !== msg && 'Ping' === msg.event;
264
+ }
265
+ function isRegisterEvent(msg) {
266
+ return 'object' == typeof msg && null !== msg && 'Register' === msg.event;
267
+ }
268
+ const DAEMON_WS_PATH = '/devtool/connector';
269
+ const DAEMON_VERSION_PATH = `${DAEMON_WS_PATH}/version`;
270
+ const DAEMON_SHUTDOWN_PATH = `${DAEMON_WS_PATH}/shutdown`;
271
+ const DAEMON_INSPECTOR_PATH = `${DAEMON_WS_PATH}/inspector`;
272
+ export { DAEMON_INSPECTOR_PATH, DAEMON_SHUTDOWN_PATH, DAEMON_VERSION_PATH, DAEMON_WS_PATH, isControlRequest, isCustomizedMessage, isListClientsRequest, isPingEvent, isRegisterEvent, node_createDebug };
package/dist/390.js ADDED
@@ -0,0 +1,102 @@
1
+ import { spawn } from "node:child_process";
2
+ import { closeSync, openSync } from "node:fs";
3
+ import promises from "node:fs/promises";
4
+ import { createRequire } from "node:module";
5
+ import node_net from "node:net";
6
+ import node_os from "node:os";
7
+ import node_path from "node:path";
8
+ import { setTimeout as promises_setTimeout } from "node:timers/promises";
9
+ import { DAEMON_WS_PATH, node_createDebug } from "./187.js";
10
+ const debug = node_createDebug('devtool-mcp-server:daemon:manager');
11
+ const DEBUG_ROUTER_DIR = node_path.join(node_os.homedir(), '.DebugRouterConnector');
12
+ const PIDFILE = node_path.join(DEBUG_ROUTER_DIR, 'daemon.pid');
13
+ const LOG = node_path.join(DEBUG_ROUTER_DIR, 'daemon.log');
14
+ const ERR = node_path.join(DEBUG_ROUTER_DIR, 'daemon.err');
15
+ function resolveDaemonEntryPath(moduleUrl = import.meta.url) {
16
+ return createRequire(moduleUrl).resolve('#daemon-entry');
17
+ }
18
+ class DaemonManager {
19
+ static async ensureRunning(port = 21783) {
20
+ const url = `ws://127.0.0.1:${port}${DAEMON_WS_PATH}`;
21
+ if (await DaemonManager.#isAlive(port)) {
22
+ debug('daemon already running on port %d', port);
23
+ return url;
24
+ }
25
+ debug('daemon not running, spawning...');
26
+ await DaemonManager.#spawn(port);
27
+ await DaemonManager.#waitReady(port, 5000);
28
+ debug('daemon is ready on port %d', port);
29
+ return url;
30
+ }
31
+ static async kill() {
32
+ try {
33
+ const pidStr = await promises.readFile(PIDFILE, 'utf-8');
34
+ const pid = Number.parseInt(pidStr.trim(), 10);
35
+ if (!Number.isNaN(pid)) {
36
+ debug('killing daemon pid %d', pid);
37
+ process.kill(pid, 'SIGTERM');
38
+ }
39
+ } catch {
40
+ debug('no pidfile found or cannot read it');
41
+ }
42
+ }
43
+ static async #isAlive(port) {
44
+ return new Promise((resolve)=>{
45
+ const socket = node_net.createConnection({
46
+ host: '127.0.0.1',
47
+ port
48
+ }, ()=>{
49
+ socket.destroy();
50
+ resolve(true);
51
+ });
52
+ socket.on('error', ()=>{
53
+ socket.destroy();
54
+ resolve(false);
55
+ });
56
+ socket.setTimeout(1000, ()=>{
57
+ socket.destroy();
58
+ resolve(false);
59
+ });
60
+ });
61
+ }
62
+ static async #spawn(port) {
63
+ await promises.mkdir(DEBUG_ROUTER_DIR, {
64
+ recursive: true
65
+ });
66
+ const entryPath = resolveDaemonEntryPath();
67
+ const out = openSync(LOG, 'w');
68
+ const err = openSync(ERR, 'w');
69
+ const child = spawn(process.execPath, [
70
+ entryPath,
71
+ '--port',
72
+ String(port)
73
+ ], {
74
+ detached: true,
75
+ stdio: [
76
+ 'ignore',
77
+ out,
78
+ err
79
+ ],
80
+ env: {
81
+ ...process.env,
82
+ DEBUG: process.env['DEBUG'] ?? ''
83
+ }
84
+ });
85
+ closeSync(out);
86
+ closeSync(err);
87
+ child.unref();
88
+ if (void 0 !== child.pid) {
89
+ await promises.writeFile(PIDFILE, String(child.pid), 'utf-8');
90
+ debug('spawned daemon with pid %d', child.pid);
91
+ }
92
+ }
93
+ static async #waitReady(port, timeoutMs) {
94
+ const deadline = Date.now() + timeoutMs;
95
+ while(Date.now() < deadline){
96
+ if (await DaemonManager.#isAlive(port)) return;
97
+ await promises_setTimeout(200);
98
+ }
99
+ throw new Error(`Daemon failed to start within ${timeoutMs}ms on port ${port}`);
100
+ }
101
+ }
102
+ export { DaemonManager };
package/dist/43.js ADDED
@@ -0,0 +1,20 @@
1
+ class ClientId {
2
+ static serialize(deviceId, port) {
3
+ return `${encodeURIComponent(deviceId)}:${port}`;
4
+ }
5
+ static deserialize(clientId) {
6
+ try {
7
+ const lastColonIndex = clientId.lastIndexOf(':');
8
+ if (-1 === lastColonIndex) return null;
9
+ const port = Number.parseInt(clientId.substring(lastColonIndex + 1), 10);
10
+ if (Number.isNaN(port)) return null;
11
+ return {
12
+ deviceId: decodeURIComponent(clientId.substring(0, lastColonIndex)),
13
+ port
14
+ };
15
+ } catch {
16
+ return null;
17
+ }
18
+ }
19
+ }
20
+ export { ClientId };