agent-device-x86sim 0.1.1 → 0.1.2

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.
@@ -1,11 +1,12 @@
1
- import { n as isPhoneRunning } from "./system-DMZAX-z7.js";
1
+ import { a as invalidArgument, d as isPhoneRunning, i as WebDriverError, l as createUploads, n as requireActiveSession, o as unknownCommand, r as webDriverRoutes, s as unknownError } from "./routes-Ctumc6oY.js";
2
2
  import path from "node:path";
3
3
  import { access, mkdtemp, readFile, readdir, realpath, rm, unlink } from "node:fs/promises";
4
4
  import { tmpdir, userInfo } from "node:os";
5
5
  import { createConnection, createServer } from "node:net";
6
- import { createHash, randomUUID } from "node:crypto";
6
+ import { createHash } from "node:crypto";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { execFile, spawn } from "node:child_process";
9
+ import { mkdtempSync, rmSync } from "node:fs";
9
10
  import { createServer as createServer$1 } from "node:http";
10
11
  //#region \0rolldown/runtime.js
11
12
  var __defProp = Object.defineProperty;
@@ -179,14 +180,14 @@ function hookSocketNames(files, udid) {
179
180
  return files.filter((file) => pattern.test(file));
180
181
  }
181
182
  const MAX_TREE_DEPTH = 80;
182
- const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
183
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
183
184
  /** The hook answered with a reason instead of a tree, such as accessibility being off in the phone. */
184
185
  var HookRefusedError = class extends Error {};
185
186
  function fail(where, expected) {
186
187
  throw new Error(`Hook reply is malformed at ${where}, expected ${expected}.`);
187
188
  }
188
189
  function parseFrame(value, where) {
189
- if (!isRecord$2(value)) fail(where, "an object with x, y, width and height");
190
+ if (!isRecord(value)) fail(where, "an object with x, y, width and height");
190
191
  const { x, y, width, height } = value;
191
192
  for (const [key, number] of Object.entries({
192
193
  x,
@@ -208,7 +209,7 @@ function parseOptionalString(record, key, where) {
208
209
  return value;
209
210
  }
210
211
  function parseNode(value, where, depth) {
211
- if (!isRecord$2(value)) fail(where, "an element object");
212
+ if (!isRecord(value)) fail(where, "an element object");
212
213
  if (depth > MAX_TREE_DEPTH) fail(where, `a tree no deeper than ${MAX_TREE_DEPTH}`);
213
214
  const { type, enabled, visible, children } = value;
214
215
  if (typeof type !== "string" || !type.startsWith("XCUIElementType")) fail(`${where}.type`, "an XCUIElementType name");
@@ -237,7 +238,7 @@ function parseHookReply(text) {
237
238
  } catch (error) {
238
239
  throw new Error(`Hook reply is not JSON: ${error instanceof Error ? error.message : String(error)}`);
239
240
  }
240
- if (!isRecord$2(json)) fail("the reply", "an object");
241
+ if (!isRecord(json)) fail("the reply", "an object");
241
242
  if (typeof json.error === "string") throw new HookRefusedError(`The hook refused the request: ${json.error}`);
242
243
  const { pid, bundleId, front } = json;
243
244
  if (typeof pid !== "number" || !Number.isInteger(pid)) fail("pid", "an integer");
@@ -250,7 +251,7 @@ function parseHookReply(text) {
250
251
  ...front === null ? { front: null } : {},
251
252
  root
252
253
  };
253
- if (!isRecord$2(front)) fail("front", "null or an object with pid and bundleId");
254
+ if (!isRecord(front)) fail("front", "null or an object with pid and bundleId");
254
255
  if (typeof front.pid !== "number" || !Number.isInteger(front.pid)) fail("front.pid", "an integer");
255
256
  if (typeof front.bundleId !== "string") fail("front.bundleId", "a string");
256
257
  return {
@@ -471,28 +472,6 @@ var X86SimBackend = class {
471
472
  }
472
473
  };
473
474
  //#endregion
474
- //#region ../server/src/errors.ts
475
- /**
476
- * A W3C WebDriver error. `error` is the spec's error code and the HTTP status follows the
477
- * spec's table, so clients can tell "this route does not exist" from "this request is bad".
478
- */
479
- var WebDriverError = class extends Error {
480
- error;
481
- status;
482
- constructor(error, status, message) {
483
- super(message);
484
- this.name = "WebDriverError";
485
- this.error = error;
486
- this.status = status;
487
- }
488
- };
489
- const unknownCommand = (message) => new WebDriverError("unknown command", 404, message);
490
- const invalidArgument = (message) => new WebDriverError("invalid argument", 400, message);
491
- const invalidSessionId = (id) => new WebDriverError("invalid session id", 404, `No active session with id ${id}`);
492
- const sessionNotCreated = (message) => new WebDriverError("session not created", 500, message);
493
- const unsupportedOperation = (message) => new WebDriverError("unsupported operation", 500, message);
494
- const unknownError = (message) => new WebDriverError("unknown error", 500, message);
495
- //#endregion
496
475
  //#region ../server/src/router.ts
497
476
  const isReply = (result) => typeof result === "object" && result !== null && "reply" in result;
498
477
  function compile(route) {
@@ -528,312 +507,15 @@ function createRouter(routes) {
528
507
  } };
529
508
  }
530
509
  //#endregion
531
- //#region ../server/src/actions.ts
532
- /** How often an interpolated drag reports a position. 16 ms is about one display frame. */
533
- const MOVE_STEP_MS = 16;
534
- const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
535
- function parsePointerAction(raw) {
536
- if (!isRecord$1(raw)) throw invalidArgument("Pointer action must be an object.");
537
- const duration = raw.duration;
538
- if (duration !== void 0 && (typeof duration !== "number" || !(duration >= 0))) throw invalidArgument("Pointer action duration must be a non-negative number.");
539
- switch (raw.type) {
540
- case "pointerMove":
541
- if (typeof raw.x !== "number" || typeof raw.y !== "number") throw invalidArgument("pointerMove needs numeric x and y.");
542
- if (raw.origin !== void 0 && raw.origin !== "viewport") throw invalidArgument("Only the viewport pointer origin is supported.");
543
- return {
544
- type: "pointerMove",
545
- x: raw.x,
546
- y: raw.y,
547
- ...duration === void 0 ? {} : { duration }
548
- };
549
- case "pointerDown":
550
- case "pointerUp": return { type: raw.type };
551
- case "pause": return {
552
- type: "pause",
553
- ...duration === void 0 ? {} : { duration }
554
- };
555
- default: throw invalidArgument(`Unsupported pointer action type: ${String(raw.type)}`);
556
- }
557
- }
558
- /** The boundary: untrusted `POST /actions` body to typed sequences. */
559
- function parseActions(body) {
560
- if (!isRecord$1(body) || !Array.isArray(body.actions)) throw invalidArgument("Request body needs an \"actions\" array.");
561
- return body.actions.map((raw) => {
562
- if (!isRecord$1(raw) || typeof raw.id !== "string" || !Array.isArray(raw.actions)) throw invalidArgument("Each action sequence needs a string id and an actions array.");
563
- if (raw.type === "pointer") {
564
- const parameters = isRecord$1(raw.parameters) ? raw.parameters : void 0;
565
- return {
566
- type: "pointer",
567
- id: raw.id,
568
- ...parameters ? { parameters } : {},
569
- actions: raw.actions.map(parsePointerAction)
570
- };
571
- }
572
- if (raw.type === "key" || raw.type === "none" || raw.type === "wheel") return {
573
- type: raw.type,
574
- id: raw.id,
575
- actions: raw.actions
576
- };
577
- throw invalidArgument(`Unsupported action source type: ${String(raw.type)}`);
578
- });
579
- }
580
- function lerp(from, to, t) {
581
- return {
582
- x: from.x + (to.x - from.x) * t,
583
- y: from.y + (to.y - from.y) * t
584
- };
585
- }
586
- /**
587
- * Flattens W3C pointer actions to the single-finger touch stream a simhid-style device takes.
588
- *
589
- * - The pointer starts at (0, 0), as in the spec, and `pointerMove` outside a press only
590
- * repositions it, so a tap is `down` and `up` at the last position.
591
- * - A timed drag becomes `move` steps every 16 ms, so the device sees a gesture with velocity
592
- * rather than a jump after a wait.
593
- * - A timed move outside a press becomes a `pause`.
594
- * - Key, none and wheel sources are ignored here. A second pointer sequence is refused,
595
- * because one touch point cannot play two fingers.
596
- */
597
- function toTouchEvents(sequences) {
598
- const pointers = sequences.filter((sequence) => sequence.type === "pointer");
599
- if (pointers.length > 1) throw unsupportedOperation("Multi-pointer actions are not supported by this touch backend.");
600
- const pointer = pointers[0];
601
- if (pointer?.type !== "pointer") return [];
602
- const events = [];
603
- let position = {
604
- x: 0,
605
- y: 0
606
- };
607
- let pressed = false;
608
- for (const action of pointer.actions) switch (action.type) {
609
- case "pointerMove": {
610
- const target = {
611
- x: action.x,
612
- y: action.y
613
- };
614
- const duration = action.duration ?? 0;
615
- if (!pressed) {
616
- if (duration > 0) events.push({
617
- kind: "pause",
618
- ms: duration
619
- });
620
- } else if (duration <= MOVE_STEP_MS) events.push({
621
- kind: "move",
622
- at: target
623
- });
624
- else {
625
- const steps = Math.ceil(duration / MOVE_STEP_MS);
626
- for (let step = 1; step <= steps; step += 1) {
627
- events.push({
628
- kind: "pause",
629
- ms: duration / steps
630
- });
631
- events.push({
632
- kind: "move",
633
- at: step === steps ? target : lerp(position, target, step / steps)
634
- });
635
- }
636
- }
637
- position = target;
638
- break;
639
- }
640
- case "pointerDown":
641
- if (!pressed) events.push({
642
- kind: "down",
643
- at: position
644
- });
645
- pressed = true;
646
- break;
647
- case "pointerUp":
648
- if (pressed) events.push({
649
- kind: "up",
650
- at: position
651
- });
652
- pressed = false;
653
- break;
654
- case "pause": if ((action.duration ?? 0) > 0) events.push({
655
- kind: "pause",
656
- ms: action.duration ?? 0
657
- });
658
- }
659
- return events;
660
- }
661
- //#endregion
662
- //#region ../server/src/xcui-source.ts
663
- const XML_ESCAPES = {
664
- "&": "&amp;",
665
- "<": "&lt;",
666
- ">": "&gt;",
667
- "\"": "&quot;",
668
- "'": "&apos;",
669
- "\n": "&#10;",
670
- "\r": "&#13;",
671
- " ": "&#9;"
672
- };
673
- function escapeAttribute(value) {
674
- return value.replace(/[&<>"'\n\r\t]/g, (char) => XML_ESCAPES[char] ?? char);
675
- }
676
- function attributes(node) {
677
- return [
678
- ["type", node.type],
679
- ["name", node.name],
680
- ["label", node.label],
681
- ["value", node.value],
682
- ["enabled", String(node.enabled)],
683
- ["visible", String(node.visible)],
684
- ["x", String(node.frame.x)],
685
- ["y", String(node.frame.y)],
686
- ["width", String(node.frame.width)],
687
- ["height", String(node.frame.height)]
688
- ].flatMap(([key, value]) => value === void 0 ? [] : [`${key}="${escapeAttribute(value)}"`]).join(" ");
689
- }
690
- function element(node, depth) {
691
- const indent = " ".repeat(depth);
692
- const open = `${indent}<${node.type} ${attributes(node)}`;
693
- if (node.children.length === 0) return `${open} />`;
694
- return `${open}>\n${node.children.map((child) => element(child, depth + 1)).join("\n")}\n${indent}</${node.type}>`;
695
- }
696
- /**
697
- * The XCUITest page source shape: an `AppiumAUT` wrapper around the element tree, one tag per
698
- * element named by its XCUIElementType, with geometry as `x`, `y`, `width` and `height`.
699
- * Absent `name`, `label` and `value` are omitted, as XCUITest omits null attributes.
700
- */
701
- function toXcuiSource(root) {
702
- return `<?xml version="1.0" encoding="UTF-8"?>\n<AppiumAUT>\n${element(root, 1)}\n</AppiumAUT>`;
703
- }
704
- //#endregion
705
- //#region ../server/src/routes.ts
706
- const SESSION_PREFIX = "/session/:sessionId";
707
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
708
- function requireString(body, ...keys) {
709
- if (isRecord(body)) for (const key of keys) {
710
- const value = body[key];
711
- if (typeof value === "string" && value.length > 0) return value;
712
- }
713
- throw invalidArgument(`Request body needs a string "${keys.join("\" or \"")}".`);
714
- }
715
- const HARDWARE_BUTTONS = {
716
- home: "home",
717
- volumeup: "volumeUp",
718
- volumedown: "volumeDown"
719
- };
720
- /** The `mobile:` scripts of XCUITest that this server answers. Others are `unknown command`. */
721
- const MOBILE_SCRIPTS = {
722
- "mobile: pressButton": async (backend, args) => {
723
- const button = HARDWARE_BUTTONS[String(args.name).toLowerCase()];
724
- if (!button) throw invalidArgument(`Unsupported hardware button: ${String(args.name)}`);
725
- await backend.pressButton(button);
726
- return null;
727
- },
728
- "mobile: deepLink": async (backend, args) => {
729
- await backend.openUrl(requireString(args, "url"));
730
- return null;
731
- },
732
- "mobile: activateApp": async (backend, args) => {
733
- await backend.launchApp(requireString(args, "bundleId", "appId"));
734
- return null;
735
- },
736
- "mobile: terminateApp": async (backend, args) => {
737
- await backend.terminateApp(requireString(args, "bundleId", "appId"));
738
- return true;
739
- }
740
- };
741
- function windowRect(backend) {
742
- return backend.screen().then((size) => ({
743
- x: 0,
744
- y: 0,
745
- ...size
746
- }));
747
- }
748
- /** The WebDriver and Appium routes this server implements. */
749
- function webDriverRoutes(backend, sessions) {
750
- const inSession = (method, suffix, handler) => ({
751
- method,
752
- path: `${SESSION_PREFIX}${suffix}`,
753
- handler
754
- });
755
- return [
756
- {
757
- method: "GET",
758
- path: "/status",
759
- handler: async () => ({
760
- ready: true,
761
- message: "x86sim-webdriver ready"
762
- })
763
- },
764
- {
765
- method: "POST",
766
- path: "/session",
767
- handler: async ({ body }) => {
768
- if (sessions.current) throw sessionNotCreated(`Session ${sessions.current.id} is still active.`);
769
- const requested = isRecord(body) && isRecord(body.capabilities) ? body.capabilities : {};
770
- const alwaysMatch = isRecord(requested.alwaysMatch) ? requested.alwaysMatch : {};
771
- const session = {
772
- id: randomUUID(),
773
- capabilities: {
774
- ...alwaysMatch,
775
- platformName: "iOS",
776
- "appium:automationName": "XCUITest"
777
- }
778
- };
779
- sessions.current = session;
780
- return {
781
- sessionId: session.id,
782
- capabilities: session.capabilities
783
- };
784
- }
785
- },
786
- inSession("DELETE", "", async ({ params }) => {
787
- if (sessions.current?.id === params.sessionId) sessions.current = void 0;
788
- return null;
789
- }),
790
- inSession("GET", "/source", async () => toXcuiSource(await backend.accessibilityTree())),
791
- inSession("GET", "/screenshot", async () => (await backend.screenshot()).toString("base64")),
792
- inSession("GET", "/window/rect", async () => await windowRect(backend)),
793
- inSession("POST", "/actions", async ({ body }) => {
794
- const events = toTouchEvents(parseActions(body));
795
- if (events.length > 0) await backend.touch(events);
796
- return null;
797
- }),
798
- inSession("DELETE", "/actions", async () => null),
799
- inSession("POST", "/keys", async ({ body }) => {
800
- const value = isRecord(body) ? body.value : void 0;
801
- if (!Array.isArray(value)) throw invalidArgument("Request body needs a \"value\" array.");
802
- await backend.typeText(value.map(String).join(""));
803
- return null;
804
- }),
805
- inSession("POST", "/appium/device/install_app", async ({ body }) => {
806
- await backend.installApp(requireString(body, "appPath"));
807
- return null;
808
- }),
809
- inSession("POST", "/appium/device/activate_app", async ({ body }) => {
810
- await backend.launchApp(requireString(body, "appId", "bundleId"));
811
- return null;
812
- }),
813
- inSession("POST", "/appium/device/terminate_app", async ({ body }) => {
814
- await backend.terminateApp(requireString(body, "appId", "bundleId"));
815
- return true;
816
- }),
817
- inSession("POST", "/execute/sync", async ({ body }) => {
818
- const script = requireString(body, "script");
819
- const handler = MOBILE_SCRIPTS[script];
820
- if (!handler) throw unknownCommand(`Unknown mobile command: ${script}`);
821
- const args = isRecord(body) && Array.isArray(body.args) ? body.args[0] : void 0;
822
- return await handler(backend, isRecord(args) ? args : {});
823
- })
824
- ];
825
- }
826
- function requireActiveSession(sessions, id) {
827
- if (sessions.current?.id !== id) throw invalidSessionId(id);
828
- return sessions.current;
829
- }
830
- //#endregion
831
510
  //#region ../server/src/server.ts
832
511
  const BODY_LOG_LIMIT = 160;
833
- async function readJson(request) {
512
+ async function readBytes(request) {
834
513
  const chunks = [];
835
514
  for await (const chunk of request) chunks.push(chunk);
836
- const text = Buffer.concat(chunks).toString("utf8");
515
+ return Buffer.concat(chunks);
516
+ }
517
+ function parseJson(bytes) {
518
+ const text = bytes.toString("utf8");
837
519
  if (text.length === 0) return void 0;
838
520
  try {
839
521
  return JSON.parse(text);
@@ -862,22 +544,27 @@ function errorReply(error) {
862
544
  }
863
545
  function bodySummary(body) {
864
546
  if (body === void 0) return "";
547
+ if (Buffer.isBuffer(body)) return ` <${body.length} bytes>`;
865
548
  const text = JSON.stringify(body);
866
549
  return ` ${text.length > BODY_LOG_LIMIT ? `${text.slice(0, BODY_LOG_LIMIT)}...` : text}`;
867
550
  }
868
551
  function createServer$2(options) {
869
552
  const sessions = { current: void 0 };
870
- const router = createRouter([...webDriverRoutes(options.backend, sessions), ...options.extraRoutes ?? []]);
553
+ const ownUploadDir = options.uploadDir === void 0;
554
+ const uploadDir = options.uploadDir ?? mkdtempSync(path.join(tmpdir(), "agent-device-x86sim-uploads-"));
555
+ const uploads = createUploads(uploadDir);
556
+ const router = createRouter([...webDriverRoutes(options.backend, sessions, uploads), ...options.extraRoutes ?? []]);
871
557
  const log = options.log ?? ((line) => process.stderr.write(`${line}\n`));
872
- return createServer$1(async (request, response) => {
558
+ const server = createServer$1(async (request, response) => {
873
559
  const started = Date.now();
874
560
  const method = request.method ?? "GET";
875
561
  const { pathname } = new URL(request.url ?? "/", "http://localhost");
876
562
  let body;
877
563
  let reply;
878
564
  try {
879
- body = await readJson(request);
565
+ const bytes = await readBytes(request);
880
566
  const { route, params } = router.match(method, pathname);
567
+ body = route.body === "bytes" ? bytes : parseJson(bytes);
881
568
  if (params.sessionId !== void 0) requireActiveSession(sessions, params.sessionId);
882
569
  const result = await route.handler({
883
570
  params,
@@ -893,6 +580,11 @@ function createServer$2(options) {
893
580
  send(response, reply.status, reply.json);
894
581
  log(`${method} ${pathname} -> ${reply.status} ${Date.now() - started}ms${bodySummary(body)}`);
895
582
  });
583
+ if (ownUploadDir) server.once("close", () => rmSync(uploadDir, {
584
+ recursive: true,
585
+ force: true
586
+ }));
587
+ return server;
896
588
  }
897
589
  //#endregion
898
590
  //#region src/cli/accessibility-prefs.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-device-x86sim",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Run an iOS simulator on Linux through x86Sim and drive it with agent-device. One package: the agent-device plugin and the `agent-device-x86sim` command.",
5
5
  "keywords": [
6
6
  "agent-device",
@@ -36,12 +36,18 @@
36
36
  "import": "./dist/index.js"
37
37
  }
38
38
  },
39
+ "scripts": {
40
+ "build": "vp pack",
41
+ "dev": "vp pack --watch",
42
+ "test": "vp test",
43
+ "prepack": "cp ../../README.md ../../LICENSE ."
44
+ },
39
45
  "devDependencies": {
40
- "@types/node": "^22.20.5",
41
- "agent-device": "0.21.35",
42
- "typescript": "^7.0.2",
43
- "vite": "npm:@voidzero-dev/vite-plus-core@0.3.3",
44
- "vite-plus": "0.3.3"
46
+ "@types/node": "catalog:",
47
+ "agent-device": "catalog:",
48
+ "typescript": "catalog:",
49
+ "vite": "catalog:",
50
+ "vite-plus": "catalog:"
45
51
  },
46
52
  "peerDependencies": {
47
53
  "agent-device": ">=0.21.35"
@@ -53,10 +59,5 @@
53
59
  },
54
60
  "engines": {
55
61
  "node": ">=22.18.0"
56
- },
57
- "scripts": {
58
- "build": "vp pack",
59
- "dev": "vp pack --watch",
60
- "test": "vp test"
61
62
  }
62
- }
63
+ }
@@ -1,203 +0,0 @@
1
- import path from "node:path";
2
- import { access, constants, readFile, readdir, readlink, realpath } from "node:fs/promises";
3
- import { homedir } from "node:os";
4
- import { createConnection } from "node:net";
5
- //#region src/cli/install.ts
6
- const BOOT_SCRIPT = "cli/libexec/arm64/boot-a64.sh";
7
- /** Where x86Sim copies itself and keeps phones, as its AppImage decides it. */
8
- const x86simDataDir = (env, home) => env.X86SIM_DATA || path.join(env.XDG_DATA_HOME || path.join(home, ".local", "share"), "x86sim");
9
- /** Where x86Sim keeps its scratch files. */
10
- const x86simCacheDir = (env, home) => env.X86SIM_CACHE || path.join(env.XDG_CACHE_HOME || path.join(home, ".cache"), "x86sim");
11
- const versionParts = (version) => version.split(/[.-]/).map((part) => /^\d+$/.test(part) ? Number(part) : -1);
12
- /** Compares versions part by part. A part that is not a number, such as `pre8`, sorts below a missing one. */
13
- function compareVersions(a, b) {
14
- const left = versionParts(a);
15
- const right = versionParts(b);
16
- for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
17
- const difference = (left[index] ?? 0) - (right[index] ?? 0);
18
- if (difference !== 0) return difference;
19
- }
20
- return 0;
21
- }
22
- const newestVersion = (versions) => [...versions].sort(compareVersions).at(-1);
23
- /**
24
- * x86Sim's AppImage copies its payload into the data folder, and phones run from there after
25
- * the launcher exits. This runs the copy the way the AppImage's `AppRun` would, with the same
26
- * environment.
27
- */
28
- function dataDirInstall(parts) {
29
- const app = path.join(parts.dataDir, "app", parts.version);
30
- const env = {
31
- X86SIM_DARLING_MODE: parts.darlingMode,
32
- X86SIM_ROOT: parts.dataDir,
33
- X86SIM_SCRATCH: parts.cacheDir,
34
- X86SIM_APP: app,
35
- X86SIM_VERSION: parts.version,
36
- X86SIM_DARLING_ID: parts.darlingId,
37
- X86SIM_PYLIB: path.join(app, "pylib"),
38
- A64_PREFIX_HEAL: "0",
39
- PATH: `${path.join(app, "bin")}:${parts.path}`
40
- };
41
- return {
42
- label: `x86Sim ${parts.version} in ${parts.dataDir}`,
43
- dataDir: parts.dataDir,
44
- cli: (args) => ({
45
- command: path.join(app, "cli", "x86sim"),
46
- args: [...args],
47
- env
48
- }),
49
- boot: () => ({
50
- command: "/bin/sh",
51
- args: ["-c", BOOT_SCRIPT],
52
- env,
53
- cwd: parts.dataDir
54
- })
55
- };
56
- }
57
- /** An AppImage the user named, which runs everything through its own entry point. */
58
- function appImageInstall(appImage, dataDir) {
59
- return {
60
- label: appImage,
61
- dataDir,
62
- cli: (args) => ({
63
- command: appImage,
64
- args: ["x86sim", ...args],
65
- env: {}
66
- }),
67
- boot: () => ({
68
- command: appImage,
69
- args: [
70
- "shell",
71
- "-c",
72
- BOOT_SCRIPT
73
- ],
74
- env: {}
75
- })
76
- };
77
- }
78
- //#endregion
79
- //#region src/cli/discovery.ts
80
- const QUICK_START_URL = "https://github.com/x86sim/x86sim#quick-start";
81
- const DEVICE_PREFIX = "device-a64-";
82
- /** x86Sim has not been set up on this machine. Callers that can run without it catch this one. */
83
- var NotSetUpError = class extends Error {};
84
- /**
85
- * x86Sim as `--appimage` or `$X86SIM_APPIMAGE` names it, else the newest copy in the data
86
- * folder. Running an AppImage copies its payload there, whatever folder the AppImage is in.
87
- */
88
- async function findX86Sim(flag, environment) {
89
- const { env, home, cwd } = environment;
90
- const dataDir = x86simDataDir(env, home);
91
- const given = flag ?? env.X86SIM_APPIMAGE;
92
- if (given) {
93
- const file = path.resolve(cwd, given);
94
- if (!await environment.isExecutable(file)) throw new Error(`The x86Sim AppImage ${file} is missing or not executable. Run: chmod +x ${file}`);
95
- return appImageInstall(file, dataDir);
96
- }
97
- const appDir = path.join(dataDir, "app");
98
- const complete = [];
99
- for (const version of await environment.listDir(appDir)) if ((await environment.listDir(path.join(appDir, version))).includes(".complete")) complete.push(version);
100
- const version = newestVersion(complete);
101
- if (!version) throw new NotSetUpError(`x86Sim is not set up. Follow ${QUICK_START_URL}`);
102
- const mode = env.X86SIM_DARLING_MODE;
103
- const link = await environment.readLink(path.join(dataDir, "darling-prefix"));
104
- return dataDirInstall({
105
- dataDir,
106
- cacheDir: x86simCacheDir(env, home),
107
- version,
108
- darlingId: (await environment.readText(path.join(appDir, version, "DARLING_ID")))?.trim() ?? "",
109
- darlingMode: mode === "system" || mode === "userns" ? mode : link?.includes("darling-userns") ? "userns" : "system",
110
- path: env.PATH ?? ""
111
- });
112
- }
113
- async function listPhones(dataDir, environment) {
114
- const varDir = path.join(dataDir, "var");
115
- const folders = (await environment.listDir(varDir)).filter((name) => name.startsWith(DEVICE_PREFIX)).sort();
116
- return await Promise.all(folders.map(async (folder) => ({
117
- folder,
118
- path: path.join(varDir, folder),
119
- name: (await environment.readText(path.join(varDir, folder, "name")))?.trim() || folder
120
- })));
121
- }
122
- const quoted = (phones) => phones.map((phone) => `"${phone.name}"`).join(", ");
123
- const pick = (phone) => `agent-device connect x86sim --device "${phone.name}"`;
124
- /**
125
- * The phone to use. `--device` names it, by the name the launcher shows or by its folder, or is
126
- * the folder's path. Without it, the phone that runs wins, else the only phone.
127
- */
128
- async function findPhone(flag, dataDir, environment) {
129
- const phones = await listPhones(dataDir, environment);
130
- if (flag?.includes("/")) {
131
- const folder = path.resolve(environment.cwd, flag);
132
- if (!(await environment.listDir(folder)).includes("sim.env")) throw new Error(`${folder} is not a phone folder, because it has no sim.env.`);
133
- return {
134
- folder: path.basename(folder),
135
- path: folder,
136
- name: path.basename(folder)
137
- };
138
- }
139
- if (flag) {
140
- const lower = flag.toLowerCase();
141
- const matches = phones.filter((phone) => phone.folder === flag || phone.name.toLowerCase() === lower);
142
- const [only] = matches;
143
- if (only && matches.length === 1) return only;
144
- if (only) throw new Error(`More than one phone is named "${flag}". Use a folder name: ${matches.map((p) => p.folder).join(", ")}.`);
145
- throw new Error(phones.length === 0 ? `No phone found in ${path.join(dataDir, "var")}. Create one on the Setup page of the x86Sim launcher. ${QUICK_START_URL}` : `No phone is named "${flag}". The phones are ${quoted(phones)}.`);
146
- }
147
- const [first] = phones;
148
- if (!first) throw new Error(`No phone found in ${path.join(dataDir, "var")}. Create one on the Setup page of the x86Sim launcher. ${QUICK_START_URL}`);
149
- const running = [];
150
- for (const phone of phones) if (await environment.isRunning(phone.path)) running.push(phone);
151
- const [firstRunning] = running;
152
- if (firstRunning && running.length === 1) return firstRunning;
153
- if (phones.length === 1) return first;
154
- throw new Error(`${running.length > 1 ? "More than one phone runs" : "There is more than one phone and none runs"}. The phones are ${quoted(running.length > 1 ? running : phones)}. Pick one with ${pick(running[0] ?? first)}.`);
155
- }
156
- //#endregion
157
- //#region src/cli/running.ts
158
- const PROBE_TIMEOUT_MS = 5e3;
159
- /** Whether the phone in this folder runs, which is whether its simhid socket accepts a connection. */
160
- async function isPhoneRunning(device) {
161
- try {
162
- const socketPath = await realpath(path.join(device, "data", "simhid.sock"));
163
- return await new Promise((resolve) => {
164
- const socket = createConnection(socketPath);
165
- const done = (answer) => {
166
- socket.destroy();
167
- resolve(answer);
168
- };
169
- socket.setTimeout(PROBE_TIMEOUT_MS, () => done(false));
170
- socket.once("connect", () => done(true));
171
- socket.once("error", () => done(false));
172
- });
173
- } catch {
174
- return false;
175
- }
176
- }
177
- //#endregion
178
- //#region src/cli/system.ts
179
- /** The machine this process runs on. */
180
- function systemEnvironment() {
181
- return {
182
- env: process.env,
183
- home: homedir(),
184
- cwd: process.cwd(),
185
- listDir: (dir) => readdir(dir).catch(() => []),
186
- readText: (file) => readFile(file, "utf8").catch(() => void 0),
187
- readLink: (file) => readlink(file).catch(() => void 0),
188
- isExecutable: (file) => access(file, constants.X_OK).then(() => true, () => false),
189
- isRunning: isPhoneRunning
190
- };
191
- }
192
- /** The x86Sim and the phone on this machine, or an error that names the fix. */
193
- async function discoverTarget(flags, environment = systemEnvironment()) {
194
- const x86sim = await findX86Sim(flags.appimage, environment);
195
- const phone = await findPhone(flags.device, x86sim.dataDir, environment);
196
- return {
197
- x86sim,
198
- device: phone.path,
199
- deviceName: phone.name
200
- };
201
- }
202
- //#endregion
203
- export { isPhoneRunning as n, NotSetUpError as r, discoverTarget as t };