@rootnative/loupe 0.0.0-alpha.1 → 0.0.0-alpha.3

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,7 +1,7 @@
1
1
  // package.json
2
2
  var package_default = {
3
3
  name: "@rootnative/loupe",
4
- version: "0.0.0-alpha.1",
4
+ version: "0.0.0-alpha.3",
5
5
  description: "loupe by Root Native: layout checks for iOS and Android, built for AI agents. Drive simulators and emulators, and measure every screen to the point.",
6
6
  license: "MIT",
7
7
  author: "Root Native",
@@ -90,22 +90,22 @@ function outputJsonSchema(command) {
90
90
  }
91
91
  var COMMAND_NAME = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
92
92
  function createRegistry(commands) {
93
- const byName = /* @__PURE__ */ new Map();
93
+ const byName2 = /* @__PURE__ */ new Map();
94
94
  for (const command of commands) {
95
95
  if (!COMMAND_NAME.test(command.name)) {
96
96
  throw new Error(
97
97
  `The command name "${command.name}" must be kebab case, for example "open-url".`
98
98
  );
99
99
  }
100
- if (byName.has(command.name)) {
100
+ if (byName2.has(command.name)) {
101
101
  throw new Error(`Two commands have the name "${command.name}".`);
102
102
  }
103
- byName.set(command.name, command);
103
+ byName2.set(command.name, command);
104
104
  }
105
- const list = [...byName.values()];
105
+ const list = [...byName2.values()];
106
106
  return {
107
107
  list: () => list,
108
- get: (name2) => byName.get(name2)
108
+ get: (name2) => byName2.get(name2)
109
109
  };
110
110
  }
111
111
 
@@ -121,16 +121,23 @@ var DEVICE_STATES = [
121
121
  "other"
122
122
  ];
123
123
  var deviceSchema = z2.object({
124
- platform: z2.enum(["android"]),
125
- kind: z2.enum(["emulator", "device"]),
126
- serial: z2.string().optional().describe("The adb serial. An AVD that does not run has none."),
124
+ platform: z2.enum(["android", "ios"]),
125
+ kind: z2.enum(["emulator", "device", "simulator"]),
126
+ serial: z2.string().optional().describe(
127
+ "The adb serial of an Android device. An AVD that does not run has none."
128
+ ),
127
129
  avd: z2.string().optional().describe("The AVD name of an emulator."),
130
+ udid: z2.string().optional().describe("The UDID of an iOS simulator."),
131
+ name: z2.string().optional().describe("The name of an iOS simulator, for example iPhone 16 Pro."),
128
132
  model: z2.string().optional(),
129
133
  state: z2.enum(DEVICE_STATES).describe(
130
- 'Only a ready device takes commands. "stopped" is an AVD that does not run.'
134
+ 'Only a ready device takes commands. "stopped" is an AVD or a simulator that does not run.'
135
+ ),
136
+ detail: z2.string().optional().describe(
137
+ 'What adb or simctl reports, for the states "no-permissions" and "other".'
131
138
  ),
132
- detail: z2.string().optional().describe('What adb reports, for the states "no-permissions" and "other".'),
133
- apiLevel: z2.number().int().optional()
139
+ apiLevel: z2.number().int().optional().describe("The API level of an Android device."),
140
+ os: z2.string().optional().describe("The runtime of an iOS simulator, for example iOS 18.6.")
134
141
  });
135
142
  var appField = z2.string().regex(
136
143
  /^[A-Za-z][A-Za-z0-9_.-]*$/,
@@ -139,7 +146,7 @@ var appField = z2.string().regex(
139
146
  "The package of the app under test, for example host.exp.exponent for Expo Go. loupe then works only while that app is in front. A real device needs it."
140
147
  );
141
148
  var deviceField = z2.string().min(1).optional().describe(
142
- "The serial or the AVD name of the device. Without it, loupe uses ANDROID_SERIAL, or the only ready device."
149
+ "The serial or the AVD name of an Android device, or the UDID or the name of an iOS simulator. Without it, loupe uses ANDROID_SERIAL, or the only ready device."
143
150
  );
144
151
 
145
152
  // src/core/errors.ts
@@ -160,6 +167,7 @@ var ERROR_CODES = [
160
167
  "element_not_found",
161
168
  "element_ambiguous",
162
169
  "no_handler",
170
+ "no_server",
163
171
  "cancelled",
164
172
  "internal"
165
173
  ];
@@ -273,6 +281,13 @@ function describeDisplay({
273
281
  import { spawn } from "child_process";
274
282
  import path from "path";
275
283
  var DEFAULT_TIMEOUT_MS = 3e4;
284
+ var FAILURE_LIMIT = 500;
285
+ function describeToolFailure(name2, result) {
286
+ const status = result.code === null ? `${name2} stopped on a signal` : `${name2} exited with code ${result.code}`;
287
+ const output = (result.stderr.length > 0 ? result.stderr : result.stdout).toString("utf8").trim();
288
+ if (!output) return `${status}.`;
289
+ return output.length > FAILURE_LIMIT ? `${status}: ${output.slice(0, FAILURE_LIMIT)}\u2026` : `${status}: ${output}`;
290
+ }
276
291
  function toolName(file) {
277
292
  return path.parse(file).name || file;
278
293
  }
@@ -335,7 +350,7 @@ var nodeExec = (file, args, options = {}) => {
335
350
  };
336
351
 
337
352
  // src/commands/background.ts
338
- import { z as z10 } from "zod";
353
+ import { z as z11 } from "zod";
339
354
 
340
355
  // src/core/wait.ts
341
356
  import { setTimeout as sleep } from "timers/promises";
@@ -376,8 +391,15 @@ var uiNodeSchema = z4.object({
376
391
  return z4.array(uiNodeSchema).optional();
377
392
  }
378
393
  });
379
- function scrollAxisOf(node) {
380
- return /HorizontalScrollView|ViewPager/.test(node.type) ? "x" : "y";
394
+ var EXPO_GO_ANDROID = "host.exp.exponent";
395
+ function isAndroidView(node) {
396
+ return node.type.startsWith("android.");
397
+ }
398
+ function isExpoGoOverlay(node, app, platform) {
399
+ return platform === "android" && app === EXPO_GO_ANDROID && !isAndroidView(node);
400
+ }
401
+ function scrollAxisOf(node, platform) {
402
+ return platform === "android" && /HorizontalScrollView|ViewPager/.test(node.type) ? "x" : "y";
381
403
  }
382
404
  function describeNode(node) {
383
405
  const { x, y, width, height } = node.frame;
@@ -768,6 +790,22 @@ function parseWindowDisplays(text, displayId = 0) {
768
790
  focusId: focus?.[1]
769
791
  };
770
792
  }
793
+ var INPUT_FOCUS_HEADER = /^\s*FocusedWindows:(.*)$/m;
794
+ var INPUT_FOCUS_ENTRY = /^\s*displayId=(-?\d+), name='(.*)'\s*$/;
795
+ var INPUT_WINDOW_HASH = /^(?:Window\{)?([0-9a-f]+) /;
796
+ function parseInputFocus(text, displayId = 0) {
797
+ const header = INPUT_FOCUS_HEADER.exec(text);
798
+ if (!header) return void 0;
799
+ if (header[1]?.includes("<none>")) return null;
800
+ const after = text.slice(header.index + header[0].length).split(/\r?\n/);
801
+ for (const line of after.slice(1)) {
802
+ const entry = INPUT_FOCUS_ENTRY.exec(line);
803
+ if (!entry) break;
804
+ if (Number(entry[1]) !== displayId) continue;
805
+ return INPUT_WINDOW_HASH.exec(entry[2] ?? "")?.[1];
806
+ }
807
+ return null;
808
+ }
771
809
  function parseWindowList(text) {
772
810
  return text.split(/\n(?=\s*Window #\d+ Window\{)/).flatMap((block) => {
773
811
  const header = /^\s*Window #\d+ Window\{(\S+) u\d+ (.+)\}:\s*$/m.exec(
@@ -1161,10 +1199,22 @@ async function backgroundAndroid(target, app, forMs, timing = {}) {
1161
1199
  const back = await foregroundAndroid(target, inFront, timing);
1162
1200
  return { app: inFront, away, back };
1163
1201
  }
1202
+ var STOP_LIMIT = 2e3;
1203
+ var STOP_INTERVAL = 100;
1204
+ async function forceStopAndroid(target, app, limit = STOP_LIMIT) {
1205
+ await target.adb.run(["shell", "am", "force-stop", app]);
1206
+ const start = Date.now();
1207
+ while (await appRuns(target, app) && Date.now() - start < limit) {
1208
+ await sleep3(STOP_INTERVAL);
1209
+ }
1210
+ }
1211
+ async function appRuns(target, app) {
1212
+ const { stdout } = await target.adb.result(["shell", "pidof", app]);
1213
+ return /\d/.test(stdout.toString("utf8"));
1214
+ }
1164
1215
 
1165
1216
  // src/drivers/android/sdk-tool.ts
1166
1217
  import path2 from "path";
1167
- var MESSAGE_LIMIT = 500;
1168
1218
  var ADB = {
1169
1219
  name: "adb",
1170
1220
  dir: "platform-tools",
@@ -1190,12 +1240,6 @@ function missingTool(tool, candidates) {
1190
1240
  `loupe can't find ${tool.name}. ${where} Install ${tool.install}, or set ANDROID_HOME to the folder of your Android SDK.`
1191
1241
  );
1192
1242
  }
1193
- function describeFailure(tool, result) {
1194
- const status = result.code === null ? `${tool.name} stopped on a signal` : `${tool.name} exited with code ${result.code}`;
1195
- const output = (result.stderr.length > 0 ? result.stderr : result.stdout).toString("utf8").trim();
1196
- if (!output) return `${status}.`;
1197
- return output.length > MESSAGE_LIMIT ? `${status}: ${output.slice(0, MESSAGE_LIMIT)}\u2026` : `${status}: ${output}`;
1198
- }
1199
1243
  function createSdkTool({ exec, env }, tool) {
1200
1244
  let found;
1201
1245
  async function execTool(args, options) {
@@ -1218,7 +1262,10 @@ function createSdkTool({ exec, env }, tool) {
1218
1262
  async function run(args, options) {
1219
1263
  const result = await execTool(args, options);
1220
1264
  if (result.code !== 0) {
1221
- throw new LoupeError("tool_failed", describeFailure(tool, result));
1265
+ throw new LoupeError(
1266
+ "tool_failed",
1267
+ describeToolFailure(tool.name, result)
1268
+ );
1222
1269
  }
1223
1270
  return result.stdout;
1224
1271
  }
@@ -1393,6 +1440,12 @@ async function findEntry(context, adb, entries, wanted) {
1393
1440
  `No device has the serial or the AVD name "${wanted}". Run "loupe devices" to see the list.`
1394
1441
  );
1395
1442
  }
1443
+ async function readyAndroidDevices(context) {
1444
+ const entries = parseAdbDevices(
1445
+ await createAdb(context).text(["devices", "-l"])
1446
+ );
1447
+ return entries.filter((entry) => entry.adbState === "device").map(label);
1448
+ }
1396
1449
  function onlyReadyEntry(entries) {
1397
1450
  const ready = entries.filter((entry) => entry.adbState === "device");
1398
1451
  const [first] = ready.length > 0 ? ready : entries;
@@ -1450,6 +1503,233 @@ async function selectAndroidDevice(context, wanted) {
1450
1503
  };
1451
1504
  }
1452
1505
 
1506
+ // src/drivers/ios/parse.ts
1507
+ import { z as z7 } from "zod";
1508
+ var listSchema = z7.object({
1509
+ runtimes: z7.array(
1510
+ z7.object({
1511
+ identifier: z7.string(),
1512
+ name: z7.string(),
1513
+ platform: z7.string().optional(),
1514
+ isAvailable: z7.boolean().optional()
1515
+ })
1516
+ ),
1517
+ devices: z7.record(
1518
+ z7.string(),
1519
+ z7.array(
1520
+ z7.object({
1521
+ udid: z7.string(),
1522
+ name: z7.string(),
1523
+ state: z7.string(),
1524
+ isAvailable: z7.boolean().optional()
1525
+ })
1526
+ )
1527
+ )
1528
+ });
1529
+ function parseSimctlList(text) {
1530
+ let list;
1531
+ try {
1532
+ list = listSchema.parse(JSON.parse(text));
1533
+ } catch (error) {
1534
+ throw new LoupeError(
1535
+ "tool_failed",
1536
+ "loupe can't read the output of simctl list.",
1537
+ { cause: error }
1538
+ );
1539
+ }
1540
+ return list.runtimes.filter(
1541
+ (runtime) => runtime.isAvailable !== false && // A runtime of an old Xcode has no platform.
1542
+ (runtime.platform ?? runtime.name.split(" ")[0]) === "iOS"
1543
+ ).flatMap(
1544
+ (runtime) => (list.devices[runtime.identifier] ?? []).filter((device) => device.isAvailable !== false).map(({ udid, name: name2, state: state2 }) => ({
1545
+ udid,
1546
+ name: name2,
1547
+ state: state2,
1548
+ os: runtime.name
1549
+ }))
1550
+ );
1551
+ }
1552
+
1553
+ // src/drivers/ios/simctl.ts
1554
+ function createSimctl({ exec }) {
1555
+ return {
1556
+ text: async (args, options) => {
1557
+ let result;
1558
+ try {
1559
+ result = await exec("xcrun", ["simctl", ...args], options);
1560
+ } catch (error) {
1561
+ if (error instanceof LoupeError && error.code === "tool_missing") {
1562
+ throw new LoupeError(
1563
+ "tool_missing",
1564
+ "loupe can't find xcrun. Install Xcode, then try again.",
1565
+ { cause: error }
1566
+ );
1567
+ }
1568
+ throw error;
1569
+ }
1570
+ if (result.code !== 0) {
1571
+ throw new LoupeError(
1572
+ "tool_failed",
1573
+ describeToolFailure("simctl", result)
1574
+ );
1575
+ }
1576
+ return result.stdout.toString("utf8");
1577
+ }
1578
+ };
1579
+ }
1580
+
1581
+ // src/drivers/ios/devices.ts
1582
+ function stateOf2(state2) {
1583
+ switch (state2) {
1584
+ case "Booted":
1585
+ return { state: "ready" };
1586
+ case "Booting":
1587
+ return { state: "booting" };
1588
+ case "Shutdown":
1589
+ return { state: "stopped" };
1590
+ }
1591
+ return { state: "other", detail: state2 };
1592
+ }
1593
+ function deviceOf({ udid, name: name2, state: state2, os }) {
1594
+ return {
1595
+ platform: "ios",
1596
+ kind: "simulator",
1597
+ udid,
1598
+ name: name2,
1599
+ os,
1600
+ ...stateOf2(state2)
1601
+ };
1602
+ }
1603
+ function hasSimulators(context) {
1604
+ return context.hostPlatform === "darwin";
1605
+ }
1606
+ async function readSimulators(context) {
1607
+ return parseSimctlList(await createSimctl(context).text(["list", "--json"]));
1608
+ }
1609
+ async function listIosSimulators(context) {
1610
+ if (!hasSimulators(context)) return { devices: [], warnings: [] };
1611
+ const devices = (await readSimulators(context)).map(deviceOf);
1612
+ return {
1613
+ devices: [
1614
+ ...devices.filter((device) => device.state !== "stopped"),
1615
+ ...devices.filter((device) => device.state === "stopped")
1616
+ ],
1617
+ warnings: []
1618
+ };
1619
+ }
1620
+
1621
+ // src/drivers/select.ts
1622
+ var BOOTED = "Booted";
1623
+ var describe = ({ name: name2, udid, os }) => `${name2} (${udid}, ${os})`;
1624
+ async function orWhenFails(promise, fallback) {
1625
+ try {
1626
+ return await promise;
1627
+ } catch (error) {
1628
+ if (error instanceof LoupeError) return fallback;
1629
+ throw error;
1630
+ }
1631
+ }
1632
+ function ios(context, { udid, name: name2, os }) {
1633
+ return {
1634
+ platform: "ios",
1635
+ target: { udid, name: name2, os, signal: context.signal }
1636
+ };
1637
+ }
1638
+ async function android(context, wanted) {
1639
+ return {
1640
+ platform: "android",
1641
+ target: await selectAndroidDevice(context, wanted)
1642
+ };
1643
+ }
1644
+ function notRunning(simulator) {
1645
+ return new LoupeError(
1646
+ "device_unavailable",
1647
+ simulator.state === "Booting" ? `The simulator ${describe(simulator)} is still booting. Wait until it's ready, then try again.` : `The simulator ${describe(simulator)} doesn't run. Start it, then try again.`
1648
+ );
1649
+ }
1650
+ function byName(named, wanted) {
1651
+ const booted = named.filter((simulator) => simulator.state === BOOTED);
1652
+ if (booted.length > 1) {
1653
+ throw new LoupeError(
1654
+ "device_ambiguous",
1655
+ `${booted.length} simulators with the name "${wanted}" run: ${booted.map(describe).join(", ")}. Give the UDID of one in the "device" option.`
1656
+ );
1657
+ }
1658
+ const [only] = booted;
1659
+ if (only) return only;
1660
+ const [first] = named;
1661
+ if (named.length === 1 && first) throw notRunning(first);
1662
+ throw new LoupeError(
1663
+ "device_unavailable",
1664
+ `No simulator with the name "${wanted}" runs. Start one, then try again.`
1665
+ );
1666
+ }
1667
+ async function selectNamed(context, wanted) {
1668
+ const simulators = await orWhenFails(readSimulators(context), []);
1669
+ const byUdid = simulators.find(
1670
+ (simulator) => simulator.udid.toLowerCase() === wanted.toLowerCase()
1671
+ );
1672
+ if (byUdid) {
1673
+ if (byUdid.state !== BOOTED) throw notRunning(byUdid);
1674
+ return ios(context, byUdid);
1675
+ }
1676
+ try {
1677
+ return await android(context, wanted);
1678
+ } catch (error) {
1679
+ const open = error instanceof LoupeError && (error.code === "no_device" || error.code === "tool_missing");
1680
+ if (!open) throw error;
1681
+ const named = simulators.filter((simulator) => simulator.name === wanted);
1682
+ if (named.length > 0) return ios(context, byName(named, wanted));
1683
+ if (error.code === "tool_missing") throw error;
1684
+ throw new LoupeError(
1685
+ "no_device",
1686
+ `No device has the serial, the AVD name, the UDID or the simulator name "${wanted}". Run "loupe devices" to see the list.`
1687
+ );
1688
+ }
1689
+ }
1690
+ async function selectOnly(context) {
1691
+ const booted = (await orWhenFails(readSimulators(context), [])).filter(
1692
+ (simulator) => simulator.state === BOOTED
1693
+ );
1694
+ if (booted.length === 0) {
1695
+ try {
1696
+ return await android(context);
1697
+ } catch (error) {
1698
+ if (error instanceof LoupeError && error.code === "no_device") {
1699
+ throw new LoupeError(
1700
+ "no_device",
1701
+ "loupe finds no Android device, no running emulator and no running iOS simulator. Start one or connect a device, then try again."
1702
+ );
1703
+ }
1704
+ throw error;
1705
+ }
1706
+ }
1707
+ const ready = await orWhenFails(readyAndroidDevices(context), []);
1708
+ const [only] = booted;
1709
+ if (ready.length === 0 && booted.length === 1 && only) {
1710
+ return ios(context, only);
1711
+ }
1712
+ throw new LoupeError(
1713
+ "device_ambiguous",
1714
+ `${ready.length + booted.length} devices are ready: ${[...ready, ...booted.map(describe)].join(", ")}. Choose one with the "device" option.`
1715
+ );
1716
+ }
1717
+ async function selectDevice(context, wanted) {
1718
+ if (!hasSimulators(context)) return android(context, wanted);
1719
+ if (wanted) return selectNamed(context, wanted);
1720
+ if (context.env.ANDROID_SERIAL) return android(context);
1721
+ return selectOnly(context);
1722
+ }
1723
+ async function selectAndroidOnly(context, wanted) {
1724
+ const selected = await selectDevice(context, wanted);
1725
+ if (selected.platform === "android") return selected.target;
1726
+ const { name: name2, udid, os } = selected.target;
1727
+ throw new LoupeError(
1728
+ "unsupported",
1729
+ `loupe doesn't drive an iOS simulator yet: "loupe devices" only lists it. The device is ${name2} (${udid}, ${os}). For an Android device, give its serial or its AVD name in the "device" option.`
1730
+ );
1731
+ }
1732
+
1453
1733
  // src/core/png.ts
1454
1734
  import { crc32, deflateSync, inflateSync } from "zlib";
1455
1735
  var SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
@@ -1751,15 +2031,15 @@ function changeShot(png, displayScale, { crop, scale }) {
1751
2031
  }
1752
2032
 
1753
2033
  // src/core/insets.ts
1754
- import { z as z7 } from "zod";
1755
- var insetsSchema = z7.object({
1756
- top: z7.number(),
1757
- right: z7.number(),
1758
- bottom: z7.number(),
1759
- left: z7.number()
2034
+ import { z as z8 } from "zod";
2035
+ var insetsSchema = z8.object({
2036
+ top: z8.number(),
2037
+ right: z8.number(),
2038
+ bottom: z8.number(),
2039
+ left: z8.number()
1760
2040
  });
1761
2041
  var insetsReadingSchema = displaySchema.extend({
1762
- source: z7.enum(["probe", "dumpsys"]).describe(
2042
+ source: z8.enum(["probe", "dumpsys"]).describe(
1763
2043
  `Where the safe area comes from: "probe" is the app's own numbers, from the <LoupeProbe /> on the screen; "dumpsys" is the system's. The system bars and the cutout always come from the system.`
1764
2044
  ),
1765
2045
  safeArea: insetsSchema.describe(
@@ -1769,8 +2049,8 @@ var insetsReadingSchema = displaySchema.extend({
1769
2049
  "The status bar and the navigation bar, per edge, in dp."
1770
2050
  ),
1771
2051
  cutout: insetsSchema.describe("The cutout, per edge, in dp."),
1772
- cutoutRects: z7.array(rectSchema).describe("The cutout shapes as rectangles, in dp. Empty with no cutout."),
1773
- warnings: z7.array(z7.string())
2052
+ cutoutRects: z8.array(rectSchema).describe("The cutout shapes as rectangles, in dp. Empty with no cutout."),
2053
+ warnings: z8.array(z8.string())
1774
2054
  });
1775
2055
  var NO_INSETS = { top: 0, right: 0, bottom: 0, left: 0 };
1776
2056
  var EDGES = ["top", "right", "bottom", "left"];
@@ -1793,18 +2073,18 @@ function describeInsets({ top, right, bottom, left }) {
1793
2073
  }
1794
2074
 
1795
2075
  // src/core/probe.ts
1796
- import { z as z8 } from "zod";
2076
+ import { z as z9 } from "zod";
1797
2077
  var PROBE_PREFIX = "loupe:";
1798
2078
  var PROBE_FORMAT = 1;
1799
- var probeReportSchema = z8.object({
2079
+ var probeReportSchema = z9.object({
1800
2080
  insets: insetsSchema.optional().describe(
1801
2081
  "The app's safe-area insets, in dp (pt on iOS). Left out when the probe has no SafeAreaProvider above it."
1802
2082
  ),
1803
- window: z8.object({ width: z8.number(), height: z8.number() }).describe("The window size that the app gets, in dp (pt on iOS)."),
1804
- scale: z8.number().describe("Pixels per dp (pt on iOS), as the app sees it."),
1805
- direction: z8.enum(["ltr", "rtl"]).describe("The layout direction."),
1806
- colorScheme: z8.enum(["light", "dark"]).optional(),
1807
- route: z8.string().optional().describe("The route that the app gives to the probe.")
2083
+ window: z9.object({ width: z9.number(), height: z9.number() }).describe("The window size that the app gets, in dp (pt on iOS)."),
2084
+ scale: z9.number().describe("Pixels per dp (pt on iOS), as the app sees it."),
2085
+ direction: z9.enum(["ltr", "rtl"]).describe("The layout direction."),
2086
+ colorScheme: z9.enum(["light", "dark"]).optional(),
2087
+ route: z9.string().optional().describe("The route that the app gives to the probe.")
1808
2088
  });
1809
2089
  function isProbeLabel(label2) {
1810
2090
  return label2?.startsWith(PROBE_PREFIX) ?? false;
@@ -1853,7 +2133,7 @@ function describeProbe(report) {
1853
2133
 
1854
2134
  // src/drivers/android/ui.ts
1855
2135
  var BOUNDS = /^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$/;
1856
- var MESSAGE_LIMIT2 = 200;
2136
+ var MESSAGE_LIMIT = 200;
1857
2137
  function frameOf(element, scale) {
1858
2138
  const match = BOUNDS.exec(element.attributes.bounds ?? "");
1859
2139
  if (!match) {
@@ -1925,7 +2205,7 @@ function readDump(target, output, parse) {
1925
2205
  const line = output.split(/\r?\n/).map((text) => text.trim()).find(Boolean);
1926
2206
  throw new LoupeError(
1927
2207
  "tool_failed",
1928
- line ? `uiautomator on ${target.serial} gave no tree: ${line.slice(0, MESSAGE_LIMIT2)}` : `uiautomator on ${target.serial} gave no tree.`
2208
+ line ? `uiautomator on ${target.serial} gave no tree: ${line.slice(0, MESSAGE_LIMIT)}` : `uiautomator on ${target.serial} gave no tree.`
1929
2209
  );
1930
2210
  }
1931
2211
  async function readAndroidUi(target, app) {
@@ -2220,14 +2500,14 @@ async function waitAfterAction(target, app, { waitStill, waitText, waitTimeout =
2220
2500
  }
2221
2501
 
2222
2502
  // src/commands/foreground.ts
2223
- import { z as z9 } from "zod";
2224
- var backSchema = z9.object({
2225
- way: z9.enum(["in-front", ...WAYS_BACK]).describe(
2503
+ import { z as z10 } from "zod";
2504
+ var backSchema = z10.object({
2505
+ way: z10.enum(["in-front", ...WAYS_BACK]).describe(
2226
2506
  'How the app came back. in-front: it was in front already. recents: the Recents key two times, as a person does. task-lock: am task lock on its task, then lock stop; Android shows an "App unpinned" toast for a few seconds.'
2227
2507
  ),
2228
- tried: z9.array(z9.enum(WAYS_BACK)).describe("Each way that loupe tried, in order."),
2229
- task: z9.number().optional().describe("The id of the task that came back."),
2230
- ms: z9.number().describe(
2508
+ tried: z10.array(z10.enum(WAYS_BACK)).describe("Each way that loupe tried, in order."),
2509
+ task: z10.number().optional().describe("The id of the task that came back."),
2510
+ ms: z10.number().describe(
2231
2511
  "Milliseconds from the first key or command until the app had the focus."
2232
2512
  )
2233
2513
  });
@@ -2240,7 +2520,7 @@ function describeBack(app, back) {
2240
2520
  var foregroundCommand = defineCommand({
2241
2521
  name: "foreground",
2242
2522
  summary: "Bring an app back to the front: its most recent task, as a person does from Recents",
2243
- input: z9.object({
2523
+ input: z10.object({
2244
2524
  app: appField.unwrap().describe(
2245
2525
  "The package of the app to bring back, for example host.exp.exponent for Expo Go."
2246
2526
  ),
@@ -2249,11 +2529,11 @@ var foregroundCommand = defineCommand({
2249
2529
  }),
2250
2530
  positionals: ["app"],
2251
2531
  output: backSchema.extend({
2252
- app: z9.string(),
2532
+ app: z10.string(),
2253
2533
  waited: waitedSchema.optional()
2254
2534
  }),
2255
2535
  run: async ({ app, device, waitStill, waitText, waitTimeout }, context) => {
2256
- const target = await selectAndroidDevice(context, device);
2536
+ const target = await selectAndroidOnly(context, device);
2257
2537
  const back = await foregroundAndroid(target, app);
2258
2538
  const waited = await waitAfterAction(
2259
2539
  target,
@@ -2270,17 +2550,17 @@ var foregroundCommand = defineCommand({
2270
2550
  var backgroundCommand = defineCommand({
2271
2551
  name: "background",
2272
2552
  summary: "Send the app in front to the background with HOME, and with --for bring it back after that time",
2273
- input: z10.object({
2274
- for: z10.number().int().min(0).max(6e5).optional().describe(
2553
+ input: z11.object({
2554
+ for: z11.number().int().min(0).max(6e5).optional().describe(
2275
2555
  "Milliseconds in the background. Then loupe brings the app back, as the foreground command does. With no value, the app stays in the background."
2276
2556
  ),
2277
2557
  ...waitFields,
2278
2558
  app: appField,
2279
2559
  device: deviceField
2280
2560
  }),
2281
- output: z10.object({
2282
- app: z10.string().describe("The package that went to the background."),
2283
- away: z10.number().optional().describe(
2561
+ output: z11.object({
2562
+ app: z11.string().describe("The package that went to the background."),
2563
+ away: z11.number().optional().describe(
2284
2564
  "Milliseconds from HOME to the first step back. Left out with no --for."
2285
2565
  ),
2286
2566
  back: backSchema.optional().describe("How the app came back."),
@@ -2294,7 +2574,7 @@ var backgroundCommand = defineCommand({
2294
2574
  "The wait options need --for: with no --for, the app stays in the background, and there is nothing to wait for."
2295
2575
  );
2296
2576
  }
2297
- const target = await selectAndroidDevice(context, input.device);
2577
+ const target = await selectAndroidOnly(context, input.device);
2298
2578
  const result = await backgroundAndroid(target, input.app, input.for);
2299
2579
  const waited = result.back ? await waitAfterAction(
2300
2580
  target,
@@ -2320,10 +2600,10 @@ var backgroundCommand = defineCommand({
2320
2600
  // src/commands/check.ts
2321
2601
  import { readFile } from "fs/promises";
2322
2602
  import path4 from "path";
2323
- import { z as z13 } from "zod";
2603
+ import { z as z14 } from "zod";
2324
2604
 
2325
2605
  // src/core/check.ts
2326
- import { z as z11 } from "zod";
2606
+ import { z as z12 } from "zod";
2327
2607
 
2328
2608
  // src/core/ink.ts
2329
2609
  var INK_TOLERANCE = 32;
@@ -2400,36 +2680,34 @@ var MIN_TOUCH_TARGET = 48;
2400
2680
  var HIT_SLOP_BAND = 8;
2401
2681
  var CENTRE_TOLERANCE = 4;
2402
2682
  var CLEAR_GAP = 24;
2403
- var findingSchema = z11.object({
2683
+ var findingSchema = z12.object({
2404
2684
  element: elementSchema,
2405
- message: z11.string().describe("What is wrong, with the numbers, for a person."),
2406
- details: z11.record(z11.string(), z11.number()).describe("The numbers of the finding, in dp, by name.")
2685
+ message: z12.string().describe("What is wrong, with the numbers, for a person."),
2686
+ details: z12.record(z12.string(), z12.number()).describe("The numbers of the finding, in dp, by name.")
2407
2687
  });
2408
- var ruleResultSchema = z11.object({
2409
- rule: z11.enum(RULES),
2410
- passed: z11.boolean(),
2411
- checked: z11.number().describe("The elements that the rule looked at."),
2412
- findings: z11.array(findingSchema),
2413
- warnings: z11.array(z11.string()).optional().describe(
2688
+ var ruleResultSchema = z12.object({
2689
+ rule: z12.enum(RULES),
2690
+ passed: z12.boolean(),
2691
+ checked: z12.number().describe("The elements that the rule looked at."),
2692
+ findings: z12.array(findingSchema),
2693
+ warnings: z12.array(z12.string()).optional().describe(
2414
2694
  "Notes that are no finding: an element that you named but the rule could not check, or a touch target that a hitSlop can make whole."
2415
2695
  )
2416
2696
  });
2417
2697
  var screenCheckSchema = displaySchema.extend({
2418
- app: z11.string().optional().describe("The package of the window in the tree."),
2419
- safeAreaSource: z11.enum(["probe", "dumpsys"]).describe("Where the safe area comes from, as in `insets`."),
2420
- passed: z11.boolean().describe("True when every rule passed."),
2421
- results: z11.array(ruleResultSchema),
2422
- warnings: z11.array(z11.string())
2698
+ app: z12.string().optional().describe("The package of the window in the tree."),
2699
+ safeAreaSource: z12.enum(["probe", "dumpsys"]).describe("Where the safe area comes from, as in `insets`."),
2700
+ passed: z12.boolean().describe("True when every rule passed."),
2701
+ results: z12.array(ruleResultSchema),
2702
+ warnings: z12.array(z12.string())
2423
2703
  });
2424
- var EXPO_GO = "host.exp.exponent";
2425
2704
  function place(screen) {
2426
- const skipOwn = screen.app === EXPO_GO;
2427
2705
  const placed = [];
2428
2706
  const walk = (nodes, scrollAxes) => {
2429
2707
  for (const node of nodes) {
2430
- if (skipOwn && !node.type.startsWith("android.")) continue;
2708
+ if (isExpoGoOverlay(node, screen.app, screen.platform)) continue;
2431
2709
  placed.push({ node, siblings: nodes, scrollAxes });
2432
- const inner = node.scrollable ? /* @__PURE__ */ new Set([...scrollAxes, scrollAxisOf(node)]) : scrollAxes;
2710
+ const inner = node.scrollable ? /* @__PURE__ */ new Set([...scrollAxes, scrollAxisOf(node, screen.platform)]) : scrollAxes;
2433
2711
  walk(node.children ?? [], inner);
2434
2712
  }
2435
2713
  };
@@ -2949,6 +3227,7 @@ async function checkAndroidUi(target, app, ui, names, options = {}, shot = false
2949
3227
  }
2950
3228
  }
2951
3229
  const screen = {
3230
+ platform: "android",
2952
3231
  display: ui.display,
2953
3232
  app: ui.app,
2954
3233
  nodes: ui.nodes,
@@ -2976,7 +3255,7 @@ async function checkAndroid(target, app, names, options = {}, shot = false) {
2976
3255
  }
2977
3256
 
2978
3257
  // src/commands/ui.ts
2979
- import { z as z12 } from "zod";
3258
+ import { z as z13 } from "zod";
2980
3259
 
2981
3260
  // src/core/output-file.ts
2982
3261
  import { mkdir, writeFile } from "fs/promises";
@@ -2993,26 +3272,26 @@ var uiCommand = defineCommand({
2993
3272
  name: "ui",
2994
3273
  summary: "Read the accessibility tree of the screen, with frames in dp",
2995
3274
  readOnly: true,
2996
- input: z12.object({
2997
- out: z12.string().min(1).optional().describe(
3275
+ input: z13.object({
3276
+ out: z13.string().min(1).optional().describe(
2998
3277
  "Also write the result as JSON to this file, to give to check as mirrorOf later. loupe makes its folder, and replaces a file that is there."
2999
3278
  ),
3000
3279
  app: appField,
3001
3280
  device: deviceField
3002
3281
  }),
3003
3282
  output: displaySchema.extend({
3004
- app: z12.string().optional().describe("The package of the window in the tree."),
3005
- nodes: z12.array(uiNodeSchema).describe(
3283
+ app: z13.string().optional().describe("The package of the window in the tree."),
3284
+ nodes: z13.array(uiNodeSchema).describe(
3006
3285
  "The tree of the window in front. A system sheet, for example the share sheet, takes the place of the app below it."
3007
3286
  ),
3008
3287
  probe: probeReportSchema.optional().describe(
3009
3288
  "The report of the app's <LoupeProbe />, when the screen shows one. The probe's own node isn't in nodes."
3010
3289
  ),
3011
- file: z12.string().optional().describe("The JSON file, as an absolute path. Left out with no out.")
3290
+ file: z13.string().optional().describe("The JSON file, as an absolute path. Left out with no out.")
3012
3291
  }),
3013
3292
  run: async ({ out, app, device }, context) => {
3014
3293
  const ui = await readAndroidUi(
3015
- await selectAndroidDevice(context, device),
3294
+ await selectAndroidOnly(context, device),
3016
3295
  app
3017
3296
  );
3018
3297
  const data = {
@@ -3034,7 +3313,7 @@ var uiCommand = defineCommand({
3034
3313
  });
3035
3314
 
3036
3315
  // src/commands/check.ts
3037
- var centredField = (by) => z13.array(z13.string().min(1)).optional().describe(
3316
+ var centredField = (by) => z14.array(z14.string().min(1)).optional().describe(
3038
3317
  `For the centred rule: the element with this ${by} must be at the centre of its container, whatever sits beside it. Give it once for each element.`
3039
3318
  );
3040
3319
  function notSaved(file, why) {
@@ -3094,6 +3373,7 @@ function otherDirection(file, saved, ui) {
3094
3373
  );
3095
3374
  }
3096
3375
  return {
3376
+ platform: "android",
3097
3377
  display: saved,
3098
3378
  app: saved.app,
3099
3379
  nodes: saved.nodes,
@@ -3104,14 +3384,14 @@ var checkCommand = defineCommand({
3104
3384
  name: "check",
3105
3385
  summary: "Check the screen for layout defects: elements under an inset, cut at an edge, off centre, too small to touch, or not mirrored in the other direction",
3106
3386
  readOnly: true,
3107
- input: z13.object({
3108
- rules: z13.string().regex(/^[a-z-]+(,[a-z-]+)*$/, "The rules are a comma list.").optional().describe(
3387
+ input: z14.object({
3388
+ rules: z14.string().regex(/^[a-z-]+(,[a-z-]+)*$/, "The rules are a comma list.").optional().describe(
3109
3389
  `The rules to run, as a comma list. Each one by default: ${RULES.join(", ")} (mirrored only with --mirror-of).`
3110
3390
  ),
3111
3391
  centred: centredField("text (the whole text)"),
3112
3392
  centredLabel: centredField("accessibility label"),
3113
3393
  centredId: centredField("id"),
3114
- mirrorOf: z13.string().min(1).optional().describe(
3394
+ mirrorOf: z14.string().min(1).optional().describe(
3115
3395
  "For the mirrored rule: a file with this screen in the other layout direction, from loupe ui --json. Each element must sit where that screen puts it, mirrored."
3116
3396
  ),
3117
3397
  app: appField,
@@ -3141,7 +3421,7 @@ var checkCommand = defineCommand({
3141
3421
  );
3142
3422
  }
3143
3423
  const saved = input.mirrorOf ? await readSavedUi(input.mirrorOf) : void 0;
3144
- const target = await selectAndroidDevice(context, input.device);
3424
+ const target = await selectAndroidOnly(context, input.device);
3145
3425
  const ui = await readAndroidUi(target, input.app);
3146
3426
  const mirrorOf = saved && input.mirrorOf ? otherDirection(input.mirrorOf, saved, ui) : void 0;
3147
3427
  const { check } = await checkAndroidUi(target, input.app, ui, names, {
@@ -3159,15 +3439,48 @@ var checkCommand = defineCommand({
3159
3439
  });
3160
3440
 
3161
3441
  // src/commands/devices.ts
3162
- import { z as z14 } from "zod";
3163
- var HEADER = ["Serial", "State", "Kind", "Name", "API"];
3442
+ import { z as z15 } from "zod";
3443
+
3444
+ // src/drivers/devices.ts
3445
+ async function attempt2(promise) {
3446
+ try {
3447
+ return { list: await promise };
3448
+ } catch (error) {
3449
+ if (error instanceof LoupeError) return { error };
3450
+ throw error;
3451
+ }
3452
+ }
3453
+ async function listDevices(context) {
3454
+ if (!hasSimulators(context)) return listAndroidDevices(context);
3455
+ const [android2, ios2] = await Promise.all([
3456
+ attempt2(listAndroidDevices(context)),
3457
+ attempt2(listIosSimulators(context))
3458
+ ]);
3459
+ if ("error" in android2 && "error" in ios2) throw android2.error;
3460
+ const lists = [android2, ios2].map(
3461
+ (listed, index) => "list" in listed ? listed.list : {
3462
+ devices: [],
3463
+ warnings: [
3464
+ `The list has no ${index === 0 ? "Android devices" : "iOS simulators"}. ${listed.error.message}`
3465
+ ]
3466
+ }
3467
+ );
3468
+ return {
3469
+ devices: lists.flatMap((list) => list.devices),
3470
+ warnings: lists.flatMap((list) => list.warnings)
3471
+ };
3472
+ }
3473
+
3474
+ // src/commands/devices.ts
3475
+ var HEADER = ["Id", "State", "Kind", "Name", "OS"];
3476
+ var idOf = (device) => device.serial ?? device.udid;
3164
3477
  function row(device) {
3165
3478
  return [
3166
- device.serial ?? "-",
3479
+ idOf(device) ?? "-",
3167
3480
  device.state,
3168
3481
  device.kind,
3169
- device.avd ?? device.model ?? "",
3170
- device.apiLevel?.toString() ?? ""
3482
+ device.avd ?? device.name ?? device.model ?? "",
3483
+ device.apiLevel === void 0 ? device.os ?? "" : `API ${device.apiLevel}`
3171
3484
  ];
3172
3485
  }
3173
3486
  function table(rows) {
@@ -3180,17 +3493,17 @@ function table(rows) {
3180
3493
  }
3181
3494
  var devicesCommand = defineCommand({
3182
3495
  name: "devices",
3183
- summary: "List the Android emulators and devices, and the AVDs that don't run",
3496
+ summary: "List the Android emulators and devices, the iOS simulators, and the AVDs that don't run",
3184
3497
  readOnly: true,
3185
- input: z14.object({}),
3186
- output: z14.object({
3187
- devices: z14.array(deviceSchema),
3188
- warnings: z14.array(z14.string())
3498
+ input: z15.object({}),
3499
+ output: z15.object({
3500
+ devices: z15.array(deviceSchema),
3501
+ warnings: z15.array(z15.string())
3189
3502
  }),
3190
- run: (_input, context) => listAndroidDevices(context),
3503
+ run: (_input, context) => listDevices(context),
3191
3504
  format: ({ devices, warnings }) => {
3192
- const lines2 = devices.length > 0 ? table([HEADER, ...devices.map(row)]) : ["No devices, and no AVDs."];
3193
- const details = devices.filter((device) => device.detail).map((device) => `${device.serial}: ${device.detail}`);
3505
+ const lines2 = devices.length > 0 ? table([HEADER, ...devices.map(row)]) : ["No devices, no AVDs, and no simulators."];
3506
+ const details = devices.filter((device) => device.detail).map((device) => `${idOf(device)}: ${device.detail}`);
3194
3507
  return [
3195
3508
  ...lines2,
3196
3509
  ...details,
@@ -3200,7 +3513,7 @@ var devicesCommand = defineCommand({
3200
3513
  });
3201
3514
 
3202
3515
  // src/commands/dismiss.ts
3203
- import { z as z15 } from "zod";
3516
+ import { z as z16 } from "zod";
3204
3517
 
3205
3518
  // src/drivers/android/dismiss.ts
3206
3519
  import { setTimeout as sleep5 } from "timers/promises";
@@ -3375,7 +3688,7 @@ function unknownWindow(owner, type) {
3375
3688
  }
3376
3689
  async function topOverlay(target, app) {
3377
3690
  const ui = await readAndroidUi(target, app);
3378
- return labelledOverlays({ ...ui, app }).at(-1)?.label;
3691
+ return labelledOverlays({ ...ui, platform: "android", app }).at(-1)?.label;
3379
3692
  }
3380
3693
  async function appFront(target, app) {
3381
3694
  try {
@@ -3426,6 +3739,27 @@ async function tapWait(target, display) {
3426
3739
  async function sendKey(target, key2) {
3427
3740
  await target.adb.run(["shell", "input", "keyevent", key2]);
3428
3741
  }
3742
+ var CLOSED_WITHOUT_KEY = /* @__PURE__ */ new Set([
3743
+ "notification-shade",
3744
+ "not-responding",
3745
+ "stylus-sheet"
3746
+ ]);
3747
+ async function untilInputFocus(target, front, { display }, { limit, interval }) {
3748
+ if (!display.focusId) return;
3749
+ const start = Date.now();
3750
+ for (; ; ) {
3751
+ const dump = await target.adb.text(["shell", "dumpsys", "input"]);
3752
+ const focus = parseInputFocus(dump);
3753
+ if (focus === void 0 || focus === display.focusId) return;
3754
+ if (Date.now() - start >= limit) {
3755
+ throw new LoupeError(
3756
+ "timeout",
3757
+ `The input focus didn't move to ${LAYER_NAMES[front.layer]} within ${limit} ms, so loupe sent no key: it could reach another window. Try again in a moment.`
3758
+ );
3759
+ }
3760
+ await sleep5(interval);
3761
+ }
3762
+ }
3429
3763
  async function close(target, front, screen) {
3430
3764
  switch (front.layer) {
3431
3765
  case "notification-shade":
@@ -3506,6 +3840,9 @@ async function dismissAndroid(target, app, { all = false, limit = 5e3, interval
3506
3840
  if (closed.length >= (all ? MAX_LAYERS : 1)) {
3507
3841
  return { app, closed, next: front.layer };
3508
3842
  }
3843
+ if (!CLOSED_WITHOUT_KEY.has(front.layer)) {
3844
+ await untilInputFocus(target, front, screen, options);
3845
+ }
3509
3846
  const start = Date.now();
3510
3847
  const way = await close(target, front, screen);
3511
3848
  const after = await untilGone(target, front, options);
@@ -3530,18 +3867,18 @@ async function dismissAndroid(target, app, { all = false, limit = 5e3, interval
3530
3867
  }
3531
3868
 
3532
3869
  // src/commands/dismiss.ts
3533
- var layerSchema = z15.enum(LAYERS).describe(
3870
+ var layerSchema = z16.enum(LAYERS).describe(
3534
3871
  `keyboard. stylus-sheet: the "Try out your stylus" sheet of Gboard's stylus mode, which a stylus touch starts (on an emulator, loupe's double-tap, drag and pinch are one). app-dialog: a dialog or a modal of the app. app-overlay: a menu, a sheet or a dialog that the app draws in its own window, found by its scrim or outside-press region: a node over the whole screen with a label and a touch. share-sheet: the system share sheet. permission-dialog: Android doesn't count Back as a denial, and the app's request can stay with no answer. notification-shade: also with the quick settings open. not-responding: an "isn't responding" dialog, of any app.`
3535
3872
  );
3536
- var closedSchema = z15.object({
3873
+ var closedSchema = z16.object({
3537
3874
  layer: layerSchema,
3538
- label: z15.string().optional().describe(
3875
+ label: z16.string().optional().describe(
3539
3876
  "The label of the scrim or the outside-press region of an app-overlay."
3540
3877
  ),
3541
- way: z15.enum(DISMISS_WAYS).describe(
3878
+ way: z16.enum(DISMISS_WAYS).describe(
3542
3879
  `back: the Back key. escape: the Escape key, for the keyboard in Gboard's stylus mode, where Back also reaches the app. tap-cancel: a tap on Cancel in the stylus sheet. collapse: the status bar collapse, which closes the shade and the quick settings in one step. tap-wait: a tap on Wait in an "isn't responding" dialog, so the app gets more time.`
3543
3880
  ),
3544
- ms: z15.number().describe(
3881
+ ms: z16.number().describe(
3545
3882
  "Milliseconds from the key, command or tap until the layer was gone."
3546
3883
  )
3547
3884
  });
@@ -3558,29 +3895,29 @@ function summaryOf(app, closed, next) {
3558
3895
  var dismissCommand = defineCommand({
3559
3896
  name: "dismiss",
3560
3897
  summary: "Close the top layer over the app: the keyboard, a dialog, the app's own menu or sheet, a system sheet or the notification shade. With --all, each layer",
3561
- input: z15.object({
3562
- all: z15.boolean().optional().describe(
3898
+ input: z16.object({
3899
+ all: z16.boolean().optional().describe(
3563
3900
  `Close each layer, from the top, until the app's own screen shows: at most ${MAX_LAYERS}.`
3564
3901
  ),
3565
3902
  ...waitFields,
3566
3903
  app: appField,
3567
3904
  device: deviceField
3568
3905
  }),
3569
- output: z15.object({
3570
- app: z15.string().optional().describe(
3906
+ output: z16.object({
3907
+ app: z16.string().optional().describe(
3571
3908
  "The package under the layers. Left out when a layer still shows and the input has no app."
3572
3909
  ),
3573
- closed: z15.array(closedSchema).describe(
3910
+ closed: z16.array(closedSchema).describe(
3574
3911
  "Each layer that loupe closed, from the top. Empty when nothing was open: then loupe sent no key."
3575
3912
  ),
3576
3913
  next: layerSchema.optional().describe(
3577
3914
  `The layer that shows now, when loupe stopped before the app: one call closes one layer, and --all stops after ${MAX_LAYERS}.`
3578
3915
  ),
3579
3916
  waited: waitedSchema.optional(),
3580
- warnings: z15.array(z15.string()).optional()
3917
+ warnings: z16.array(z16.string()).optional()
3581
3918
  }),
3582
3919
  run: async ({ all, app, device, ...wait }, context) => {
3583
- const target = await selectAndroidDevice(context, device);
3920
+ const target = await selectAndroidOnly(context, device);
3584
3921
  const result = await dismissAndroid(target, app, { all });
3585
3922
  const waited = await waitAfterAction(target, app, wait, "dismiss");
3586
3923
  return { ...result, waited };
@@ -3592,24 +3929,24 @@ var dismissCommand = defineCommand({
3592
3929
  });
3593
3930
 
3594
3931
  // src/commands/double-tap.ts
3595
- import { z as z17 } from "zod";
3932
+ import { z as z18 } from "zod";
3596
3933
 
3597
3934
  // src/core/touch.ts
3598
- import { z as z16 } from "zod";
3599
- var pointSchema = z16.object({ x: z16.number(), y: z16.number() });
3935
+ import { z as z17 } from "zod";
3936
+ var pointSchema = z17.object({ x: z17.number(), y: z17.number() });
3600
3937
  function coordinateField(axis) {
3601
- return z16.number().min(0).describe(
3938
+ return z17.number().min(0).describe(
3602
3939
  `${axis === "x" ? "Across" : "Down"} from the top-left corner of the screen, in dp (pt on iOS), not px.`
3603
3940
  );
3604
3941
  }
3605
3942
  function durationField(byDefault, what) {
3606
- return z16.number().int().min(0).default(byDefault).describe(`Milliseconds ${what}.`);
3943
+ return z17.number().int().min(0).default(byDefault).describe(`Milliseconds ${what}.`);
3607
3944
  }
3608
- var touchSchema = z16.object({
3609
- orientation: z16.enum(ORIENTATIONS),
3610
- points: z16.array(pointSchema).describe("The points of the touch, in dp."),
3611
- pixels: z16.array(pointSchema).describe("The same points in px, as loupe sent them."),
3612
- duration: z16.number().optional().describe("In milliseconds.")
3945
+ var touchSchema = z17.object({
3946
+ orientation: z17.enum(ORIENTATIONS),
3947
+ points: z17.array(pointSchema).describe("The points of the touch, in dp."),
3948
+ pixels: z17.array(pointSchema).describe("The same points in px, as loupe sent them."),
3949
+ duration: z17.number().optional().describe("In milliseconds.")
3613
3950
  });
3614
3951
  var aimedTouchSchema = touchSchema.extend({
3615
3952
  element: elementSchema.optional().describe("The element that loupe touched, when the input named one.")
@@ -3979,7 +4316,7 @@ async function dragAndroid(target, from, to, options, app) {
3979
4316
  var doubleTapCommand = defineCommand({
3980
4317
  name: "double-tap",
3981
4318
  summary: "Tap one point or element twice, as a double-tap, by text, label or id",
3982
- input: z17.object({
4319
+ input: z18.object({
3983
4320
  x: coordinateField("x").optional(),
3984
4321
  y: coordinateField("y").optional(),
3985
4322
  ...selectorFields,
@@ -3989,13 +4326,13 @@ var doubleTapCommand = defineCommand({
3989
4326
  }),
3990
4327
  positionals: ["x", "y"],
3991
4328
  output: aimedTouchSchema.extend({
3992
- gap: z17.number().describe(
4329
+ gap: z18.number().describe(
3993
4330
  "Milliseconds between the two taps: on an emulator, measured on the host through the emulator console; on a real device, measured on the device."
3994
4331
  ),
3995
4332
  waited: waitedSchema.optional()
3996
4333
  }),
3997
4334
  run: async ({ app, device, waitStill, waitText, waitTimeout, ...input }, context) => {
3998
- const target = await selectAndroidDevice(context, device);
4335
+ const target = await selectAndroidOnly(context, device);
3999
4336
  const { point, element } = await aimAndroid(target, targetOf(input), app);
4000
4337
  const touch2 = await doubleTapAndroid(target, point, app);
4001
4338
  const waited = await waitAfterAction(
@@ -4013,11 +4350,11 @@ var doubleTapCommand = defineCommand({
4013
4350
  });
4014
4351
 
4015
4352
  // src/commands/drag.ts
4016
- import { z as z18 } from "zod";
4353
+ import { z as z19 } from "zod";
4017
4354
  var dragCommand = defineCommand({
4018
4355
  name: "drag",
4019
4356
  summary: "Touch, hold, move, hold and lift, with a screenshot while the touch is down",
4020
- input: z18.object({
4357
+ input: z19.object({
4021
4358
  fromX: coordinateField("x"),
4022
4359
  fromY: coordinateField("y"),
4023
4360
  toX: coordinateField("x"),
@@ -4028,10 +4365,10 @@ var dragCommand = defineCommand({
4028
4365
  ),
4029
4366
  holdStart: durationField(0, "to hold the touch before it moves"),
4030
4367
  holdEnd: durationField(0, "to hold the touch at the end, before it lifts"),
4031
- shot: z18.string().min(1).optional().describe(
4368
+ shot: z19.string().min(1).optional().describe(
4032
4369
  "A PNG file. loupe takes a screenshot while the touch is down, and writes it there."
4033
4370
  ),
4034
- shotAt: z18.number().min(0).max(1).default(1).describe(
4371
+ shotAt: z19.number().min(0).max(1).default(1).describe(
4035
4372
  "Where along the move loupe takes the screenshot: 0 is after the start hold, 1 is after the end hold. In between, the touch pauses there while the screenshot runs."
4036
4373
  ),
4037
4374
  ...waitFields,
@@ -4040,12 +4377,12 @@ var dragCommand = defineCommand({
4040
4377
  }),
4041
4378
  positionals: ["fromX", "fromY", "toX", "toY"],
4042
4379
  output: touchSchema.extend({
4043
- holdStart: z18.number(),
4044
- holdEnd: z18.number(),
4045
- moveTime: z18.number().describe(
4380
+ holdStart: z19.number(),
4381
+ holdEnd: z19.number(),
4382
+ moveTime: z19.number().describe(
4046
4383
  "Milliseconds that the move took, with a screenshot in the move: on an emulator, measured on the host through the emulator console; on a real device, measured on the device."
4047
4384
  ),
4048
- shot: z18.string().optional().describe("The PNG file, as an absolute path."),
4385
+ shot: z19.string().optional().describe("The PNG file, as an absolute path."),
4049
4386
  waited: waitedSchema.optional()
4050
4387
  }),
4051
4388
  run: async ({
@@ -4062,7 +4399,7 @@ var dragCommand = defineCommand({
4062
4399
  waitTimeout,
4063
4400
  ...timing
4064
4401
  }, context) => {
4065
- const target = await selectAndroidDevice(context, device);
4402
+ const target = await selectAndroidOnly(context, device);
4066
4403
  const { png, ...drag } = await dragAndroid(
4067
4404
  target,
4068
4405
  { x: fromX, y: fromY },
@@ -4088,72 +4425,926 @@ var dragCommand = defineCommand({
4088
4425
  )
4089
4426
  });
4090
4427
 
4091
- // src/commands/hold.ts
4092
- import { z as z19 } from "zod";
4093
- var holdCommand = defineCommand({
4094
- name: "hold",
4095
- summary: "Touch one point or element and hold it (a long press), by text, label or id",
4096
- input: z19.object({
4097
- x: coordinateField("x").optional(),
4098
- y: coordinateField("y").optional(),
4099
- ...selectorFields,
4100
- duration: durationField(1e3, "to hold the touch"),
4101
- ...waitFields,
4102
- app: appField,
4103
- device: deviceField
4104
- }),
4105
- positionals: ["x", "y"],
4106
- output: aimedTouchSchema.extend({ waited: waitedSchema.optional() }),
4107
- run: async ({ duration, app, device, waitStill, waitText, waitTimeout, ...input }, context) => {
4108
- const target = await selectAndroidDevice(context, device);
4109
- const { point, element } = await aimAndroid(target, targetOf(input), app);
4110
- const touch2 = await holdAndroid(target, point, duration, app);
4111
- const waited = await waitAfterAction(
4112
- target,
4113
- app,
4114
- { waitStill, waitText, waitTimeout },
4115
- "hold"
4116
- );
4117
- return { ...touch2, element, waited };
4118
- },
4119
- format: (touch2) => withWaited(
4120
- `Held ${describeTouched(touch2)} dp for ${touch2.duration} ms`,
4121
- touch2.waited
4122
- )
4123
- });
4428
+ // src/commands/expo-open.ts
4429
+ import { z as z21 } from "zod";
4124
4430
 
4125
- // src/commands/insets.ts
4126
- import { z as z20 } from "zod";
4127
- var insetsCommand = defineCommand({
4128
- name: "insets",
4129
- summary: "Read the safe-area insets and the cutout of the current orientation",
4130
- readOnly: true,
4131
- input: z20.object({
4132
- app: appField.describe(
4133
- "The package of the app under test, for example host.exp.exponent for Expo Go. loupe then reads the app's probe only while that app is in front. On a real device, loupe reads the probe only with this option."
4134
- ),
4135
- device: deviceField
4136
- }),
4137
- output: insetsReadingSchema,
4138
- run: async ({ app, device }, context) => readAndroidInsets(await selectAndroidDevice(context, device), app),
4139
- format: (reading) => [
4140
- describeDisplay(reading),
4141
- `Safe area, from ${reading.source === "probe" ? "the app's probe" : "dumpsys"}: ${describeInsets(reading.safeArea)}`,
4142
- `System bars: ${describeInsets(reading.systemBars)}`,
4143
- `Cutout: ${describeInsets(reading.cutout)}`,
4144
- ...reading.warnings.map((warning) => `Warning: ${warning}`)
4145
- ].join("\n")
4146
- });
4431
+ // src/drivers/android/expo.ts
4432
+ import { setTimeout as sleep7 } from "timers/promises";
4147
4433
 
4148
- // src/commands/key.ts
4149
- import { z as z21 } from "zod";
4434
+ // src/expo/expo-go.ts
4435
+ var EXPO_GO = "host.exp.exponent";
4436
+ var CLOSE_BUTTON = {
4437
+ onboarding: { by: "text", value: "Continue" },
4438
+ "dev-menu": { by: "label", value: "Close" }
4439
+ };
4440
+ function* eachNode(nodes) {
4441
+ for (const node of nodes) {
4442
+ yield node;
4443
+ yield* eachNode(node.children ?? []);
4444
+ }
4445
+ }
4446
+ function expoGoScreenOf(nodes) {
4447
+ const all = [...eachNode(nodes)];
4448
+ const has = (test) => all.some(test);
4449
+ if (has((node) => node.text === "Continue") && has((node) => node.text?.startsWith("This is the developer menu") === true)) {
4450
+ return "onboarding";
4451
+ }
4452
+ if (has((node) => node.text === "Go home") && has((node) => node.label === "Close")) {
4453
+ return "dev-menu";
4454
+ }
4455
+ if (has((node) => node.id === "host.exp.exponent:id/progressBar")) {
4456
+ return "loading";
4457
+ }
4458
+ return void 0;
4459
+ }
4460
+ function hasAppContent(nodes, platform) {
4461
+ return nodes.some(
4462
+ (node) => !isExpoGoOverlay(node, EXPO_GO, platform) && ((node.text || node.label || node.clickable || node.longClickable) && node.frame.width > 0 && node.frame.height > 0 || hasAppContent(node.children ?? [], platform))
4463
+ );
4464
+ }
4465
+ function normalRoute(route) {
4466
+ const path8 = route.split(/[?#]/)[0] ?? "";
4467
+ return `/${path8.replace(/^\/+|\/+$/g, "")}`;
4468
+ }
4469
+ function routeOfLink(link) {
4470
+ if (!/^exps?:\/\//.test(link)) return void 0;
4471
+ const at = link.indexOf("/--/");
4472
+ return at === -1 ? "/" : normalRoute(link.slice(at + 3));
4473
+ }
4474
+ function expoLink(port, route = "/") {
4475
+ const path8 = route.replace(/^\/+/, "");
4476
+ return path8 ? `exp://127.0.0.1:${port}/--/${path8}` : `exp://127.0.0.1:${port}`;
4477
+ }
4478
+ var majorOf = (version2) => version2.split(".")[0] ?? "";
4479
+ function sdkWarning(expoGo, sdk) {
4480
+ if (!expoGo || !sdk || majorOf(expoGo) === majorOf(sdk)) return void 0;
4481
+ return `Expo Go ${expoGo} is for SDK ${majorOf(expoGo)}, and the app is on SDK ${sdk}, so Expo Go shows an error, not the app. Ask the user to install the Expo Go of SDK ${majorOf(sdk)}: press "a" in "npx expo start".`;
4482
+ }
4150
4483
 
4151
- // src/core/keys.ts
4152
- var KEY_NAMES = [
4153
- "back",
4154
- "home",
4155
- "recents",
4156
- "enter",
4484
+ // src/drivers/android/open-url.ts
4485
+ async function openUrlAndroid(target, url, app) {
4486
+ if (!app && target.kind === "device") {
4487
+ throw new LoupeError(
4488
+ "invalid_input",
4489
+ `${target.serial} is a real device, so loupe needs the "app" option: the package of the app under test. Then only that app opens the link.`
4490
+ );
4491
+ }
4492
+ const result = await target.adb.result([
4493
+ "shell",
4494
+ "am",
4495
+ "start",
4496
+ "-W",
4497
+ "-a",
4498
+ "android.intent.action.VIEW",
4499
+ "-d",
4500
+ shellQuote(url),
4501
+ ...app ? ["-p", app] : []
4502
+ ]);
4503
+ const start = parseAmStart(
4504
+ `${result.stdout.toString("utf8")}
4505
+ ${result.stderr.toString("utf8")}`
4506
+ );
4507
+ if (start.unresolved) {
4508
+ throw new LoupeError(
4509
+ "no_handler",
4510
+ app ? `${app} doesn't open ${url} on ${target.serial}.` : `No app on ${target.serial} opens ${url}.`
4511
+ );
4512
+ }
4513
+ if (start.status !== "ok") {
4514
+ throw new LoupeError(
4515
+ "tool_failed",
4516
+ start.error ? `am start failed on ${target.serial}: ${start.error}` : `am start failed on ${target.serial} with exit code ${result.code}.`
4517
+ );
4518
+ }
4519
+ return {
4520
+ url,
4521
+ activity: start.activity,
4522
+ launchState: start.launchState?.toLowerCase(),
4523
+ totalTime: start.totalTime
4524
+ };
4525
+ }
4526
+
4527
+ // src/drivers/android/expo.ts
4528
+ var OPEN_AGAIN_MS = 2e4;
4529
+ var READ_INTERVAL = 500;
4530
+ async function readExpoGoVersion(target) {
4531
+ const installed = await target.adb.result(["shell", "pm", "path", EXPO_GO]);
4532
+ if (installed.code !== 0 || !installed.stdout.toString("utf8").includes("package:")) {
4533
+ throw new LoupeError(
4534
+ "no_handler",
4535
+ `Expo Go isn't on ${target.serial}. Ask the user to install it: press "a" in "npx expo start", and the Expo CLI installs the Expo Go of the app's SDK.`
4536
+ );
4537
+ }
4538
+ const dump = await target.adb.text(["shell", "dumpsys", "package", EXPO_GO]);
4539
+ return /versionName=(\S+)/.exec(dump)?.[1];
4540
+ }
4541
+ function forceStopExpoGo(target, limit) {
4542
+ return forceStopAndroid(target, EXPO_GO, limit);
4543
+ }
4544
+ async function reverseAndroid(target, port) {
4545
+ await target.adb.run(["reverse", `tcp:${port}`, `tcp:${port}`]);
4546
+ }
4547
+ async function readExpoGo(target) {
4548
+ try {
4549
+ return await readAndroidUi(target, EXPO_GO);
4550
+ } catch (error) {
4551
+ if (error instanceof LoupeError && error.code === "not_idle") {
4552
+ return "not_idle";
4553
+ }
4554
+ if (error instanceof LoupeError && error.code === "app_not_in_front") {
4555
+ return void 0;
4556
+ }
4557
+ throw error;
4558
+ }
4559
+ }
4560
+ var treeOf2 = (read) => typeof read === "object" ? read : void 0;
4561
+ async function probeRouteInExpoGo(target) {
4562
+ return treeOf2(await readExpoGo(target))?.probe?.report?.route;
4563
+ }
4564
+ async function showInExpoGo(target, { link, route, direction, timeout, openAgain = OPEN_AGAIN_MS }) {
4565
+ const start = Date.now();
4566
+ const opened = await openUrlAndroid(target, link, EXPO_GO);
4567
+ let opens = 1;
4568
+ let openedAt = start;
4569
+ const reopens = [];
4570
+ const closed = [];
4571
+ let last = "nothing yet";
4572
+ let notIdle = false;
4573
+ while (Date.now() - start < timeout) {
4574
+ throwIfCancelled(target.signal);
4575
+ const { focus } = await readWindowDisplay(target);
4576
+ const inExperience = isAppWindow(focus, EXPO_GO) && !focus?.includes("LauncherActivity");
4577
+ let appShows = false;
4578
+ if (!inExperience) {
4579
+ notIdle = false;
4580
+ if (notRespondingPackage(focus) !== void 0) {
4581
+ await readInFront(target, EXPO_GO);
4582
+ }
4583
+ last = isAppWindow(focus, EXPO_GO) ? "Expo Go's home screen" : target.kind === "device" ? "another window in front" : `${focus ?? "no window"} in front`;
4584
+ } else {
4585
+ const read = await readExpoGo(target);
4586
+ notIdle = read === "not_idle";
4587
+ const ui = treeOf2(read);
4588
+ const screen = ui && expoGoScreenOf(ui.nodes);
4589
+ if (!ui) {
4590
+ last = "Expo Go's screen, which didn't keep still for uiautomator";
4591
+ } else if (screen === "onboarding" || screen === "dev-menu") {
4592
+ const { point } = findElement(
4593
+ ui.nodes,
4594
+ CLOSE_BUTTON[screen],
4595
+ ui.display.size
4596
+ );
4597
+ await tapAndroid(target, point, EXPO_GO);
4598
+ closed.push(screen);
4599
+ last = `Expo Go's ${screen === "onboarding" ? "onboarding sheet" : "developer menu"}`;
4600
+ } else if (screen === "loading") {
4601
+ last = "Expo Go's loading screen";
4602
+ } else if (!ui.probe?.report && !hasAppContent(ui.nodes, "android")) {
4603
+ last = "a screen with no text, label or touch yet";
4604
+ } else if (!ui.probe?.report) {
4605
+ appShows = true;
4606
+ const remaining = Math.max(0, timeout - (Date.now() - start));
4607
+ if (await stillAppInExpoGo(target, remaining)) {
4608
+ return { opened, opens, reopens, closed, ms: Date.now() - start };
4609
+ }
4610
+ last = "the app with no probe, then another screen";
4611
+ } else {
4612
+ const probe = ui.probe.report;
4613
+ appShows = true;
4614
+ const onRoute = route === void 0 || probe.route === void 0 || normalRoute(probe.route) === normalRoute(route);
4615
+ const inDirection = direction === void 0 || probe.direction === direction;
4616
+ if (onRoute && inDirection) {
4617
+ return {
4618
+ opened,
4619
+ opens,
4620
+ reopens,
4621
+ closed,
4622
+ ms: Date.now() - start,
4623
+ probe
4624
+ };
4625
+ }
4626
+ last = onRoute ? `the app in ${probe.direction}` : `the app on ${probe.route}`;
4627
+ }
4628
+ }
4629
+ const stuck = !inExperience || appShows;
4630
+ if (stuck && Date.now() - openedAt >= openAgain) {
4631
+ await openUrlAndroid(target, link, EXPO_GO);
4632
+ opens += 1;
4633
+ reopens.push(last);
4634
+ openedAt = Date.now();
4635
+ }
4636
+ await sleep7(READ_INTERVAL);
4637
+ }
4638
+ if (notIdle) {
4639
+ throw new LoupeError(
4640
+ "not_idle",
4641
+ `Expo Go shows a screen after loupe opened ${link}, but it didn't keep still in ${Math.round(timeout / 1e3)} s, so uiautomator can't read it. An animation that never stops, or a long one, can cause this. Take a screenshot to see the screen, wait until the animation ends, or open a route with no such animation.`
4642
+ );
4643
+ }
4644
+ throw new LoupeError(
4645
+ "timeout",
4646
+ `Expo Go didn't show the app in ${Math.round(timeout / 1e3)} s after loupe opened ${link} (${opens === 1 ? "once" : `${opens} times`}). The last read: ${last}.`
4647
+ );
4648
+ }
4649
+ async function stillAppInExpoGo(target, timeout) {
4650
+ await waitStillInExpoGo(target, timeout);
4651
+ const again = treeOf2(await readExpoGo(target));
4652
+ return again !== void 0 && expoGoScreenOf(again.nodes) === void 0 && !again.probe?.report && hasAppContent(again.nodes, "android");
4653
+ }
4654
+ async function waitStillInExpoGo(target, timeout) {
4655
+ const still = await waitStillAndroid(target, EXPO_GO, {
4656
+ timeout,
4657
+ interval: READ_INTERVAL
4658
+ });
4659
+ if (!still.still) {
4660
+ throw new LoupeError(
4661
+ "timeout",
4662
+ `The app shows in Expo Go, but its screen didn't keep still in ${Math.round(timeout / 1e3)} s.`
4663
+ );
4664
+ }
4665
+ }
4666
+
4667
+ // src/expo/metro.ts
4668
+ import { createHash } from "crypto";
4669
+ import { setTimeout as sleep8 } from "timers/promises";
4670
+ import { z as z20 } from "zod";
4671
+ var DEFAULT_PORT = 8081;
4672
+ var DEFAULT_BUNDLE_TIMEOUT = 3e5;
4673
+ var REQUEST_TIMEOUT = 1e4;
4674
+ var portField = z20.number().int().min(1).max(65535).optional().describe(
4675
+ `The port of Metro on this machine (npx expo start). ${DEFAULT_PORT} by default.`
4676
+ );
4677
+ var metroBase = (port) => `http://127.0.0.1:${port}`;
4678
+ var MANIFEST_HEADERS = {
4679
+ "expo-platform": "android",
4680
+ accept: "application/expo+json,application/json"
4681
+ };
4682
+ var manifestSchema = z20.object({
4683
+ launchAsset: z20.object({ url: z20.string() }),
4684
+ extra: z20.object({
4685
+ expoClient: z20.object({
4686
+ name: z20.string().optional(),
4687
+ slug: z20.string().optional(),
4688
+ sdkVersion: z20.string().optional(),
4689
+ // Read with type checks in `readExpoApp`: Expo CLI sends
4690
+ // `_internal.dynamicConfigPath` as `{}` when the app has no
4691
+ // dynamic config, and a field of another type must not drop the
4692
+ // whole manifest.
4693
+ extra: z20.unknown().optional(),
4694
+ _internal: z20.unknown().optional()
4695
+ }).optional(),
4696
+ expoGo: z20.object({
4697
+ developer: z20.object({ projectRoot: z20.string().optional() }).optional()
4698
+ }).optional()
4699
+ }).optional()
4700
+ });
4701
+ function fieldsOf(value) {
4702
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
4703
+ }
4704
+ var noServer = (port) => `Nothing answers on port ${port}. Ask the user to start Metro with "npx expo start" in the folder of the app, or give the port of Metro.`;
4705
+ function isRefused(error) {
4706
+ const cause = error instanceof Error ? error.cause : void 0;
4707
+ return error instanceof TypeError && typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ECONNREFUSED";
4708
+ }
4709
+ async function askMetro(context, { port, path: path8, what, timeout, headers }, read) {
4710
+ throwIfCancelled(context.signal);
4711
+ const limit = AbortSignal.timeout(timeout);
4712
+ const signal = context.signal ? AbortSignal.any([limit, context.signal]) : limit;
4713
+ try {
4714
+ const response = await context.fetch(`${metroBase(port)}${path8}`, {
4715
+ headers,
4716
+ signal
4717
+ });
4718
+ return await read(response);
4719
+ } catch (error) {
4720
+ if (error instanceof LoupeError) throw error;
4721
+ throwIfCancelled(context.signal);
4722
+ if (limit.aborted) {
4723
+ throw new LoupeError(
4724
+ "timeout",
4725
+ `Metro on port ${port} didn't give ${what} in ${Math.round(timeout / 1e3)} s.`
4726
+ );
4727
+ }
4728
+ if (isRefused(error)) throw new LoupeError("no_server", noServer(port));
4729
+ throw new LoupeError(
4730
+ "tool_failed",
4731
+ `loupe couldn't get ${what} from Metro on port ${port}: ${error instanceof Error ? error.message : String(error)}`,
4732
+ { cause: error }
4733
+ );
4734
+ }
4735
+ }
4736
+ async function readMetroStatus(context, port) {
4737
+ const status = await askMetro(
4738
+ context,
4739
+ { port, path: "/status", what: "its status", timeout: REQUEST_TIMEOUT },
4740
+ (response) => response.text()
4741
+ );
4742
+ if (!status.includes("packager-status:running")) {
4743
+ throw new LoupeError(
4744
+ "no_server",
4745
+ `Something answers on port ${port}, but it isn't Metro. Give the port that "npx expo start" prints.`
4746
+ );
4747
+ }
4748
+ }
4749
+ async function readExpoApp(context, port) {
4750
+ const manifest = await askMetro(
4751
+ context,
4752
+ {
4753
+ port,
4754
+ path: "/",
4755
+ what: "the manifest",
4756
+ timeout: REQUEST_TIMEOUT,
4757
+ headers: MANIFEST_HEADERS
4758
+ },
4759
+ async (response) => {
4760
+ const text = await response.text();
4761
+ if (!response.ok) return void 0;
4762
+ try {
4763
+ return manifestSchema.safeParse(JSON.parse(text)).data;
4764
+ } catch {
4765
+ return void 0;
4766
+ }
4767
+ }
4768
+ );
4769
+ if (!manifest) {
4770
+ throw new LoupeError(
4771
+ "unsupported",
4772
+ `Metro on port ${port} gives no Expo manifest. The Expo commands need the dev server of the Expo CLI: "npx expo start".`
4773
+ );
4774
+ }
4775
+ const client = manifest.extra?.expoClient;
4776
+ const bundle = new URL(manifest.launchAsset.url, metroBase(port));
4777
+ const extra = fieldsOf(client?.extra);
4778
+ const dynamicConfigPath = fieldsOf(client?._internal).dynamicConfigPath;
4779
+ return {
4780
+ name: client?.name,
4781
+ slug: client?.slug,
4782
+ sdkVersion: client?.sdkVersion,
4783
+ projectRoot: manifest.extra?.expoGo?.developer?.projectRoot,
4784
+ dynamicConfigPath: typeof dynamicConfigPath === "string" ? dynamicConfigPath : void 0,
4785
+ rtl: {
4786
+ supports: extra.supportsRTL === true,
4787
+ forces: extra.forcesRTL === true
4788
+ },
4789
+ bundlePath: `${bundle.pathname}${bundle.search}`
4790
+ };
4791
+ }
4792
+ var MANIFEST_LIMIT = 1e4;
4793
+ var MANIFEST_INTERVAL = 250;
4794
+ async function untilManifestRtl(context, port, forces, timeout = MANIFEST_LIMIT) {
4795
+ const limit = Math.min(timeout, MANIFEST_LIMIT);
4796
+ const start = Date.now();
4797
+ for (; ; ) {
4798
+ const app = await readExpoApp(context, port);
4799
+ if (app.rtl.forces === forces) return;
4800
+ if (Date.now() - start >= limit) {
4801
+ throw new LoupeError(
4802
+ "unsupported",
4803
+ `loupe wrote app.json, but after ${Math.round(limit / 1e3)} s the manifest of Metro still gives forcesRTL ${app.rtl.forces}. ${app.dynamicConfigPath?.split(/[\\/]/).pop() ?? "A dynamic config"} can replace extra: it must keep the extra of app.json ("...config.extra").`
4804
+ );
4805
+ }
4806
+ throwIfCancelled(context.signal);
4807
+ await sleep8(MANIFEST_INTERVAL);
4808
+ }
4809
+ }
4810
+ function bundleError(status, text) {
4811
+ let detail = text;
4812
+ try {
4813
+ const json = JSON.parse(text);
4814
+ if (typeof json === "object" && json !== null) {
4815
+ detail = ["type", "message"].map((key2) => json[key2]).filter((value) => typeof value === "string").join(": ");
4816
+ }
4817
+ } catch {
4818
+ }
4819
+ const line = detail.split("\n").map((part) => part.trim()).find(Boolean);
4820
+ return `Metro couldn't build the bundle (HTTP ${status})${line ? `: ${line.slice(0, 500)}` : "."} Fix the code of the app, then run expo-warm again.`;
4821
+ }
4822
+ async function fetchBundle(context, port, path8, timeout) {
4823
+ const start = performance.now();
4824
+ return askMetro(
4825
+ context,
4826
+ { port, path: path8, what: "the bundle", timeout },
4827
+ async (response) => {
4828
+ if (!response.ok) {
4829
+ throw new LoupeError(
4830
+ "tool_failed",
4831
+ bundleError(response.status, await response.text())
4832
+ );
4833
+ }
4834
+ const body = Buffer.from(await response.arrayBuffer());
4835
+ return {
4836
+ ms: Math.round(performance.now() - start),
4837
+ bytes: body.length,
4838
+ sha256: createHash("sha256").update(body).digest("hex")
4839
+ };
4840
+ }
4841
+ );
4842
+ }
4843
+ async function warmExpo(context, { port = DEFAULT_PORT, timeout = DEFAULT_BUNDLE_TIMEOUT }, total = 3) {
4844
+ await readMetroStatus(context, port);
4845
+ context.progress?.({ progress: 1, total, message: "Metro runs." });
4846
+ const app = await readExpoApp(context, port);
4847
+ context.progress?.({
4848
+ progress: 2,
4849
+ total,
4850
+ message: "Metro builds the bundle."
4851
+ });
4852
+ const bundle = await fetchBundle(context, port, app.bundlePath, timeout);
4853
+ context.progress?.({ progress: 3, total });
4854
+ return {
4855
+ server: metroBase(port),
4856
+ link: `exp://127.0.0.1:${port}`,
4857
+ app: { name: app.name, slug: app.slug, sdkVersion: app.sdkVersion },
4858
+ projectRoot: app.projectRoot,
4859
+ bundle: { path: app.bundlePath, ...bundle }
4860
+ };
4861
+ }
4862
+
4863
+ // src/commands/expo-open.ts
4864
+ var DEFAULT_SHOW_TIMEOUT = 12e4;
4865
+ var STEPS = 5;
4866
+ var showTimeoutField = z21.number().int().min(1e3).max(6e5).optional().describe(
4867
+ `How long to wait for the app after the open, in ms. ${DEFAULT_SHOW_TIMEOUT} by default.`
4868
+ );
4869
+ var shownSchema = z21.object({
4870
+ link: z21.string().describe("The link that loupe opened in Expo Go."),
4871
+ app: z21.object({
4872
+ name: z21.string().optional(),
4873
+ slug: z21.string().optional(),
4874
+ sdkVersion: z21.string().optional()
4875
+ }),
4876
+ expoGo: z21.string().optional().describe("The version of Expo Go on the device."),
4877
+ launchState: z21.string().optional().describe("cold, warm or hot, as Android measured the first open."),
4878
+ opens: z21.number().describe(
4879
+ "How many times loupe opened the link. Expo Go can lose a link while it starts."
4880
+ ),
4881
+ reopens: z21.array(z21.string()).describe(
4882
+ "What the last read saw before each time that loupe opened the link again."
4883
+ ),
4884
+ closed: z21.array(z21.enum(["onboarding", "dev-menu"])).describe(
4885
+ "The Expo Go sheets that loupe closed: the onboarding sheet of the first open, and the developer menu."
4886
+ ),
4887
+ ms: z21.number().describe("From the open until the app showed, in ms."),
4888
+ route: z21.string().optional().describe("The route that the app's probe shows."),
4889
+ direction: z21.enum(["ltr", "rtl"]).optional().describe("The layout direction that the app's probe shows."),
4890
+ probe: z21.boolean().describe(
4891
+ "True when the app has the probe. With no probe, loupe waited until the screen had text, a label or a touch, kept still, and then still showed no Expo Go screen."
4892
+ ),
4893
+ warnings: z21.array(z21.string())
4894
+ });
4895
+ async function showApp(context, {
4896
+ route,
4897
+ port = DEFAULT_PORT,
4898
+ timeout = DEFAULT_SHOW_TIMEOUT,
4899
+ device
4900
+ }, { reload = false, prepare } = {}) {
4901
+ const target = await selectAndroidOnly(context, device);
4902
+ const expoGo = await readExpoGoVersion(target);
4903
+ const warmed = await warmExpo(context, { port }, STEPS);
4904
+ const direction = await prepare?.();
4905
+ const warnings = [];
4906
+ const sdk = sdkWarning(expoGo, warmed.app.sdkVersion);
4907
+ if (sdk) warnings.push(sdk);
4908
+ await reverseAndroid(target, port);
4909
+ const openRoute = reload ? route ?? await probeRouteInExpoGo(target) : route;
4910
+ context.progress?.({
4911
+ progress: 4,
4912
+ total: STEPS,
4913
+ message: reload ? "Expo Go stops, then opens the app again." : "Expo Go opens the app."
4914
+ });
4915
+ if (reload) await forceStopExpoGo(target);
4916
+ const link = expoLink(port, openRoute);
4917
+ const start = Date.now();
4918
+ const shown = await showInExpoGo(target, {
4919
+ link,
4920
+ route: openRoute,
4921
+ direction,
4922
+ timeout
4923
+ });
4924
+ context.progress?.({ progress: STEPS, total: STEPS });
4925
+ const { launchState } = shown.opened;
4926
+ const proved = direction !== void 0 && shown.probe?.direction === direction;
4927
+ if (reload && launchState !== void 0 && launchState !== "cold" && !proved) {
4928
+ warnings.push(
4929
+ `Android gave the launch state ${launchState} after the force-stop, not cold, so Expo Go can still have run. Check that the app shows your change.`
4930
+ );
4931
+ }
4932
+ return {
4933
+ link,
4934
+ app: warmed.app,
4935
+ expoGo,
4936
+ launchState,
4937
+ opens: shown.opens,
4938
+ reopens: shown.reopens,
4939
+ closed: shown.closed,
4940
+ ms: Date.now() - start,
4941
+ route: shown.probe?.route,
4942
+ direction: shown.probe?.direction,
4943
+ probe: shown.probe !== void 0,
4944
+ warnings
4945
+ };
4946
+ }
4947
+ function describeShown(lead, { app, opens, reopens, closed, ms, route, direction, warnings }) {
4948
+ return [
4949
+ [
4950
+ `${lead}: ${app.name ?? app.slug ?? "the app"} shows`,
4951
+ ...route ? [` on ${route}`] : [],
4952
+ ...direction ? [` in ${direction.toUpperCase()}`] : [],
4953
+ ` after ${ms} ms`,
4954
+ ...closed.length ? [`; closed ${closed.join(", ")}`] : [],
4955
+ ...opens > 1 ? [`; opened ${opens} times, again after: ${reopens.join("; ")}`] : [],
4956
+ "."
4957
+ ].join(""),
4958
+ ...warnings.map((warning) => `Warning: ${warning}`)
4959
+ ].join("\n");
4960
+ }
4961
+ var expoOpenCommand = defineCommand({
4962
+ name: "expo-open",
4963
+ summary: "Open the app in Expo Go on the device, at a route, and wait until it shows",
4964
+ input: z21.object({
4965
+ route: z21.string().optional().describe(
4966
+ "The route to open, for example /settings. The root by default. When the app has the probe, loupe waits until the probe shows this route."
4967
+ ),
4968
+ port: portField,
4969
+ timeout: showTimeoutField,
4970
+ device: deviceField
4971
+ }),
4972
+ positionals: ["route"],
4973
+ output: shownSchema,
4974
+ run: (input, context) => showApp(context, input),
4975
+ format: (shown) => describeShown(
4976
+ `Opened ${shown.link} in Expo Go${shown.expoGo ? ` ${shown.expoGo}` : ""}`,
4977
+ shown
4978
+ )
4979
+ });
4980
+
4981
+ // src/commands/expo-reload.ts
4982
+ import { z as z22 } from "zod";
4983
+ var expoReloadCommand = defineCommand({
4984
+ name: "expo-reload",
4985
+ summary: "Stop Expo Go and open the app again, so its JavaScript starts again, and wait until it shows",
4986
+ input: z22.object({
4987
+ route: z22.string().optional().describe(
4988
+ "The route to open after the stop, for example /settings. By default the route that the probe shows before the stop, else the root."
4989
+ ),
4990
+ port: portField,
4991
+ timeout: showTimeoutField,
4992
+ device: deviceField
4993
+ }),
4994
+ positionals: ["route"],
4995
+ output: shownSchema,
4996
+ run: (input, context) => showApp(context, input, { reload: true }),
4997
+ format: (shown) => describeShown(
4998
+ `Stopped Expo Go${shown.expoGo ? ` ${shown.expoGo}` : ""} and opened ${shown.link} again`,
4999
+ shown
5000
+ )
5001
+ });
5002
+
5003
+ // src/commands/expo-rtl.ts
5004
+ import { z as z24 } from "zod";
5005
+
5006
+ // src/expo/app-config.ts
5007
+ import { mkdir as mkdir2, readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
5008
+ import path5 from "path";
5009
+ import { z as z23 } from "zod";
5010
+ var KEYS2 = ["supportsRTL", "forcesRTL"];
5011
+ var RECORD_PATH = path5.join(".expo", "loupe-rtl.json");
5012
+ var recordSchema = z23.object({ original: z23.string(), written: z23.string() });
5013
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5014
+ function parseAppJson(text, file) {
5015
+ let json;
5016
+ try {
5017
+ json = JSON.parse(text);
5018
+ } catch {
5019
+ json = void 0;
5020
+ }
5021
+ if (!isObject(json)) {
5022
+ throw new LoupeError(
5023
+ "unsupported",
5024
+ `${file} isn't a JSON object, so loupe can't edit it.`
5025
+ );
5026
+ }
5027
+ return json;
5028
+ }
5029
+ var expoConfigOf = (json) => isObject(json.expo) ? json.expo : json;
5030
+ function formatLike(json, like) {
5031
+ const indent = /^[^\n]*\n([ \t]+)\S/.exec(like)?.[1] ?? " ";
5032
+ const text = `${JSON.stringify(json, null, indent)}${like.endsWith("\n") ? "\n" : ""}`;
5033
+ return like.includes("\r\n") ? text.replace(/\n/g, "\r\n") : text;
5034
+ }
5035
+ function withRtl(text, file) {
5036
+ const json = parseAppJson(text, file);
5037
+ const config = expoConfigOf(json);
5038
+ const extra = isObject(config.extra) ? config.extra : {};
5039
+ if (extra.supportsRTL === true && extra.forcesRTL === true) return text;
5040
+ config.extra = { ...extra, supportsRTL: true, forcesRTL: true };
5041
+ return formatLike(json, text);
5042
+ }
5043
+ function withKeysOf(text, original, file) {
5044
+ const json = parseAppJson(text, file);
5045
+ const config = expoConfigOf(json);
5046
+ const before = expoConfigOf(parseAppJson(original, file)).extra;
5047
+ const extra = isObject(config.extra) ? { ...config.extra } : {};
5048
+ for (const key2 of KEYS2) {
5049
+ if (isObject(before) && key2 in before) extra[key2] = before[key2];
5050
+ else delete extra[key2];
5051
+ }
5052
+ if (Object.keys(extra).length === 0 && !isObject(before)) delete config.extra;
5053
+ else config.extra = extra;
5054
+ const unchanged = JSON.stringify(json) === JSON.stringify(parseAppJson(text, file));
5055
+ return unchanged ? text : formatLike(json, text);
5056
+ }
5057
+ function rtlOf(text, file) {
5058
+ const extra = expoConfigOf(parseAppJson(text, file)).extra;
5059
+ return {
5060
+ supports: isObject(extra) && extra.supportsRTL === true,
5061
+ forces: isObject(extra) && extra.forcesRTL === true
5062
+ };
5063
+ }
5064
+ async function readText(file) {
5065
+ try {
5066
+ return await readFile2(file, "utf8");
5067
+ } catch (error) {
5068
+ if (error.code === "ENOENT") return void 0;
5069
+ throw error;
5070
+ }
5071
+ }
5072
+ async function readRecord(file) {
5073
+ const text = await readText(file);
5074
+ if (text === void 0) return void 0;
5075
+ let record;
5076
+ try {
5077
+ record = recordSchema.safeParse(JSON.parse(text)).data;
5078
+ } catch {
5079
+ record = void 0;
5080
+ }
5081
+ if (!record) {
5082
+ throw new LoupeError(
5083
+ "unsupported",
5084
+ `${file} isn't a record of loupe, so loupe can't put app.json back. Compare app.json with the version in git, then delete the record.`
5085
+ );
5086
+ }
5087
+ return record;
5088
+ }
5089
+ async function writeRecord(file, record) {
5090
+ await mkdir2(path5.dirname(file), { recursive: true });
5091
+ await writeFile2(file, `${JSON.stringify(record, null, 2)}
5092
+ `);
5093
+ }
5094
+ async function requireAppJson(projectRoot, mode, dynamicConfigPath) {
5095
+ const file = path5.resolve(projectRoot, "app.json");
5096
+ const text = await readText(file);
5097
+ if (text === void 0) {
5098
+ const config = dynamicConfigPath?.split(/[\\/]/).pop() ?? "app.config.js";
5099
+ throw new LoupeError(
5100
+ "unsupported",
5101
+ `loupe edits only app.json, and ${projectRoot} has none. Ask the user to ${mode === "on" ? 'add "supportsRTL: true" and "forcesRTL: true" to' : 'remove "supportsRTL" and "forcesRTL" from'} the extra of ${config}, then run expo-reload.`
5102
+ );
5103
+ }
5104
+ return { file, text };
5105
+ }
5106
+ async function setRtl(projectRoot, mode, dynamicConfigPath) {
5107
+ const { file, text } = await requireAppJson(
5108
+ projectRoot,
5109
+ mode,
5110
+ dynamicConfigPath
5111
+ );
5112
+ const recordFile = path5.resolve(projectRoot, RECORD_PATH);
5113
+ const record = await readRecord(recordFile);
5114
+ let next = text;
5115
+ let nextRecord = record;
5116
+ if (mode === "on") {
5117
+ next = withRtl(text, file);
5118
+ if (record) nextRecord = { ...record, written: next };
5119
+ else if (next !== text) nextRecord = { original: text, written: next };
5120
+ } else if (record) {
5121
+ next = text === record.written ? record.original : withKeysOf(text, record.original, file);
5122
+ nextRecord = void 0;
5123
+ } else if (rtlOf(text, file).forces) {
5124
+ throw new LoupeError(
5125
+ "unsupported",
5126
+ `${file} sets forcesRTL, and loupe didn't set it, so loupe doesn't change it. Ask the user.`
5127
+ );
5128
+ }
5129
+ if (nextRecord) await writeRecord(recordFile, nextRecord);
5130
+ if (next !== text) await writeFile2(file, next);
5131
+ if (!nextRecord && record) await rm(recordFile, { force: true });
5132
+ return {
5133
+ file,
5134
+ changed: next !== text,
5135
+ ...rtlOf(next, file),
5136
+ undo: async () => {
5137
+ if (next !== text) await writeFile2(file, text);
5138
+ if (record) await writeRecord(recordFile, record);
5139
+ else await rm(recordFile, { force: true });
5140
+ }
5141
+ };
5142
+ }
5143
+
5144
+ // src/expo/rtl.ts
5145
+ async function expoProject(context, port) {
5146
+ const app = await readExpoApp(context, port);
5147
+ if (!app.projectRoot) {
5148
+ throw new LoupeError(
5149
+ "unsupported",
5150
+ "The manifest of Metro gives no folder of the app, so loupe can't find app.json."
5151
+ );
5152
+ }
5153
+ return {
5154
+ projectRoot: app.projectRoot,
5155
+ dynamicConfigPath: app.dynamicConfigPath
5156
+ };
5157
+ }
5158
+ async function switchRtl(context, port, rtl, timeout) {
5159
+ const { projectRoot, dynamicConfigPath } = await expoProject(context, port);
5160
+ const change = await setRtl(projectRoot, rtl, dynamicConfigPath);
5161
+ try {
5162
+ await untilManifestRtl(context, port, change.forces, timeout);
5163
+ } catch (error) {
5164
+ await change.undo();
5165
+ throw error;
5166
+ }
5167
+ return change;
5168
+ }
5169
+ function directionOf({
5170
+ forces,
5171
+ supports
5172
+ }) {
5173
+ if (forces) return "rtl";
5174
+ return supports ? void 0 : "ltr";
5175
+ }
5176
+
5177
+ // src/commands/expo-rtl.ts
5178
+ var expoRtlCommand = defineCommand({
5179
+ name: "expo-rtl",
5180
+ summary: "Turn RTL on or off in the app.json of the app in Expo Go, then open the app again in that direction",
5181
+ input: z24.object({
5182
+ rtl: z24.enum(["on", "off"]).describe(
5183
+ `on: supportsRTL and forcesRTL in the extra of app.json; loupe keeps app.json as it was in ${RECORD_PATH}. off: app.json as it was before on.`
5184
+ ),
5185
+ route: z24.string().optional().describe(
5186
+ "The route to open after the change, for example /settings. By default the route that the probe shows before it, else the root."
5187
+ ),
5188
+ port: portField,
5189
+ timeout: showTimeoutField,
5190
+ device: deviceField
5191
+ }),
5192
+ positionals: ["rtl", "route"],
5193
+ output: shownSchema.extend({
5194
+ rtl: z24.enum(["on", "off"]),
5195
+ file: z24.string().describe("The app.json of the app, as an absolute path."),
5196
+ changed: z24.boolean().describe("True when loupe wrote app.json.")
5197
+ }),
5198
+ run: async ({ rtl, ...input }, context) => {
5199
+ const port = input.port ?? DEFAULT_PORT;
5200
+ const state2 = {};
5201
+ let shown;
5202
+ try {
5203
+ shown = await showApp(context, input, {
5204
+ reload: true,
5205
+ prepare: async () => {
5206
+ state2.change = await switchRtl(context, port, rtl, input.timeout);
5207
+ return directionOf(state2.change);
5208
+ }
5209
+ });
5210
+ } catch (error) {
5211
+ if (rtl === "on" && state2.change?.changed && error instanceof LoupeError) {
5212
+ throw new LoupeError(
5213
+ error.code,
5214
+ `${error.message} app.json keeps RTL on: run expo-rtl off to put it back.`,
5215
+ { cause: error }
5216
+ );
5217
+ }
5218
+ throw error;
5219
+ }
5220
+ const { file, changed } = state2.change;
5221
+ return {
5222
+ ...shown,
5223
+ warnings: shown.probe ? shown.warnings : [
5224
+ ...shown.warnings,
5225
+ "The app has no probe, so loupe didn't see the direction on the screen."
5226
+ ],
5227
+ rtl,
5228
+ file,
5229
+ changed
5230
+ };
5231
+ },
5232
+ format: ({ rtl, file, changed, ...shown }) => describeShown(
5233
+ `RTL ${rtl}: loupe ${changed ? "wrote" : "didn't change"} ${file}, stopped Expo Go and opened ${shown.link} again`,
5234
+ shown
5235
+ )
5236
+ });
5237
+
5238
+ // src/commands/expo-warm.ts
5239
+ import { z as z25 } from "zod";
5240
+ var expoWarmCommand = defineCommand({
5241
+ name: "expo-warm",
5242
+ summary: "Ask Metro for the app and its bundle, so that the first open in Expo Go is fast, and give the hash of the bundle",
5243
+ readOnly: true,
5244
+ input: z25.object({
5245
+ port: portField,
5246
+ timeout: z25.number().int().min(1e3).max(6e5).optional().describe(
5247
+ `How long to wait for the bundle at most, in ms. ${DEFAULT_BUNDLE_TIMEOUT} by default: a cold bundle of a large app can take minutes.`
5248
+ )
5249
+ }),
5250
+ output: z25.object({
5251
+ server: z25.string().describe("The Metro server that loupe asked."),
5252
+ link: z25.string().describe(
5253
+ "The link that opens the app in Expo Go on Android, after adb reverse of the port."
5254
+ ),
5255
+ app: z25.object({
5256
+ name: z25.string().optional(),
5257
+ slug: z25.string().optional(),
5258
+ sdkVersion: z25.string().optional().describe(
5259
+ "The Expo SDK of the app, for example 58.0.0. Expo Go must have the same major version."
5260
+ )
5261
+ }),
5262
+ projectRoot: z25.string().optional().describe("The folder of the app on this machine, as Metro gives it."),
5263
+ bundle: z25.object({
5264
+ path: z25.string().describe("The path and query of the launch bundle on Metro."),
5265
+ ms: z25.number().describe(
5266
+ "How long the bundle took, in ms: seconds when cold, under a second when warm."
5267
+ ),
5268
+ bytes: z25.number(),
5269
+ sha256: z25.string().describe(
5270
+ "The SHA-256 of the bundle. After an edit of the app's code, the same hash means that Metro didn't see the edit."
5271
+ )
5272
+ })
5273
+ }),
5274
+ run: (input, context) => warmExpo(context, input),
5275
+ format: ({ server, app, bundle }) => [
5276
+ `Metro at ${server}: ${app.name ?? app.slug ?? "the app"}`,
5277
+ ...app.sdkVersion ? [` (SDK ${app.sdkVersion})`] : [],
5278
+ `. The bundle: ${(bundle.bytes / 1e6).toFixed(2)} MB in ${bundle.ms} ms, sha256 ${bundle.sha256.slice(0, 12)}.`
5279
+ ].join("")
5280
+ });
5281
+
5282
+ // src/commands/hold.ts
5283
+ import { z as z26 } from "zod";
5284
+ var holdCommand = defineCommand({
5285
+ name: "hold",
5286
+ summary: "Touch one point or element and hold it (a long press), by text, label or id",
5287
+ input: z26.object({
5288
+ x: coordinateField("x").optional(),
5289
+ y: coordinateField("y").optional(),
5290
+ ...selectorFields,
5291
+ duration: durationField(1e3, "to hold the touch"),
5292
+ ...waitFields,
5293
+ app: appField,
5294
+ device: deviceField
5295
+ }),
5296
+ positionals: ["x", "y"],
5297
+ output: aimedTouchSchema.extend({ waited: waitedSchema.optional() }),
5298
+ run: async ({ duration, app, device, waitStill, waitText, waitTimeout, ...input }, context) => {
5299
+ const target = await selectAndroidOnly(context, device);
5300
+ const { point, element } = await aimAndroid(target, targetOf(input), app);
5301
+ const touch2 = await holdAndroid(target, point, duration, app);
5302
+ const waited = await waitAfterAction(
5303
+ target,
5304
+ app,
5305
+ { waitStill, waitText, waitTimeout },
5306
+ "hold"
5307
+ );
5308
+ return { ...touch2, element, waited };
5309
+ },
5310
+ format: (touch2) => withWaited(
5311
+ `Held ${describeTouched(touch2)} dp for ${touch2.duration} ms`,
5312
+ touch2.waited
5313
+ )
5314
+ });
5315
+
5316
+ // src/commands/insets.ts
5317
+ import { z as z27 } from "zod";
5318
+ var insetsCommand = defineCommand({
5319
+ name: "insets",
5320
+ summary: "Read the safe-area insets and the cutout of the current orientation",
5321
+ readOnly: true,
5322
+ input: z27.object({
5323
+ app: appField.describe(
5324
+ "The package of the app under test, for example host.exp.exponent for Expo Go. loupe then reads the app's probe only while that app is in front. On a real device, loupe reads the probe only with this option."
5325
+ ),
5326
+ device: deviceField
5327
+ }),
5328
+ output: insetsReadingSchema,
5329
+ run: async ({ app, device }, context) => readAndroidInsets(await selectAndroidOnly(context, device), app),
5330
+ format: (reading) => [
5331
+ describeDisplay(reading),
5332
+ `Safe area, from ${reading.source === "probe" ? "the app's probe" : "dumpsys"}: ${describeInsets(reading.safeArea)}`,
5333
+ `System bars: ${describeInsets(reading.systemBars)}`,
5334
+ `Cutout: ${describeInsets(reading.cutout)}`,
5335
+ ...reading.warnings.map((warning) => `Warning: ${warning}`)
5336
+ ].join("\n")
5337
+ });
5338
+
5339
+ // src/commands/key.ts
5340
+ import { z as z28 } from "zod";
5341
+
5342
+ // src/core/keys.ts
5343
+ var KEY_NAMES = [
5344
+ "back",
5345
+ "home",
5346
+ "recents",
5347
+ "enter",
4157
5348
  "tab",
4158
5349
  "space",
4159
5350
  "delete",
@@ -4221,19 +5412,19 @@ async function pressAndroid(target, key2, app) {
4221
5412
  var keyCommand = defineCommand({
4222
5413
  name: "key",
4223
5414
  summary: "Press one key, for example back, home or enter",
4224
- input: z21.object({
4225
- key: z21.enum(KEY_NAMES),
5415
+ input: z28.object({
5416
+ key: z28.enum(KEY_NAMES),
4226
5417
  ...waitFields,
4227
5418
  app: appField,
4228
5419
  device: deviceField
4229
5420
  }),
4230
5421
  positionals: ["key"],
4231
- output: z21.object({
4232
- key: z21.enum(KEY_NAMES),
5422
+ output: z28.object({
5423
+ key: z28.enum(KEY_NAMES),
4233
5424
  waited: waitedSchema.optional()
4234
5425
  }),
4235
5426
  run: async ({ key: key2, app, device, ...wait }, context) => {
4236
- const target = await selectAndroidDevice(context, device);
5427
+ const target = await selectAndroidOnly(context, device);
4237
5428
  const pressed = await pressAndroid(target, key2, app);
4238
5429
  const waited = await waitAfterAction(target, app, wait, "key");
4239
5430
  return { ...pressed, waited };
@@ -4242,10 +5433,10 @@ var keyCommand = defineCommand({
4242
5433
  });
4243
5434
 
4244
5435
  // src/commands/measure.ts
4245
- import { z as z23 } from "zod";
5436
+ import { z as z30 } from "zod";
4246
5437
 
4247
5438
  // src/core/measure.ts
4248
- import { z as z22 } from "zod";
5439
+ import { z as z29 } from "zod";
4249
5440
  function measureTargetOf(input) {
4250
5441
  const targets = [
4251
5442
  ...input.row === void 0 ? [] : [{ line: { axis: "row", at: input.row } }],
@@ -4325,12 +5516,12 @@ function joinShortRuns(runs, minLength) {
4325
5516
  flush();
4326
5517
  return out;
4327
5518
  }
4328
- var runSchema = z22.object({
4329
- from: z22.number().describe("The start along the line, in dp."),
4330
- to: z22.number().describe("The end along the line, in dp."),
4331
- length: z22.number().describe("In dp."),
4332
- pixels: z22.object({ from: z22.number(), to: z22.number() }).describe("The same run in px: from the first pixel to past the last."),
4333
- colour: z22.string().optional().describe(
5519
+ var runSchema = z29.object({
5520
+ from: z29.number().describe("The start along the line, in dp."),
5521
+ to: z29.number().describe("The end along the line, in dp."),
5522
+ length: z29.number().describe("In dp."),
5523
+ pixels: z29.object({ from: z29.number(), to: z29.number() }).describe("The same run in px: from the first pixel to past the last."),
5524
+ colour: z29.string().optional().describe(
4334
5525
  "The mean colour: #rrggbb, or #rrggbbaa when not opaque. Left out for a mix of short runs, for example text."
4335
5526
  )
4336
5527
  });
@@ -4343,20 +5534,20 @@ function runInDp(run, scale) {
4343
5534
  colour: run.colour
4344
5535
  };
4345
5536
  }
4346
- var lineSchema = z22.object({
4347
- axis: z22.enum(["row", "column"]),
4348
- at: z22.number().describe("The row (y) or the column (x) in dp, at the whole pixel used."),
4349
- pixel: z22.number().describe("The row or the column in px."),
4350
- runs: z22.array(runSchema)
5537
+ var lineSchema = z29.object({
5538
+ axis: z29.enum(["row", "column"]),
5539
+ at: z29.number().describe("The row (y) or the column (x) in dp, at the whole pixel used."),
5540
+ pixel: z29.number().describe("The row or the column in px."),
5541
+ runs: z29.array(runSchema)
4351
5542
  });
4352
- var elementMeasureSchema = z22.object({
5543
+ var elementMeasureSchema = z29.object({
4353
5544
  toScreen: insetsSchema.describe(
4354
5545
  "From each edge of the screen to the element, in dp."
4355
5546
  ),
4356
5547
  toSafeArea: insetsSchema.describe(
4357
5548
  "From each edge of the safe area to the element, in dp. Negative: the element reaches into the inset by that much."
4358
5549
  ),
4359
- offCentre: z22.object({
5550
+ offCentre: z29.object({
4360
5551
  screen: pointSchema,
4361
5552
  safeArea: pointSchema
4362
5553
  }).describe(
@@ -4398,14 +5589,14 @@ function describeRun({ from, to, length, colour }) {
4398
5589
  // src/commands/measure.ts
4399
5590
  var DEFAULT_TOLERANCE = 8;
4400
5591
  var DEFAULT_MIN_LENGTH = 1;
4401
- var lineField = (axis, coordinate) => z23.number().min(0).optional().describe(
5592
+ var lineField = (axis, coordinate) => z30.number().min(0).optional().describe(
4402
5593
  `Measure the colour runs along this ${axis} of a new screenshot: ${coordinate} in dp, from the top-left corner.`
4403
5594
  );
4404
5595
  var measureCommand = defineCommand({
4405
5596
  name: "measure",
4406
5597
  summary: "Measure the colour runs along a row or a column, or where an element sits on the screen and in the safe area",
4407
5598
  readOnly: true,
4408
- input: z23.object({
5599
+ input: z30.object({
4409
5600
  row: lineField("row", "y"),
4410
5601
  column: lineField("column", "x"),
4411
5602
  text: selectorFields.text.describe(
@@ -4417,10 +5608,10 @@ var measureCommand = defineCommand({
4417
5608
  id: selectorFields.id.describe(
4418
5609
  'Measure the element with this id: the resource-id on Android, or the part after ":id/".'
4419
5610
  ),
4420
- tolerance: z23.number().int().min(0).max(255).optional().describe(
5611
+ tolerance: z30.number().int().min(0).max(255).optional().describe(
4421
5612
  `For a row or a column: a pixel stays in the run while no colour channel differs from the run's first pixel by more than this (0\u2013255). ${DEFAULT_TOLERANCE} by default.`
4422
5613
  ),
4423
- minLength: z23.number().min(0).optional().describe(
5614
+ minLength: z30.number().min(0).optional().describe(
4424
5615
  `For a row or a column, in dp: two or more runs in a row that are each shorter than this become one run with no colour, for example text. ${DEFAULT_MIN_LENGTH} by default; 0 keeps each run.`
4425
5616
  ),
4426
5617
  app: appField,
@@ -4431,14 +5622,14 @@ var measureCommand = defineCommand({
4431
5622
  "The colour runs, from the left or the top. They cover the whole line."
4432
5623
  ),
4433
5624
  element: elementSchema.extend(elementMeasureSchema.shape).extend({
4434
- safeAreaSource: z23.enum(["probe", "dumpsys"]).describe("Where the safe area comes from, as in `insets`.")
5625
+ safeAreaSource: z30.enum(["probe", "dumpsys"]).describe("Where the safe area comes from, as in `insets`.")
4435
5626
  }).optional(),
4436
- warnings: z23.array(z23.string())
5627
+ warnings: z30.array(z30.string())
4437
5628
  }),
4438
5629
  run: async (input, context) => {
4439
5630
  const { tolerance: tolerance2 = DEFAULT_TOLERANCE, minLength = DEFAULT_MIN_LENGTH } = input;
4440
5631
  const measured = measureTargetOf(input);
4441
- const target = await selectAndroidDevice(context, input.device);
5632
+ const target = await selectAndroidOnly(context, input.device);
4442
5633
  if (measured.line) {
4443
5634
  const { axis, at } = measured.line;
4444
5635
  const { png, display } = await captureAndroid(target, input.app);
@@ -4509,57 +5700,12 @@ var measureCommand = defineCommand({
4509
5700
  });
4510
5701
 
4511
5702
  // src/commands/open-url.ts
4512
- import { z as z24 } from "zod";
4513
-
4514
- // src/drivers/android/open-url.ts
4515
- async function openUrlAndroid(target, url, app) {
4516
- if (!app && target.kind === "device") {
4517
- throw new LoupeError(
4518
- "invalid_input",
4519
- `${target.serial} is a real device, so loupe needs the "app" option: the package of the app under test. Then only that app opens the link.`
4520
- );
4521
- }
4522
- const result = await target.adb.result([
4523
- "shell",
4524
- "am",
4525
- "start",
4526
- "-W",
4527
- "-a",
4528
- "android.intent.action.VIEW",
4529
- "-d",
4530
- shellQuote(url),
4531
- ...app ? ["-p", app] : []
4532
- ]);
4533
- const start = parseAmStart(
4534
- `${result.stdout.toString("utf8")}
4535
- ${result.stderr.toString("utf8")}`
4536
- );
4537
- if (start.unresolved) {
4538
- throw new LoupeError(
4539
- "no_handler",
4540
- app ? `${app} doesn't open ${url} on ${target.serial}.` : `No app on ${target.serial} opens ${url}.`
4541
- );
4542
- }
4543
- if (start.status !== "ok") {
4544
- throw new LoupeError(
4545
- "tool_failed",
4546
- start.error ? `am start failed on ${target.serial}: ${start.error}` : `am start failed on ${target.serial} with exit code ${result.code}.`
4547
- );
4548
- }
4549
- return {
4550
- url,
4551
- activity: start.activity,
4552
- launchState: start.launchState?.toLowerCase(),
4553
- totalTime: start.totalTime
4554
- };
4555
- }
4556
-
4557
- // src/commands/open-url.ts
5703
+ import { z as z31 } from "zod";
4558
5704
  var openUrlCommand = defineCommand({
4559
5705
  name: "open-url",
4560
5706
  summary: "Open a link (a deep link or a web page), and wait until it opens",
4561
- input: z24.object({
4562
- url: z24.string().regex(
5707
+ input: z31.object({
5708
+ url: z31.string().regex(
4563
5709
  /^[A-Za-z][A-Za-z0-9+.-]*:\S+$/,
4564
5710
  "A URL starts with a scheme, for example https: or exp:, and has no spaces."
4565
5711
  ),
@@ -4570,15 +5716,15 @@ var openUrlCommand = defineCommand({
4570
5716
  device: deviceField
4571
5717
  }),
4572
5718
  positionals: ["url"],
4573
- output: z24.object({
4574
- url: z24.string(),
4575
- activity: z24.string().optional().describe("The activity that opened the link: package/activity."),
4576
- launchState: z24.string().optional().describe("cold, warm or hot."),
4577
- totalTime: z24.number().optional().describe("Milliseconds, as Android measured the start."),
5719
+ output: z31.object({
5720
+ url: z31.string(),
5721
+ activity: z31.string().optional().describe("The activity that opened the link: package/activity."),
5722
+ launchState: z31.string().optional().describe("cold, warm or hot."),
5723
+ totalTime: z31.number().optional().describe("Milliseconds, as Android measured the start."),
4578
5724
  waited: waitedSchema.optional()
4579
5725
  }),
4580
5726
  run: async ({ url, app, device, ...wait }, context) => {
4581
- const target = await selectAndroidDevice(context, device);
5727
+ const target = await selectAndroidOnly(context, device);
4582
5728
  const opened = await openUrlAndroid(target, url, app);
4583
5729
  const waited = await waitAfterAction(target, app, wait, "open-url");
4584
5730
  return { ...opened, waited };
@@ -4594,21 +5740,21 @@ var openUrlCommand = defineCommand({
4594
5740
  });
4595
5741
 
4596
5742
  // src/commands/pinch.ts
4597
- import { z as z26 } from "zod";
5743
+ import { z as z33 } from "zod";
4598
5744
 
4599
5745
  // src/core/pinch.ts
4600
- import { z as z25 } from "zod";
5746
+ import { z as z32 } from "zod";
4601
5747
  var pinchFields = {
4602
- scale: z25.number().positive().default(1).describe(
5748
+ scale: z32.number().positive().default(1).describe(
4603
5749
  "The span between the fingers at the end \xF7 the span at the start. Above 1 spreads them (zoom in); below 1 brings them together (zoom out)."
4604
5750
  ),
4605
- distance: z25.number().positive().default(200).describe(
5751
+ distance: z32.number().positive().default(200).describe(
4606
5752
  "The smaller span between the fingers, in dp: where a spread starts, or where a pinch ends. Android ignores a span under about 170 dp."
4607
5753
  ),
4608
- angle: z25.number().min(0).max(180).optional().describe(
5754
+ angle: z32.number().min(0).max(180).optional().describe(
4609
5755
  "The line between the fingers at the start, in degrees clockwise from across the screen: 0 is across, 90 is down. Default: along the longer side of the screen."
4610
5756
  ),
4611
- turn: z25.number().default(0).describe(
5757
+ turn: z32.number().default(0).describe(
4612
5758
  "Degrees to turn the fingers around the centre during the gesture, clockwise. A negative value turns them the other way (on the CLI: --turn=-90)."
4613
5759
  )
4614
5760
  };
@@ -4651,21 +5797,21 @@ function planPinch(shape, screen, steps) {
4651
5797
  });
4652
5798
  return { angle, span: { from, to }, steps: plan };
4653
5799
  }
4654
- var pinchSchema = z25.object({
4655
- orientation: z25.enum(ORIENTATIONS),
5800
+ var pinchSchema = z32.object({
5801
+ orientation: z32.enum(ORIENTATIONS),
4656
5802
  centre: pointSchema.describe("The centre of the pinch, in dp."),
4657
5803
  element: elementSchema.optional().describe("The element that loupe pinched, when the input named one."),
4658
- fingers: z25.array(z25.object({ from: pointSchema, to: pointSchema })).describe("Where each finger touched and where it lifted, in dp."),
4659
- span: z25.object({ from: z25.number(), to: z25.number() }).describe(
5804
+ fingers: z32.array(z32.object({ from: pointSchema, to: pointSchema })).describe("Where each finger touched and where it lifted, in dp."),
5805
+ span: z32.object({ from: z32.number(), to: z32.number() }).describe(
4660
5806
  "The span between the fingers at the start and at the end, in dp."
4661
5807
  ),
4662
- scale: z25.number(),
4663
- angle: z25.number().describe(
5808
+ scale: z32.number(),
5809
+ angle: z32.number().describe(
4664
5810
  "The line between the fingers at the start, in degrees clockwise from across the screen."
4665
5811
  ),
4666
- turn: z25.number().describe("In degrees, clockwise."),
4667
- duration: z25.number().describe("In milliseconds."),
4668
- moveTime: z25.number().describe("Milliseconds that the move took, measured on the host.")
5812
+ turn: z32.number().describe("In degrees, clockwise."),
5813
+ duration: z32.number().describe("In milliseconds."),
5814
+ moveTime: z32.number().describe("Milliseconds that the move took, measured on the host.")
4669
5815
  });
4670
5816
  function describePinch(pinch) {
4671
5817
  const { centre, element, span, turn, orientation, moveTime } = pinch;
@@ -4712,7 +5858,7 @@ async function pinchAndroid(target, centre, options, app) {
4712
5858
  var pinchCommand = defineCommand({
4713
5859
  name: "pinch",
4714
5860
  summary: "Pinch or spread two fingers around a point or an element, and turn them (emulator only)",
4715
- input: z26.object({
5861
+ input: z33.object({
4716
5862
  x: coordinateField("x").optional(),
4717
5863
  y: coordinateField("y").optional(),
4718
5864
  ...selectorFields,
@@ -4740,7 +5886,7 @@ var pinchCommand = defineCommand({
4740
5886
  waitTimeout,
4741
5887
  ...shape
4742
5888
  }, context) => {
4743
- const target = await selectAndroidDevice(context, device);
5889
+ const target = await selectAndroidOnly(context, device);
4744
5890
  const { point, element } = await aimAndroid(
4745
5891
  target,
4746
5892
  targetOf({ x, y, text, label: label2, id }),
@@ -4759,38 +5905,38 @@ var pinchCommand = defineCommand({
4759
5905
  });
4760
5906
 
4761
5907
  // src/commands/rotate.ts
4762
- import { z as z27 } from "zod";
5908
+ import { z as z34 } from "zod";
4763
5909
  var rotateCommand = defineCommand({
4764
5910
  name: "rotate",
4765
5911
  summary: "Turn the screen, and wait until it has turned",
4766
- input: z27.object({
4767
- to: z27.enum(["portrait", "landscape-left", "landscape-right"]).describe(orientationDescription),
5912
+ input: z34.object({
5913
+ to: z34.enum(["portrait", "landscape-left", "landscape-right"]).describe(orientationDescription),
4768
5914
  device: deviceField,
4769
- timeout: z27.number().int().min(0).default(5e3).describe("Milliseconds to wait for the screen to turn.")
5915
+ timeout: z34.number().int().min(0).default(5e3).describe("Milliseconds to wait for the screen to turn.")
4770
5916
  }),
4771
5917
  positionals: ["to"],
4772
5918
  output: displaySchema,
4773
- run: async ({ to, device, timeout }, context) => rotateAndroid(await selectAndroidDevice(context, device), to, { timeout }),
5919
+ run: async ({ to, device, timeout }, context) => rotateAndroid(await selectAndroidOnly(context, device), to, { timeout }),
4774
5920
  format: describeDisplay
4775
5921
  });
4776
5922
 
4777
5923
  // src/commands/screenshot.ts
4778
- import { z as z28 } from "zod";
5924
+ import { z as z35 } from "zod";
4779
5925
  var screenshotCommand = defineCommand({
4780
5926
  name: "screenshot",
4781
5927
  summary: "Save the screen as a PNG file, upright in each orientation",
4782
5928
  readOnly: true,
4783
- input: z28.object({
4784
- out: z28.string().min(1).describe(
5929
+ input: z35.object({
5930
+ out: z35.string().min(1).describe(
4785
5931
  "The PNG file to write. loupe makes its folder, and replaces a file that is there."
4786
5932
  ),
4787
- crop: z28.string().regex(
5933
+ crop: z35.string().regex(
4788
5934
  CROP_PATTERN,
4789
5935
  "A crop is x,y,width,height in dp, for example 0,0,411,64."
4790
5936
  ).optional().describe(
4791
5937
  "Save only this part of the screen: x,y,width,height in dp, from the top-left corner of the current orientation. The part outside the screen is left out."
4792
5938
  ),
4793
- scale: z28.number().gt(0).max(1).optional().describe(
5939
+ scale: z35.number().gt(0).max(1).optional().describe(
4794
5940
  "Scale the image down by this factor, for example 0.5 for half the width and half the height. A smaller file costs fewer tokens."
4795
5941
  ),
4796
5942
  app: appField,
@@ -4798,8 +5944,8 @@ var screenshotCommand = defineCommand({
4798
5944
  }),
4799
5945
  positionals: ["out"],
4800
5946
  output: displaySchema.extend({
4801
- file: z28.string().describe("The PNG file, as an absolute path."),
4802
- image: z28.object({ width: z28.number(), height: z28.number() }).describe(
5947
+ file: z35.string().describe("The PNG file, as an absolute path."),
5948
+ image: z35.object({ width: z35.number(), height: z35.number() }).describe(
4803
5949
  "The size of the PNG file, in px: the screen, or the crop, after the scale."
4804
5950
  ),
4805
5951
  crop: rectSchema.optional().describe(
@@ -4808,7 +5954,7 @@ var screenshotCommand = defineCommand({
4808
5954
  }),
4809
5955
  run: async ({ out, crop, scale, app, device }, context) => {
4810
5956
  const capture = await captureAndroid(
4811
- await selectAndroidDevice(context, device),
5957
+ await selectAndroidOnly(context, device),
4812
5958
  app
4813
5959
  );
4814
5960
  const { pixels, display } = capture;
@@ -4847,7 +5993,7 @@ var screenshotCommand = defineCommand({
4847
5993
  });
4848
5994
 
4849
5995
  // src/commands/scroll-to.ts
4850
- import { z as z29 } from "zod";
5996
+ import { z as z36 } from "zod";
4851
5997
 
4852
5998
  // src/core/scroll.ts
4853
5999
  var DIRECTIONS = ["down", "up", "left", "right"];
@@ -4862,7 +6008,7 @@ function everyNode3(nodes) {
4862
6008
  function area({ width, height }) {
4863
6009
  return width * height;
4864
6010
  }
4865
- function scrollViewFor(nodes, direction, screen, id) {
6011
+ function scrollViewFor(nodes, direction, screen, platform, id) {
4866
6012
  if (id !== void 0) {
4867
6013
  const named = findNode(
4868
6014
  nodes,
@@ -4883,7 +6029,7 @@ function scrollViewFor(nodes, direction, screen, id) {
4883
6029
  (node) => node.scrollable && node.frame.width > 0 && node.frame.height > 0 && intersection(node.frame, screenRect2) !== null
4884
6030
  );
4885
6031
  const along = scrollers.filter(
4886
- (node) => scrollAxisOf(node) === axisOf(direction)
6032
+ (node) => scrollAxisOf(node, platform) === axisOf(direction)
4887
6033
  );
4888
6034
  const candidates = along.length > 0 ? along : scrollers;
4889
6035
  const innermost = candidates.filter((node) => {
@@ -4901,19 +6047,21 @@ function scrollStroke(frame, direction, share = SCROLL_SHARE) {
4901
6047
  const along = (at) => axisOf(direction) === "y" ? { x: frame.x + frame.width / 2, y: frame.y + frame.height * at } : { x: frame.x + frame.width * at, y: frame.y + frame.height / 2 };
4902
6048
  return direction === "down" || direction === "right" ? { from: along(start), to: along(end) } : { from: along(end), to: along(start) };
4903
6049
  }
4904
- function viewContent(nodes, frame) {
4905
- return JSON.stringify(
4906
- everyNode3(nodes).filter((node) => intersection(node.frame, frame) !== null).map(({ type, text, label: label2, id, frame: { x, y, width, height } }) => [
4907
- type,
4908
- text,
4909
- label2,
4910
- id,
4911
- x,
4912
- y,
4913
- width,
4914
- height
4915
- ])
4916
- );
6050
+ function viewContent(nodes, frame, platform, app) {
6051
+ const rows = [];
6052
+ const walk = (list) => {
6053
+ for (const node of list) {
6054
+ if (isExpoGoOverlay(node, app, platform)) continue;
6055
+ if (intersection(node.frame, frame) !== null) {
6056
+ const { type, text, label: label2, id } = node;
6057
+ const { x, y, width, height } = node.frame;
6058
+ rows.push([type, text, label2, id, x, y, width, height]);
6059
+ }
6060
+ walk(node.children ?? []);
6061
+ }
6062
+ };
6063
+ walk(nodes);
6064
+ return JSON.stringify(rows);
4917
6065
  }
4918
6066
  function cutAtIncomingEdge(element, view, direction, tolerance2) {
4919
6067
  switch (direction) {
@@ -4949,7 +6097,13 @@ async function scrollToAndroid(target, selector, options, app) {
4949
6097
  let nudged = false;
4950
6098
  let ended = false;
4951
6099
  const scroll = async (share) => {
4952
- const next = scrollViewFor(ui.nodes, direction, ui.display.size, options.in);
6100
+ const next = scrollViewFor(
6101
+ ui.nodes,
6102
+ direction,
6103
+ ui.display.size,
6104
+ "android",
6105
+ options.in
6106
+ );
4953
6107
  if (!next) {
4954
6108
  throw new LoupeError(
4955
6109
  "element_not_found",
@@ -4957,12 +6111,12 @@ async function scrollToAndroid(target, selector, options, app) {
4957
6111
  );
4958
6112
  }
4959
6113
  view = next;
4960
- const before = viewContent(ui.nodes, next.frame);
6114
+ const before = viewContent(ui.nodes, next.frame, "android", app);
4961
6115
  const { from, to } = scrollStroke(next.frame, direction, share);
4962
6116
  await dragAndroid(target, from, to, STROKE, app);
4963
6117
  scrolls += 1;
4964
6118
  ui = await readAndroidUi(target, app);
4965
- ended = viewContent(ui.nodes, next.frame) === before;
6119
+ ended = viewContent(ui.nodes, next.frame, "android", app) === before;
4966
6120
  };
4967
6121
  for (; ; ) {
4968
6122
  if (elementsOnScreen(ui.nodes, selector, ui.display.size).length > 0) {
@@ -4972,7 +6126,13 @@ async function scrollToAndroid(target, selector, options, app) {
4972
6126
  ui.display.size,
4973
6127
  "Scroll to one by another selector."
4974
6128
  );
4975
- const around = view ?? scrollViewFor(ui.nodes, direction, ui.display.size, options.in);
6129
+ const around = view ?? scrollViewFor(
6130
+ ui.nodes,
6131
+ direction,
6132
+ ui.display.size,
6133
+ "android",
6134
+ options.in
6135
+ );
4976
6136
  const cut = around !== null && intersection(element.frame, around.frame) !== null && cutAtIncomingEdge(
4977
6137
  element.frame,
4978
6138
  around.frame,
@@ -5009,13 +6169,13 @@ async function scrollToAndroid(target, selector, options, app) {
5009
6169
  }
5010
6170
  async function scrollOnceAndroid(target, app) {
5011
6171
  const ui = await readAndroidUi(target, app);
5012
- const view = scrollViewFor(ui.nodes, "down", ui.display.size);
5013
- if (!view || scrollAxisOf(view) !== "y") return void 0;
5014
- const top = viewContent(ui.nodes, view.frame);
6172
+ const view = scrollViewFor(ui.nodes, "down", ui.display.size, "android");
6173
+ if (!view || scrollAxisOf(view, "android") !== "y") return void 0;
6174
+ const top = viewContent(ui.nodes, view.frame, "android", app);
5015
6175
  const { from, to } = scrollStroke(view.frame, "down");
5016
6176
  await dragAndroid(target, from, to, STROKE, app);
5017
6177
  const after = await readAndroidUi(target, app);
5018
- return viewContent(after.nodes, view.frame) === top ? void 0 : { frame: view.frame, top };
6178
+ return viewContent(after.nodes, view.frame, "android", app) === top ? void 0 : { frame: view.frame, top };
5019
6179
  }
5020
6180
  async function flingToTopAndroid(target, { frame, top }, app) {
5021
6181
  const { from, to } = scrollStroke(frame, "up");
@@ -5024,7 +6184,12 @@ async function flingToTopAndroid(target, { frame, top }, app) {
5024
6184
  while (flings < MAX_FLINGS) {
5025
6185
  await swipeAndroid(target, from, to, FLING_MS, app);
5026
6186
  flings += 1;
5027
- const now = viewContent((await readAndroidUi(target, app)).nodes, frame);
6187
+ const now = viewContent(
6188
+ (await readAndroidUi(target, app)).nodes,
6189
+ frame,
6190
+ "android",
6191
+ app
6192
+ );
5028
6193
  if (now === top) return [];
5029
6194
  if (now === shown) break;
5030
6195
  shown = now;
@@ -5039,7 +6204,7 @@ var DEFAULT_MAX_SCROLLS = 20;
5039
6204
  var scrollToCommand = defineCommand({
5040
6205
  name: "scroll-to",
5041
6206
  summary: "Scroll until the element with a text, label or id is in view, and give its frame",
5042
- input: z29.object({
6207
+ input: z36.object({
5043
6208
  text: selectorFields.text.describe(
5044
6209
  "Scroll to the element with this text: the whole text, not a part."
5045
6210
  ),
@@ -5049,13 +6214,13 @@ var scrollToCommand = defineCommand({
5049
6214
  id: selectorFields.id.describe(
5050
6215
  'Scroll to the element with this id: the resource-id on Android, or the part after ":id/".'
5051
6216
  ),
5052
- direction: z29.enum(DIRECTIONS).default("down").describe(
6217
+ direction: z36.enum(DIRECTIONS).default("down").describe(
5053
6218
  "Where the content to show is: down shows what is below, so the touch moves up."
5054
6219
  ),
5055
- maxScrolls: z29.number().int().min(0).max(200).default(DEFAULT_MAX_SCROLLS).describe(
6220
+ maxScrolls: z36.number().int().min(0).max(200).default(DEFAULT_MAX_SCROLLS).describe(
5056
6221
  "The most drags. Each one moves the scroll view by 60 % of its length."
5057
6222
  ),
5058
- in: z29.string().min(1).optional().describe(
6223
+ in: z36.string().min(1).optional().describe(
5059
6224
  "The id of the scroll view to drag. By default, the innermost scroll view on the screen that scrolls along the direction; the largest one when there are more."
5060
6225
  ),
5061
6226
  app: appField,
@@ -5063,13 +6228,13 @@ var scrollToCommand = defineCommand({
5063
6228
  }),
5064
6229
  output: displaySchema.extend({
5065
6230
  element: elementSchema.describe("The element, as it shows at the end."),
5066
- direction: z29.enum(DIRECTIONS),
5067
- scrolls: z29.number().describe("The drags that loupe made: 0 when the element was in view."),
6231
+ direction: z36.enum(DIRECTIONS),
6232
+ scrolls: z36.number().describe("The drags that loupe made: 0 when the element was in view."),
5068
6233
  scrollView: elementSchema.optional().describe("The scroll view of the last drag. Left out with no drag.")
5069
6234
  }),
5070
6235
  run: async (input, context) => {
5071
6236
  const selector = selectorOf(input);
5072
- const target = await selectAndroidDevice(context, input.device);
6237
+ const target = await selectAndroidOnly(context, input.device);
5073
6238
  const { display, ...scrolled } = await scrollToAndroid(
5074
6239
  target,
5075
6240
  selector,
@@ -5093,12 +6258,12 @@ var scrollToCommand = defineCommand({
5093
6258
  });
5094
6259
 
5095
6260
  // src/commands/sweep.ts
5096
- import path6 from "path";
5097
- import { z as z31 } from "zod";
6261
+ import path7 from "path";
6262
+ import { z as z38 } from "zod";
5098
6263
 
5099
6264
  // src/core/sweep.ts
5100
- import path5 from "path";
5101
- import { z as z30 } from "zod";
6265
+ import path6 from "path";
6266
+ import { z as z37 } from "zod";
5102
6267
 
5103
6268
  // src/core/contact-sheet.ts
5104
6269
  var BACKGROUND = [32, 32, 32];
@@ -5208,47 +6373,56 @@ function contactSheet(cells, { thumbnailWidth = 240, columns, maxWidth = 1600 }
5208
6373
 
5209
6374
  // src/core/sweep.ts
5210
6375
  var SWEEP_THEMES = ["light", "dark"];
6376
+ var SWEEP_DIRECTIONS = ["ltr", "rtl"];
5211
6377
  var THUMBNAIL_WIDTH = 240;
5212
6378
  var NO_SHOT = { width: THUMBNAIL_WIDTH, height: 427 };
5213
- var sweepScreenSchema = z30.object({
5214
- number: z30.number().describe(
6379
+ var sweepScreenSchema = z37.object({
6380
+ number: z37.number().describe(
5215
6381
  "The place of the link in the list, from 1: the number of its cell on each contact sheet, and of its screenshot file."
5216
6382
  ),
5217
- url: z30.string(),
5218
- variant: z30.string().describe("The orientation and the theme: portrait-dark."),
5219
- scrolled: z30.boolean().describe(
6383
+ url: z37.string(),
6384
+ variant: z37.string().describe(
6385
+ "The orientation and the theme, and the direction in a sweep with directions: portrait-dark, portrait-dark-rtl."
6386
+ ),
6387
+ scrolled: z37.boolean().describe(
5220
6388
  "True for the check after one scroll down. It comes right after the check of its link at the top."
5221
6389
  ),
5222
- passed: z30.boolean().describe("True when loupe checked the screen and every rule passed."),
6390
+ reloaded: z37.boolean().describe(
6391
+ "True when loupe stopped the app before this link, so the link started it again."
6392
+ ),
6393
+ passed: z37.boolean().describe("True when loupe checked the screen and every rule passed."),
5223
6394
  check: screenCheckSchema.optional().describe("The result of each rule, as `check` gives it."),
5224
- error: z30.object({ code: z30.enum(ERROR_CODES), message: z30.string() }).optional().describe(
6395
+ error: z37.object({ code: z37.enum(ERROR_CODES), message: z37.string() }).optional().describe(
5225
6396
  "Why loupe could not check this screen. The sweep went on with the next one."
5226
6397
  ),
5227
- screenshot: z30.string().optional().describe("The file. Left out when loupe could take no screenshot."),
5228
- warnings: z30.array(z30.string()),
5229
- ms: z30.number().describe(
6398
+ screenshot: z37.string().optional().describe("The file. Left out when loupe could take no screenshot."),
6399
+ warnings: z37.array(z37.string()),
6400
+ ms: z37.number().describe(
5230
6401
  "Milliseconds for this screen, from the open, or from the scroll for a scrolled screen."
5231
6402
  )
5232
6403
  });
5233
- var sweepVariantSchema = z30.object({
5234
- name: z30.string().describe("The orientation and the theme: portrait-dark."),
5235
- orientation: z30.enum(ORIENTATIONS),
5236
- theme: z30.string().describe("light or dark, or the setting of the device."),
5237
- sheet: z30.string().describe(
6404
+ var sweepVariantSchema = z37.object({
6405
+ name: z37.string().describe(
6406
+ "The orientation and the theme, and the direction in a sweep with directions: portrait-dark, portrait-dark-rtl."
6407
+ ),
6408
+ orientation: z37.enum(ORIENTATIONS),
6409
+ theme: z37.string().describe("light or dark, or the setting of the device."),
6410
+ direction: z37.enum(SWEEP_DIRECTIONS).optional().describe("ltr or rtl. Left out in a sweep with no directions."),
6411
+ sheet: z37.string().describe(
5238
6412
  "The contact sheet: a thumbnail of each screen with its number, in a red frame when the screen failed."
5239
6413
  ),
5240
- scrolledSheet: z30.string().optional().describe(
6414
+ scrolledSheet: z37.string().optional().describe(
5241
6415
  "The contact sheet of the scrolled screens, each with the number of its link. Left out when no screen scrolled."
5242
6416
  ),
5243
- screens: z30.number().describe("The screens checked: one for each link, and each scrolled one."),
5244
- failed: z30.number()
6417
+ screens: z37.number().describe("The screens checked: one for each link, and each scrolled one."),
6418
+ failed: z37.number()
5245
6419
  });
5246
- var sweepReportSchema = z30.object({
5247
- out: z30.string().describe("The folder with each file of the sweep."),
5248
- passed: z30.boolean().describe("True when every screen passed."),
5249
- variants: z30.array(sweepVariantSchema),
5250
- screens: z30.array(sweepScreenSchema),
5251
- warnings: z30.array(z30.string())
6420
+ var sweepReportSchema = z37.object({
6421
+ out: z37.string().describe("The folder with each file of the sweep."),
6422
+ passed: z37.boolean().describe("True when every screen passed."),
6423
+ variants: z37.array(sweepVariantSchema),
6424
+ screens: z37.array(sweepScreenSchema),
6425
+ warnings: z37.array(z37.string())
5252
6426
  });
5253
6427
  function fileNumber(number, count) {
5254
6428
  return String(number).padStart(Math.max(2, String(count).length), "0");
@@ -5318,107 +6492,134 @@ function outcomeOf(screen) {
5318
6492
  if (screen.error) return `error ${screen.error.code}`;
5319
6493
  return screen.passed ? "passed" : "failed";
5320
6494
  }
5321
- async function sweep(driver, { urls, orientations, themes, out, scroll }, { signal, progress } = {}) {
5322
- const folder = path5.resolve(out);
6495
+ async function sweep(driver, {
6496
+ urls,
6497
+ orientations,
6498
+ themes,
6499
+ out,
6500
+ scroll,
6501
+ reloadEvery,
6502
+ directions
6503
+ }, { signal, progress } = {}) {
6504
+ const folder = path6.resolve(out);
5323
6505
  const start = await driver.look();
5324
6506
  const screens = [];
5325
6507
  const variants = [];
5326
6508
  const warnings = [];
5327
6509
  const orientationList = orientations ?? [start.orientation];
5328
6510
  const themeList = themes ?? [start.theme];
5329
- const total = urls.length * orientationList.length * themeList.length;
6511
+ const directionList = directions ? [...directions] : [void 0];
6512
+ const total = urls.length * orientationList.length * themeList.length * directionList.length;
5330
6513
  let done = 0;
6514
+ let opens = 0;
6515
+ let coldNext = false;
5331
6516
  try {
5332
- for (const orientation of orientationList) {
5333
- for (const theme of themeList) {
5334
- const name2 = `${orientation}-${theme}`;
5335
- const topCells = [];
5336
- const scrolledCells = [];
5337
- let count = 0;
5338
- let failed = 0;
5339
- const keep = async (screen, png, began) => {
5340
- if (png) {
5341
- const file = `${fileNumber(screen.number, urls.length)}${screen.scrolled ? "-scrolled" : ""}.png`;
5342
- screen.screenshot = await writeOutputFile(
5343
- path5.join(folder, name2, file),
5344
- png
5345
- );
5346
- }
5347
- screen.ms = Date.now() - began;
5348
- screens.push(screen);
5349
- count += 1;
5350
- if (!screen.passed) failed += 1;
5351
- const image = thumbnailOf(png);
5352
- const { number } = screen;
5353
- const cells = screen.scrolled ? scrolledCells : topCells;
5354
- cells.push(
5355
- image ? { number, image, failed: !screen.passed } : { number, failed: true }
5356
- );
5357
- };
5358
- for (const [index, url] of urls.entries()) {
5359
- if (signal?.aborted) {
5360
- throw new LoupeError(
5361
- "cancelled",
5362
- `The call was cancelled, so loupe stopped the sweep after ${done} of ${total} screens. The screenshots so far are in ${folder}; it wrote no report.`
6517
+ for (const direction of directionList) {
6518
+ if (direction) {
6519
+ const { restarted } = await driver.setDirection(direction);
6520
+ if (restarted) coldNext = true;
6521
+ }
6522
+ for (const orientation of orientationList) {
6523
+ for (const theme of themeList) {
6524
+ const name2 = direction ? `${orientation}-${theme}-${direction}` : `${orientation}-${theme}`;
6525
+ const topCells = [];
6526
+ const scrolledCells = [];
6527
+ let count = 0;
6528
+ let failed = 0;
6529
+ const keep = async (screen, png, began) => {
6530
+ if (png) {
6531
+ const file = `${fileNumber(screen.number, urls.length)}${screen.scrolled ? "-scrolled" : ""}.png`;
6532
+ screen.screenshot = await writeOutputFile(
6533
+ path6.join(folder, name2, file),
6534
+ png
6535
+ );
6536
+ }
6537
+ screen.ms = Date.now() - began;
6538
+ screens.push(screen);
6539
+ count += 1;
6540
+ if (!screen.passed) failed += 1;
6541
+ const image = thumbnailOf(png);
6542
+ const { number } = screen;
6543
+ const cells = screen.scrolled ? scrolledCells : topCells;
6544
+ cells.push(
6545
+ image ? { number, image, failed: !screen.passed } : { number, failed: true }
5363
6546
  );
5364
- }
5365
- const screenOf = (scrolled) => ({
5366
- number: index + 1,
5367
- url,
5368
- variant: name2,
5369
- scrolled,
5370
- passed: false,
5371
- warnings: [],
5372
- ms: 0
5373
- });
5374
- const opened = Date.now();
5375
- const top = screenOf(false);
5376
- const png = await checkScreen(driver, top, async () => {
5377
- await driver.open(url);
5378
- if (orientations) await driver.rotate(orientation);
5379
- if (themes) {
5380
- top.warnings.push(...await driver.setTheme(theme));
6547
+ };
6548
+ for (const [index, url] of urls.entries()) {
6549
+ if (signal?.aborted) {
6550
+ throw new LoupeError(
6551
+ "cancelled",
6552
+ `The call was cancelled, so loupe stopped the sweep after ${done} of ${total} screens. The screenshots so far are in ${folder}; it wrote no report.`
6553
+ );
5381
6554
  }
5382
- });
5383
- await keep(top, png, opened);
5384
- let below;
5385
- if (scroll && !top.error) {
5386
- const began = Date.now();
5387
- const screen = screenOf(true);
5388
- const shown = await checkScrolled(driver, screen);
5389
- if (shown) {
5390
- await keep(screen, shown.png, began);
5391
- below = screen;
6555
+ const reload = reloadEvery !== void 0 && opens > 0 && opens % reloadEvery === 0;
6556
+ opens += 1;
6557
+ const cold = reload || coldNext;
6558
+ coldNext = false;
6559
+ const screenOf = (scrolled) => ({
6560
+ number: index + 1,
6561
+ url,
6562
+ variant: name2,
6563
+ scrolled,
6564
+ reloaded: reload && !scrolled,
6565
+ passed: false,
6566
+ warnings: [],
6567
+ ms: 0
6568
+ });
6569
+ const opened = Date.now();
6570
+ const top = screenOf(false);
6571
+ const png = await checkScreen(driver, top, async () => {
6572
+ if (reload) await driver.reload();
6573
+ await driver.open(url, { cold, direction });
6574
+ if (orientations) await driver.rotate(orientation);
6575
+ if (themes) {
6576
+ top.warnings.push(
6577
+ ...await driver.setTheme(theme)
6578
+ );
6579
+ }
6580
+ });
6581
+ await keep(top, png, opened);
6582
+ let below;
6583
+ if (scroll && !top.error) {
6584
+ const began = Date.now();
6585
+ const screen = screenOf(true);
6586
+ const shown = await checkScrolled(driver, screen);
6587
+ if (shown) {
6588
+ await keep(screen, shown.png, began);
6589
+ below = screen;
6590
+ }
5392
6591
  }
6592
+ done += 1;
6593
+ progress?.({
6594
+ progress: done,
6595
+ total,
6596
+ message: `${name2}, link ${index + 1} of ${urls.length}${reload ? ", after a restart" : ""}: ${outcomeOf(top)}${below ? `; scrolled: ${outcomeOf(below)}` : ""}`
6597
+ });
5393
6598
  }
5394
- done += 1;
5395
- progress?.({
5396
- progress: done,
5397
- total,
5398
- message: `${name2}, link ${index + 1} of ${urls.length}: ${outcomeOf(top)}${below ? `; scrolled: ${outcomeOf(below)}` : ""}`
6599
+ variants.push({
6600
+ name: name2,
6601
+ orientation,
6602
+ theme,
6603
+ ...direction ? { direction } : {},
6604
+ sheet: await writeSheet(path6.join(folder, `${name2}.png`), topCells),
6605
+ ...scrolledCells.length > 0 ? {
6606
+ scrolledSheet: await writeSheet(
6607
+ path6.join(folder, `${name2}-scrolled.png`),
6608
+ scrolledCells
6609
+ )
6610
+ } : {},
6611
+ screens: count,
6612
+ failed
5399
6613
  });
5400
6614
  }
5401
- variants.push({
5402
- name: name2,
5403
- orientation,
5404
- theme,
5405
- sheet: await writeSheet(path5.join(folder, `${name2}.png`), topCells),
5406
- ...scrolledCells.length > 0 ? {
5407
- scrolledSheet: await writeSheet(
5408
- path5.join(folder, `${name2}-scrolled.png`),
5409
- scrolledCells
5410
- )
5411
- } : {},
5412
- screens: count,
5413
- failed
5414
- });
5415
6615
  }
5416
6616
  }
5417
6617
  } finally {
5418
6618
  warnings.push(
5419
6619
  ...await driver.restore(start, {
5420
6620
  orientation: orientations !== void 0,
5421
- theme: themes !== void 0
6621
+ theme: themes !== void 0,
6622
+ direction: directions !== void 0
5422
6623
  })
5423
6624
  );
5424
6625
  }
@@ -5430,7 +6631,7 @@ async function sweep(driver, { urls, orientations, themes, out, scroll }, { sign
5430
6631
  warnings
5431
6632
  };
5432
6633
  await writeOutputFile(
5433
- path5.join(folder, "report.json"),
6634
+ path6.join(folder, "report.json"),
5434
6635
  Buffer.from(`${JSON.stringify(report, null, 2)}
5435
6636
  `)
5436
6637
  );
@@ -5438,7 +6639,7 @@ async function sweep(driver, { urls, orientations, themes, out, scroll }, { sign
5438
6639
  }
5439
6640
 
5440
6641
  // src/drivers/android/theme.ts
5441
- import { setTimeout as sleep7 } from "timers/promises";
6642
+ import { setTimeout as sleep9 } from "timers/promises";
5442
6643
  var THEMES = ["light", "dark"];
5443
6644
  var THEME_SETTINGS = [...THEMES, "auto", "custom"];
5444
6645
  var NIGHT = { light: "no", dark: "yes" };
@@ -5488,7 +6689,7 @@ async function probeScheme(target, app, theme, { timeout, interval }) {
5488
6689
  `The theme is ${theme} now, but loupe can't see the app show it. ${failure2.message}`
5489
6690
  );
5490
6691
  }
5491
- await sleep7(interval);
6692
+ await sleep9(interval);
5492
6693
  }
5493
6694
  }
5494
6695
  async function setThemeAndroid(target, theme, app, { timeout = 5e3, interval = DEFAULT_WAIT_INTERVAL } = {}) {
@@ -5553,15 +6754,56 @@ async function orWarning(restore) {
5553
6754
  return [error.message];
5554
6755
  }
5555
6756
  }
5556
- function androidSweepDriver(target, app, rules, { waitTimeout, rotateTimeout = 5e3 }) {
6757
+ function androidSweepDriver(target, app, rules, { waitTimeout, rotateTimeout = 5e3, coldTimeout = 12e4 }, metro) {
6758
+ let lastUrl;
6759
+ const openCold = (url, direction) => showInExpoGo(target, {
6760
+ link: url,
6761
+ route: routeOfLink(url),
6762
+ direction,
6763
+ timeout: coldTimeout
6764
+ });
6765
+ const needMetro = () => {
6766
+ if (!metro || app !== EXPO_GO) {
6767
+ throw new LoupeError(
6768
+ "invalid_input",
6769
+ "A sweep with direction needs the app in Expo Go: app host.exp.exponent."
6770
+ );
6771
+ }
6772
+ return metro;
6773
+ };
5557
6774
  return {
5558
6775
  look: async () => ({
5559
6776
  orientation: (await readAndroidDisplay(target)).orientation,
5560
6777
  theme: await readThemeAndroid(target)
5561
6778
  }),
5562
- open: async (url) => {
6779
+ open: async (url, { cold, direction }) => {
6780
+ lastUrl = url;
6781
+ if (cold && app === EXPO_GO) {
6782
+ await openCold(url, direction);
6783
+ return;
6784
+ }
5563
6785
  await openUrlAndroid(target, url, app);
5564
6786
  },
6787
+ setDirection: async (direction) => {
6788
+ const { context, port } = needMetro();
6789
+ const change = await switchRtl(
6790
+ context,
6791
+ port,
6792
+ direction === "rtl" ? "on" : "off"
6793
+ );
6794
+ if (!change.changed) return { restarted: false };
6795
+ await forceStopAndroid(target, EXPO_GO);
6796
+ return { restarted: true };
6797
+ },
6798
+ reload: async () => {
6799
+ if (!app) {
6800
+ throw new LoupeError(
6801
+ "invalid_input",
6802
+ "A sweep with reloadEvery needs app: the package that loupe stops."
6803
+ );
6804
+ }
6805
+ await forceStopAndroid(target, app);
6806
+ },
5565
6807
  rotate: async (orientation) => {
5566
6808
  if ((await readAndroidDisplay(target)).orientation === orientation) return;
5567
6809
  await rotateAndroid(target, orientation, { timeout: rotateTimeout });
@@ -5604,7 +6846,15 @@ function androidSweepDriver(target, app, rules, { waitTimeout, rotateTimeout = 5
5604
6846
  }) : [],
5605
6847
  ...changed.theme ? await orWarning(
5606
6848
  () => restoreThemeAndroid(target, look.theme)
5607
- ) : []
6849
+ ) : [],
6850
+ // app.json goes back as it was, and the app opens its last link again
6851
+ // in that direction.
6852
+ ...changed.direction && metro ? await orWarning(async () => {
6853
+ const change = await switchRtl(metro.context, metro.port, "off");
6854
+ if (!change.changed) return;
6855
+ await forceStopAndroid(target, EXPO_GO);
6856
+ if (lastUrl) await openCold(lastUrl, directionOf(change));
6857
+ }) : []
5608
6858
  ]
5609
6859
  };
5610
6860
  }
@@ -5631,43 +6881,53 @@ var failureSchema = sweepScreenSchema.pick({
5631
6881
  url: true,
5632
6882
  variant: true,
5633
6883
  scrolled: true,
6884
+ reloaded: true,
5634
6885
  screenshot: true,
5635
6886
  error: true
5636
6887
  }).extend({
5637
- rules: z31.array(z31.string()).describe("The rules that failed."),
5638
- findings: z31.array(
5639
- findingSchema.pick({ element: true, message: true }).extend({ rule: z31.enum(RULES) })
6888
+ rules: z38.array(z38.string()).describe("The rules that failed."),
6889
+ findings: z38.array(
6890
+ findingSchema.pick({ element: true, message: true }).extend({ rule: z38.enum(RULES) })
5640
6891
  ).describe(
5641
6892
  "Each finding of those rules: the element, and a message with the numbers in dp. The report also has the numbers by name."
5642
6893
  )
5643
6894
  });
5644
6895
  var sweepCommand = defineCommand({
5645
6896
  name: "sweep",
5646
- summary: "Open each link in each orientation and theme, check each screen, and write a report, the screenshots and a contact sheet for each variant",
5647
- input: z31.object({
5648
- url: z31.array(
5649
- z31.string().regex(
6897
+ summary: "Open each link in each orientation, theme and direction, check each screen, and write a report, the screenshots and a contact sheet for each variant",
6898
+ input: z38.object({
6899
+ url: z38.array(
6900
+ z38.string().regex(
5650
6901
  /^[A-Za-z][A-Za-z0-9+.-]*:\S+$/,
5651
6902
  "A URL starts with a scheme, for example https: or exp:, and has no spaces."
5652
6903
  )
5653
6904
  ).min(1).describe(
5654
6905
  "A link to open and check: a deep link or a web page. Give it once for each screen."
5655
6906
  ),
5656
- orientation: z31.string().regex(LIST, "The orientations are a comma list.").optional().describe(
6907
+ orientation: z38.string().regex(LIST, "The orientations are a comma list.").optional().describe(
5657
6908
  `The orientations to check, as a comma list of ${ORIENTATIONS.join(", ")}. Left out: only the one that the device has, and loupe turns nothing.`
5658
6909
  ),
5659
- theme: z31.string().regex(LIST, "The themes are a comma list.").optional().describe(
6910
+ theme: z38.string().regex(LIST, "The themes are a comma list.").optional().describe(
5660
6911
  `The themes to check, as a comma list of ${SWEEP_THEMES.join(", ")}. Left out: only the one that the device has, and loupe sets nothing.`
5661
6912
  ),
5662
- rules: z31.string().regex(LIST, "The rules are a comma list.").optional().describe(
6913
+ rules: z38.string().regex(LIST, "The rules are a comma list.").optional().describe(
5663
6914
  `The rules to run on each screen, as a comma list. Each one by default: ${SWEEP_RULES.join(", ")}.`
5664
6915
  ),
5665
- out: z31.string().min(1).default("loupe-sweep").describe(
6916
+ out: z38.string().min(1).default("loupe-sweep").describe(
5666
6917
  "The folder for report.json, the screenshots (<variant>/<number>.png) and the contact sheets (<variant>.png). Files that are there are replaced."
5667
6918
  ),
5668
- scroll: z31.boolean().optional().describe(
6919
+ scroll: z38.boolean().optional().describe(
5669
6920
  "Also scroll each screen down once, by 60 % of its largest vertical scroll view, and check it again: <variant>/<number>-scrolled.png and <variant>-scrolled.png. Then loupe scrolls back to the top."
5670
6921
  ),
6922
+ direction: z38.string().regex(LIST, "The directions are a comma list.").optional().describe(
6923
+ `The layout directions to check, as a comma list of ${SWEEP_DIRECTIONS.join(", ")}. Only for an app in Expo Go (app ${EXPO_GO}): loupe sets each one in app.json as expo-rtl does, opens the app again, and puts app.json back at the end. Left out: only the direction that the app has.`
6924
+ ),
6925
+ port: portField.describe(
6926
+ `The port of Metro on this machine (npx expo start), for direction. ${DEFAULT_PORT} by default.`
6927
+ ),
6928
+ reloadEvery: z38.number().int().min(1).optional().describe(
6929
+ "Stop the app before each N-th link that the sweep opens, over all the variants, so the link starts it again: stacked screens slow an app down. In Expo Go, loupe then waits until the app shows the route of the link. Needs app. Left out: no restart."
6930
+ ),
5671
6931
  waitTimeout: timeoutField.describe(
5672
6932
  `How long each screen can take to keep still after its link opens, in ms. ${DEFAULT_WAIT_TIMEOUT} by default.`
5673
6933
  ),
@@ -5676,26 +6936,26 @@ var sweepCommand = defineCommand({
5676
6936
  ),
5677
6937
  device: deviceField
5678
6938
  }),
5679
- output: z31.object({
5680
- out: z31.string().describe("The folder with each file of the sweep."),
5681
- report: z31.string().describe(
6939
+ output: z38.object({
6940
+ out: z38.string().describe("The folder with each file of the sweep."),
6941
+ report: z38.string().describe(
5682
6942
  "report.json: each screen with its number, link, variant, the result of each rule with its numbers, and its screenshot."
5683
6943
  ),
5684
- passed: z31.boolean().describe("True when every screen passed."),
5685
- screens: z31.number().describe("Links \xD7 variants, and each scrolled screen."),
5686
- failed: z31.number(),
5687
- variants: z31.array(sweepVariantSchema),
5688
- failures: z31.array(failureSchema).describe(
6944
+ passed: z38.boolean().describe("True when every screen passed."),
6945
+ screens: z38.number().describe("Links \xD7 variants, and each scrolled screen."),
6946
+ failed: z38.number(),
6947
+ variants: z38.array(sweepVariantSchema),
6948
+ failures: z38.array(failureSchema).describe(
5689
6949
  "The screens that failed, each with its findings or its error. The report also has the screens that passed, and the warnings of each rule."
5690
6950
  ),
5691
- warnings: z31.array(z31.string())
6951
+ warnings: z38.array(z38.string())
5692
6952
  }),
5693
6953
  run: async (input, context) => {
5694
6954
  const rules = input.rules === void 0 ? SWEEP_RULES : rulesOf(input.rules);
5695
6955
  if (rules.includes("mirrored")) {
5696
6956
  throw new LoupeError(
5697
6957
  "invalid_input",
5698
- "A sweep runs in one layout direction, so it has no mirrored rule. Run check --mirror-of on a screen for that."
6958
+ "A sweep checks each screen on its own, so it has no mirrored rule. Run check --mirror-of on a screen for that."
5699
6959
  );
5700
6960
  }
5701
6961
  const orientations = listOf(
@@ -5704,43 +6964,88 @@ var sweepCommand = defineCommand({
5704
6964
  "an orientation"
5705
6965
  );
5706
6966
  const themes = listOf(input.theme, SWEEP_THEMES, "a theme");
5707
- const target = await selectAndroidDevice(context, input.device);
6967
+ if (input.reloadEvery !== void 0 && input.app === void 0) {
6968
+ throw new LoupeError(
6969
+ "invalid_input",
6970
+ "reloadEvery needs app: the package that loupe stops before each N-th link."
6971
+ );
6972
+ }
6973
+ const directions = listOf(
6974
+ input.direction,
6975
+ SWEEP_DIRECTIONS,
6976
+ "a direction"
6977
+ );
6978
+ const port = input.port ?? DEFAULT_PORT;
6979
+ if (directions) {
6980
+ if (input.app !== EXPO_GO) {
6981
+ throw new LoupeError(
6982
+ "invalid_input",
6983
+ `direction needs the app in Expo Go: app ${EXPO_GO}. loupe sets the direction in app.json, as expo-rtl does.`
6984
+ );
6985
+ }
6986
+ const { projectRoot, dynamicConfigPath } = await expoProject(
6987
+ context,
6988
+ port
6989
+ );
6990
+ await requireAppJson(projectRoot, "on", dynamicConfigPath);
6991
+ }
6992
+ const target = await selectAndroidOnly(context, input.device);
5708
6993
  requireAppOnDevice(target, input.app);
5709
6994
  const report = await sweep(
5710
- androidSweepDriver(target, input.app, rules, {
5711
- waitTimeout: input.waitTimeout ?? DEFAULT_WAIT_TIMEOUT
5712
- }),
6995
+ androidSweepDriver(
6996
+ target,
6997
+ input.app,
6998
+ rules,
6999
+ { waitTimeout: input.waitTimeout ?? DEFAULT_WAIT_TIMEOUT },
7000
+ directions ? { context, port } : void 0
7001
+ ),
5713
7002
  {
5714
7003
  urls: input.url,
5715
7004
  orientations,
5716
7005
  themes,
5717
7006
  out: input.out,
5718
- scroll: input.scroll
7007
+ scroll: input.scroll,
7008
+ reloadEvery: input.reloadEvery,
7009
+ directions
5719
7010
  },
5720
7011
  context
5721
7012
  );
5722
- const failures = report.screens.filter((screen) => !screen.passed).map(({ number, url, variant, scrolled, screenshot, check, error }) => {
5723
- const failed = (check?.results ?? []).filter((result) => !result.passed);
5724
- return {
7013
+ const failures = report.screens.filter((screen) => !screen.passed).map(
7014
+ ({
5725
7015
  number,
5726
7016
  url,
5727
7017
  variant,
5728
7018
  scrolled,
7019
+ reloaded,
5729
7020
  screenshot,
5730
- rules: failed.map((result) => result.rule),
5731
- findings: failed.flatMap(
5732
- ({ rule, findings }) => findings.map(({ element, message }) => ({
5733
- rule,
5734
- element,
5735
- message
5736
- }))
5737
- ),
7021
+ check,
5738
7022
  error
5739
- };
5740
- });
7023
+ }) => {
7024
+ const failed = (check?.results ?? []).filter(
7025
+ (result) => !result.passed
7026
+ );
7027
+ return {
7028
+ number,
7029
+ url,
7030
+ variant,
7031
+ scrolled,
7032
+ reloaded,
7033
+ screenshot,
7034
+ rules: failed.map((result) => result.rule),
7035
+ findings: failed.flatMap(
7036
+ ({ rule, findings }) => findings.map(({ element, message }) => ({
7037
+ rule,
7038
+ element,
7039
+ message
7040
+ }))
7041
+ ),
7042
+ error
7043
+ };
7044
+ }
7045
+ );
5741
7046
  return {
5742
7047
  out: report.out,
5743
- report: path6.join(report.out, "report.json"),
7048
+ report: path7.join(report.out, "report.json"),
5744
7049
  passed: report.passed,
5745
7050
  screens: report.screens.length,
5746
7051
  failed: failures.length,
@@ -5759,8 +7064,17 @@ var sweepCommand = defineCommand({
5759
7064
  (variant) => `${variant.name}: ${variant.failed === 0 ? "pass" : `${variant.failed} failed`}, contact sheet ${variant.sheet}${variant.scrolledSheet ? `, scrolled ${variant.scrolledSheet}` : ""}`
5760
7065
  ),
5761
7066
  ...failures.flatMap(
5762
- ({ number, url, variant, scrolled, rules, findings, error }) => {
5763
- const where = ` ${number} ${variant}${scrolled ? " scrolled" : ""} ${url}`;
7067
+ ({
7068
+ number,
7069
+ url,
7070
+ variant,
7071
+ scrolled,
7072
+ reloaded,
7073
+ rules,
7074
+ findings,
7075
+ error
7076
+ }) => {
7077
+ const where = ` ${number} ${variant}${scrolled ? " scrolled" : ""}${reloaded ? " after a restart" : ""} ${url}`;
5764
7078
  if (error) return [`${where}: ${error.code}: ${error.message}`];
5765
7079
  return [
5766
7080
  `${where}: ${rules.join(", ")}`,
@@ -5774,11 +7088,11 @@ var sweepCommand = defineCommand({
5774
7088
  });
5775
7089
 
5776
7090
  // src/commands/swipe.ts
5777
- import { z as z32 } from "zod";
7091
+ import { z as z39 } from "zod";
5778
7092
  var swipeCommand = defineCommand({
5779
7093
  name: "swipe",
5780
7094
  summary: "Move one touch in a straight line from one point to another",
5781
- input: z32.object({
7095
+ input: z39.object({
5782
7096
  fromX: coordinateField("x"),
5783
7097
  fromY: coordinateField("y"),
5784
7098
  toX: coordinateField("x"),
@@ -5791,7 +7105,7 @@ var swipeCommand = defineCommand({
5791
7105
  positionals: ["fromX", "fromY", "toX", "toY"],
5792
7106
  output: touchSchema.extend({ waited: waitedSchema.optional() }),
5793
7107
  run: async ({ fromX, fromY, toX, toY, duration, app, device, ...wait }, context) => {
5794
- const target = await selectAndroidDevice(context, device);
7108
+ const target = await selectAndroidOnly(context, device);
5795
7109
  const touch2 = await swipeAndroid(
5796
7110
  target,
5797
7111
  { x: fromX, y: fromY },
@@ -5809,11 +7123,11 @@ var swipeCommand = defineCommand({
5809
7123
  });
5810
7124
 
5811
7125
  // src/commands/tap.ts
5812
- import { z as z33 } from "zod";
7126
+ import { z as z40 } from "zod";
5813
7127
  var tapCommand = defineCommand({
5814
7128
  name: "tap",
5815
7129
  summary: "Tap one point of the screen, or the element with a text, label or id",
5816
- input: z33.object({
7130
+ input: z40.object({
5817
7131
  x: coordinateField("x").optional(),
5818
7132
  y: coordinateField("y").optional(),
5819
7133
  ...selectorFields,
@@ -5824,7 +7138,7 @@ var tapCommand = defineCommand({
5824
7138
  positionals: ["x", "y"],
5825
7139
  output: aimedTouchSchema.extend({ waited: waitedSchema.optional() }),
5826
7140
  run: async ({ app, device, waitStill, waitText, waitTimeout, ...input }, context) => {
5827
- const target = await selectAndroidDevice(context, device);
7141
+ const target = await selectAndroidOnly(context, device);
5828
7142
  const { point, element } = await aimAndroid(target, targetOf(input), app);
5829
7143
  const touch2 = await tapAndroid(target, point, app);
5830
7144
  const waited = await waitAfterAction(
@@ -5842,8 +7156,8 @@ var tapCommand = defineCommand({
5842
7156
  });
5843
7157
 
5844
7158
  // src/commands/theme.ts
5845
- import { z as z34 } from "zod";
5846
- var settingSchema = z34.enum(THEME_SETTINGS).describe(
7159
+ import { z as z41 } from "zod";
7160
+ var settingSchema = z41.enum(THEME_SETTINGS).describe(
5847
7161
  "light or dark; auto: Android picks one by the time of day; custom: by a schedule."
5848
7162
  );
5849
7163
  function describeSetting(setting) {
@@ -5859,9 +7173,9 @@ function describeSetting(setting) {
5859
7173
  var themeCommand = defineCommand({
5860
7174
  name: "theme",
5861
7175
  summary: "Set the system theme to light or dark, and wait until the app shows it. With no theme, read it",
5862
- input: z34.object({
5863
- theme: z34.enum(THEMES).optional().describe("light or dark. Left out: loupe only reads the setting."),
5864
- timeout: z34.number().int().min(0).default(5e3).describe(
7176
+ input: z41.object({
7177
+ theme: z41.enum(THEMES).optional().describe("light or dark. Left out: loupe only reads the setting."),
7178
+ timeout: z41.number().int().min(0).default(5e3).describe(
5865
7179
  "Milliseconds to wait until the app's probe shows the theme. A screen with no probe has no wait."
5866
7180
  ),
5867
7181
  ...waitFields,
@@ -5869,18 +7183,18 @@ var themeCommand = defineCommand({
5869
7183
  device: deviceField
5870
7184
  }),
5871
7185
  positionals: ["theme"],
5872
- output: z34.object({
7186
+ output: z41.object({
5873
7187
  theme: settingSchema.describe("The system theme setting now."),
5874
7188
  was: settingSchema.optional().describe("The setting before. Left out when loupe only read it."),
5875
- source: z34.enum(["probe", "setting"]).optional().describe(
7189
+ source: z41.enum(["probe", "setting"]).optional().describe(
5876
7190
  "What showed the theme: probe, the app's probe on the screen; setting, the system setting alone (no probe on the screen, or a probe that kept the other scheme)."
5877
7191
  ),
5878
- ms: z34.number().optional().describe("Milliseconds from the write until the source showed it."),
5879
- warnings: z34.array(z34.string()),
7192
+ ms: z41.number().optional().describe("Milliseconds from the write until the source showed it."),
7193
+ warnings: z41.array(z41.string()),
5880
7194
  waited: waitedSchema.optional()
5881
7195
  }),
5882
7196
  run: async ({ theme, timeout, app, device, ...wait }, context) => {
5883
- const target = await selectAndroidDevice(context, device);
7197
+ const target = await selectAndroidOnly(context, device);
5884
7198
  if (!theme) return { theme: await readThemeAndroid(target), warnings: [] };
5885
7199
  const change = await setThemeAndroid(target, theme, app, { timeout });
5886
7200
  const waited = await waitAfterAction(target, app, wait, "theme");
@@ -5900,12 +7214,12 @@ var themeCommand = defineCommand({
5900
7214
  });
5901
7215
 
5902
7216
  // src/commands/type.ts
5903
- import { z as z35 } from "zod";
7217
+ import { z as z42 } from "zod";
5904
7218
  var typeCommand = defineCommand({
5905
7219
  name: "type",
5906
7220
  summary: "Type text into the field that has the focus",
5907
- input: z35.object({
5908
- text: z35.string().min(1).describe(
7221
+ input: z42.object({
7222
+ text: z42.string().min(1).describe(
5909
7223
  "The text to type. On Android, printable ASCII only; press Enter with the key command."
5910
7224
  ),
5911
7225
  ...waitFields,
@@ -5914,12 +7228,12 @@ var typeCommand = defineCommand({
5914
7228
  }),
5915
7229
  positionals: ["text"],
5916
7230
  // The output has no text: it can be a password.
5917
- output: z35.object({
5918
- characters: z35.number().int(),
7231
+ output: z42.object({
7232
+ characters: z42.number().int(),
5919
7233
  waited: waitedSchema.optional()
5920
7234
  }),
5921
7235
  run: async ({ text, app, device, ...wait }, context) => {
5922
- const target = await selectAndroidDevice(context, device);
7236
+ const target = await selectAndroidOnly(context, device);
5923
7237
  const typed = await typeAndroid(target, text, app);
5924
7238
  const waited = await waitAfterAction(target, app, wait, "type");
5925
7239
  return { ...typed, waited };
@@ -5931,17 +7245,17 @@ var typeCommand = defineCommand({
5931
7245
  });
5932
7246
 
5933
7247
  // src/commands/version.ts
5934
- import { z as z36 } from "zod";
7248
+ import { z as z43 } from "zod";
5935
7249
  var versionCommand = defineCommand({
5936
7250
  name: "version",
5937
7251
  summary: "Print the loupe version and the host it runs on",
5938
7252
  readOnly: true,
5939
- input: z36.object({}),
5940
- output: z36.object({
5941
- loupe: z36.string(),
5942
- node: z36.string(),
5943
- platform: z36.string(),
5944
- arch: z36.string()
7253
+ input: z43.object({}),
7254
+ output: z43.object({
7255
+ loupe: z43.string(),
7256
+ node: z43.string(),
7257
+ platform: z43.string(),
7258
+ arch: z43.string()
5945
7259
  }),
5946
7260
  run: () => ({
5947
7261
  loupe: version,
@@ -5953,7 +7267,7 @@ var versionCommand = defineCommand({
5953
7267
  });
5954
7268
 
5955
7269
  // src/commands/wait.ts
5956
- import { z as z37 } from "zod";
7270
+ import { z as z44 } from "zod";
5957
7271
  function sentence(text) {
5958
7272
  return text.charAt(0).toUpperCase() + text.slice(1);
5959
7273
  }
@@ -5961,8 +7275,8 @@ var waitCommand = defineCommand({
5961
7275
  name: "wait",
5962
7276
  summary: "Wait until the screen keeps still, or until an element is on the screen",
5963
7277
  readOnly: true,
5964
- input: z37.object({
5965
- still: z37.boolean().optional().describe(
7278
+ input: z44.object({
7279
+ still: z44.boolean().optional().describe(
5966
7280
  "Wait until the screen keeps still: two equal screenshots in a row, with the system bars left out (the clock ticks there)."
5967
7281
  ),
5968
7282
  text: selectorFields.text.describe(
@@ -5975,7 +7289,7 @@ var waitCommand = defineCommand({
5975
7289
  "Wait until an element with this id is on the screen."
5976
7290
  ),
5977
7291
  timeout: timeoutField,
5978
- interval: z37.number().int().min(0).max(1e4).optional().describe(
7292
+ interval: z44.number().int().min(0).max(1e4).optional().describe(
5979
7293
  `The pause between two screenshots or two reads, in ms. ${DEFAULT_WAIT_INTERVAL} by default.`
5980
7294
  ),
5981
7295
  app: appField,
@@ -5999,7 +7313,7 @@ var waitCommand = defineCommand({
5999
7313
  timeout: input.timeout ?? DEFAULT_WAIT_TIMEOUT,
6000
7314
  interval: input.interval ?? DEFAULT_WAIT_INTERVAL
6001
7315
  };
6002
- const target = await selectAndroidDevice(context, device);
7316
+ const target = await selectAndroidOnly(context, device);
6003
7317
  if (!selector) {
6004
7318
  const result2 = await waitStillAndroid(target, app, options);
6005
7319
  if (!result2.still) {
@@ -6028,6 +7342,10 @@ var registry = createRegistry([
6028
7342
  dismissCommand,
6029
7343
  doubleTapCommand,
6030
7344
  dragCommand,
7345
+ expoOpenCommand,
7346
+ expoReloadCommand,
7347
+ expoRtlCommand,
7348
+ expoWarmCommand,
6031
7349
  foregroundCommand,
6032
7350
  holdCommand,
6033
7351
  insetsCommand,
@@ -6049,8 +7367,24 @@ var registry = createRegistry([
6049
7367
  ]);
6050
7368
 
6051
7369
  // src/core/context.ts
7370
+ var LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
7371
+ var localFetch = async (input, init) => {
7372
+ const url = new URL(input instanceof Request ? input.url : input);
7373
+ if (!LOOPBACK.has(url.hostname)) {
7374
+ throw new LoupeError(
7375
+ "internal",
7376
+ `loupe calls only servers on this machine, not ${url.host}.`
7377
+ );
7378
+ }
7379
+ return fetch(input, init);
7380
+ };
6052
7381
  function createContext() {
6053
- return { exec: nodeExec, env: process.env };
7382
+ return {
7383
+ exec: nodeExec,
7384
+ env: process.env,
7385
+ fetch: localFetch,
7386
+ hostPlatform: process.platform
7387
+ };
6054
7388
  }
6055
7389
 
6056
7390
  // src/core/run-command.ts