brickproof-adb 0.0.0-stage → 1.1.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.
package/src/adb.js ADDED
@@ -0,0 +1,376 @@
1
+ 'use strict';
2
+ /**
3
+ * adb.js — the adb binary and everything around it that knows nothing about
4
+ * particular tools: running commands, turning typical failures into advice,
5
+ * quoting for the device shell, client argument coercion, host temp dirs.
6
+ *
7
+ * Every adb call goes through run(): adb() for buffered output, spawnAdb() for
8
+ * a stream (the screenshot). The server never starts, stops or moves the adb
9
+ * server: the first client call starts it on 127.0.0.1:5037 if it is not
10
+ * running, and that server is shared with the user's own adb.
11
+ */
12
+
13
+ const { execFile, spawn } = require('child_process');
14
+ const { AsyncLocalStorage } = require('async_hooks');
15
+ const fs = require('fs');
16
+ const os = require('os');
17
+ const path = require('path');
18
+
19
+ const ADB_TIMEOUT_MS = 30000;
20
+ const ADB_MAX_BUFFER = 16 * 1024 * 1024;
21
+
22
+ // The binary: adb_path, or "adb" looked up on PATH (libuv finds adb.exe on
23
+ // Windows). PREFIX is empty in production; tests put a script there.
24
+ let ADB_BIN = 'adb';
25
+ let ADB_PREFIX = [];
26
+
27
+ function configure({ adbPath } = {}) {
28
+ ADB_BIN = adbPath || 'adb';
29
+ ADB_PREFIX = [];
30
+ }
31
+
32
+ /**
33
+ * Tests only: run `bin prefix... <adb args>` instead of adb, e.g.
34
+ * (process.execPath, ['test/fake-adb.js']). A script cannot be adb_path on
35
+ * Windows (execFile runs no .js or .cmd without a shell), so the fake adb is
36
+ * started through node. Not a setting, not an environment variable.
37
+ */
38
+ function useTestRunner(bin, prefix = []) {
39
+ ADB_BIN = bin;
40
+ ADB_PREFIX = prefix.slice();
41
+ }
42
+
43
+ function adbBinary() {
44
+ return ADB_BIN;
45
+ }
46
+
47
+ // ---------------------------------------------------------------- call notes
48
+ // Warnings that belong to the whole tool call rather than to one adb command
49
+ // (another adb restarted the server). server.js collects them per call and
50
+ // appends them to the result.
51
+
52
+ const callNotes = new AsyncLocalStorage();
53
+
54
+ async function collectNotes(fn) {
55
+ const notes = new Set();
56
+ try {
57
+ const value = await callNotes.run(notes, fn);
58
+ return { value, notes: [...notes] };
59
+ } catch (e) {
60
+ e.adbNotes = [...notes];
61
+ throw e;
62
+ }
63
+ }
64
+
65
+ function addNote(msg) {
66
+ const store = callNotes.getStore();
67
+ if (store) store.add(msg);
68
+ }
69
+
70
+ // The client prints this to stderr when its version differs from the running
71
+ // server's, then kills that server and starts its own; network devices drop.
72
+ // The numbers are the protocol version: two builds of one protocol print the
73
+ // same number twice.
74
+ const FOREIGN_ADB_RE = /adb server version \((\d+)\) doesn't match this client \((\d+)\)/;
75
+
76
+ function foreignAdbWarning(stderr) {
77
+ const m = FOREIGN_ADB_RE.exec(String(stderr || ''));
78
+ if (!m) return null;
79
+ const versions = m[1] !== m[2] ? ` (server version ${m[1]}, client version ${m[2]})` : '';
80
+ return `⚠ the adb server was started by another adb on this machine and this client restarted it${versions}, ` +
81
+ 'so network devices may need adb_connect again. Set adb_path to the same adb your other programs use (Android Studio, scrcpy, vendor tools); `brickproof-adb check` lists every adb it finds.';
82
+ }
83
+
84
+ /**
85
+ * `<bin> version` of any adb found on the machine, for `check`: { ok, build,
86
+ * protocol, error }. The only adb call that does not use the configured
87
+ * binary.
88
+ */
89
+ function adbVersionOf(bin, timeout = 10000) {
90
+ return new Promise(resolve => {
91
+ execFile(bin, ['version'], { timeout, windowsHide: true }, (err, stdout) => {
92
+ if (err) return resolve({ ok: false, error: err.code || err.message });
93
+ const out = String(stdout || '');
94
+ const protocol = (/Android Debug Bridge version (\S+)/.exec(out) || [])[1] || null;
95
+ const build = (/^Version (\S+)/m.exec(out) || [])[1] || null;
96
+ resolve({ ok: true, protocol, build });
97
+ });
98
+ });
99
+ }
100
+
101
+ function noteForeignAdb(stderr) {
102
+ const w = foreignAdbWarning(stderr);
103
+ if (w) addNote(w);
104
+ }
105
+
106
+ // ------------------------------------------------------------------ failures
107
+
108
+ function installHint(platform = process.platform) {
109
+ const cmd = platform === 'win32' ? 'winget install Google.PlatformTools'
110
+ : platform === 'darwin' ? 'brew install --cask android-platform-tools'
111
+ : 'the adb or android-tools package of your distribution';
112
+ return 'Run `brickproof-adb get-adb` to download Google\'s platform-tools, ' +
113
+ `or install them yourself (${cmd}; https://developer.android.com/tools/releases/platform-tools), ` +
114
+ 'or set adb_path to the adb executable.';
115
+ }
116
+
117
+ // Typical adb errors get the action that fixes them.
118
+ function friendlyAdbError(msg) {
119
+ if (/device '.*' not found|no devices\/emulators found/i.test(msg))
120
+ return `${msg}. Call adb_devices to list what is connected; network devices may need adb_connect first (wireless-debug ports change after phone reboot). ` +
121
+ 'A device that is not in that list: adb_devices discover=true searches the network for it.';
122
+ if (/device offline/i.test(msg))
123
+ return `${msg}. The TCP session died (device slept or rebooted) - run adb_disconnect for this host, then adb_connect again.`;
124
+ if (/device unauthorized|failed to authenticate/i.test(msg))
125
+ return `${msg}. Confirm the prompt to allow debugging on the device screen (check "Always allow").`;
126
+ if (/INSTALL_FAILED_VERIFICATION_FAILURE/i.test(msg))
127
+ return `${msg}. The on-device package verifier rejects ADB installs - disable it once via adb_shell (needs allow_shell): settings put global verifier_verify_adb_installs 0`;
128
+ return msg;
129
+ }
130
+
131
+ /**
132
+ * The text of a failed adb call, built from the execFile fields. A non-empty
133
+ * stderr is the message (plus the stdout tail). With an empty stderr only the
134
+ * adb subcommand is named, never the argv: the argv carries call arguments
135
+ * (typed text, pairing codes).
136
+ *
137
+ * ⚠ maxBuffer is checked first: Node reports it as the string code
138
+ * ERR_CHILD_PROCESS_STDIO_MAXBUFFER without `killed`, which would otherwise
139
+ * read as "adb could not start".
140
+ */
141
+ function describeAdbFailure(err, stderr, stdout, args, opts = {}) {
142
+ const raw = (stderr || '').toString();
143
+ // "* daemon not running; starting now", "* daemon started successfully":
144
+ // progress of the adb server start, never the cause of a failure.
145
+ let msg = raw.split(/\r?\n/).filter(l => !/^\s*\* daemon /i.test(l)).join('\n').trim();
146
+ const out = opts.binary ? '' : (stdout || '').toString().trim();
147
+ const a = args || [];
148
+ const sub = (a[0] === '-s' ? a[2] : a[0]) || '(no subcommand)';
149
+ const e = err || {};
150
+ const secs = +((opts.timeout || ADB_TIMEOUT_MS) / 1000).toFixed(3);
151
+ if (e.killed === true && /daemon not running; starting now/i.test(raw))
152
+ msg = `adb ${sub} timed out after ${secs} s: the adb server was still starting (it can take about 20 s on Windows); call again`;
153
+ if (!msg) {
154
+ if (e.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER')
155
+ msg = `adb ${sub} output exceeded ${ADB_MAX_BUFFER / 1024 / 1024} MB and was killed`;
156
+ else if (e.killed === true)
157
+ msg = `adb ${sub} timed out after ${secs} s and was killed${e.signal ? ` (${e.signal})` : ''}`;
158
+ else if (e.signal)
159
+ msg = `adb ${sub} was terminated by ${e.signal}`;
160
+ else if (typeof e.code === 'number')
161
+ msg = out ? `adb ${sub} exited with code ${e.code}` : `adb ${sub} exited with code ${e.code} and printed nothing`;
162
+ else if (e.code === 'ENOENT')
163
+ msg = `adb could not start: ENOENT - adb was not found (adb_path: ${JSON.stringify(ADB_BIN)}). ${installHint()}`;
164
+ else if (e.code === 'EINVAL' && process.platform === 'win32')
165
+ msg = 'adb could not start: EINVAL - adb_path must point to the adb executable (adb.exe), not to a .cmd or .bat file';
166
+ else if (typeof e.code === 'string')
167
+ msg = `adb could not start: ${e.code}`;
168
+ else
169
+ msg = `adb ${sub} failed without output`;
170
+ }
171
+ // stdout is kept on a non-zero exit: a failed device pipeline is unreadable
172
+ // without its output.
173
+ if (out) msg = `${msg}\nstdout (tail): ${out.slice(-2000)}`;
174
+ return friendlyAdbError(msg);
175
+ }
176
+
177
+ // --------------------------------------------------------------------- calls
178
+
179
+ function adb(args, opts = {}) {
180
+ return new Promise((resolve, reject) => {
181
+ execFile(ADB_BIN, [...ADB_PREFIX, ...args], {
182
+ timeout: opts.timeout || ADB_TIMEOUT_MS,
183
+ maxBuffer: ADB_MAX_BUFFER,
184
+ encoding: opts.binary ? 'buffer' : 'utf8',
185
+ windowsHide: true,
186
+ }, (err, stdout, stderr) => {
187
+ noteForeignAdb(stderr);
188
+ if (err) return reject(new Error(describeAdbFailure(err, stderr, stdout, args, opts)));
189
+ resolve(opts.withStderr ? { stdout, stderr } : stdout);
190
+ });
191
+ });
192
+ }
193
+
194
+ /**
195
+ * adb with stdout going straight into a file descriptor (the screenshot PNG):
196
+ * the bytes never pass through this process. Resolves { code, signal,
197
+ * timedOut, stderr }; rejects only when adb cannot be started.
198
+ */
199
+ function spawnAdb(args, outFd, opts = {}) {
200
+ const timeout = opts.timeout || ADB_TIMEOUT_MS;
201
+ return new Promise((resolve, reject) => {
202
+ let child;
203
+ try {
204
+ child = spawn(ADB_BIN, [...ADB_PREFIX, ...args], { stdio: ['ignore', outFd, 'pipe'], windowsHide: true });
205
+ } catch (e) {
206
+ reject(new Error(describeAdbFailure(e, '', '', args, opts)));
207
+ return;
208
+ }
209
+ let stderr = '';
210
+ let timedOut = false;
211
+ let settled = false;
212
+ const timer = setTimeout(() => { timedOut = true; child.kill(); }, timeout);
213
+ child.stderr.on('data', c => { if (stderr.length < 64 * 1024) stderr += c; });
214
+ child.on('error', e => {
215
+ clearTimeout(timer);
216
+ if (settled) return;
217
+ settled = true;
218
+ reject(new Error(describeAdbFailure(e, '', '', args, opts)));
219
+ });
220
+ child.on('close', (code, signal) => {
221
+ clearTimeout(timer);
222
+ if (settled) return;
223
+ settled = true;
224
+ noteForeignAdb(stderr);
225
+ resolve({ code, signal, timedOut, stderr });
226
+ });
227
+ });
228
+ }
229
+
230
+ function withSerial(serial, args) {
231
+ return serial ? ['-s', serial, ...args] : args;
232
+ }
233
+
234
+ // Single quotes for the DEVICE shell.
235
+ function sq(x) {
236
+ return `'${String(x).replace(/'/g, `'\\''`)}'`;
237
+ }
238
+
239
+ /**
240
+ * Run a command in the device shell and return stdout as a string.
241
+ *
242
+ * ⚠ tolerant (on by default) appends `; :`. Without it the last command of a
243
+ * chain sets the exit code, and a grep with no match (exit 1) fails the whole
244
+ * call with a useless "Command failed".
245
+ */
246
+ async function adbSh(serial, cmd, opts = {}) {
247
+ const body = opts.tolerant === false ? cmd : `${cmd}; :`;
248
+ const out = await adb(withSerial(serial, ['shell', body]), opts);
249
+ return out.toString();
250
+ }
251
+
252
+ function text(t) { return [{ type: 'text', text: t }]; }
253
+
254
+ function json(obj) { return text(JSON.stringify(obj, null, 2)); }
255
+
256
+ // The argument of `input text`, before sq() quotes it for the device shell.
257
+ // `input text` (Input.java up to SDK 30, InputShellCommand from SDK 31) has
258
+ // one rule of its own: "%s" is a space. Every other character is typed as it
259
+ // is, so nothing else is escaped; a space becomes %s, as it always worked.
260
+ function escapeInputText(s) {
261
+ return s.replace(/ /g, '%s');
262
+ }
263
+
264
+ // Some MCP clients send array parameters as JSON strings.
265
+ function coerceArray(v) {
266
+ if (v === undefined || v === null) return [];
267
+ if (Array.isArray(v)) return v;
268
+ if (typeof v === 'string') {
269
+ const s = v.trim();
270
+ if (s.startsWith('[') && s.endsWith(']')) {
271
+ try {
272
+ const parsed = JSON.parse(s);
273
+ if (Array.isArray(parsed)) return parsed;
274
+ } catch { /* not JSON: a single value */ }
275
+ }
276
+ }
277
+ return [v];
278
+ }
279
+
280
+ // The same for booleans: "true"/"false" strings.
281
+ function coerceBool(v, dflt) {
282
+ if (v === undefined || v === null || v === '') return dflt;
283
+ if (typeof v === 'boolean') return v;
284
+ return String(v).toLowerCase() === 'true';
285
+ }
286
+
287
+ // The same for objects (adb_app action=launch extras): a JSON string is accepted.
288
+ function coerceObject(v) {
289
+ if (v === undefined || v === null) return {};
290
+ if (typeof v === 'object' && !Array.isArray(v)) return v;
291
+ if (typeof v === 'string') {
292
+ const s = v.trim();
293
+ if (!s) return {};
294
+ if (s.startsWith('{') && s.endsWith('}')) {
295
+ try {
296
+ const parsed = JSON.parse(s);
297
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
298
+ } catch { /* not JSON: refused below */ }
299
+ }
300
+ }
301
+ throw new Error(`extras: expected a key-value object, got ${JSON.stringify(v).slice(0, 120)}`);
302
+ }
303
+
304
+ function ensureDir(p) {
305
+ fs.mkdirSync(p, { recursive: true });
306
+ return p;
307
+ }
308
+
309
+ // A serial as a directory name: 192.0.2.50:5555 -> 192.0.2.50_5555. Trailing
310
+ // dots are dropped, Windows would drop them silently.
311
+ function sanitizeSerial(serial) {
312
+ const s = String(serial || 'default').replace(/[^\w.\-]+/g, '_').replace(/\.+$/, '');
313
+ return s || '_';
314
+ }
315
+
316
+ const RENAME_RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);
317
+ const RENAME_RETRIES = 5;
318
+
319
+ /**
320
+ * rename() with retries for a target held open by another process (an
321
+ * antivirus or indexer on Windows): up to RENAME_RETRIES more attempts with a
322
+ * growing pause, one stderr line per retry. Other errors throw at once.
323
+ */
324
+ async function renameWithRetry(from, to, {
325
+ fsImpl = fs, retries = RENAME_RETRIES, delayMs = 100,
326
+ sleep = ms => new Promise(r => setTimeout(r, ms)),
327
+ log = line => process.stderr.write(line + '\n'),
328
+ } = {}) {
329
+ for (let attempt = 0; ; attempt++) {
330
+ try {
331
+ fsImpl.renameSync(from, to);
332
+ return attempt;
333
+ } catch (e) {
334
+ if (!RENAME_RETRY_CODES.has(e.code) || attempt >= retries) throw e;
335
+ log(`brickproof-adb: rename ${from} -> ${to} failed with ${e.code}, retry ${attempt + 1}/${retries}`);
336
+ await sleep(delayMs * (attempt + 1));
337
+ }
338
+ }
339
+ }
340
+
341
+ // ------------------------------------------------------------ host temp dirs
342
+ // Every temporary directory on the host is <tmpdir>/brickproof-*, removed in
343
+ // a finally; sweepTempDirs() at start removes those left by a killed process.
344
+
345
+ const TEMP_PREFIX = 'brickproof-';
346
+
347
+ function makeTempDir(kind = '') {
348
+ return fs.mkdtempSync(path.join(os.tmpdir(), `${TEMP_PREFIX}${kind}`));
349
+ }
350
+
351
+ function sweepTempDirs({ maxAgeMs = 3600000, dir = os.tmpdir(), now = Date.now() } = {}) {
352
+ const removed = [];
353
+ let names = [];
354
+ try { names = fs.readdirSync(dir); } catch { return removed; }
355
+ for (const n of names) {
356
+ if (!n.startsWith(TEMP_PREFIX)) continue;
357
+ const full = path.join(dir, n);
358
+ try {
359
+ const st = fs.lstatSync(full);
360
+ if (!st.isDirectory() || now - st.mtimeMs < maxAgeMs) continue;
361
+ fs.rmSync(full, { recursive: true, force: true });
362
+ removed.push(full);
363
+ } catch { /* another process, or no permission: leave it */ }
364
+ }
365
+ return removed;
366
+ }
367
+
368
+ module.exports = {
369
+ ADB_TIMEOUT_MS, ADB_MAX_BUFFER, TEMP_PREFIX,
370
+ configure, useTestRunner, adbBinary,
371
+ adb, spawnAdb, adbSh, withSerial, friendlyAdbError, describeAdbFailure, installHint,
372
+ collectNotes, addNote, foreignAdbWarning, FOREIGN_ADB_RE, adbVersionOf,
373
+ sq, text, json, escapeInputText,
374
+ coerceArray, coerceBool, coerceObject,
375
+ ensureDir, sanitizeSerial, makeTempDir, sweepTempDirs, renameWithRetry,
376
+ };