stim 1.13.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +2 -0
  2. package/dist/{activity-DfVKZTEB.mjs → activity-B2-kb7k0.mjs} +281 -41
  3. package/dist/{android-BHfAu2mf.mjs → android-CYmq0jNi.mjs} +2 -2
  4. package/dist/{android-CD8pr8Q2.mjs → android-Cu_L4RpL.mjs} +524 -412
  5. package/dist/{android-qx_31wJo.mjs → android-Db2eEMaf.mjs} +152 -65
  6. package/dist/android-cas-PnKfAdB2.mjs +167 -0
  7. package/dist/android-cas-compiler.mjs +2 -2
  8. package/dist/{app-install-CDFY2nUL.mjs → app-install-CAAplXAt.mjs} +162 -173
  9. package/dist/{budget-E5o91NR1.mjs → budget-CMiqghig.mjs} +1048 -77
  10. package/dist/{build-plan-BTa93o_r.mjs → build-plan-aeGMFX7e.mjs} +193 -650
  11. package/dist/build-progress-C2Jv1AtA.mjs +872 -0
  12. package/dist/build-slots-Df1ApSuH.mjs +127 -0
  13. package/dist/{cache-manifest-DWPF4RKJ.mjs → cache-manifest-DnUHBJaU.mjs} +2 -2
  14. package/dist/cache-manifest.mjs +1 -1
  15. package/dist/{chrome-B5hWgQJS.mjs → chrome-BrcVWQyD.mjs} +4 -4
  16. package/dist/cli-0cX5s4NM.mjs +45 -0
  17. package/dist/cli.mjs +6 -42
  18. package/dist/client-C2IS36Qf.mjs +1333 -0
  19. package/dist/collector-run.mjs +8 -7
  20. package/dist/{command-output-BIL7rlX7.mjs → command-output-CliHHn7a.mjs} +1 -1
  21. package/dist/{config-0jCcMM0E.mjs → config-D0DbpZtM.mjs} +29 -29
  22. package/dist/{created-devices-Cd558h31.mjs → created-devices-BwVb3liH.mjs} +2 -2
  23. package/dist/{dependency-state-DNN0yfx6.mjs → dependency-state-BmsjKZ2H.mjs} +2 -2
  24. package/dist/{deps-2Wo81np9.mjs → deps-BFlKbOIp.mjs} +3 -3
  25. package/dist/{detached-entry-DJHoca49.mjs → detached-entry-CiTEgMR1.mjs} +1 -1
  26. package/dist/dev-client-CjzLoNs0.mjs +80 -0
  27. package/dist/{device-Cf7vl-so.mjs → device-BZ1IyS5A.mjs} +7 -7
  28. package/dist/device-capacity-DMuKC7nx.mjs +136 -0
  29. package/dist/device-host-worker.d.mts +1 -0
  30. package/dist/device-host-worker.mjs +769 -0
  31. package/dist/device-ios-DMQBUPus.mjs +381 -0
  32. package/dist/{device-lease-CL9dZf73.mjs → device-lease-W5Pi1q38.mjs} +43 -36
  33. package/dist/{device-pool-MuoiyRcu.mjs → device-pool-B2r38YjS.mjs} +4 -4
  34. package/dist/{device-remote-DT9ngZiD.mjs → device-remote-9ulPsdhY.mjs} +68 -162
  35. package/dist/{doctor-D2iysNNH.mjs → doctor-BcE5xsBn.mjs} +191 -99
  36. package/dist/{error-diagnostics-BoiOhck8.mjs → error-diagnostics-Cb0P1WLS.mjs} +12 -11
  37. package/dist/{exec-DK8KaVHK.mjs → exec-CaErVv7t.mjs} +5 -1
  38. package/dist/{gc-eA-PRBX8.mjs → gc-BuL1Genr.mjs} +430 -102
  39. package/dist/{android-cas-B9Kv9aIy.mjs → gradle-CmdOBq1d.mjs} +8 -294
  40. package/dist/{guide-BfZ0OmiP.mjs → guide-cCSGRFd3.mjs} +2052 -240
  41. package/dist/{guide-status-BaMYu55M.mjs → guide-status-CIoWK6mG.mjs} +3 -3
  42. package/dist/hosted-macos-DwowNU7W.mjs +447 -0
  43. package/dist/idle-shutdown-B5LPaNyY.mjs +122 -0
  44. package/dist/in-use-CndPMilN.mjs +110 -0
  45. package/dist/{ios-CmEzZiOj.mjs → ios-3CtCRhwr.mjs} +201 -10
  46. package/dist/{ios-CcfCeZ19.mjs → ios-Chob8ny7.mjs} +560 -259
  47. package/dist/{ios-device-BW-t_Lkv.mjs → ios-device-DERmMmk-.mjs} +12 -7
  48. package/dist/{ios-device-BiOsSVzd.mjs → ios-device-Ee7sDXfp.mjs} +1 -1
  49. package/dist/{launch-verify-CuJaBpEa.mjs → launch-verify-CLlofxRt.mjs} +42 -11
  50. package/dist/{logs-DcSRbC2t.mjs → logs-h9h6MUvE.mjs} +95 -13
  51. package/dist/machine-usage-D_YYMzfR.mjs +283 -0
  52. package/dist/machines-CYtOCqcj.mjs +259 -0
  53. package/dist/macos-BwtbUtTN.mjs +468 -0
  54. package/dist/macos-run.d.mts +5 -0
  55. package/dist/macos-run.mjs +2 -0
  56. package/dist/{merge-state-ytFQCeh4.mjs → merge-state-BnxLNQiM.mjs} +22 -12
  57. package/dist/{metro-BPeY1YMh.mjs → metro-Di8EN2Tb.mjs} +20 -120
  58. package/dist/{named-ports-n7tnJsI8.mjs → named-ports-Dj_XBNaL.mjs} +8 -64
  59. package/dist/native-run-DFDoIRbY.mjs +147 -0
  60. package/dist/{native-runtime-CiiFHt0e.mjs → native-runtime-i6OkVg-w.mjs} +11 -6
  61. package/dist/offload-worker.d.mts +121 -0
  62. package/dist/offload-worker.mjs +601 -0
  63. package/dist/{ownership-Bz2kETAS.mjs → ownership-BkYxUtuj.mjs} +3 -2
  64. package/dist/{page-BTu7I60K.mjs → page-QF_Ke10s.mjs} +7 -2
  65. package/dist/{ports-C5UutqpJ.mjs → ports-DddwttKM.mjs} +3 -3
  66. package/dist/prebuild-BvxDlD6C.mjs +213 -0
  67. package/dist/process-identity-BmRm1qV0.mjs +12 -0
  68. package/dist/{project-DGeclhvO.mjs → project-CV3tDFHl.mjs} +9 -18
  69. package/dist/pull-request-pxnDCQzn.mjs +322 -0
  70. package/dist/pull-requests.d.mts +120 -0
  71. package/dist/pull-requests.mjs +2 -0
  72. package/dist/recordings-GEXp4iBT.mjs +37 -0
  73. package/dist/{reload-C-cV5yy_.mjs → reload-ChPiwvot.mjs} +70 -22
  74. package/dist/{remote-cache--aehr4Pr.mjs → remote-cache-CO2elm_b.mjs} +4 -4
  75. package/dist/run-B-xqRrsg.mjs +119 -0
  76. package/dist/{server-bare-Bq8BpSIo.mjs → server-bare-X7PUgizL.mjs} +60 -13
  77. package/dist/{server-expo-DUCg52-K.mjs → server-expo-DhtX6bom.mjs} +6 -10
  78. package/dist/server-expo-KJeD109I.mjs +2 -0
  79. package/dist/{settings-xB0Frkg6.mjs → settings-CduVcoxj.mjs} +77 -26
  80. package/dist/{settings-ssVBToDR.mjs → settings-DbL6uhH8.mjs} +16 -10
  81. package/dist/settings.schema.json +357 -2
  82. package/dist/{simslim-Bbg9UWrt.mjs → simslim-Ciluxlq4.mjs} +8 -132
  83. package/dist/slot-launch-BY0BrOLh.mjs +65 -0
  84. package/dist/{spawn-claims-PT8aQpCa.mjs → spawn-claims-D0XfSe8u.mjs} +1 -1
  85. package/dist/spawn-entry-DncpJvWL.mjs +16 -0
  86. package/dist/stage-CzaiwFsI.mjs +143 -0
  87. package/dist/start-CPO4wRg7.mjs +2 -0
  88. package/dist/{start-BZhItkiL.mjs → start-CUD9nasA.mjs} +108 -61
  89. package/dist/state-B4PQFXMW.d.mts +12 -0
  90. package/dist/state-BxCgeTQu.mjs +41 -0
  91. package/dist/{state-DwAU2_-D.mjs → state-CaeaHbDA.mjs} +7 -4
  92. package/dist/{state-l1pYwOre.mjs → state-DFm77wRn.mjs} +67 -5
  93. package/dist/stats-DBLLFmKd.mjs +66 -0
  94. package/dist/{status-TJlL0HWo.mjs → status-DYXxNOT0.mjs} +425 -260
  95. package/dist/{status-sszP4XKU.mjs → status-l84Gbvp2.mjs} +122 -20
  96. package/dist/stdout-reader-C8yjre1x.mjs +23 -0
  97. package/dist/stim-desktop-Cnz8CPnl.mjs +63 -0
  98. package/dist/stim-footprint.swift +32 -0
  99. package/dist/{stim-installations-CINXy_su.mjs → stim-installations-QMEI32v1.mjs} +1 -1
  100. package/dist/{stop-BZ2qMiBP.mjs → stop-Bad61z_2.mjs} +128 -19
  101. package/dist/stop-Bvf1MflS.mjs +48 -0
  102. package/dist/{stop-DskDKNTU.mjs → stop-CceYh1yG.mjs} +2 -2
  103. package/dist/stop-cause-CZ_Mr-v9.mjs +665 -0
  104. package/dist/supervisor-run.d.mts +44 -12
  105. package/dist/supervisor-run.mjs +276 -33
  106. package/dist/support-CDQbDkL5.mjs +315 -0
  107. package/dist/support-WLOzVKUv.mjs +176 -0
  108. package/dist/teardown-BYuQafiA.mjs +718 -0
  109. package/dist/{xcode-LM6A8cNZ.mjs → toolchain-DmeYjXD9.mjs} +363 -13
  110. package/dist/warm-progress-DVHLN4uC.mjs +463 -0
  111. package/dist/{idle-DxLi5OkN.mjs → watchman-Bx0wceoF.mjs} +55 -8
  112. package/dist/{web-sWXd5iek.mjs → web-k6w8-HnE.mjs} +39 -22
  113. package/dist/web-run.mjs +326 -13
  114. package/dist/workspace-process-lock-BL7Q0HCO.mjs +57 -0
  115. package/dist/workspace-state-CL2V2Ons.mjs +371 -0
  116. package/dist/worktree-BT_uULFx.mjs +2 -0
  117. package/dist/{worktree-DeBQSVtR.mjs → worktree-C0c5Udwa.mjs} +55 -54
  118. package/dist/{worktree-D4Do_XiQ.mjs → worktree-qXKzADSC.mjs} +161 -255
  119. package/package.json +10 -5
  120. package/shim/bundle-response.cjs +55 -10
  121. package/shim/bundle-response.d.cts +1 -0
  122. package/shim/expo-metro-config.cjs +10 -2
  123. package/dist/build-progress-l7d-X-ZP.mjs +0 -247
  124. package/dist/in-use-wYEaKQM9.mjs +0 -249
  125. package/dist/ownership-PUP4Dwai.mjs +0 -1138
  126. package/dist/server-expo-BeYwP_Xy.mjs +0 -2
  127. package/dist/slot-launch-BIWEW-wI.mjs +0 -19
  128. package/dist/start-Rw2GD3nV.mjs +0 -2
  129. package/dist/stats-CaSwmsSZ.mjs +0 -62
  130. package/dist/stats-D8rUTPHd.mjs +0 -368
  131. package/dist/stim-desktop-CXt8-Z3J.mjs +0 -40
  132. package/dist/worktree-3cBa-bQt.mjs +0 -2
  133. package/dist/{metro-store-DzeWkfqW.mjs → metro-store-CDDZHtPl.mjs} +1 -1
@@ -0,0 +1,718 @@
1
+ import { t as getExecutor } from "./exec-CaErVv7t.mjs";
2
+ import { D as withConfigLock, H as projectDeviceSlots, _ as loadConfig, k as acquireAvdClaim, p as getProject, z as deviceSlotPlatforms } from "./config-D0DbpZtM.mjs";
3
+ import { n as ownership_claim_exports, t as process_identity_exports } from "./process-identity-BmRm1qV0.mjs";
4
+ import { b as workspaceDir } from "./workspace-state-CL2V2Ons.mjs";
5
+ import { y as repoRoot } from "./worktree-C0c5Udwa.mjs";
6
+ import { t as withWorkspaceProcessLock } from "./workspace-process-lock-BL7Q0HCO.mjs";
7
+ import { o as readAgentDeviceRecords } from "./activity-B2-kb7k0.mjs";
8
+ import { l as phaseLine } from "./command-output-CliHHn7a.mjs";
9
+ import { B as ownedAvdSystemImage, I as ownedAvdDirectory, J as resolveOwnedAvdSerial, L as ownedAvdMatchesConfiguration, M as listOrphanedAvdDirectories, O as listAdbDevices, X as shutdownAndroidEmulator, Z as sleepSync, _ as avdStorageRoots, ct as eraseParkedAfter, et as waitForAndroidEmulatorShutdown, f as assertOwnedAvdStopped, ft as readParked, h as avdPathExists, nt as wipeAvdUserData, pt as removeParkedAfter, rt as isStimOwnedAvd, ut as parkSim, x as deleteAvd } from "./android-Db2eEMaf.mjs";
10
+ import { n as readCreatedDevices, r as recordCreatedDevice, t as forgetCreatedDevice } from "./created-devices-BwVb3liH.mjs";
11
+ import { u as signalProcessTree } from "./metro-Di8EN2Tb.mjs";
12
+ import { r as releaseBrowserPort } from "./named-ports-Dj_XBNaL.mjs";
13
+ import { _ as removeSingletonFiles, c as webClaimRoot, f as webProfileDir, g as liveProfileHolder, h as chromeProcessState, i as clearWebRecord, o as readWebRecord, t as CDP_PORT_LABEL } from "./state-DFm77wRn.mjs";
14
+ import { E as shutdownIosSim, _ as parseRuntimeVersion, a as deleteIosSim, b as renameIosSim, f as listIosDeviceTypes, g as parkedSimName, o as deleteParkedIosSim, s as eraseIosSim, w as resolveOwnedIosSim } from "./ios-3CtCRhwr.mjs";
15
+ import { randomUUID } from "node:crypto";
16
+ import { existsSync, lstatSync, realpathSync, renameSync, rmSync } from "node:fs";
17
+ import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
18
+ import { homedir } from "node:os";
19
+ import { isDeepStrictEqual } from "node:util";
20
+ //#region src/devices/agent-device-cleanup.ts
21
+ function parseAgentDeviceSessions(output) {
22
+ const result = JSON.parse(output);
23
+ if (result?.success !== true || !Array.isArray(result.data?.sessions)) throw new Error("agent-device did not return a successful session list");
24
+ return result.data.sessions.flatMap((entry) => {
25
+ if (!entry || typeof entry !== "object") return [];
26
+ const row = entry;
27
+ const id = row.platform === "ios" ? row.device_udid : row.id;
28
+ if (row.platform !== "ios" && row.platform !== "android" || typeof row.name !== "string" || !row.name.trim() || typeof id !== "string" || !id || typeof row.createdAt !== "number" || !Number.isFinite(row.createdAt) || row.platform === "ios" && row.id !== void 0 && row.id !== id) return [];
29
+ return [{
30
+ name: typeof row.address === "string" && row.address.trim() ? row.address : row.name,
31
+ platform: row.platform,
32
+ id,
33
+ device: typeof row.device === "string" ? row.device : null,
34
+ createdAt: row.createdAt
35
+ }];
36
+ });
37
+ }
38
+ function isOwnDeviceSession(session, device, owner) {
39
+ if (session.platform !== device.platform || device.id !== null && session.id !== device.id) return false;
40
+ if (device.platform === "android" && session.device !== device.avdName.replaceAll("_", " ")) return false;
41
+ if (!owner) return true;
42
+ return owner.claims.some((claim) => claim.deviceId === session.id && claim.session === session.name && claim.workspace !== null && (within(owner.workspace, claim.workspace) || claim.workspace === owner.repoRoot));
43
+ }
44
+ function within(root, path) {
45
+ const rest = relative(root, path);
46
+ return rest === "" || !isAbsolute(rest) && rest.split(sep)[0] !== "..";
47
+ }
48
+ function canonical(path) {
49
+ try {
50
+ return realpathSync(path);
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+ function deviceClaims(device) {
56
+ return readAgentDeviceRecords(homedir()).filter((record) => record.kind === "claim" && (device.id === null || record.deviceId === device.id)).map((record) => ({
57
+ deviceId: record.deviceId,
58
+ session: record.session,
59
+ workspace: record.workspace && canonical(record.workspace)
60
+ }));
61
+ }
62
+ function report(message) {
63
+ process.stderr.write(`${phaseLine("device", message)}\n`);
64
+ }
65
+ function closeOwnedDeviceSessions(device, stillOwned, workspace, repoRoot) {
66
+ const exec = getExecutor();
67
+ const deadline = Date.now() + 15e3;
68
+ const run = (args) => {
69
+ const remaining = deadline - Date.now();
70
+ if (remaining <= 0) throw new Error("agent-device cleanup timed out");
71
+ return exec.runFile("agent-device", [
72
+ ...args,
73
+ "--json",
74
+ "--daemon-transport",
75
+ "socket"
76
+ ], {
77
+ timeoutMs: Math.min(5e3, remaining),
78
+ killSignal: "SIGKILL"
79
+ });
80
+ };
81
+ const list = () => parseAgentDeviceSessions(run([
82
+ "session",
83
+ "list",
84
+ "--session",
85
+ "stim-teardown-inventory"
86
+ ]));
87
+ try {
88
+ if (!exec.findExecutable("agent-device")) return;
89
+ const root = workspace === void 0 ? void 0 : canonical(workspace);
90
+ if (root === null) return;
91
+ const owner = root === void 0 ? void 0 : {
92
+ workspace: root,
93
+ repoRoot: repoRoot && (canonical(repoRoot) ?? void 0),
94
+ claims: deviceClaims(device)
95
+ };
96
+ const sessions = list().filter((session) => isOwnDeviceSession(session, device, owner));
97
+ for (const session of sessions) try {
98
+ if (!list().some((current) => current.name === session.name && current.platform === session.platform && current.id === session.id && current.createdAt === session.createdAt)) continue;
99
+ if (!stillOwned(session.id)) continue;
100
+ if (JSON.parse(run([
101
+ "close",
102
+ "--session",
103
+ session.name,
104
+ "--session-lock",
105
+ "reject",
106
+ "--platform",
107
+ device.platform,
108
+ device.platform === "ios" ? "--udid" : "--serial",
109
+ session.id
110
+ ]))?.success !== true) throw new Error("agent-device did not confirm session close");
111
+ report(`closed agent-device session ${session.name} on ${session.id}`);
112
+ } catch (error) {
113
+ report(`could not close agent-device session ${session.name} on ${session.id}: ${error.message}`);
114
+ }
115
+ } catch (error) {
116
+ report(`could not list agent-device sessions for ${device.platform === "ios" ? device.id : device.id ?? device.avdName}: ${error.message}`);
117
+ }
118
+ }
119
+ //#endregion
120
+ //#region src/devices/teardown.ts
121
+ function teardownParkedAvd(avdName) {
122
+ try {
123
+ return removeParkedAfter("android", avdName, () => {
124
+ const result = teardownOwnedAvd(avdName, {
125
+ del: true,
126
+ owner: { pool: true }
127
+ });
128
+ if (result.status !== "torn-down" && result.status !== "missing") throw new Error(result.reason);
129
+ }) ? {
130
+ status: "torn-down",
131
+ label: avdName
132
+ } : {
133
+ status: "skipped",
134
+ kind: "not-parked",
135
+ reason: "emulator is no longer parked"
136
+ };
137
+ } catch (error) {
138
+ return {
139
+ status: "failed",
140
+ reason: String(error?.message || error)
141
+ };
142
+ }
143
+ }
144
+ function teardownParkedIosSim(udid, { label, deleteSim = deleteParkedIosSim } = {}) {
145
+ try {
146
+ const removed = removeParkedAfter("ios", udid, () => {
147
+ closeOwnedDeviceSessions({
148
+ platform: "ios",
149
+ id: udid
150
+ }, () => Boolean(resolveOwnedIosSim(udid).sim));
151
+ deleteSim(udid);
152
+ });
153
+ if (!removed) return {
154
+ status: "skipped",
155
+ kind: "not-parked",
156
+ reason: "simulator is no longer parked"
157
+ };
158
+ return {
159
+ status: "torn-down",
160
+ label: label ?? removed.name
161
+ };
162
+ } catch (error) {
163
+ return {
164
+ status: "failed",
165
+ reason: String(error?.message || error)
166
+ };
167
+ }
168
+ }
169
+ function eraseParkedIosSim(udid, { label } = {}) {
170
+ try {
171
+ const erased = eraseParkedAfter("ios", udid, (_record, eraseStarted) => {
172
+ closeOwnedDeviceSessions({
173
+ platform: "ios",
174
+ id: udid
175
+ }, () => Boolean(resolveOwnedIosSim(udid).sim));
176
+ const resolved = resolveOwnedIosSim(udid);
177
+ if (resolved.missing) throw new Error(`simulator ${udid} is not on this machine`);
178
+ if (resolved.notOwned) throw new Error(`simulator ${udid} is now named ${JSON.stringify(resolved.notOwned)}`);
179
+ const state = resolved.sim.state;
180
+ if (state !== "Shutdown") throw new Error(`simulator ${udid} is ${state}, not Shutdown; it was kept`);
181
+ eraseStarted();
182
+ eraseIosSim(udid);
183
+ });
184
+ if (!erased) return {
185
+ status: "skipped",
186
+ kind: "not-parked",
187
+ reason: "simulator is no longer parked"
188
+ };
189
+ return {
190
+ status: "torn-down",
191
+ label: label ?? erased.name
192
+ };
193
+ } catch (error) {
194
+ return {
195
+ status: "failed",
196
+ reason: String(error?.message || error)
197
+ };
198
+ }
199
+ }
200
+ function eraseParkedAvd(avdName) {
201
+ try {
202
+ return eraseParkedAfter("android", avdName, (_record, eraseStarted) => {
203
+ if (resolveOwnedAvdSerial(avdName).serial) throw new Error(`AVD ${avdName} is running; it was kept`);
204
+ const result = teardownOwnedAvd(avdName, {
205
+ wipe: true,
206
+ owner: { pool: true },
207
+ onWipeStart: eraseStarted
208
+ });
209
+ if (result.status !== "torn-down") throw new Error(result.reason ?? `AVD ${avdName} is ${result.status}`);
210
+ }) ? {
211
+ status: "torn-down",
212
+ label: avdName
213
+ } : {
214
+ status: "skipped",
215
+ kind: "not-parked",
216
+ reason: "emulator is no longer parked"
217
+ };
218
+ } catch (error) {
219
+ return {
220
+ status: "failed",
221
+ reason: String(error?.message || error)
222
+ };
223
+ }
224
+ }
225
+ const IOS_SHUTDOWN_SETTLE_MS = 15e3;
226
+ const ADB_RELEASE_WAIT_MS = 3e3;
227
+ function repoRootAbove(workspace) {
228
+ if (workspace === void 0 || !getExecutor().findExecutable("agent-device")) return void 0;
229
+ const root = repoRoot(workspace);
230
+ try {
231
+ return root && realpathSync(root) !== realpathSync(workspace) ? root : void 0;
232
+ } catch {
233
+ return;
234
+ }
235
+ }
236
+ const IOS_SHUTDOWN_POLL_MS = 250;
237
+ const IOS_SHUTDOWN_ATTEMPTS = 2;
238
+ function settleIosSimShutdown(udid, { now = Date.now, sleep = sleepSync }) {
239
+ let resolved = resolveOwnedIosSim(udid);
240
+ for (let attempt = 1;; attempt++) {
241
+ const deadline = now() + IOS_SHUTDOWN_SETTLE_MS;
242
+ while (resolved.sim && resolved.sim.state !== "Shutdown" && now() < deadline) {
243
+ sleep(IOS_SHUTDOWN_POLL_MS);
244
+ resolved = resolveOwnedIosSim(udid);
245
+ }
246
+ if (!resolved.sim || resolved.sim.state === "Shutdown" || attempt === IOS_SHUTDOWN_ATTEMPTS) return resolved;
247
+ shutdownIosSim(udid);
248
+ resolved = resolveOwnedIosSim(udid);
249
+ }
250
+ }
251
+ function iosShutdownFailureReason(udid, state) {
252
+ return `simulator ${udid} is still ${state} after ${IOS_SHUTDOWN_ATTEMPTS} shutdown attempts and ${IOS_SHUTDOWN_ATTEMPTS * IOS_SHUTDOWN_SETTLE_MS / 1e3}s of waiting`;
253
+ }
254
+ function parkOwnedIosSim(settled, udid, park) {
255
+ if (settled.missing) throw new Error(`simulator ${udid} disappeared after shutdown`);
256
+ if (settled.notOwned) throw new Error(`simulator ${udid} is now named ${JSON.stringify(settled.notOwned)}`);
257
+ const sim = settled.sim;
258
+ if (sim.state !== "Shutdown") throw new Error(iosShutdownFailureReason(udid, sim.state));
259
+ const model = listIosDeviceTypes().find((d) => d.identifier === sim.deviceTypeIdentifier)?.name ?? null;
260
+ const runtime = parseRuntimeVersion(sim.runtime);
261
+ const name = parkedSimName(sim.udid, {
262
+ model,
263
+ runtime
264
+ });
265
+ renameIosSim(sim.udid, name);
266
+ const record = {
267
+ udid: sim.udid,
268
+ name,
269
+ deviceTypeIdentifier: sim.deviceTypeIdentifier,
270
+ runtimeIdentifier: sim.runtime,
271
+ parkedAt: (/* @__PURE__ */ new Date()).toISOString(),
272
+ simslimManaged: Boolean(park.simslimManaged),
273
+ ...park.appId ? { bundleId: park.appId } : {},
274
+ ...park.cacheKey ? { cacheKey: park.cacheKey } : {}
275
+ };
276
+ return {
277
+ record,
278
+ evicted: parkSim({
279
+ platform: "ios",
280
+ projectPath: park.projectPath,
281
+ slot: park.slot,
282
+ record,
283
+ max: park.max
284
+ })
285
+ };
286
+ }
287
+ function teardownOwnedIosSim(udid, { del = false, label, park, workspace, shutdownClock = {} } = {}) {
288
+ let parkFallback;
289
+ try {
290
+ const resolved = resolveOwnedIosSim(udid);
291
+ if (resolved.notOwned) return {
292
+ status: "skipped",
293
+ kind: "not-owned",
294
+ reason: `sim "${resolved.notOwned}" is not Stim-owned: Stim has no record of creating it`
295
+ };
296
+ if (resolved.missing) return { status: "missing" };
297
+ closeOwnedDeviceSessions({
298
+ platform: "ios",
299
+ id: udid
300
+ }, () => Boolean(resolveOwnedIosSim(udid).sim), workspace);
301
+ const current = resolveOwnedIosSim(udid);
302
+ if (current.missing) return { status: "missing" };
303
+ if (current.notOwned) return {
304
+ status: "skipped",
305
+ kind: "not-owned",
306
+ reason: "simulator ownership changed before shutdown"
307
+ };
308
+ shutdownIosSim(udid);
309
+ const sim = resolved.sim;
310
+ if (del && park && park.max > 0) try {
311
+ const { record, evicted } = parkOwnedIosSim(settleIosSimShutdown(udid, shutdownClock), udid, park);
312
+ const removed = [];
313
+ const failures = [];
314
+ for (const entry of evicted) {
315
+ const result = teardownParkedIosSim(entry.udid, { label: entry.name });
316
+ if (result.status === "torn-down") removed.push({
317
+ udid: entry.udid,
318
+ name: entry.name
319
+ });
320
+ else if (result.status === "failed") failures.push(`could not delete evicted ${entry.name} (${entry.udid}): ${result.reason}`);
321
+ }
322
+ return {
323
+ status: "torn-down",
324
+ label: label ?? sim.name ?? udid,
325
+ parked: {
326
+ udid: record.udid,
327
+ name: record.name
328
+ },
329
+ evicted: removed,
330
+ ...failures.length ? { evictionFailures: failures } : {}
331
+ };
332
+ } catch (e) {
333
+ parkFallback = String(e?.message || e);
334
+ }
335
+ if (del) {
336
+ deleteIosSim(udid);
337
+ return {
338
+ status: "torn-down",
339
+ label: label ?? sim.name ?? udid,
340
+ ...parkFallback ? { parkFallback } : {}
341
+ };
342
+ }
343
+ const settled = settleIosSimShutdown(udid, shutdownClock);
344
+ if (settled.sim && settled.sim.state !== "Shutdown") return {
345
+ status: "failed",
346
+ label: label ?? sim.name ?? udid,
347
+ reason: iosShutdownFailureReason(udid, settled.sim.state)
348
+ };
349
+ const root = sim.state === "Shutdown" ? void 0 : repoRootAbove(workspace);
350
+ if (root && settled.sim) closeOwnedDeviceSessions({
351
+ platform: "ios",
352
+ id: udid
353
+ }, () => resolveOwnedIosSim(udid).sim?.state === "Shutdown", workspace, root);
354
+ return {
355
+ status: "torn-down",
356
+ label: label ?? sim.name ?? udid
357
+ };
358
+ } catch (e) {
359
+ return {
360
+ status: "failed",
361
+ reason: String(e?.message || e),
362
+ ...parkFallback ? { parkFallback } : {}
363
+ };
364
+ }
365
+ }
366
+ function assertAvdReferences(avdName, owner) {
367
+ const config = loadConfig();
368
+ if (!config) throw new Error("Cannot verify AVD references without a Stim config; the data was kept.");
369
+ if (owner && "projectPath" in owner && owner.expectedRecord && !isDeepStrictEqual(deviceSlotPlatforms(config.projects[owner.projectPath], owner.slot)?.android, owner.expectedRecord)) throw new Error(`AVD ${avdName} has a changed workspace record; its data was kept.`);
370
+ for (const [projectPath, project] of Object.entries(config.projects)) for (const { slot, platforms } of projectDeviceSlots(project)) {
371
+ if (platforms.android?.avdName?.toLowerCase() !== avdName.toLowerCase()) continue;
372
+ if (!owner || !("projectPath" in owner) || owner.projectPath !== projectPath || (owner.slot ?? "default") !== slot || !platforms.android.owned) throw new Error(`AVD ${avdName} is referenced by ${projectPath} (${slot}); its data was kept.`);
373
+ }
374
+ if (readParked("android", { config }).some((entry) => entry.name.toLowerCase() === avdName.toLowerCase()) && !(owner && "pool" in owner)) throw new Error(`AVD ${avdName} is in the emulator pool; its data was kept.`);
375
+ }
376
+ function removeOrphanedAvdDirectory(candidate, owner) {
377
+ const surveyed = listOrphanedAvdDirectories(candidate.name).find((entry) => entry.directory === candidate.directory);
378
+ if (!surveyed || surveyed.name !== candidate.name || surveyed.dev !== candidate.dev || surveyed.ino !== candidate.ino) throw new Error(`AVD data at ${candidate.directory} changed or is registered; it was kept.`);
379
+ assertOwnedAvdStopped(candidate.name, { resolveDirectory: () => candidate.directory });
380
+ const detached = withConfigLock(() => {
381
+ const current = lstatSync(candidate.directory);
382
+ if (!current.isDirectory() || current.dev !== candidate.dev || current.ino !== candidate.ino) throw new Error(`AVD data at ${candidate.directory} changed or is registered; it was kept.`);
383
+ assertAvdReferences(candidate.name, owner);
384
+ const name = `stim-gc-${randomUUID()}`;
385
+ recordCreatedDevice("android", name);
386
+ const destination = join(dirname(candidate.directory), `${name}.avd`);
387
+ try {
388
+ renameSync(candidate.directory, destination);
389
+ } catch (error) {
390
+ forgetCreatedDevice("android", name);
391
+ throw error;
392
+ }
393
+ forgetCreatedDevice("android", candidate.name);
394
+ return destination;
395
+ });
396
+ const current = lstatSync(detached);
397
+ if (!current.isDirectory() || current.dev !== candidate.dev || current.ino !== candidate.ino) throw new Error(`Detached AVD data changed at ${detached}; it was kept.`);
398
+ try {
399
+ rmSync(detached, { recursive: true });
400
+ } catch (error) {
401
+ throw new Error(`Could not remove AVD data at ${detached}; retry gc --delete: ${error.message}`, { cause: error });
402
+ }
403
+ forgetCreatedDevice("android", basename(detached, ".avd"));
404
+ }
405
+ function teardownUnregisteredAvd(avdName, del, owner, surveyed) {
406
+ const candidates = surveyed ? [surveyed] : listOrphanedAvdDirectories(avdName);
407
+ if (candidates.length === 0) {
408
+ if (avdStorageRoots().some((root) => avdPathExists(join(root, `${avdName}.ini`)) || avdPathExists(join(root, `${avdName}.avd`)))) throw new Error(`AVD ${avdName} is not listed but its storage remains; it was kept.`);
409
+ return { status: "missing" };
410
+ }
411
+ if (!del) return {
412
+ status: "skipped",
413
+ reason: "AVD registration is missing; its data was kept."
414
+ };
415
+ for (const candidate of candidates) {
416
+ if (candidate.name !== avdName) throw new Error(`AVD data does not match ${avdName}; it was kept.`);
417
+ removeOrphanedAvdDirectory(candidate, owner);
418
+ }
419
+ return {
420
+ status: "torn-down",
421
+ label: avdName
422
+ };
423
+ }
424
+ function teardownOwnedAvd(avdName, options = {}) {
425
+ let claim;
426
+ try {
427
+ if (!isStimOwnedAvd(avdName)) return {
428
+ status: "skipped",
429
+ kind: "not-owned",
430
+ reason: `AVD ${avdName} is not Stim-owned: Stim has no record of creating it`
431
+ };
432
+ claim = acquireAvdClaim(avdName);
433
+ const result = teardownClaimedAvd(avdName, claim, options);
434
+ if (result.status === "torn-down" || result.status === "missing") options.onRemoved?.();
435
+ return result;
436
+ } catch (error) {
437
+ return {
438
+ status: "failed",
439
+ reason: String(error?.message || error)
440
+ };
441
+ } finally {
442
+ (0, ownership_claim_exports.releaseClaim)(claim);
443
+ }
444
+ }
445
+ function serialFree(serial) {
446
+ const adb = listAdbDevices();
447
+ return ![
448
+ ...adb.emulators,
449
+ ...adb.physical,
450
+ ...adb.unhealthy
451
+ ].some((entry) => entry.serial === serial);
452
+ }
453
+ function teardownClaimedAvd(avdName, claim, { del = false, wipe = false, park, owner, workspace, orphanedDirectory, onlyIfMissing = false, onWipeStart, waitForShutdown = waitForAndroidEmulatorShutdown, assertStopped = assertOwnedAvdStopped, resolveAvd = resolveOwnedAvdSerial }) {
454
+ let parkFallback;
455
+ try {
456
+ if (del || wipe) withConfigLock(() => assertAvdReferences(avdName, owner));
457
+ const resolved = resolveAvd(avdName);
458
+ if (resolved.notOwned) return {
459
+ status: "skipped",
460
+ kind: "not-owned",
461
+ reason: `AVD ${avdName} is not Stim-owned: Stim has no record of creating it`
462
+ };
463
+ if (resolved.missing) {
464
+ if (wipe) throw new Error(`AVD ${avdName} is not registered; its data was kept.`);
465
+ return teardownUnregisteredAvd(avdName, del, owner, orphanedDirectory);
466
+ }
467
+ if (onlyIfMissing) return {
468
+ status: "skipped",
469
+ reason: "AVD registration appeared; its record was kept."
470
+ };
471
+ if (orphanedDirectory) return {
472
+ status: "skipped",
473
+ reason: "AVD registration appeared; its data was kept."
474
+ };
475
+ const serial = resolved.serial;
476
+ const stillStopped = (sessionSerial) => {
477
+ const current = resolveAvd(avdName);
478
+ return !current.notOwned && !current.missing && !current.serial && serialFree(sessionSerial);
479
+ };
480
+ if (serial) {
481
+ const stillOwned = () => {
482
+ const current = resolveAvd(avdName);
483
+ return !current.notOwned && !current.missing && current.serial === serial;
484
+ };
485
+ closeOwnedDeviceSessions({
486
+ platform: "android",
487
+ id: serial,
488
+ avdName
489
+ }, stillOwned, workspace);
490
+ if (!stillOwned()) throw new Error(`Owned AVD ${avdName} changed before shutdown; it was kept.`);
491
+ waitForShutdown(avdName, (timeoutMs) => {
492
+ (0, ownership_claim_exports.markClaimChildPending)(claim);
493
+ try {
494
+ shutdownAndroidEmulator(serial, timeoutMs);
495
+ } finally {
496
+ (0, ownership_claim_exports.clearClaimChild)(claim);
497
+ }
498
+ });
499
+ const root = repoRootAbove(workspace);
500
+ if (root) {
501
+ const deadline = Date.now() + ADB_RELEASE_WAIT_MS;
502
+ while (!serialFree(serial) && Date.now() < deadline) sleepSync(250);
503
+ closeOwnedDeviceSessions({
504
+ platform: "android",
505
+ id: serial,
506
+ avdName
507
+ }, stillStopped, workspace, root);
508
+ }
509
+ } else {
510
+ closeOwnedDeviceSessions({
511
+ platform: "android",
512
+ id: null,
513
+ avdName
514
+ }, stillStopped, workspace);
515
+ waitForShutdown(avdName, null);
516
+ }
517
+ if (wipe && !del) {
518
+ const current = resolveAvd(avdName);
519
+ if (current.notOwned || current.missing) throw new Error(`AVD ${avdName} changed before its data was wiped.`);
520
+ if (current.serial) throw new Error(`Owned AVD ${avdName} started again before its data was wiped.`);
521
+ assertStopped(avdName);
522
+ withConfigLock(() => assertAvdReferences(avdName, owner));
523
+ const directory = ownedAvdDirectory(avdName);
524
+ if (!directory) throw new Error(`The data directory of AVD ${avdName} could not be resolved.`);
525
+ onWipeStart?.();
526
+ wipeAvdUserData(directory);
527
+ }
528
+ if (del) {
529
+ const current = resolveAvd(avdName);
530
+ if (current.notOwned) return {
531
+ status: "skipped",
532
+ kind: "not-owned",
533
+ reason: `AVD ${avdName} is not Stim-owned: Stim has no record of creating it`
534
+ };
535
+ if (current.missing) return teardownUnregisteredAvd(avdName, del, owner);
536
+ if (current.serial) throw new Error(`Owned AVD ${avdName} started again before deletion.`);
537
+ assertStopped(avdName);
538
+ withConfigLock(() => assertAvdReferences(avdName, owner));
539
+ if (park && park.max > 0) try {
540
+ const systemImage = ownedAvdSystemImage(avdName);
541
+ if (!systemImage || !park.configuration || !ownedAvdMatchesConfiguration(avdName, park.configuration)) throw new Error("the AVD has no verified creation configuration");
542
+ const evicted = parkSim({
543
+ platform: "android",
544
+ projectPath: park.projectPath,
545
+ slot: park.slot,
546
+ max: park.max,
547
+ record: {
548
+ udid: avdName,
549
+ name: avdName,
550
+ systemImage,
551
+ configuration: park.configuration,
552
+ parkedAt: (/* @__PURE__ */ new Date()).toISOString(),
553
+ ...park.appId ? { packageName: park.appId } : {},
554
+ ...park.cacheKey ? { cacheKey: park.cacheKey } : {}
555
+ }
556
+ });
557
+ const removed = [];
558
+ const failures = [];
559
+ for (const entry of evicted) {
560
+ const result = teardownParkedAvd(entry.name);
561
+ if (result.status === "torn-down") removed.push({
562
+ udid: entry.name,
563
+ name: entry.name,
564
+ platform: "android"
565
+ });
566
+ else if (result.status === "failed") failures.push(`could not delete evicted ${entry.name}: ${result.reason}`);
567
+ }
568
+ return {
569
+ status: "torn-down",
570
+ label: avdName,
571
+ parked: {
572
+ udid: avdName,
573
+ name: avdName,
574
+ platform: "android"
575
+ },
576
+ evicted: removed,
577
+ ...failures.length ? { evictionFailures: failures } : {}
578
+ };
579
+ } catch (error) {
580
+ parkFallback = String(error?.message || error);
581
+ }
582
+ const directory = ownedAvdDirectory(avdName);
583
+ const paths = avdStorageRoots().map((root) => join(root, `${avdName}.ini`));
584
+ if (directory) paths.push(directory);
585
+ (0, ownership_claim_exports.markClaimChildPending)(claim);
586
+ try {
587
+ deleteAvd(avdName);
588
+ } finally {
589
+ (0, ownership_claim_exports.clearClaimChild)(claim);
590
+ }
591
+ const remaining = paths.filter(avdPathExists);
592
+ if (remaining.length) throw new Error(`AVD ${avdName} was only partially deleted; data remains at ${remaining.join(", ")}.`);
593
+ }
594
+ return {
595
+ status: "torn-down",
596
+ label: avdName,
597
+ serial: resolved.serial ?? null,
598
+ ...parkFallback ? { parkFallback } : {}
599
+ };
600
+ } catch (e) {
601
+ return {
602
+ status: "failed",
603
+ reason: String(e?.message || e)
604
+ };
605
+ }
606
+ }
607
+ const BROWSER_EXIT_WAIT_MS = 15e3;
608
+ const CHROME_KILL_WAIT_MS = 5e3;
609
+ async function stopOwnedChrome(record) {
610
+ for (const signal of ["SIGTERM", "SIGKILL"]) {
611
+ const state = chromeProcessState(record);
612
+ if (state === "gone") return true;
613
+ if (state === "unknown") return false;
614
+ try {
615
+ signalProcessTree(record.pid, signal, { group: true });
616
+ } catch {}
617
+ const deadline = Date.now() + CHROME_KILL_WAIT_MS;
618
+ while (chromeProcessState(record) !== "gone" && Date.now() < deadline) await sleepAsync(50);
619
+ }
620
+ return chromeProcessState(record) === "gone";
621
+ }
622
+ const sleepAsync = (ms) => new Promise((done) => setTimeout(done, ms));
623
+ /**
624
+ * Closes the workspace's Stim-owned Chrome and its supervisor, after verifying both process identities. With
625
+ * `deleteProfile`, it also deletes the profile directory, only when the created-devices ledger lists it.
626
+ */
627
+ async function teardownOwnedBrowser(root, options = {}) {
628
+ try {
629
+ return await withWorkspaceProcessLock(workspaceDir(root), "web", () => teardownBrowserHeld(root, options), {
630
+ external: true,
631
+ ownerPurpose: "browser teardown"
632
+ });
633
+ } catch (error) {
634
+ return {
635
+ status: "failed",
636
+ reason: String(error?.message || error)
637
+ };
638
+ }
639
+ }
640
+ /** {@link teardownOwnedBrowser} for a caller that already holds the {@link BROWSER_LOCK} lock. */
641
+ async function teardownBrowserHeld(root, { deleteProfile = false } = {}) {
642
+ try {
643
+ const record = readWebRecord(root);
644
+ const profile = record?.profile ?? webProfileDir(root);
645
+ if (record) {
646
+ const supervisor = (0, process_identity_exports.inspectProcessIdentity)(record);
647
+ const chrome = record.chromeProcess ? (0, process_identity_exports.inspectProcessIdentity)(record.chromeProcess) : "gone";
648
+ if (supervisor === "unknown" || chrome === "unknown") return {
649
+ status: "skipped",
650
+ kind: "not-verified",
651
+ reason: `the browser supervisor (pid ${record.pid}) or its Chrome could not be verified; its record was kept`
652
+ };
653
+ if (supervisor === "same") {
654
+ try {
655
+ process.kill(record.pid, "SIGTERM");
656
+ } catch {}
657
+ if (!await (0, process_identity_exports.waitForProcessExit)(record, BROWSER_EXIT_WAIT_MS)) return {
658
+ status: "failed",
659
+ reason: `browser supervisor pid ${record.pid} did not exit`
660
+ };
661
+ }
662
+ if (record.chromeProcess && !await stopOwnedChrome(record.chromeProcess)) return {
663
+ status: "failed",
664
+ reason: `Chrome pid ${record.chromeProcess.pid} did not exit`
665
+ };
666
+ const holder = liveProfileHolder(profile);
667
+ if (holder !== null) return {
668
+ status: "skipped",
669
+ kind: "not-verified",
670
+ reason: `pid ${holder} still holds ${profile}, and the browser record does not name it; it was left running`
671
+ };
672
+ const claims = (0, ownership_claim_exports.clearFreeClaimSet)({
673
+ root: webClaimRoot(root),
674
+ label: "browser supervisor"
675
+ });
676
+ if (claims.status !== "cleared") return {
677
+ status: "skipped",
678
+ kind: "not-verified",
679
+ reason: claims.status === "held" ? `the browser supervisor claim is still held${claims.holder ? ` by pid ${claims.holder.owner.pid}` : ""}` : `the browser supervisor claim could not be cleared (${claims.reason}); remove it with ${(0, ownership_claim_exports.claimRemoveCommand)(webClaimRoot(root))}`
680
+ };
681
+ clearWebRecord(root, record);
682
+ await releaseBrowserPort(root, record.cdpPort);
683
+ } else {
684
+ const holder = liveProfileHolder(profile);
685
+ if (holder !== null) return {
686
+ status: "skipped",
687
+ kind: "not-verified",
688
+ reason: `pid ${holder} holds ${profile} but no browser supervisor is recorded; it was left running`
689
+ };
690
+ const port = getProject(root)?.ports?.[CDP_PORT_LABEL];
691
+ if (typeof port === "number") await releaseBrowserPort(root, port);
692
+ }
693
+ if (existsSync(profile)) removeSingletonFiles(profile);
694
+ if (deleteProfile && existsSync(profile)) {
695
+ if (!readCreatedDevices().web.has(profile)) return {
696
+ status: "skipped",
697
+ kind: "not-owned",
698
+ reason: `${profile} is not in Stim's ledger; it was kept`
699
+ };
700
+ rmSync(profile, {
701
+ recursive: true,
702
+ force: true
703
+ });
704
+ forgetCreatedDevice("web", profile);
705
+ }
706
+ return record ? {
707
+ status: "torn-down",
708
+ label: `Chrome (${profile})`
709
+ } : { status: "missing" };
710
+ } catch (error) {
711
+ return {
712
+ status: "failed",
713
+ reason: String(error?.message || error)
714
+ };
715
+ }
716
+ }
717
+ //#endregion
718
+ export { teardownOwnedBrowser as a, teardownParkedIosSim as c, teardownOwnedAvd as i, eraseParkedIosSim as n, teardownOwnedIosSim as o, teardownBrowserHeld as r, teardownParkedAvd as s, eraseParkedAvd as t };