stim 1.10.0 → 1.11.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 (58) hide show
  1. package/dist/{build-progress-BXx-ZBe4.mjs → activity-BtG4Va9l.mjs} +8 -182
  2. package/dist/{android-DPov-fv2.mjs → android-BA2i_KAV.mjs} +1 -1
  3. package/dist/{android-DBkeHwpm.mjs → android-C1q4l523.mjs} +376 -99
  4. package/dist/{android-787HhP5w.mjs → android-C4zG2Tuc.mjs} +63 -18
  5. package/dist/{android-cas-CITmIeWY.mjs → android-cas-DfJkwCXW.mjs} +3 -3
  6. package/dist/{app-install-CrJ6t_bv.mjs → app-install-DHut6JnV.mjs} +1 -1
  7. package/dist/{budget-BP4jZZL4.mjs → budget-De3P2rq_.mjs} +9 -9
  8. package/dist/{dev-client-92U593KT.mjs → build-plan-CeAYgKAx.mjs} +415 -24
  9. package/dist/build-progress-CDwogz6R.mjs +179 -0
  10. package/dist/cli.mjs +14 -14
  11. package/dist/collector-run.mjs +1 -1
  12. package/dist/{deps-DP4eWqea.mjs → deps-OF7CD5Dx.mjs} +2 -2
  13. package/dist/{device-DhTZe7L4.mjs → device-BwH2iI3O.mjs} +47 -9
  14. package/dist/{device-lease-CbEaIk7b.mjs → device-lease-D83nqeMX.mjs} +51 -51
  15. package/dist/{device-pool-Di8Q-9Ro.mjs → device-pool-DHj7cdPy.mjs} +2 -2
  16. package/dist/{device-remote-Dy1jGj3U.mjs → device-remote-BQZSnnmE.mjs} +7 -7
  17. package/dist/{doctor-B-inAJmt.mjs → doctor-D8QdMRMf.mjs} +12 -12
  18. package/dist/{error-diagnostics-xxWKNO3-.mjs → error-diagnostics-UYFSQwRy.mjs} +3 -3
  19. package/dist/{gc-ChPFZMRC.mjs → gc-COZteyiq.mjs} +27 -253
  20. package/dist/{guide-DwmaD_Wa.mjs → guide-NDvTmMi-.mjs} +336 -48
  21. package/dist/{idle-DpRLp5lj.mjs → idle-NETbeNiQ.mjs} +4 -3
  22. package/dist/{in-use-CjUluqIX.mjs → in-use-DVhlSoyn.mjs} +4 -4
  23. package/dist/{ios-Dd-hYJBh.mjs → ios-CQLKpNfr.mjs} +294 -81
  24. package/dist/{ios-B2Fpqvlb.mjs → ios-DArbmwer.mjs} +16 -7
  25. package/dist/{ios-device-CtRdEVjx.mjs → ios-device-CwDZo0X4.mjs} +1 -1
  26. package/dist/{launch-verify-CQS_Kg-C.mjs → launch-verify-CuPDGXdr.mjs} +1 -1
  27. package/dist/logs-B44a1UeU.mjs +485 -0
  28. package/dist/merge-state-DDxS-XIZ.mjs +232 -0
  29. package/dist/{named-ports-DiTfSz6p.mjs → named-ports-Dc7neAlc.mjs} +1 -1
  30. package/dist/native-run-D7yB_AsB.mjs +143 -0
  31. package/dist/{ownership-DZjdx8Gq.mjs → ownership-BiojdtAp.mjs} +3 -3
  32. package/dist/{ports-CLSSFOuz.mjs → ports-DwBaRFJs.mjs} +1 -1
  33. package/dist/{reload-DoETJ3rl.mjs → reload-By9Dwsrt.mjs} +4 -4
  34. package/dist/{server-bare-DVbb7kXH.mjs → server-bare-D_RK1RCj.mjs} +1 -1
  35. package/dist/server-expo-B-CCUJZj.mjs +2 -0
  36. package/dist/{server-expo-BvOCeakp.mjs → server-expo-o6H5gcBc.mjs} +1 -1
  37. package/dist/{settings-DOugPlPz.mjs → settings-B5oFZEri.mjs} +12 -3
  38. package/dist/{settings-EWYNwe72.mjs → settings-C0ugALSC.mjs} +1 -1
  39. package/dist/settings.schema.json +52 -0
  40. package/dist/{simslim-Ca3487H6.mjs → simslim-CIR3IYJO.mjs} +150 -95
  41. package/dist/{slot-launch-C5cg0fmk.mjs → slot-launch-rggO1Esw.mjs} +2 -2
  42. package/dist/{spawn-claims-CUleC2cM.mjs → spawn-claims-BJwXTMPt.mjs} +24 -1
  43. package/dist/{start-F9gv5dcC.mjs → start-BSsf2tUs.mjs} +4 -4
  44. package/dist/{start-VoFsPSes.mjs → start-i8zc9VmS.mjs} +1 -1
  45. package/dist/{status-DLCD-o3s.mjs → status-CitcBRsC.mjs} +227 -22
  46. package/dist/{status-Dr4fRkym.mjs → status-Q-WDEGCB.mjs} +20 -6
  47. package/dist/{stop-Dj4pfmyv.mjs → stop-DIhrvu0B.mjs} +188 -27
  48. package/dist/stop-rst5mL14.mjs +3 -0
  49. package/dist/supervisor-run.mjs +7 -7
  50. package/dist/{workspace-process-lock-BXA96myD.mjs → workspace-process-lock-Cx74RSDZ.mjs} +9 -4
  51. package/dist/{workspaces-BTUyFfkv.mjs → workspaces-COD2xCz-.mjs} +15 -5
  52. package/dist/{worktree-4aZg2NnI.mjs → worktree-DhxDTK44.mjs} +1 -1
  53. package/dist/{worktree-BMS7GeqB.mjs → worktree-KOjMX3zA.mjs} +8 -8
  54. package/dist/{xcode-B2tBkf0m.mjs → xcode-B5SPD--o.mjs} +3 -3
  55. package/package.json +5 -5
  56. package/dist/logs-MARIy6m9.mjs +0 -209
  57. package/dist/server-expo-DBVTdult.mjs +0 -2
  58. package/dist/stop-ZvOeTmKb.mjs +0 -3
@@ -1,7 +1,7 @@
1
1
  import { g as loadConfig$1 } from "./config-BEq0Qw_a.mjs";
2
2
  import { t as getExecutor } from "./exec-DK8KaVHK.mjs";
3
3
  import { n as stripAnsi, r as waitForChild, t as createLineReader } from "./process-output-Fpl8PYi8.mjs";
4
- import { J as recordCreatedDevice, K as isStimOwnedSim, q as forgetCreatedDevice } from "./android-787HhP5w.mjs";
4
+ import { X as forgetCreatedDevice, Y as isStimOwnedSim, Z as recordCreatedDevice } from "./android-C4zG2Tuc.mjs";
5
5
  import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
6
6
  import { IOS_SIMULATOR_APPS } from "@stim-cli/core/state";
7
7
  import { dirname, join, resolve } from "node:path";
@@ -42,6 +42,7 @@ function configuredIosSimulatorViewer(override) {
42
42
  const exec = getExecutor();
43
43
  if (app === "stim-desktop") return { open: (udid) => {
44
44
  exec.runFileQuiet("open", [
45
+ "-g",
45
46
  "-a",
46
47
  "Stim",
47
48
  `stim-desktop://open?udid=${udid}`
@@ -300,16 +301,24 @@ function rankIphone(name) {
300
301
  function iosRuntimeMatches(runtime, requested) {
301
302
  return runtime.version === requested || runtime.name === requested;
302
303
  }
304
+ function bestIphone(candidates) {
305
+ return candidates.toSorted((a, b) => {
306
+ const ra = rankIphone(a.name), rb = rankIphone(b.name);
307
+ return rb.gen - ra.gen || rb.variant - ra.variant || b.name.localeCompare(a.name, void 0, { numeric: true });
308
+ })[0];
309
+ }
303
310
  function pickDefaultIosCreation(_deviceTypes, runtimes, { deviceType, runtime } = {}) {
304
311
  const rts = runtimes.toSorted((a, b) => String(b.version).localeCompare(String(a.version), void 0, { numeric: true }));
305
312
  const wantedRts = runtime ? rts.filter((r) => iosRuntimeMatches(r, runtime)) : rts;
313
+ if (!deviceType) for (const rt of wantedRts) {
314
+ const best = bestIphone((rt.supportedDeviceTypes || []).filter((d) => /^iPhone/i.test(d.name) && rankIphone(d.name).gen >= 0));
315
+ if (best !== void 0) return {
316
+ deviceTypeId: best.identifier,
317
+ runtimeId: rt.identifier
318
+ };
319
+ }
306
320
  for (const rt of wantedRts) {
307
- const supported = (rt.supportedDeviceTypes || []).filter((d) => deviceType ? d.name === deviceType : /^iPhone/i.test(d.name));
308
- if (supported.length === 0) continue;
309
- const best = supported.toSorted((a, b) => {
310
- const ra = rankIphone(a.name), rb = rankIphone(b.name);
311
- return rb.gen - ra.gen || rb.variant - ra.variant || b.name.localeCompare(a.name, void 0, { numeric: true });
312
- })[0];
321
+ const best = bestIphone((rt.supportedDeviceTypes || []).filter((d) => deviceType ? d.name === deviceType : /^iPhone/i.test(d.name)));
313
322
  if (best === void 0) continue;
314
323
  return {
315
324
  deviceTypeId: best.identifier,
@@ -1,6 +1,6 @@
1
1
  import { t as getExecutor } from "./exec-DK8KaVHK.mjs";
2
2
  import { n as TOOL_ERROR_PREFIX } from "./ios-device-BiOsSVzd.mjs";
3
- import { i as INSTALL_ERROR } from "./app-install-CrJ6t_bv.mjs";
3
+ import { i as INSTALL_ERROR } from "./app-install-DHut6JnV.mjs";
4
4
  import { mkdtempSync, readFileSync, rmSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { tmpdir } from "node:os";
@@ -2,7 +2,7 @@ import { t as getExecutor } from "./exec-DK8KaVHK.mjs";
2
2
  import { o as readNdjsonGenerations } from "./ndjson-CDY9IkVC.mjs";
3
3
  import { s as isAppLaunchError } from "./command-output-D5z2_bcF.mjs";
4
4
  import { t as DEV_MENU_LAUNCH_ARGS } from "./ios-device-BiOsSVzd.mjs";
5
- import { d as deviceShellArg, n as ANDROID_DISABLE_AUTO_LAUNCH_EXTRA, o as androidAppProcess } from "./app-install-CrJ6t_bv.mjs";
5
+ import { d as deviceShellArg, n as ANDROID_DISABLE_AUTO_LAUNCH_EXTRA, o as androidAppProcess } from "./app-install-DHut6JnV.mjs";
6
6
  import { join } from "node:path";
7
7
  //#region src/engine/app-readiness.ts
8
8
  const APP_READINESS_TIMEOUT_MS = 3e4;
@@ -0,0 +1,485 @@
1
+ import { D as process_identity_exports, H as projectDeviceSlots, V as parseDeviceSlotOption, g as loadConfig$1, h as isPathPrefix } from "./config-BEq0Qw_a.mjs";
2
+ import { n as SOURCES, t as LEVELS } from "./ndjson-CDY9IkVC.mjs";
3
+ import { j as workspaceLogsDir, m as readWorkspaceState$1 } from "./metro-BWLOJ_Wr.mjs";
4
+ import { o as findProjectRoot } from "./project-BXZzOABt.mjs";
5
+ import { f as refuseNoProject, v as launchErrorPreview } from "./command-output-D5z2_bcF.mjs";
6
+ import { i as readAgentDeviceRecords, t as agentDeviceLiveness } from "./activity-BtG4Va9l.mjs";
7
+ import { i as captureWorkspaceCrashes, t as errorDiagnostics } from "./error-diagnostics-UYFSQwRy.mjs";
8
+ import { closeSync, fstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync } from "node:fs";
9
+ import { buildCriteria, compileGrep, fileSizes, followLogs, logFiles, parseSince, queryLogs, readLogRecords, recordMatches, sortByTs } from "@stim-cli/core/state";
10
+ import { join, relative, resolve, sep } from "node:path";
11
+ import { homedir } from "node:os";
12
+ import chalk from "chalk";
13
+ //#region src/devices/agent-actions.ts
14
+ const EVENTS_VERSION = 1;
15
+ function object(value) {
16
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
17
+ }
18
+ function parseAgentEvents(lines) {
19
+ const events = [];
20
+ let session = null;
21
+ let unknownVersion = null;
22
+ for (const line of lines) {
23
+ let entry;
24
+ try {
25
+ entry = object(JSON.parse(line));
26
+ } catch {
27
+ continue;
28
+ }
29
+ if (!entry) continue;
30
+ const ts = typeof entry.ts === "string" ? Date.parse(entry.ts) : NaN;
31
+ if (entry.version !== EVENTS_VERSION) {
32
+ unknownVersion ??= {
33
+ version: entry.version,
34
+ ts: Number.isFinite(ts) ? ts : null
35
+ };
36
+ continue;
37
+ }
38
+ if (typeof entry.session === "string") session ??= entry.session;
39
+ const { kind, command, summary } = entry;
40
+ if (kind !== "action.recorded" && kind !== "request.finished") continue;
41
+ const failed = kind === "request.finished" && entry.status === "error";
42
+ if (kind === "request.finished" && !failed) continue;
43
+ if (!Number.isFinite(ts) || typeof entry.session !== "string" || typeof command !== "string") continue;
44
+ if (typeof summary !== "string") continue;
45
+ events.push({
46
+ ts,
47
+ session: entry.session,
48
+ kind,
49
+ command,
50
+ summary,
51
+ failed,
52
+ details: object(entry.details)
53
+ });
54
+ }
55
+ return {
56
+ events,
57
+ session,
58
+ unknownVersion
59
+ };
60
+ }
61
+ const RUNNER_DEVICE = /-destination\s+"?platform=iOS Simulator,id=([^",\s]+)|AgentDeviceRunner\.env\.session-(.+?)-owner-/;
62
+ const LOG_TIME = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)?([+-]\d{2})?(\d{2})?\b/;
63
+ function logTime(line) {
64
+ const match = LOG_TIME.exec(line);
65
+ if (!match) return null;
66
+ const [, date, time, fraction = "", offsetHours, offsetMinutes] = match;
67
+ const offset = offsetHours && offsetMinutes ? `${offsetHours}:${offsetMinutes}` : "";
68
+ const at = Date.parse(`${date}T${time}${fraction.slice(0, 4)}${offset}`);
69
+ return Number.isFinite(at) ? at : null;
70
+ }
71
+ function parseRunnerSpans(text) {
72
+ const spans = [];
73
+ let pending = null;
74
+ for (const line of text.split("\n")) {
75
+ const device = RUNNER_DEVICE.exec(line);
76
+ if (device) {
77
+ pending = device[1] ?? device[2] ?? null;
78
+ continue;
79
+ }
80
+ if (pending === null) continue;
81
+ const at = logTime(line);
82
+ if (at === null) continue;
83
+ if (spans.at(-1)?.deviceId !== pending) spans.push({
84
+ deviceId: pending,
85
+ from: spans.length ? at : -Infinity
86
+ });
87
+ pending = null;
88
+ }
89
+ return spans;
90
+ }
91
+ function sessionSpans(runner, closes) {
92
+ return runner.map((span, i) => {
93
+ const previous = runner[i - 1]?.from ?? -Infinity;
94
+ const close = closes.findLast((at) => at > previous && at < span.from);
95
+ return close === void 0 ? span : {
96
+ ...span,
97
+ from: close + 1
98
+ };
99
+ });
100
+ }
101
+ function spanDevice(spans, ts) {
102
+ let device = null;
103
+ for (const span of spans) if (span.from <= ts) device = span.deviceId;
104
+ return device;
105
+ }
106
+ function agentRecord(event, deviceId, target) {
107
+ return {
108
+ ts: event.ts,
109
+ src: "agent",
110
+ level: event.failed ? "error" : "info",
111
+ msg: event.summary,
112
+ event: event.failed ? "agent_failed" : "agent_action",
113
+ command: event.command,
114
+ session: event.session,
115
+ platform: target.platform,
116
+ deviceId,
117
+ ...target.slot === "default" ? {} : { slot: target.slot },
118
+ ...event.details ? { details: event.details } : {}
119
+ };
120
+ }
121
+ function formatUnknownRecord(session, unknown, target, now) {
122
+ return {
123
+ ts: unknown.ts ?? now,
124
+ src: "agent",
125
+ level: "warn",
126
+ msg: `agent-device session ${session} records events in an unrecognized format (version ${JSON.stringify(unknown.version) ?? "missing"}); its actions are not shown.`,
127
+ event: "agent_format_unknown",
128
+ session,
129
+ platform: target.platform,
130
+ ...target.slot === "default" ? {} : { slot: target.slot }
131
+ };
132
+ }
133
+ function workspaceAgentTargets(project) {
134
+ const targets = [];
135
+ let slots;
136
+ try {
137
+ slots = projectDeviceSlots(project);
138
+ } catch {
139
+ return [];
140
+ }
141
+ for (const { slot, platforms } of slots) {
142
+ const { ios, android } = platforms;
143
+ if (ios?.owned && typeof ios.deviceUdid === "string") targets.push({
144
+ platform: "ios",
145
+ id: ios.deviceUdid,
146
+ slot
147
+ });
148
+ if (android?.owned && typeof android.consolePort === "number" && typeof android.avdName === "string") targets.push({
149
+ platform: "android",
150
+ id: `emulator-${android.consolePort}`,
151
+ slot,
152
+ name: android.avdName
153
+ });
154
+ }
155
+ return targets;
156
+ }
157
+ function envDir(name) {
158
+ const value = process.env[name]?.trim();
159
+ return value ? resolve(value) : null;
160
+ }
161
+ function readCompleteLines(path, start) {
162
+ let fd;
163
+ try {
164
+ fd = openSync(path, "r");
165
+ const size = fstatSync(fd).size;
166
+ if (size <= start) return {
167
+ text: "",
168
+ next: start,
169
+ size
170
+ };
171
+ const buffer = Buffer.alloc(size - start);
172
+ const read = readSync(fd, buffer, 0, buffer.length, start);
173
+ const end = buffer.subarray(0, read).lastIndexOf(10);
174
+ return {
175
+ text: end < 0 ? "" : buffer.toString("utf8", 0, end + 1),
176
+ next: start + end + 1,
177
+ size
178
+ };
179
+ } catch {
180
+ return null;
181
+ } finally {
182
+ if (fd !== void 0) closeSync(fd);
183
+ }
184
+ }
185
+ /**
186
+ * Returns a reader of agent-device actions on the given devices. Each call returns the records written
187
+ * since the previous call; the first call returns the retained history newer than `sinceTs`. It only reads
188
+ * agent-device's state directory, and any file it cannot read or recognize yields no records.
189
+ */
190
+ function createAgentActionReader({ targets, sinceTs = -Infinity, home = homedir(), now = Date.now, startOf = process_identity_exports.inspectProcessStart }) {
191
+ const sessionsDir = join(envDir("AGENT_DEVICE_STATE_DIR") ?? join(home, ".agent-device"), "sessions");
192
+ const cursors = /* @__PURE__ */ new Map();
193
+ const byId = new Map(targets.map((target) => [target.id, target]));
194
+ return () => {
195
+ if (!targets.length) return [];
196
+ let names;
197
+ try {
198
+ names = readdirSync(sessionsDir);
199
+ } catch {
200
+ return [];
201
+ }
202
+ let claimed;
203
+ const claimedDevice = (session) => (claimed ??= new Map(readAgentDeviceRecords(home).filter((record) => record.kind === "claim" && record.session && record.deviceId).filter((record) => {
204
+ const target = byId.get(record.deviceId);
205
+ return target?.name === void 0 || target.name === record.deviceName;
206
+ }).filter((record) => agentDeviceLiveness(record, startOf) === "live").map((record) => [record.session, record.deviceId]))).get(session) ?? null;
207
+ const out = [];
208
+ for (const name of names) {
209
+ const dir = join(sessionsDir, name);
210
+ const eventsPath = join(dir, "events.ndjson");
211
+ const lines = [];
212
+ let cursor = cursors.get(name);
213
+ if (!cursor) {
214
+ try {
215
+ if (statSync(eventsPath).mtimeMs < sinceTs) continue;
216
+ } catch {
217
+ continue;
218
+ }
219
+ cursor = {
220
+ offset: 0,
221
+ closes: [],
222
+ runner: null,
223
+ session: null,
224
+ unknownReported: false
225
+ };
226
+ cursors.set(name, cursor);
227
+ try {
228
+ lines.push(...readFileSync(`${eventsPath}.1`, "utf8").split("\n"));
229
+ } catch {}
230
+ }
231
+ let chunk = readCompleteLines(eventsPath, cursor.offset);
232
+ if (chunk && chunk.size < cursor.offset) chunk = readCompleteLines(eventsPath, 0);
233
+ if (!chunk) continue;
234
+ cursor.offset = chunk.next;
235
+ lines.push(...chunk.text.split("\n"));
236
+ const parsed = parseAgentEvents(lines);
237
+ cursor.session ??= parsed.session;
238
+ const session = cursor.session;
239
+ if (!parsed.events.length && !parsed.unknownVersion) continue;
240
+ const runnerPath = join(dir, "runner.log");
241
+ let runnerSize = -1;
242
+ try {
243
+ runnerSize = statSync(runnerPath).size;
244
+ } catch {}
245
+ if (cursor.runner?.size !== runnerSize) {
246
+ let text = "";
247
+ try {
248
+ text = readFileSync(runnerPath, "utf8");
249
+ } catch {}
250
+ cursor.runner = {
251
+ size: runnerSize,
252
+ spans: parseRunnerSpans(text)
253
+ };
254
+ }
255
+ for (const event of parsed.events) if (event.command === "close" && !event.failed) cursor.closes.push(event.ts);
256
+ const spans = sessionSpans(cursor.runner.spans, cursor.closes);
257
+ const deviceAt = (ts) => spans.length ? spanDevice(spans, ts) : session && claimedDevice(session);
258
+ if (parsed.unknownVersion && !cursor.unknownReported) {
259
+ const deviceId = spans.at(-1)?.deviceId ?? (session && claimedDevice(session));
260
+ const target = deviceId ? byId.get(deviceId) : void 0;
261
+ if (target) {
262
+ cursor.unknownReported = true;
263
+ out.push(formatUnknownRecord(session ?? name, parsed.unknownVersion, target, now()));
264
+ }
265
+ }
266
+ for (const event of parsed.events) {
267
+ if (event.ts < sinceTs) continue;
268
+ const deviceId = deviceAt(event.ts);
269
+ const target = deviceId ? byId.get(deviceId) : void 0;
270
+ if (target && deviceId) out.push(agentRecord(event, deviceId, target));
271
+ }
272
+ }
273
+ return out.toSorted((a, b) => a.ts - b.ts);
274
+ };
275
+ }
276
+ //#endregion
277
+ //#region src/commands/logs.ts
278
+ const LEVEL_WIDTH = 5;
279
+ const SRC_WIDTH = 6;
280
+ const INDENT = " ";
281
+ function padTimePart(value, width = 2) {
282
+ return String(value).padStart(width, "0");
283
+ }
284
+ function formatTime(ts) {
285
+ if (typeof ts !== "number" || !Number.isFinite(ts)) return "--:--:--.---";
286
+ const d = new Date(ts);
287
+ return `${padTimePart(d.getHours())}:${padTimePart(d.getMinutes())}:${padTimePart(d.getSeconds())}.${padTimePart(d.getMilliseconds(), 3)}`;
288
+ }
289
+ function formatStackFrame(frame) {
290
+ if (!frame || typeof frame !== "object") return null;
291
+ const where = [
292
+ frame.file,
293
+ frame.line,
294
+ frame.column
295
+ ].filter((p) => p !== void 0 && p !== null && p !== "").join(":");
296
+ if (frame.fn && where) return `at ${frame.fn} (${where})`;
297
+ if (frame.fn) return `at ${frame.fn}`;
298
+ if (where) return `at ${where}`;
299
+ return null;
300
+ }
301
+ function formatRecord(record, { paint } = {}) {
302
+ const colour = paint || ((t) => t);
303
+ const level = String(record?.level ?? "").padEnd(LEVEL_WIDTH);
304
+ const src = String(record?.src ?? "").padEnd(SRC_WIDTH);
305
+ const [first, ...rest] = (record?.msg === void 0 || record?.msg === null ? "" : String(record.msg)).split("\n");
306
+ const lines = [`${formatTime(record?.ts)} ${colour(level)} ${src} ${first}`];
307
+ for (const line of rest) lines.push(`${INDENT}${line}`);
308
+ for (const frame of Array.isArray(record?.stack) ? record.stack : []) {
309
+ const rendered = formatStackFrame(frame);
310
+ if (rendered) lines.push(`${INDENT}${rendered}`);
311
+ }
312
+ return lines.join("\n");
313
+ }
314
+ function parseTail(value) {
315
+ if (typeof value === "number" && Number.isInteger(value) && value >= 0) return { n: value };
316
+ if (typeof value !== "string" || !/^\d+$/.test(value.trim())) return { error: `Invalid --tail value ${JSON.stringify(value)}. Use a non-negative whole number, e.g. --tail 50.` };
317
+ return { n: parseInt(value.trim(), 10) };
318
+ }
319
+ function validateSources(sources) {
320
+ if (sources === void 0 || sources === null) return { sources: void 0 };
321
+ const list = Array.isArray(sources) ? sources : [sources];
322
+ if (list.includes("all")) return { sources: [...SOURCES] };
323
+ const unknown = list.filter((s) => !SOURCES.includes(s));
324
+ if (unknown.length > 0) return { error: `Unknown --source value(s): ${unknown.join(", ")}. Use one or more of: ${SOURCES.join(", ")}, or all.` };
325
+ return { sources: list };
326
+ }
327
+ function validateLevel(level) {
328
+ if (LEVELS.includes(level)) return { level };
329
+ return { error: `Invalid --level value ${JSON.stringify(level)}. Use one of: ${LEVELS.join(", ")}.` };
330
+ }
331
+ const ERRORS_PRINT_CAP = 20;
332
+ function nearestRegisteredLogsProject(root, candidates) {
333
+ return candidates.filter((candidate) => candidate !== root && isPathPrefix(root, candidate)).toSorted((a, b) => {
334
+ const depth = (path) => relative(root, path).split(sep).length;
335
+ return depth(a) - depth(b) || a.length - b.length || a.localeCompare(b);
336
+ })[0] ?? null;
337
+ }
338
+ function registeredDescendantWithLogs(root) {
339
+ const candidates = Object.keys(loadConfig$1()?.projects ?? {}).flatMap((path) => {
340
+ try {
341
+ const canonical = realpathSync(path);
342
+ return logFiles(workspaceLogsDir(canonical)).length > 0 ? [canonical] : [];
343
+ } catch {
344
+ return [];
345
+ }
346
+ });
347
+ return nearestRegisteredLogsProject(root, [...new Set(candidates)]);
348
+ }
349
+ function requireLogsWorkspace(root, dir) {
350
+ if (logFiles(dir).length > 0) return;
351
+ const descendant = registeredDescendantWithLogs(root);
352
+ fail(`STIM_NO_PROJECT: No Stim workspace has run in ${root}.${descendant ? ` The nearest registered app with logs is ${descendant}; run this command from there.` : " Run `stim start`, `stim ios`, or `stim android` in the app first."}`);
353
+ }
354
+ const LEVEL_COLOURS = {
355
+ debug: chalk.dim,
356
+ info: chalk.reset,
357
+ warn: chalk.yellow,
358
+ error: chalk.red,
359
+ fatal: chalk.bgRed
360
+ };
361
+ function logsCommand(program) {
362
+ program.command("logs").description("Query this workspace's merged NDJSON log timeline (bundler, client, device, build, agent-device actions). Prints and exits; an existing timeline with nothing matching is a successful, empty result. Use --follow to stream.").option("--slot <name>", "Only records attributed to this device slot", parseDeviceSlotOption).option("--source <s...>", "Only these sources: metro, client, device, build, agent, or all").option("--level <l>", `Minimum level: ${LEVELS.join(", ")}`).option("--since <d>", "Only records newer than this, e.g. 30s, 5m, 2h").option("--grep <re>", "Only records whose message matches this regular expression").option("--tail <n>", "Only the last n matching records").option("--errors", "Errors and fatals since the last marker, from metro, client and build, plus confirmed native app-crash reports. Add --source device or --source all for general device errors.").option("--follow", "Keep streaming new records until interrupted").option("--json", "Emit the raw records, one per line (valid NDJSON; zero matches is zero bytes, exit 0)").action(async (opts) => {
363
+ const root = findProjectRoot(process.cwd());
364
+ if (!root) {
365
+ refuseNoProject({ json: false });
366
+ return;
367
+ }
368
+ const dir = workspaceLogsDir(root);
369
+ let sources;
370
+ if (opts.source !== void 0) {
371
+ const checked = validateSources(opts.source);
372
+ if (checked.error) fail(checked.error);
373
+ sources = checked.sources;
374
+ }
375
+ let minLevel;
376
+ if (opts.level !== void 0) {
377
+ const checked = validateLevel(opts.level);
378
+ if (checked.error) fail(checked.error);
379
+ minLevel = checked.level;
380
+ }
381
+ if (opts.since !== void 0) {
382
+ const parsed = parseSince(opts.since);
383
+ if (parsed.error) fail(parsed.error);
384
+ }
385
+ let tail;
386
+ if (opts.tail !== void 0) {
387
+ const parsed = parseTail(opts.tail);
388
+ if (parsed.error) fail(parsed.error);
389
+ tail = parsed.n;
390
+ }
391
+ if (opts.grep !== void 0) {
392
+ const compiled = compileGrep(opts.grep);
393
+ if (compiled.error) fail(compiled.error);
394
+ }
395
+ requireLogsWorkspace(root, dir);
396
+ const query = {
397
+ slot: opts.slot,
398
+ dir,
399
+ sources,
400
+ minLevel,
401
+ since: opts.since,
402
+ grep: opts.grep,
403
+ tail,
404
+ errorsOnly: Boolean(opts.errors),
405
+ errorContext: Boolean(opts.errors && !opts.json && !opts.follow)
406
+ };
407
+ const emit = (record) => {
408
+ if (opts.json) {
409
+ console.log(JSON.stringify(record));
410
+ return;
411
+ }
412
+ const rendered = {
413
+ ...record,
414
+ msg: launchErrorPreview([record], root, { full: true }).join("\n"),
415
+ stack: void 0
416
+ };
417
+ console.log(formatRecord(rendered, { paint: record?.level ? LEVEL_COLOURS[record.level] : void 0 }));
418
+ };
419
+ const captured = captureWorkspaceCrashes(root, dir);
420
+ const offsets = opts.follow ? fileSizes(dir) : null;
421
+ const workspaceTimeline = opts.follow ? readLogRecords(dir) : captured;
422
+ const agentSince = workspaceTimeline[0]?.ts ?? (opts.follow ? Date.now() : void 0);
423
+ const readAgent = (sources ? sources.includes("agent") : !opts.errors) && agentSince !== void 0 ? createAgentActionReader({
424
+ targets: workspaceAgentTargets(loadConfig$1()?.projects?.[root]),
425
+ sinceTs: agentSince
426
+ }) : null;
427
+ const timeline = readAgent ? sortByTs([...workspaceTimeline, ...readAgent()]) : workspaceTimeline;
428
+ const rawRecords = queryLogs({
429
+ ...query,
430
+ records: timeline
431
+ });
432
+ const supervisorPort = readWorkspaceState$1(root)?.supervisor?.port;
433
+ const records = opts.json ? rawRecords : await errorDiagnostics(rawRecords, {
434
+ root,
435
+ logsDir: dir,
436
+ port: typeof supervisorPort === "number" ? supervisorPort : null,
437
+ allowRequest: true,
438
+ timeline
439
+ });
440
+ const errorCount = records.filter((record) => record.errorContext !== true).length;
441
+ let seenErrors = 0;
442
+ const capped = opts.errors && !opts.json && tail === void 0 && errorCount > 20 ? records.filter((record) => {
443
+ if (record.errorContext === true) return seenErrors <= 20;
444
+ seenErrors += 1;
445
+ return seenErrors <= 20;
446
+ }) : records;
447
+ for (const record of capped) emit(record);
448
+ const hidden = errorCount - capped.filter((record) => record.errorContext !== true).length;
449
+ if (hidden > 0) console.log(chalk.dim(`Showing 20 of ${errorCount} matching error records; ${hidden} not shown. Add --tail ${rawRecords.length} to include all captured records before grouping, or --json for raw records. Stacks are shown in full.`));
450
+ if (!opts.follow) {
451
+ if (records.length === 0 && !opts.json) console.error(chalk.dim(`No matching log records in ${dir}`));
452
+ return;
453
+ }
454
+ const criteria = buildCriteria({
455
+ slot: opts.slot,
456
+ sources,
457
+ minLevel,
458
+ since: opts.since,
459
+ grep: opts.grep,
460
+ errorsOnly: Boolean(opts.errors)
461
+ });
462
+ const stop = followLogs({
463
+ dir,
464
+ offsets,
465
+ criteria,
466
+ onRecord: emit
467
+ });
468
+ const agentTimer = readAgent ? setInterval(() => {
469
+ for (const record of readAgent()) if (recordMatches(record, criteria)) emit(record);
470
+ }, 500) : null;
471
+ const finish = () => {
472
+ stop();
473
+ if (agentTimer) clearInterval(agentTimer);
474
+ process.exit(0);
475
+ };
476
+ process.on("SIGINT", finish);
477
+ process.on("SIGTERM", finish);
478
+ });
479
+ }
480
+ function fail(message) {
481
+ console.error(chalk.red(message));
482
+ process.exit(1);
483
+ }
484
+ //#endregion
485
+ export { ERRORS_PRINT_CAP, logsCommand as default, formatRecord, formatStackFrame, formatTime, parseTail, validateLevel, validateSources };