brickproof-adb 0.0.0-stage → 1.0.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/cli.js ADDED
@@ -0,0 +1,497 @@
1
+ 'use strict';
2
+ // The commands; src/main.js runs them. Nothing happens on require(). stdout
3
+ // belongs to the MCP protocol in stdio mode: logs go to stderr only.
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { parseArgs } = require('util');
8
+ const C = require('./config');
9
+ const { VERSION, PNGJS_VERSION, JPEG_JS_VERSION } = require('./version');
10
+
11
+ const USAGE = `brickproof-adb ${VERSION}
12
+
13
+ Usage:
14
+ brickproof-adb [<folder>...] MCP server on stdio; the folders, when given,
15
+ are file_roots
16
+ brickproof-adb serve [--port 3200] [--host 127.0.0.1] [--token-file F]
17
+ MCP server over Streamable HTTP
18
+ brickproof-adb set <key> [<value>...]
19
+ write a setting into the settings file;
20
+ no value: back to the default
21
+ brickproof-adb get-adb [--accept-license]
22
+ download Google's platform-tools (adb)
23
+ brickproof-adb token [--new] print the connector path and the Bearer line;
24
+ --new replaces the token
25
+ brickproof-adb check [--offline] settings, adb, the image pipeline, file roots,
26
+ store; connected devices unless --offline
27
+ brickproof-adb --version | --help
28
+ `;
29
+
30
+ function say(msg) {
31
+ process.stderr.write(`brickproof-adb: ${msg}\n`);
32
+ }
33
+
34
+ function usageError(msg) {
35
+ say(`${msg}\n\n${USAGE}`);
36
+ return 2;
37
+ }
38
+
39
+ function load(flags) {
40
+ return C.loadConfig({ flags });
41
+ }
42
+
43
+ // The adb the server will use (only files are checked) and init().
44
+ function initServer(loaded) {
45
+ const PT = require('./platform-tools');
46
+ const adb = PT.resolveAdbPath(loaded.settings, loaded.sources);
47
+ const S = require('./server');
48
+ S.init(loaded.settings, { hints: C.settingHints(loaded), adbPath: adb.path });
49
+ return { S, adb };
50
+ }
51
+
52
+ // What runs before either transport serves: stale temp dirs from a killed
53
+ // process are removed, the devices of the settings and the remembered ones
54
+ // are connected in the background (a failure is a line in stderr, not a start
55
+ // failure).
56
+ function startBackground(s) {
57
+ const A = require('./adb');
58
+ for (const dir of A.sweepTempDirs()) say(`removed a stale temporary directory: ${dir}`);
59
+ const session = require('./session');
60
+ const all = [...new Set([...s.devices, ...session.readKnown()])];
61
+ if (!all.length) return;
62
+ (async () => {
63
+ for (const d of all) {
64
+ try {
65
+ const r = await session.connect({ host: d });
66
+ say(`adb connect ${d}: ${r[0].text.split('\n')[0]}`);
67
+ } catch (e) {
68
+ say(`adb connect ${d} failed (adb_connect can retry): ${e.message.split('\n')[0]}`);
69
+ }
70
+ }
71
+ })();
72
+ }
73
+
74
+ function rootsText(s, src) {
75
+ if (!s.file_roots.length) return 'none';
76
+ return s.file_roots.join(', ') + (String(src.file_roots).startsWith('default') ? ' (default)' : '');
77
+ }
78
+
79
+ // The start lines that follow the first one: a doubtful Downloads folder.
80
+ function startWarnings(loaded) {
81
+ return loaded.downloadsWarning ? [`brickproof-adb: warning: ${loaded.downloadsWarning}`] : [];
82
+ }
83
+
84
+ function settingsLine(loaded, adb) {
85
+ const s = loaded.settings, src = loaded.sources;
86
+ return `allow_shell ${s.allow_shell ? 'ON' : 'off'}, allow_uninstall ${s.allow_uninstall ? 'ON' : 'off'}, ` +
87
+ `file roots ${rootsText(s, src)}, store ${s.store}, ` +
88
+ `adb ${adb.chosen ? `${adb.path} (${adb.source}${adb.chosen.found ? '' : ', missing'})` : 'not found'}`;
89
+ }
90
+
91
+ // ---------------------------------------------------------------------------
92
+ // serve
93
+ // ---------------------------------------------------------------------------
94
+
95
+ async function serveCommand(rest) {
96
+ let opts;
97
+ try {
98
+ opts = parseArgs({
99
+ args: rest,
100
+ options: { port: { type: 'string' }, host: { type: 'string' }, 'token-file': { type: 'string' } },
101
+ }).values;
102
+ } catch (e) {
103
+ return usageError(e.message);
104
+ }
105
+ const flags = { host: opts.host };
106
+ if (opts.port !== undefined) {
107
+ flags.port = Number(opts.port);
108
+ if (!/^\d+$/.test(opts.port) || flags.port > 65535) return usageError('--port must be an integer 0-65535');
109
+ }
110
+ if (opts.host === '') return usageError('--host must not be empty');
111
+
112
+ const { resolveToken, connectionLines } = require('./token');
113
+ const loaded = load(flags);
114
+ const s = loaded.settings;
115
+ C.ensureStateDir(s.state_dir);
116
+
117
+ let tok;
118
+ try {
119
+ tok = resolveToken({ tokenFile: opts['token-file'], env: process.env, stateDir: s.state_dir });
120
+ } catch (e) {
121
+ if (e.name !== 'TokenError') throw e;
122
+ say(e.message);
123
+ return 1;
124
+ }
125
+
126
+ const { adb } = initServer(loaded);
127
+ const H = require('./http');
128
+
129
+ let server, localGuards;
130
+ try {
131
+ ({ server, localGuards } = await H.startHttp({
132
+ port: s.port, host: s.host, token: tok.token, allowedHosts: s.allowed_hosts, logRequests: s.log_requests, legacyToken: tok.legacy,
133
+ }));
134
+ } catch (e) {
135
+ say(`cannot listen on ${s.host}:${s.port} (${e.code || e.message})`);
136
+ return 1;
137
+ }
138
+
139
+ // One write, so the lines stay together in the log.
140
+ const port = server.address().port;
141
+ const hosts = s.allowed_hosts;
142
+ const hostsSuffix = localGuards && hosts.length ? `, allowed hosts ${hosts.join(', ')}` : '';
143
+ const lines = [`brickproof-adb ${VERSION} on ${s.host}:${port}, ${settingsLine(loaded, adb)}${hostsSuffix}${H.bindNote(localGuards)}`, ...startWarnings(loaded)];
144
+ if (!localGuards && hosts.length)
145
+ lines.push('brickproof-adb: note: allowed_hosts is not used on a non-local bind (there are no Host/Origin checks to relax)');
146
+ if (tok.legacy)
147
+ lines.push(`brickproof-adb: warning: the token from ${tok.source} does not meet the token rules and is accepted only because BRICKPROOF_ALLOW_LEGACY_TOKEN=1 inside Home Assistant; clear the token option and restart to get a generated one, then update the connector`);
148
+ if (tok.generated) {
149
+ const [p, b] = connectionLines(tok.token);
150
+ lines.push(
151
+ `brickproof-adb: new token generated and saved to ${tok.file}`,
152
+ `brickproof-adb: claude.ai connector path: ${p}`,
153
+ `brickproof-adb: Bearer header: ${b}`,
154
+ 'brickproof-adb: shown once; `brickproof-adb token` shows it again');
155
+ }
156
+ process.stderr.write(lines.join('\n') + '\n');
157
+ startBackground(s);
158
+
159
+ const stop = () => {
160
+ server.close();
161
+ process.exit(0);
162
+ };
163
+ process.on('SIGINT', stop);
164
+ process.on('SIGTERM', stop);
165
+ return null;
166
+ }
167
+
168
+ // ---------------------------------------------------------------------------
169
+ // stdio (no command)
170
+ // ---------------------------------------------------------------------------
171
+
172
+ async function stdioCommand(args) {
173
+ const option = args.find(a => a.startsWith('-'));
174
+ if (option) return usageError(`unknown option ${option}`);
175
+ // Nothing but the protocol on stdout: a stray console.log goes to stderr.
176
+ console.log = console.error;
177
+ console.info = console.error;
178
+ const loaded = load({ file_roots: args });
179
+ const s = loaded.settings;
180
+ // A state directory that cannot be created does not stop stdio (the tools
181
+ // that need it fail on their own); the client gets its tool list.
182
+ try { C.ensureStateDir(s.state_dir); } catch (e) { say(`warning: ${e.message}`); }
183
+ const { adb } = initServer(loaded);
184
+ const { serveStdio } = require('./stdio');
185
+ const { closed } = serveStdio();
186
+ process.stderr.write([`brickproof-adb ${VERSION} on stdio, ${settingsLine(loaded, adb)}`, ...startWarnings(loaded)].join('\n') + '\n');
187
+ startBackground(s);
188
+ closed.then(() => process.exit(0));
189
+ return null;
190
+ }
191
+
192
+ // ---------------------------------------------------------------------------
193
+ // set
194
+ // ---------------------------------------------------------------------------
195
+
196
+ function setCommand(rest) {
197
+ const [key, ...values] = rest;
198
+ if (!key || key.startsWith('-')) return usageError(`set needs a setting name: ${C.SETTABLE.join(', ')}`);
199
+ const target = load({}).writeTarget;
200
+ let r;
201
+ try {
202
+ r = C.writeSetting(target, key, values);
203
+ } catch (e) {
204
+ if (e.name !== 'ConfigError') throw e;
205
+ say(e.message);
206
+ return 1;
207
+ }
208
+ const now = load({});
209
+ const out = [r.removed
210
+ ? `${key} removed from ${r.file}: the default applies (now ${JSON.stringify(now.settings[key])})`
211
+ : `${key} = ${JSON.stringify(r.value)} written to ${r.file}`];
212
+ const src = now.sources[key];
213
+ if (typeof src === 'string' && (src.startsWith('env ') || src.startsWith('flag')))
214
+ out.push(`warning: ${src} is set and overrides the settings file: the server keeps using ${JSON.stringify(now.settings[key])} until it is removed`);
215
+ out.push('A running server uses the change after a restart (over stdio: restart the client, such as Claude Desktop).');
216
+ process.stdout.write(out.join('\n') + '\n');
217
+ return 0;
218
+ }
219
+
220
+ // ---------------------------------------------------------------------------
221
+ // get-adb
222
+ // ---------------------------------------------------------------------------
223
+
224
+ function ask(question) {
225
+ return new Promise(resolve => {
226
+ const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
227
+ let answered = false;
228
+ rl.question(question, a => { answered = true; rl.close(); resolve(a); });
229
+ rl.on('close', () => { if (!answered) resolve(''); });
230
+ });
231
+ }
232
+
233
+ async function getAdbCommand(rest) {
234
+ let opts;
235
+ try {
236
+ opts = parseArgs({ args: rest, options: { 'accept-license': { type: 'boolean' } } }).values;
237
+ } catch (e) {
238
+ return usageError(e.message);
239
+ }
240
+ const PT = require('./platform-tools');
241
+ const refusal = PT.getAdbRefusal();
242
+ if (refusal) { say(refusal); return 1; }
243
+ const s = load({}).settings;
244
+ const url = PT.PLATFORM_ZIP[process.platform];
245
+ const dir = path.join(s.state_dir, 'platform-tools');
246
+ process.stdout.write(`Android SDK Platform-Tools come from Google and are subject to Google's terms:\n ${PT.LICENSE_URL}\n` +
247
+ `Source: ${url}\nWill be installed into: ${dir}\n`);
248
+ if (!opts['accept-license']) {
249
+ const a = (await ask('Accept the terms and download? [y/N] ')).trim().toLowerCase();
250
+ if (a !== 'y' && a !== 'yes') { process.stdout.write('Nothing was downloaded.\n'); return 1; }
251
+ }
252
+ C.ensureStateDir(s.state_dir);
253
+ let buf;
254
+ try {
255
+ buf = await PT.download(url);
256
+ } catch (e) {
257
+ say(`download failed: ${e.message}. Nothing was changed.`);
258
+ return 1;
259
+ }
260
+ let r;
261
+ try {
262
+ r = PT.installPlatformTools(buf, s.state_dir);
263
+ } catch (e) {
264
+ say(`could not install platform-tools: ${e.message}${e.code === 'EPERM' || e.code === 'EBUSY' ? ' (an adb from that folder may be running: stop it with `adb kill-server` and try again)' : ''}. The previous state was kept.`);
265
+ return 1;
266
+ }
267
+ const v = await require('./adb').adbVersionOf(r.adb);
268
+ process.stdout.write(`Downloaded ${(buf.length / 1048576).toFixed(1)} MB, ${r.files} files.\n` +
269
+ `adb: ${r.adb}${v.ok ? ` — ${v.build || v.protocol}` : ` — does not run (${v.error})`}\n` +
270
+ 'brickproof-adb finds it there by itself; restart a running server to use it.\n');
271
+ return v.ok ? 0 : 1;
272
+ }
273
+
274
+ // ---------------------------------------------------------------------------
275
+ // token
276
+ // ---------------------------------------------------------------------------
277
+
278
+ function tokenCommand(rest) {
279
+ let opts;
280
+ try {
281
+ opts = parseArgs({ args: rest, options: { new: { type: 'boolean' } } }).values;
282
+ } catch (e) {
283
+ return usageError(e.message);
284
+ }
285
+ const T = require('./token');
286
+ const s = load({}).settings;
287
+ if (opts.new) {
288
+ C.ensureStateDir(s.state_dir);
289
+ const { token, file } = T.replaceToken(s.state_dir);
290
+ process.stdout.write(T.connectionLines(token).join('\n') + '\n');
291
+ say(`new token saved to ${file}; a running server accepts the old token until it is restarted; every connected client must be updated (connector URL or Bearer header)`);
292
+ if (process.env.BRICKPROOF_TOKEN)
293
+ say('warning: env BRICKPROOF_TOKEN is set and takes precedence over the saved token; unset it for the new one to take effect');
294
+ return 0;
295
+ }
296
+ let tok;
297
+ try {
298
+ tok = T.resolveToken({ env: process.env, stateDir: s.state_dir, generate: false });
299
+ } catch (e) {
300
+ if (e.name !== 'TokenError') throw e;
301
+ say(e.message);
302
+ return 1;
303
+ }
304
+ process.stdout.write(T.connectionLines(tok.token).join('\n') + '\n');
305
+ return 0;
306
+ }
307
+
308
+ // ---------------------------------------------------------------------------
309
+ // check
310
+ // ---------------------------------------------------------------------------
311
+
312
+ // "exists, writable" / "missing" / "not a directory" / "will be created".
313
+ function dirState(dir, { mayCreate = false } = {}) {
314
+ let st;
315
+ try { st = fs.statSync(dir); } catch { st = null; }
316
+ if (!st) {
317
+ if (!mayCreate) return { ok: false, text: 'missing' };
318
+ let up = path.dirname(dir);
319
+ while (up !== path.dirname(up) && !fs.existsSync(up)) up = path.dirname(up);
320
+ try { fs.accessSync(up, fs.constants.W_OK); return { ok: true, text: 'will be created' }; }
321
+ catch { return { ok: false, text: `cannot be created (${up} is not writable)` }; }
322
+ }
323
+ if (!st.isDirectory()) return { ok: false, text: 'not a directory' };
324
+ try { fs.accessSync(dir, fs.constants.W_OK); return { ok: true, text: 'directory, writable' }; }
325
+ catch { return { ok: false, text: 'directory, NOT writable' }; }
326
+ }
327
+
328
+ // The image pipeline on generated frames: the very function adb_screenshot
329
+ // uses (image.processFrame), not a copy of it.
330
+ async function imageSmoke() {
331
+ const I = require('./image');
332
+ const A = require('./adb');
333
+ const cases = [
334
+ { W: 3840, H: 2160, w: 1024, h: 576, dark: false, fill: (x, y, W, H) => [x * 255 / W | 0, y * 255 / H | 0, 128] },
335
+ { W: 1080, H: 2400, w: 461, h: 1024, dark: false, fill: (x, y, W, H) => [(x + y) % 256, x * 255 / W | 0, y * 255 / H | 0] },
336
+ { W: 1080, H: 2340, w: 473, h: 1024, dark: true, fill: () => [0, 0, 0] },
337
+ ];
338
+ const dir = A.makeTempDir('check-');
339
+ const lines = [], problems = [];
340
+ try {
341
+ for (const c of cases) {
342
+ const file = path.join(dir, `${c.W}x${c.H}.png`);
343
+ fs.writeFileSync(file, I.makePng(c.W, c.H, (x, y) => c.fill(x, y, c.W, c.H)));
344
+ const t0 = Date.now();
345
+ try {
346
+ const r = await I.processFrame(file, 1024, 70);
347
+ const ms = Date.now() - t0;
348
+ const dark = I.isDark(r.mean, r.sd);
349
+ const ok = r.W === c.W && r.H === c.H && r.w === c.w && r.h === c.h && dark === c.dark && r.jpeg[0] === 0xff && r.jpeg[1] === 0xd8;
350
+ lines.push(` ${c.W}x${c.H} -> ${r.w}x${r.h} in ${ms} ms, JPEG ${r.jpeg.length} bytes, mean ${r.mean.toFixed(3)} sd ${r.sd.toFixed(3)}${dark ? ' (dark)' : ''}${ok ? '' : ' — UNEXPECTED'}`);
351
+ if (!ok) problems.push(`image pipeline: ${c.W}x${c.H} gave ${r.w}x${r.h}, dark ${dark}; expected ${c.w}x${c.h}, dark ${c.dark}`);
352
+ } catch (e) {
353
+ lines.push(` ${c.W}x${c.H}: FAILED (${e.message})`);
354
+ problems.push(`image pipeline: ${c.W}x${c.H}: ${e.message}`);
355
+ }
356
+ }
357
+ } finally {
358
+ fs.rmSync(dir, { recursive: true, force: true });
359
+ }
360
+ return { lines, problems };
361
+ }
362
+
363
+ async function checkCommand(rest) {
364
+ let opts;
365
+ try {
366
+ opts = parseArgs({ args: rest, options: { offline: { type: 'boolean' } } }).values;
367
+ } catch (e) {
368
+ return usageError(e.message);
369
+ }
370
+ const problems = [], warnings = [];
371
+ const out = [`brickproof-adb ${VERSION} (node ${process.versions.node}, pngjs ${PNGJS_VERSION}, jpeg-js ${JPEG_JS_VERSION}, ${process.platform}-${process.arch})`];
372
+ const loaded = load({});
373
+ const s = loaded.settings, src = loaded.sources;
374
+ out.push(`settings file: ${loaded.file ? `${loaded.file} (${loaded.fileSource})` : `none (\`brickproof-adb set\` writes ${loaded.writeTarget})`}`);
375
+ if (loaded.settingsUi) out.push(`settings are changed in: ${loaded.settingsUi}`);
376
+
377
+ const sd = dirState(s.state_dir, { mayCreate: true });
378
+ if (!sd.ok) problems.push(`state_dir ${s.state_dir}: ${sd.text}`);
379
+ out.push(`state_dir: ${s.state_dir} (${src.state_dir}) — ${sd.text}`);
380
+ const st = dirState(s.store, { mayCreate: true });
381
+ if (!st.ok) problems.push(`store ${s.store}: ${st.text}`);
382
+ out.push(`store: ${s.store} (${src.store}) — ${st.text}`);
383
+
384
+ if (!s.file_roots.length) out.push(`file_roots: none (${src.file_roots}) — adb_push, adb_pull and adb_install refuse until it is set`);
385
+ else {
386
+ out.push(`file_roots (${src.file_roots}):`);
387
+ for (const r of s.file_roots) {
388
+ const d = dirState(r);
389
+ if (!d.ok) problems.push(`file_root ${r}: ${d.text}`);
390
+ out.push(` ${r} — ${d.text}`);
391
+ }
392
+ }
393
+ out.push(`allow_shell: ${s.allow_shell} (${src.allow_shell}), allow_uninstall: ${s.allow_uninstall} (${src.allow_uninstall}), log_requests: ${s.log_requests} (${src.log_requests})`);
394
+ const known = require('./session');
395
+ known.configure({ stateDir: s.state_dir });
396
+ const remembered = known.readKnown();
397
+ out.push(`devices connected at start: ${s.devices.length ? s.devices.join(', ') : 'none'} (settings), ${remembered.length ? remembered.join(', ') : 'none'} (remembered)`);
398
+ out.push(`scan_subnets: ${s.scan_subnets.length ? s.scan_subnets.join(', ') : 'none (the private /24 networks of this computer)'}`);
399
+ out.push(`serve: ${s.host}:${s.port}`);
400
+
401
+ const T = require('./token');
402
+ try {
403
+ const tok = T.resolveToken({ env: process.env, stateDir: s.state_dir, generate: false });
404
+ out.push(`token: ${tok.source}${tok.legacy ? ' (legacy, accepted inside Home Assistant only)' : ''}`);
405
+ } catch (e) {
406
+ if (e.name !== 'TokenError') throw e;
407
+ if (/^no token yet/.test(e.message)) out.push('token: none yet (generated on the first `brickproof-adb serve`; stdio needs none)');
408
+ else { problems.push(e.message); out.push('token: invalid'); }
409
+ }
410
+
411
+ // Every adb on the machine with its version; the one in use first found.
412
+ const A = require('./adb');
413
+ const PT = require('./platform-tools');
414
+ const found = PT.resolveAdbPath(s, src);
415
+ A.configure({ adbPath: found.path });
416
+ out.push('adb:');
417
+ const builds = new Set();
418
+ let adbOk = false;
419
+ for (const p of found.places.filter(x => x.found)) {
420
+ const v = await A.adbVersionOf(p.path);
421
+ const used = found.chosen && p.path === found.chosen.path;
422
+ if (v.ok) builds.add(v.build || v.protocol);
423
+ if (used) adbOk = v.ok;
424
+ out.push(` ${used ? '*' : ' '} ${p.path} (${p.source}) — ${v.ok ? `${v.build || '?'} (protocol ${v.protocol || '?'})` : `does not run (${v.error})`}${used ? ' ← used' : ''}`);
425
+ }
426
+ if (!found.chosen) {
427
+ out.push(` none found; looked in: ${PT.lookedIn(found).join(', ')}`);
428
+ problems.push(`adb was not found. ${A.installHint()}`);
429
+ } else if (!found.chosen.found) {
430
+ out.push(` * ${found.chosen.path} (${found.chosen.source}) — does not exist ← used`);
431
+ problems.push(`adb_path ${found.chosen.path} does not exist or cannot be run. ${A.installHint()}`);
432
+ } else if (!adbOk) {
433
+ problems.push(`the adb in use (${found.chosen.path}) does not run`);
434
+ }
435
+ if (builds.size > 1)
436
+ warnings.push(`${builds.size} different adb versions on this machine (${[...builds].join(', ')}): two different adb restart each other's adb server, and network devices drop. Use one for everything (set adb_path).`);
437
+
438
+ out.push('image pipeline:');
439
+ const img = await imageSmoke();
440
+ out.push(...img.lines);
441
+ problems.push(...img.problems);
442
+
443
+ if (!opts.offline && adbOk) {
444
+ out.push('devices:');
445
+ try {
446
+ const d = await A.adb(['devices', '-l'], { timeout: 15000, withStderr: true });
447
+ for (const l of String(d.stdout).split('\n').map(x => x.trimEnd()).filter(Boolean)) out.push(` ${l}`);
448
+ const w = A.foreignAdbWarning(d.stderr);
449
+ if (w) out.push(` ${w}`);
450
+ } catch (e) {
451
+ problems.push(`adb devices failed: ${e.message}`);
452
+ }
453
+ }
454
+
455
+ if (warnings.length) out.push(`\nwarnings:\n ${warnings.join('\n ')}`);
456
+ out.push(problems.length ? `\nproblems:\n ${problems.join('\n ')}` : '\nok');
457
+ process.stdout.write(out.join('\n') + '\n');
458
+ return problems.length ? 1 : 0;
459
+ }
460
+
461
+ // ---------------------------------------------------------------------------
462
+
463
+ async function main(rawArgv) {
464
+ // A launcher may leave an empty or unresolved placeholder for a form field
465
+ // that was not filled in (a desktop extension's folders): not an argument.
466
+ const argv = rawArgv.filter(a => a !== '' && !/^\$\{user_config\.[A-Za-z0-9_]+\}$/.test(a));
467
+ const [cmd, ...rest] = argv;
468
+ if (cmd === '--version' || cmd === '-v') { process.stdout.write(VERSION + '\n'); return 0; }
469
+ if (cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(USAGE); return 0; }
470
+
471
+ try {
472
+ if (cmd === 'serve') return await serveCommand(rest);
473
+ if (cmd === 'set') return setCommand(rest);
474
+ if (cmd === 'get-adb') return await getAdbCommand(rest);
475
+ if (cmd === 'token') return tokenCommand(rest);
476
+ if (cmd === 'check') return await checkCommand(rest);
477
+ // No command, or folders: stdio. A word that is neither a command nor a
478
+ // path is a mistake, not a folder.
479
+ if (cmd === undefined || argv.every(a => !a.startsWith('-') && /[\\/]|^\.{1,2}$/.test(a)) || cmd.startsWith('-'))
480
+ return await stdioCommand(argv);
481
+ } catch (e) {
482
+ if (e.name !== 'ConfigError') throw e;
483
+ say(e.message);
484
+ return 1;
485
+ }
486
+ return usageError(`unknown command "${cmd}"`);
487
+ }
488
+
489
+ /** Run main() and set the exit code; main.js calls it. */
490
+ function run(argv) {
491
+ return main(argv).then(
492
+ code => { if (code !== null) process.exitCode = code; },
493
+ err => { say(err && err.stack || String(err)); process.exitCode = 1; },
494
+ );
495
+ }
496
+
497
+ module.exports = { main, run, USAGE };