dsh-apk-vm 0.6.2 → 0.8.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.
package/index.js CHANGED
@@ -14,7 +14,7 @@
14
14
  * and the open-source framework choices are documented in README.md / DESIGN.md.
15
15
  */
16
16
  import { randomUUID } from 'node:crypto';
17
- import { createReadStream, existsSync } from 'node:fs';
17
+ import { createReadStream, existsSync, readFileSync } from 'node:fs';
18
18
  import { promises as fsp } from 'node:fs';
19
19
  import net from 'node:net';
20
20
  import os from 'node:os';
@@ -29,6 +29,18 @@ import { acceptWebSocket } from './lib/ws.js';
29
29
  import { parseUiHierarchy, decorateUiNodes, buildInspectorPayload } from './lib/ui-inspector.js';
30
30
  import { FlowRecorder } from './lib/flows.js';
31
31
  import { collectStorage, cleanTempFiles, cleanSnapshots, cleanOrphanAvds, formatBytes } from './lib/storage.js';
32
+ import { buildApksFromAab, aabInfo, detectBundletool } from './lib/aab.js';
33
+ import { readHarFile, summarizeHar, filterHar, toCurl } from './lib/har.js';
34
+ import { runAssertions, compareScreenshot, createTestReport, reportMarkdown } from './lib/ui-tests.js';
35
+ import { SshAdbTunnel } from './lib/remote.js';
36
+
37
+ const PLUGIN_VERSION = (() => {
38
+ try {
39
+ return JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version || 'unknown';
40
+ } catch {
41
+ return 'unknown';
42
+ }
43
+ })();
32
44
 
33
45
  export const name = 'dsh-apk-vm';
34
46
 
@@ -285,6 +297,7 @@ export function apply(ctx, config = {}) {
285
297
  };
286
298
  }
287
299
  let installInFlight = null;
300
+ let remoteTunnel = null;
288
301
  let startKick = null;
289
302
  let autoStartKicked = false;
290
303
  const frame = { buffer: null, at: 0, inFlight: null, receivedAt: [] };
@@ -318,6 +331,42 @@ export function apply(ctx, config = {}) {
318
331
  maxFps: Math.min(60, Math.max(1, Number(cfg.scrcpyMaxFps) || 60)),
319
332
  port: Number(cfg.scrcpyPort) || 27183,
320
333
  };
334
+ const STREAM_PRESETS = Object.freeze({
335
+ low: { maxSize: 540, bitrate: 2_500_000, maxFps: 30 },
336
+ balanced: { maxSize: 720, bitrate: 4_000_000, maxFps: 60 },
337
+ high: { maxSize: 960, bitrate: 6_000_000, maxFps: 60 },
338
+ });
339
+ let streamPreset = 'custom';
340
+ for (const [name, preset] of Object.entries(STREAM_PRESETS)) {
341
+ if (
342
+ preset.maxSize === scrcpyConfig.maxSize &&
343
+ preset.bitrate === scrcpyConfig.bitrate &&
344
+ preset.maxFps === scrcpyConfig.maxFps
345
+ ) {
346
+ streamPreset = name;
347
+ break;
348
+ }
349
+ }
350
+
351
+ async function setStreamQuality(preset) {
352
+ const name = String(preset || '').toLowerCase();
353
+ const config = STREAM_PRESETS[name];
354
+ if (!config) throw new Error(`unknown stream preset: ${preset || '(missing)'}`);
355
+ scrcpyConfig.maxSize = config.maxSize;
356
+ scrcpyConfig.bitrate = config.bitrate;
357
+ scrcpyConfig.maxFps = config.maxFps;
358
+ streamPreset = name;
359
+ const wasActive = Boolean(scrcpyState && scrcpyState.session && scrcpyState.session.state === 'running');
360
+ if (wasActive) await stopScrcpy();
361
+ return {
362
+ ok: true,
363
+ preset: name,
364
+ maxSize: config.maxSize,
365
+ bitrate: config.bitrate,
366
+ maxFps: config.maxFps,
367
+ restarted: wasActive,
368
+ };
369
+ }
321
370
  let scrcpyState = null;
322
371
  let scrcpyIdleTimer = null;
323
372
  let scrcpyInitClients = null; // WeakSet of clients that already got the init JSON
@@ -427,6 +476,9 @@ export function apply(ctx, config = {}) {
427
476
  clients: st ? st.clients.size : 0,
428
477
  fps: st ? st.fps : 0,
429
478
  maxFps: scrcpyConfig.maxFps,
479
+ maxSize: scrcpyConfig.maxSize,
480
+ bitrate: scrcpyConfig.bitrate,
481
+ preset: streamPreset,
430
482
  width: st && st.dims ? st.dims.width : null,
431
483
  height: st && st.dims ? st.dims.height : null,
432
484
  error: st && st.lastError ? String(st.lastError.message || st.lastError) : null,
@@ -612,12 +664,23 @@ export function apply(ctx, config = {}) {
612
664
  let apkPath;
613
665
  if (options.trustedPath === true) {
614
666
  apkPath = path.resolve(String(candidate || ''));
615
- if (!/\.(?:apk|apks|xapk)$/i.test(apkPath) || !existsSync(apkPath)) {
667
+ if (!/\.(?:apk|apks|xapk|aab)$/i.test(apkPath) || !existsSync(apkPath)) {
616
668
  throw new Error(`uploaded APK/bundle is missing or invalid: ${apkPath}`);
617
669
  }
618
670
  } else {
619
671
  apkPath = resolveApkPath(candidate, rootsFor());
620
672
  }
673
+ if (/\.aab$/i.test(apkPath)) {
674
+ const built = await buildApksFromAab({
675
+ aabPath: apkPath,
676
+ outDir: path.join(os.tmpdir(), 'dsh-apk-vm-aab'),
677
+ mode: 'universal',
678
+ bundletoolPath: options.bundletoolPath,
679
+ javaPath: options.javaPath,
680
+ });
681
+ if (!built.ok) throw new Error(built.error || 'AAB conversion failed; install bundletool and retry');
682
+ apkPath = built.apksPath;
683
+ }
621
684
  const status = await vm.status();
622
685
  if (!isReady(status)) throw new Error(`VM is not ready (state: ${status.state}); start it first`);
623
686
  const meta = await vm.installApk(apkPath);
@@ -747,6 +810,7 @@ export function apply(ctx, config = {}) {
747
810
  maybeAutoStart(status);
748
811
  return {
749
812
  ok: true,
813
+ pluginVersion: PLUGIN_VERSION,
750
814
  vm: {
751
815
  state: status.state,
752
816
  serial: status.serial || null,
@@ -980,7 +1044,7 @@ export function apply(ctx, config = {}) {
980
1044
  return;
981
1045
  }
982
1046
  if (action === 'install-image') {
983
- if (cfg.allowSetupDownloads !== true) {
1047
+ if (cfg.allowSetupDownloads !== true && body.confirmDownload !== true) {
984
1048
  sendError(res, 403, 'downloading Android system images is disabled; set allowSetupDownloads: true to enable it');
985
1049
  return;
986
1050
  }
@@ -994,7 +1058,7 @@ export function apply(ctx, config = {}) {
994
1058
  return;
995
1059
  }
996
1060
  if (action === 'install-tools') {
997
- if (cfg.allowSetupDownloads !== true) {
1061
+ if (cfg.allowSetupDownloads !== true && body.confirmDownload !== true) {
998
1062
  sendError(res, 403, 'downloading Android SDK components is disabled; set allowSetupDownloads: true to enable it');
999
1063
  return;
1000
1064
  }
@@ -1013,7 +1077,7 @@ export function apply(ctx, config = {}) {
1013
1077
  return;
1014
1078
  }
1015
1079
  if (action === 'bootstrap-sdk') {
1016
- if (cfg.allowSetupDownloads !== true) {
1080
+ if (cfg.allowSetupDownloads !== true && body.confirmDownload !== true) {
1017
1081
  sendError(res, 403, 'downloading Android SDK components is disabled; set allowSetupDownloads: true to enable it');
1018
1082
  return;
1019
1083
  }
@@ -1127,6 +1191,7 @@ export function apply(ctx, config = {}) {
1127
1191
  }
1128
1192
  return {
1129
1193
  ok: true,
1194
+ pluginVersion: PLUGIN_VERSION,
1130
1195
  instance: { id: instance.id, kind: 'extra', avdName: instance.avdName, port: instance.port },
1131
1196
  vm: {
1132
1197
  state: status.state,
@@ -1224,6 +1289,27 @@ export function apply(ctx, config = {}) {
1224
1289
  });
1225
1290
  return;
1226
1291
  }
1292
+ if (rest === 'snapshots') {
1293
+ if (req.method === 'GET') {
1294
+ sendJson(res, 200, instance.vm.listNamedSnapshots());
1295
+ return;
1296
+ }
1297
+ if (req.method !== 'POST') {
1298
+ sendError(res, 405, 'GET or POST only');
1299
+ return;
1300
+ }
1301
+ const body = await readJsonBody(req);
1302
+ const action = String(body.action || '').toLowerCase();
1303
+ try {
1304
+ if (action === 'save') sendJson(res, 200, await instance.vm.saveNamedSnapshot(body.name));
1305
+ else if (action === 'load') sendJson(res, 200, await instance.vm.loadNamedSnapshot(body.name));
1306
+ else if (action === 'delete') sendJson(res, 200, await instance.vm.deleteNamedSnapshot(body.name));
1307
+ else throw new Error(`unsupported snapshot action: ${action || '(missing)'}`);
1308
+ } catch (error) {
1309
+ sendError(res, 400, error.message);
1310
+ }
1311
+ return;
1312
+ }
1227
1313
  if (rest === 'network') {
1228
1314
  if (!(await ready())) return;
1229
1315
  if (req.method === 'GET') {
@@ -1318,7 +1404,7 @@ export function apply(ctx, config = {}) {
1318
1404
  name = 'upload.apk';
1319
1405
  }
1320
1406
  name = path.basename(name).replace(/[^A-Za-z0-9._-]+/g, '_') || 'upload.apk';
1321
- if (!/\.apk$/i.test(name)) name += '.apk';
1407
+ if (!/\.(?:apk|aab)$/i.test(name)) name += '.apk';
1322
1408
  const data = await readRawBody(req, UPLOAD_LIMIT_BYTES);
1323
1409
  if (data.length < 4 || data[0] !== 0x50 || data[1] !== 0x4b) {
1324
1410
  sendError(res, 400, 'uploaded file is not a ZIP/APK');
@@ -1443,6 +1529,10 @@ export function apply(ctx, config = {}) {
1443
1529
  if (action === 'force-stop') result = await instance.forceStop(body.packageName);
1444
1530
  else if (action === 'clear-data') result = await instance.clearData(body.packageName);
1445
1531
  else if (action === 'uninstall') result = await instance.uninstall(body.packageName);
1532
+ else if (action === 'launch') result = await instance.vm.launchPackage(body.packageName, body.activity);
1533
+ else if (action === 'open-url') result = await instance.vm.openUrl(body.url);
1534
+ else if (action === 'grant') result = await instance.vm.setPermission(body.packageName, body.permission, true);
1535
+ else if (action === 'revoke') result = await instance.vm.setPermission(body.packageName, body.permission, false);
1446
1536
  else {
1447
1537
  sendError(res, 400, `unsupported debug action: ${action || '(missing)'}`);
1448
1538
  return;
@@ -1509,6 +1599,7 @@ export function apply(ctx, config = {}) {
1509
1599
  'flows',
1510
1600
  'network',
1511
1601
  'network/pcap',
1602
+ 'snapshots',
1512
1603
  ];
1513
1604
  const disposers = [];
1514
1605
  for (const suffix of suffixes) {
@@ -1698,6 +1789,65 @@ export function apply(ctx, config = {}) {
1698
1789
  sendJson(res, 200, { ok: true, attached: serial, vm: await vm.status(), devices: await vm.listDevices() });
1699
1790
  });
1700
1791
 
1792
+ register('/apk-vm/remote', async (req, res) => {
1793
+ if (req.method === 'GET') {
1794
+ sendJson(res, 200, { ok: true, tunnel: remoteTunnel ? remoteTunnel.status() : null });
1795
+ return;
1796
+ }
1797
+ if (req.method !== 'POST') {
1798
+ sendError(res, 405, 'GET or POST only');
1799
+ return;
1800
+ }
1801
+ const body = await readJsonBody(req);
1802
+ const action = String(body.action || 'connect').toLowerCase();
1803
+ try {
1804
+ if (action === 'disconnect') {
1805
+ if (remoteTunnel) {
1806
+ await remoteTunnel.stop();
1807
+ remoteTunnel = null;
1808
+ }
1809
+ await stopScrcpy();
1810
+ await vm.detachDevice();
1811
+ frame.buffer = null;
1812
+ frame.at = 0;
1813
+ sendJson(res, 200, { ok: true, detached: true, tunnel: null, vm: await vm.status() });
1814
+ return;
1815
+ }
1816
+ if (action !== 'connect') throw new Error(`unsupported remote action: ${action}`);
1817
+ if (remoteTunnel) {
1818
+ await remoteTunnel.stop();
1819
+ remoteTunnel = null;
1820
+ }
1821
+ const tunnel = new SshAdbTunnel({
1822
+ host: body.host,
1823
+ user: body.user,
1824
+ port: body.sshPort,
1825
+ keyPath: body.keyPath,
1826
+ remotePort: body.remotePort,
1827
+ localPort: body.localPort,
1828
+ sshPath: body.sshPath,
1829
+ });
1830
+ const started = await tunnel.start().catch(async (error) => {
1831
+ await tunnel.stop();
1832
+ throw error;
1833
+ });
1834
+ remoteTunnel = tunnel;
1835
+ try {
1836
+ await stopScrcpy();
1837
+ await vm.attachDevice(started.serial);
1838
+ } catch (error) {
1839
+ await tunnel.stop();
1840
+ remoteTunnel = null;
1841
+ throw error;
1842
+ }
1843
+ frame.buffer = null;
1844
+ frame.at = 0;
1845
+ sendJson(res, 200, { ok: true, tunnel: tunnel.status(), vm: await vm.status() });
1846
+ } catch (error) {
1847
+ sendError(res, 400, error.message);
1848
+ }
1849
+ });
1850
+
1701
1851
  register('/apk-vm/vm', async (req, res) => {
1702
1852
  if (req.method !== 'POST') {
1703
1853
  sendError(res, 405, 'POST only');
@@ -1781,7 +1931,7 @@ export function apply(ctx, config = {}) {
1781
1931
  }
1782
1932
  let safeName = path.basename(rawName || 'upload.apk').replace(/[^A-Za-z0-9._-]+/g, '_');
1783
1933
  if (!safeName) safeName = 'upload.apk';
1784
- if (!/\.(?:apk|apks|xapk)$/i.test(safeName)) safeName += '.apk';
1934
+ if (!/\.(?:apk|apks|xapk|aab)$/i.test(safeName)) safeName += '.apk';
1785
1935
  let data;
1786
1936
  try {
1787
1937
  data = await readRawBody(req, UPLOAD_LIMIT_BYTES);
@@ -1930,6 +2080,19 @@ export function apply(ctx, config = {}) {
1930
2080
  sendJson(res, 200, { ok: true, fps: streamFps });
1931
2081
  });
1932
2082
 
2083
+ register('/apk-vm/stream/quality', async (req, res) => {
2084
+ if (req.method !== 'POST') {
2085
+ sendError(res, 405, 'POST only');
2086
+ return;
2087
+ }
2088
+ const body = await readJsonBody(req);
2089
+ try {
2090
+ sendJson(res, 200, await setStreamQuality(body.preset));
2091
+ } catch (error) {
2092
+ sendError(res, 400, error.message);
2093
+ }
2094
+ });
2095
+
1933
2096
  /* ---- rooted debug surface ---------------------------------------- *
1934
2097
  * These routes (and the `apk_vm` Agent tool) expose the guest's root
1935
2098
  * shell and low-level device operations to DSH. They are local-only,
@@ -2000,6 +2163,43 @@ export function apply(ctx, config = {}) {
2000
2163
  sendError(res, 405, 'GET or POST only');
2001
2164
  });
2002
2165
 
2166
+ register('/apk-vm/ui-test', async (req, res) => {
2167
+ if (req.method !== 'POST') {
2168
+ sendError(res, 405, 'POST only');
2169
+ return;
2170
+ }
2171
+ if (!(await ensureDebugReady(res))) return;
2172
+ const body = await readJsonBody(req);
2173
+ const name = String(body.name || 'ui-check').slice(0, 80);
2174
+ const started = Date.now();
2175
+ try {
2176
+ const dump = await vm.uiDump();
2177
+ const assertions = runAssertions(dump.xml, Array.isArray(body.assertions) ? body.assertions : []);
2178
+ const png = await vm.screenshot();
2179
+ const visual = await compareScreenshot(
2180
+ png,
2181
+ path.join(os.tmpdir(), 'dsh-apk-vm-baselines'),
2182
+ name,
2183
+ { update: body.updateBaseline === true },
2184
+ );
2185
+ const report = createTestReport({
2186
+ name,
2187
+ instanceId: 'default',
2188
+ assertions,
2189
+ visual,
2190
+ durationMs: Date.now() - started,
2191
+ });
2192
+ const reportBody = report && report.report ? report.report : report;
2193
+ sendJson(res, 200, {
2194
+ ok: assertions.ok !== false && visual.ok !== false,
2195
+ report: reportBody,
2196
+ markdown: (report && report.markdown) || reportMarkdown(reportBody),
2197
+ });
2198
+ } catch (error) {
2199
+ sendError(res, 400, error.message);
2200
+ }
2201
+ });
2202
+
2003
2203
  register('/apk-vm/debug/packages', async (req, res) => {
2004
2204
  if (req.method !== 'GET') {
2005
2205
  sendError(res, 405, 'GET only');
@@ -2065,6 +2265,10 @@ export function apply(ctx, config = {}) {
2065
2265
  if (action === 'force-stop') result = await vm.forceStop(packageName);
2066
2266
  else if (action === 'clear-data') result = await vm.clearData(packageName);
2067
2267
  else if (action === 'uninstall') result = await vm.uninstall(packageName);
2268
+ else if (action === 'launch') result = await vm.launchPackage(packageName, body.activity);
2269
+ else if (action === 'open-url') result = await vm.openUrl(body.url);
2270
+ else if (action === 'grant') result = await vm.setPermission(packageName, body.permission, true);
2271
+ else if (action === 'revoke') result = await vm.setPermission(packageName, body.permission, false);
2068
2272
  else {
2069
2273
  sendError(res, 400, `unsupported debug action: ${action || '(missing)'}`);
2070
2274
  return;
@@ -2072,6 +2276,27 @@ export function apply(ctx, config = {}) {
2072
2276
  sendJson(res, 200, { ok: result.ok === true, action, result });
2073
2277
  });
2074
2278
 
2279
+ register('/apk-vm/snapshots', async (req, res) => {
2280
+ if (req.method === 'GET') {
2281
+ sendJson(res, 200, vm.listNamedSnapshots());
2282
+ return;
2283
+ }
2284
+ if (req.method !== 'POST') {
2285
+ sendError(res, 405, 'GET or POST only');
2286
+ return;
2287
+ }
2288
+ const body = await readJsonBody(req);
2289
+ const action = String(body.action || '').toLowerCase();
2290
+ try {
2291
+ if (action === 'save') sendJson(res, 200, await vm.saveNamedSnapshot(body.name));
2292
+ else if (action === 'load') sendJson(res, 200, await vm.loadNamedSnapshot(body.name));
2293
+ else if (action === 'delete') sendJson(res, 200, await vm.deleteNamedSnapshot(body.name));
2294
+ else throw new Error(`unsupported snapshot action: ${action || '(missing)'}`);
2295
+ } catch (error) {
2296
+ sendError(res, 400, error.message);
2297
+ }
2298
+ });
2299
+
2075
2300
  register('/apk-vm/debug/rotate', async (req, res) => {
2076
2301
  if (req.method !== 'POST') {
2077
2302
  sendError(res, 405, 'POST only');
@@ -2143,6 +2368,37 @@ export function apply(ctx, config = {}) {
2143
2368
  }
2144
2369
  });
2145
2370
 
2371
+ register('/apk-vm/network/har', async (req, res) => {
2372
+ if (req.method !== 'POST') {
2373
+ sendError(res, 405, 'POST only');
2374
+ return;
2375
+ }
2376
+ const body = await readJsonBody(req);
2377
+ try {
2378
+ const loaded = await readHarFile(body.path);
2379
+ const entries = filterHar(loaded.entries, {
2380
+ method: body.method,
2381
+ status: body.status,
2382
+ domain: body.domain,
2383
+ search: body.search,
2384
+ });
2385
+ const sliced = entries.slice(0, 500).map((entry) => ({
2386
+ ...entry,
2387
+ curl: toCurl(entry),
2388
+ }));
2389
+ sendJson(res, 200, {
2390
+ ok: true,
2391
+ path: loaded.file,
2392
+ bytes: loaded.bytes,
2393
+ summary: summarizeHar(loaded.entries),
2394
+ filtered: entries.length,
2395
+ entries: sliced,
2396
+ });
2397
+ } catch (error) {
2398
+ sendError(res, 400, error.message);
2399
+ }
2400
+ });
2401
+
2146
2402
  register('/apk-vm/network', async (req, res) => {
2147
2403
  if (req.method === 'GET') {
2148
2404
  if (!(await ensureDebugReady(res))) return;
@@ -2327,6 +2583,14 @@ export function apply(ctx, config = {}) {
2327
2583
  host.effect(() => mountRoutes(host.webServer), 'dsh-apk-vm: http routes');
2328
2584
  });
2329
2585
 
2586
+ ctx.effect(() => {
2587
+ return () => {
2588
+ const tunnel = remoteTunnel;
2589
+ remoteTunnel = null;
2590
+ if (tunnel) void tunnel.stop().catch(() => {});
2591
+ };
2592
+ }, 'dsh-apk-vm: ssh tunnel');
2593
+
2330
2594
  // Optional warm start: boot the VM right after the plugin activates so the
2331
2595
  // first panel/tab open lands on a running (or nearly booted) device. This is
2332
2596
  // what makes the visible "open the VM" step effectively instant; opt in with