@cnc-tools/storm 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/bin/storm.js +3 -14
  2. package/dist/application.d.ts +18 -10
  3. package/dist/application.js +10 -11
  4. package/dist/bin/storm.js +97 -41
  5. package/dist/build-info.js +1 -1
  6. package/dist/chunks/chunk-5CQCRX2L.js +5768 -0
  7. package/dist/chunks/chunk-5U5Q6VZR.js +556 -0
  8. package/dist/chunks/chunk-7O6UN63H.js +63 -0
  9. package/dist/chunks/chunk-I5GZLOLQ.js +38 -0
  10. package/dist/chunks/chunk-NX55IJ5S.js +1842 -0
  11. package/dist/chunks/chunk-OCZJE5XV.js +910 -0
  12. package/dist/chunks/chunk-RRQ2ZGSE.js +1512 -0
  13. package/dist/chunks/chunk-S5NAIZYS.js +13 -0
  14. package/dist/chunks/chunk-UHO5OCEX.js +360 -0
  15. package/dist/chunks/chunk-WBIHJM7D.js +188 -0
  16. package/dist/chunks/chunk-WV6WQFC6.js +436 -0
  17. package/dist/chunks/live-app-X3PW2W42.js +89 -0
  18. package/dist/chunks/version-X7RMSKZI.js +12 -0
  19. package/dist/commands/exec/command.js +35 -21
  20. package/dist/commands/exec/metadata.js +66 -58
  21. package/dist/commands/exec/redaction.js +1 -1
  22. package/dist/commands/exec/run-collector.d.ts +1 -1
  23. package/dist/commands/exec/run-collector.js +1 -1
  24. package/dist/commands/exec/run-record.d.ts +1 -1
  25. package/dist/commands/exec/tests-summary.d.ts +1 -1
  26. package/dist/commands/exec/worker-chart.d.ts +1 -1
  27. package/dist/commands/runs/list/command.js +136 -33
  28. package/dist/commands/runs/list/metadata.js +22 -18
  29. package/dist/commands/runs/logs/command.js +131 -48
  30. package/dist/commands/runs/logs/metadata.js +24 -20
  31. package/dist/commands/runs/metadata.js +6 -2
  32. package/dist/commands/runs/past-run.d.ts +1 -1
  33. package/dist/commands/runs/past-run.js +1 -1
  34. package/dist/commands/runs/show/command.js +396 -74
  35. package/dist/commands/runs/show/metadata.js +24 -20
  36. package/dist/commands/vitest/command.js +195 -128
  37. package/dist/commands/vitest/metadata.js +45 -37
  38. package/dist/context.d.ts +1 -1
  39. package/dist/core/events.d.ts +1 -1
  40. package/dist/core/payload.d.ts +1 -1
  41. package/dist/core/payload.js +1 -1
  42. package/dist/core/provider.d.ts +12 -2
  43. package/dist/core/run.js +1 -1
  44. package/dist/live-app.d.ts +9 -0
  45. package/dist/live-app.js +21 -0
  46. package/dist/resource-commands.d.ts +13 -0
  47. package/dist/resource-commands.js +22 -0
  48. package/dist/resources/github/provider.d.ts +1 -1
  49. package/dist/resources/testserver/command-tree.d.ts +4 -0
  50. package/dist/resources/testserver/command-tree.js +12 -0
  51. package/dist/resources/testserver/commands/create/command.js +373 -194
  52. package/dist/resources/testserver/commands/create/metadata.js +52 -48
  53. package/dist/resources/testserver/commands/list/command.js +195 -50
  54. package/dist/resources/testserver/commands/list/metadata.js +12 -8
  55. package/dist/resources/testserver/provider.d.ts +1 -1
  56. package/dist/resources/testserver/resource-provider.js +2 -8
  57. package/dist/resources.d.ts +0 -3
  58. package/dist/resources.js +5 -10
  59. package/dist/runner/recipe.js +1 -1
  60. package/dist/runner/remote-command.js +1 -1
  61. package/dist/sdk/host.d.ts +2 -0
  62. package/dist/sdk/host.js +7 -0
  63. package/dist/version.d.ts +2 -2
  64. package/dist/version.js +10 -11
  65. package/dist/vitest/config.d.ts +4 -8
  66. package/dist/vitest/config.js +5 -9
  67. package/dist/vitest/container-scope.d.ts +12 -5
  68. package/dist/vitest/container-scope.js +27 -4
  69. package/dist/vitest/diagnostics.d.ts +8 -2
  70. package/dist/vitest/diagnostics.js +7 -4
  71. package/dist/vitest/fixtures.d.ts +4 -1
  72. package/dist/vitest/fixtures.js +17 -6
  73. package/dist/vitest/plan.d.ts +1 -1
  74. package/dist/vitest/plan.js +2 -2
  75. package/dist/vitest/sandbox.d.ts +6 -0
  76. package/dist/vitest/sandbox.js +6 -0
  77. package/package.json +4 -3
  78. package/bin/node-version.js +0 -24
  79. package/dist/closed-terminal.d.ts +0 -7
  80. package/dist/closed-terminal.js +0 -18
@@ -0,0 +1,1512 @@
1
+ import {
2
+ versionText
3
+ } from "./chunk-I5GZLOLQ.js";
4
+ import {
5
+ criticalPathStep,
6
+ laneLabel,
7
+ testsChart,
8
+ testsSummaryLines,
9
+ waterfallLines
10
+ } from "./chunk-WV6WQFC6.js";
11
+ import {
12
+ mintFailedErrors,
13
+ outcomes,
14
+ runErrors,
15
+ runRecordText,
16
+ testTotals
17
+ } from "./chunk-5U5Q6VZR.js";
18
+ import {
19
+ RESOURCES,
20
+ RESOURCE_COMMANDS,
21
+ RESOURCE_CONFIGS,
22
+ RESOURCE_PRESENTATIONS,
23
+ RESOURCE_REPORTS,
24
+ RUN_CLEANUP,
25
+ applyStormRunEvent,
26
+ isoSecondsText,
27
+ keepTimeText,
28
+ keptText,
29
+ notDeletedText,
30
+ notKeptText,
31
+ notStoppedText,
32
+ paint,
33
+ seconds,
34
+ short,
35
+ shortFile,
36
+ spread,
37
+ stormTimeline,
38
+ truncate,
39
+ visibleLength
40
+ } from "./chunk-NX55IJ5S.js";
41
+ import {
42
+ fileOptions,
43
+ fileSettings,
44
+ givenOptionsOf,
45
+ invalidConfig,
46
+ loadSettingsFile,
47
+ optionKeyPath,
48
+ parseSetFlags,
49
+ settleResourceOptions
50
+ } from "./chunk-OCZJE5XV.js";
51
+ import {
52
+ EMPTY_RUN_STATE,
53
+ RUNNER_SECRET_MIN_LENGTH,
54
+ RUN_DIRECTORIES_KEPT,
55
+ cleanupProblems,
56
+ commandExitStatus,
57
+ describeMintFailure,
58
+ executeRun,
59
+ megabytesText,
60
+ mintTargetText,
61
+ observeAll,
62
+ parseKeepTime,
63
+ parseTestEvent,
64
+ prepareRunner,
65
+ readRunnerSecrets,
66
+ redactSecrets,
67
+ requireTarget,
68
+ runDirectoryObserver,
69
+ secondsOf,
70
+ secondsText,
71
+ settleCredential,
72
+ stepLog,
73
+ testEventLine,
74
+ testEventsPath,
75
+ timedProgress
76
+ } from "./chunk-5CQCRX2L.js";
77
+
78
+ // src/commands/exec/testserver-flags.ts
79
+ var TESTSERVER_FLAGS = {
80
+ sandboxes: { field: "testserverSandboxes", flag: "--testserver-sandboxes" },
81
+ build: { field: "testserverBuild", flag: "--testserver-build" },
82
+ minTimeLeft: { field: "testserverMinTimeLeft", flag: "--testserver-min-time-left" },
83
+ ttl: { field: "testserverTtl", flag: "--testserver-ttl" },
84
+ noCreate: { field: "testserverNoCreate", flag: "--testserver-no-create" }
85
+ };
86
+ function isTestserverPoolConfig(config) {
87
+ return config.name === "testserverPool";
88
+ }
89
+ function testserverPoolConfig() {
90
+ const config = RESOURCE_CONFIGS.find(isTestserverPoolConfig);
91
+ if (config === void 0) throw new Error("The registry has no testserverPool resource config");
92
+ return config;
93
+ }
94
+ var CONFIG = testserverPoolConfig();
95
+ var RULES = CONFIG.options;
96
+ var TESTSERVER_OWN_FLAGS = Object.fromEntries(
97
+ Object.entries(TESTSERVER_FLAGS).map(([option, { flag }]) => [optionKeyPath(CONFIG.name, option), flag])
98
+ );
99
+ function readTestserverFlags(request) {
100
+ const values = {};
101
+ const problems = [];
102
+ for (const [option, { field, flag }] of Object.entries(TESTSERVER_FLAGS)) {
103
+ const value = request[field];
104
+ if (value === void 0) continue;
105
+ const rule = RULES[option];
106
+ if (rule === void 0) throw new Error(`testserverPool has no option ${option}`);
107
+ const checked = rule.check(value);
108
+ if (checked.ok) values[option] = checked.value;
109
+ else problems.push(...checked.problems.map(({ problem }) => ({ field, message: `${flag} ${problem}.` })));
110
+ }
111
+ if (problems.length > 0) return { ok: false, problems };
112
+ return { ok: true, values: Object.keys(values).length === 0 ? void 0 : givenOptionsOf(CONFIG, values) };
113
+ }
114
+ function testserverFlagProblems(request) {
115
+ const read = readTestserverFlags(request);
116
+ return read.ok ? [] : read.problems;
117
+ }
118
+ function withTestserverFlags(sets, request) {
119
+ const read = readTestserverFlags(request);
120
+ if (!read.ok) throw new Error(`The flags should have been refused: ${read.problems.map((p) => p.message).join(" ")}`);
121
+ return read.values === void 0 ? sets : { ...sets, testserverPool: read.values };
122
+ }
123
+ function testserverSandboxesSource(request, file) {
124
+ if (request[TESTSERVER_FLAGS.sandboxes.field] !== void 0) return "flag";
125
+ return fileOptions(file, CONFIG)?.sandboxes === void 0 ? "default" : "file";
126
+ }
127
+
128
+ // src/commands/exec/run-command.ts
129
+ import {
130
+ refused
131
+ } from "@vercel/clinkr";
132
+ import { NodeSignalCancellation } from "@vercel/clinkr/node";
133
+ import { z } from "zod";
134
+
135
+ // src/commands/exec/job-summary.ts
136
+ function jobSummaryMarkdown(timeline, extras) {
137
+ const lines = [`### storm ${extras.command}`, ""];
138
+ if (timeline.rows.length > 0) {
139
+ lines.push("| Lane | Start | Duration | Idle | Steps |", "| --- | ---: | ---: | ---: | --- |");
140
+ for (const row of timeline.rows) lines.push(tableRow(row));
141
+ lines.push("");
142
+ }
143
+ if (timeline.criticalPath.length > 0) {
144
+ const path = timeline.criticalPath.map((name) => criticalPathStep(name, timeline));
145
+ lines.push(`Critical path: ${path.join(" \u2192 ")}`, "");
146
+ }
147
+ for (const detail of extras.details ?? []) lines.push(`${detail.trim()} `);
148
+ if ((extras.details ?? []).length > 0) lines.push("");
149
+ if (extras.logs !== void 0) lines.push(`Run directory: \`${extras.logs}\``, "");
150
+ return lines.join("\n");
151
+ }
152
+ function tableRow(row) {
153
+ const outcome = row.outcome === "done" ? "" : ` (${row.outcome})`;
154
+ const steps = row.steps.map((step) => `${step.name} ${seconds(step.endMs - step.startMs)}`).join(" \xB7 ");
155
+ const idle = row.idleMs > 0 ? seconds(row.idleMs) : "";
156
+ return `| ${laneLabel(row.name)}${outcome} | +${seconds(row.startMs)} | ${seconds(row.endMs - row.startMs)} | ${idle} | ${steps} |`;
157
+ }
158
+
159
+ // src/commands/exec/progress.ts
160
+ function lineProgress(write, options = { github: false }) {
161
+ let failed = false;
162
+ const render = plainRenderer(options);
163
+ return {
164
+ observe: async (timed) => {
165
+ for (const line of render(timed)) {
166
+ if (failed) return;
167
+ try {
168
+ await write(line);
169
+ } catch {
170
+ failed = true;
171
+ }
172
+ }
173
+ }
174
+ };
175
+ }
176
+ function plainRenderer(options) {
177
+ const state = {
178
+ origin: void 0,
179
+ resourceLanes: RESOURCE_PRESENTATIONS.lanes.map(({ lane }) => lane),
180
+ heldResources: [],
181
+ mintStartedAt: void 0,
182
+ lanesStartedAt: void 0,
183
+ readyAt: {},
184
+ cleanupStartedAt: void 0,
185
+ folded: false
186
+ };
187
+ const resources = RESOURCE_PRESENTATIONS.plain({ verbose: options.verbose === true });
188
+ return ({ event, at }) => {
189
+ const now = at.getTime();
190
+ state.origin ??= now;
191
+ const origin = state.origin;
192
+ const line = (lane, text) => progressLine(now - origin, lane, text);
193
+ if (event.kind === "resource") return resources(event, now).map(({ lane, text }) => line(lane, text));
194
+ return eventLines(event, now, state, line, options);
195
+ };
196
+ }
197
+ function progressLine(elapsedMs, lane, text) {
198
+ return `[+${secondsText(secondsOf(elapsedMs))}] ${lane.padEnd(LANE_WIDTH)} ${text}`;
199
+ }
200
+ var LANE_WIDTH = Math.max(
201
+ ...["run", "mint", "runner", "command", "cleanup", ...RESOURCE_PRESENTATIONS.lanes.map(({ lane }) => lane)].map(
202
+ (lane) => lane.length
203
+ )
204
+ );
205
+ function eventLines(event, now, state, line, options) {
206
+ const since = (start) => seconds(now - (start ?? now));
207
+ switch (event.kind) {
208
+ case "started":
209
+ state.resourceLanes = event.lanes;
210
+ state.heldResources = event.resources;
211
+ return [
212
+ line("run", `storm ${versionText(event.version, event.commit)}`),
213
+ ...event.configFile === null ? [] : [line("run", `config ${event.configFile}`)]
214
+ ];
215
+ case "minting":
216
+ state.mintStartedAt = now;
217
+ return [line("mint", `credential for ${mintTargetText(event.target)}\u2026`)];
218
+ case "minted":
219
+ return [
220
+ line(
221
+ "mint",
222
+ `${event.ok ? "credential" : "no credential"} for ${mintTargetText(event.target)} (${since(state.mintStartedAt)})`
223
+ )
224
+ ];
225
+ case "requesting-token":
226
+ return [line("mint", "requesting a GitHub Actions OIDC token\u2026")];
227
+ case "lanes-started":
228
+ state.lanesStartedAt = now;
229
+ return state.resourceLanes.length === 0 ? [] : [line("run", `${[...state.resourceLanes, "runner"].join(" \u2016 ")} start together`)];
230
+ case "lane-ended": {
231
+ const ran = since(state.lanesStartedAt ?? state.origin);
232
+ if (event.outcome !== "ready") return [line(event.lane, `${event.outcome} (${ran})`)];
233
+ if (state.lanesStartedAt === void 0) return [];
234
+ state.readyAt[event.lane] = now;
235
+ const ready = `ready (${ran})`;
236
+ if (state.resourceLanes.length === 0) return [line(event.lane, ready)];
237
+ const others = event.lane === "runner" ? state.resourceLanes : ["runner"];
238
+ const waiting = others.filter((other) => state.readyAt[other] === void 0);
239
+ if (waiting.length > 0) return [line(event.lane, `${ready}; waiting for ${waiting.join(", ")}`)];
240
+ const waited = others.map((other) => `${other} waited ${seconds(now - (state.readyAt[other] ?? now))}`);
241
+ return [line(event.lane, `${ready}; ${waited.join(", ")}`)];
242
+ }
243
+ // A resource lane's start shows in its first line of its own.
244
+ case "lane-started":
245
+ return [];
246
+ case "command-started":
247
+ return [line("command", `running ${event.argv.join(" ")}`)];
248
+ case "command-ended":
249
+ return [line("command", `${event.command} ${commandEnd(event.outcome)} after ${seconds(event.ms)}`)];
250
+ case "cleanup-started":
251
+ state.cleanupStartedAt = now;
252
+ return [
253
+ line("cleanup", cleanupText(event.runnerSandbox, RESOURCE_PRESENTATIONS.releaseTexts(event.holdings, "doing")))
254
+ ];
255
+ case "cleanup-finished": {
256
+ const problems = [
257
+ ...event.notStopped === 0 ? [] : [`${event.notStopped} not stopped`],
258
+ ...event.notDeleted === 0 ? [] : [`${event.notDeleted} not deleted`],
259
+ ...RESOURCE_REPORTS.failuresTexts(event.resourceFailures)
260
+ ];
261
+ return [
262
+ line(
263
+ "cleanup",
264
+ `${problems.length === 0 ? "done" : `done: ${problems.join(", ")}`} (${since(state.cleanupStartedAt)})`
265
+ )
266
+ ];
267
+ }
268
+ case "runner-prepared":
269
+ return [
270
+ line("runner", `base ${short(event.base)}, HEAD's merge-base with ${event.baseRef}`),
271
+ ...preparedNoteTexts(event).map((text) => line("runner", text))
272
+ ];
273
+ // The command's own output carries its tests' results; the summary counts them.
274
+ // The summary says when the test results may be incomplete.
275
+ case "test":
276
+ case "test-event-unreadable":
277
+ case "test-events-incomplete":
278
+ return [];
279
+ case "runner":
280
+ return runnerLines(event.event, state, line, options);
281
+ }
282
+ }
283
+ function runnerLines(event, state, line, options) {
284
+ switch (event.kind) {
285
+ case "snapshot-reused":
286
+ return [line("runner", snapshotReusedText(event))];
287
+ case "snapshot-build-started":
288
+ return [
289
+ line(
290
+ "runner",
291
+ `building a runner snapshot of base ${short(event.base)} (${event.reason === "rebuild" ? "--rebuild-snapshot" : "no cached runner snapshot fits"}); this takes a few minutes: ${event.summary}`
292
+ )
293
+ ];
294
+ case "runner-sandbox-starting":
295
+ return [];
296
+ case "sandbox-started":
297
+ return [
298
+ line(
299
+ "runner",
300
+ `started the ${event.role === "runner" ? "runner" : "build"} sandbox ${event.name} in ${event.region}, ${event.vcpus} vCPUs (${seconds(event.ms)})`
301
+ )
302
+ ];
303
+ case "output-started":
304
+ return [];
305
+ case "output-ended":
306
+ return event.outcome === "finished" ? [] : [...closeFold(state), line("runner", `${event.section} ${event.outcome}`)];
307
+ case "step-started": {
308
+ const text = `${event.phase}: ${event.label}`;
309
+ if (!options.github) return [line("runner", text)];
310
+ state.folded = true;
311
+ return [`::group::${line("runner", text)}`];
312
+ }
313
+ case "step-output":
314
+ return [event.line];
315
+ case "step-finished":
316
+ return [...closeFold(state), line("runner", `${event.phase}: ${event.label}, done in ${seconds(event.ms)}`)];
317
+ case "snapshot-saving":
318
+ return [line("runner", "saving the build sandbox as a runner snapshot\u2026")];
319
+ case "snapshot-built":
320
+ return [
321
+ line(
322
+ "runner",
323
+ `built runner snapshot ${event.snapshotId} of base ${short(event.base)} in ${seconds(event.ms)} (${megabytesText(event.sizeBytes)})`
324
+ )
325
+ ];
326
+ case "snapshot-entry-not-written":
327
+ return [line("runner", cacheWriteFailureText(event.failure))];
328
+ case "uploading":
329
+ return [];
330
+ case "uploaded":
331
+ return [line("runner", `uploaded your changes, ${megabytesText(event.bytes)} (${seconds(event.ms)})`)];
332
+ case "command-output-started":
333
+ return [line("command", `in the runner sandbox ${event.sandbox} (${event.region})`)];
334
+ case "command-stopped":
335
+ return [line("command", `${event.command} stopped`)];
336
+ case "stopping":
337
+ return [
338
+ line(
339
+ "cleanup",
340
+ `stopping: ${event.commandRunning ? "killing the command, then " : ""}${event.keepMs > 0 ? `keeping the runner sandbox running ${keepTimeText(event.keepMs)}` : "stopping and deleting the runner's sandboxes"}${releasingText(state.heldResources)}\u2026`
341
+ )
342
+ ];
343
+ case "waiting-for-snapshot":
344
+ return [
345
+ line(
346
+ "cleanup",
347
+ `waiting up to ${Math.round(event.settleMs / 6e4)} minutes for the runner snapshot still saving\u2026`
348
+ )
349
+ ];
350
+ case "sandbox-kept":
351
+ return [line("cleanup", `kept the runner sandbox ${event.name} running until ${isoSecondsText(event.stopsAt)}`)];
352
+ // The cleanup line says the run saves a branch snapshot.
353
+ case "branch-snapshot-saving":
354
+ return [];
355
+ case "branch-snapshot-saved":
356
+ case "branch-snapshot-not-saved":
357
+ return [line("cleanup", branchSnapshotSaveText(event))];
358
+ case "branch-snapshots-dropped":
359
+ case "branch-snapshots-not-dropped":
360
+ return [line("runner", branchSnapshotsDropText(event))];
361
+ }
362
+ }
363
+ function snapshotReusedText(event) {
364
+ const reused = `reusing runner snapshot ${event.snapshotId} of base ${short(event.base)}`;
365
+ return event.branch === null || event.head === null ? reused : `${reused} (branch ${event.branch} at ${short(event.head)})`;
366
+ }
367
+ function branchSnapshotSaveText(event) {
368
+ if (event.kind === "branch-snapshot-saved") {
369
+ return `saved branch snapshot ${event.snapshotId} for ${event.branch} at ${short(event.head)} in ${seconds(event.ms)} (${megabytesText(event.sizeBytes)})`;
370
+ }
371
+ return `not saving a branch snapshot: ${notSavedReason(event.save)}`;
372
+ }
373
+ function notSavedReason(save) {
374
+ switch (save.kind) {
375
+ case "failed":
376
+ return `the ${save.step === "scrub" ? "scrub" : "save"} failed: ${save.message}`;
377
+ case "stopped":
378
+ return "the run is stopping";
379
+ }
380
+ }
381
+ function branchSnapshotsDropText(event) {
382
+ if (event.kind === "branch-snapshots-not-dropped")
383
+ return `couldn't drop a branch snapshot of ${event.branch} from the cache at ${event.failure.path}: ${event.failure.message}; a later run on the branch may start from it`;
384
+ const count = event.snapshotIds.length;
385
+ return `dropped ${count} branch ${count === 1 ? "snapshot" : "snapshots"} of ${event.branch} from the cache: ${event.snapshotIds.join(", ")}`;
386
+ }
387
+ function releasingText(held) {
388
+ return RESOURCE_PRESENTATIONS.stoppingTexts(held).map((text) => ` and ${text}`).join("");
389
+ }
390
+ function closeFold(state) {
391
+ if (!state.folded) return [];
392
+ state.folded = false;
393
+ return ["::endgroup::"];
394
+ }
395
+ function cleanupText(sandbox, releases) {
396
+ const release = releases.length === 0 ? void 0 : releases.join(", ");
397
+ if (sandbox === null) return release === void 0 ? "nothing to release" : `${release}\u2026`;
398
+ if (sandbox.kind === "save")
399
+ return `saving a branch snapshot of ${sandbox.branch}${release === void 0 ? "" : ` while ${release}`}\u2026`;
400
+ const sandboxes = sandbox.ms > 0 ? `keeping the runner sandbox running ${keepTimeText(sandbox.ms)}` : "stopping and deleting the runner's sandboxes";
401
+ return `${sandboxes}${release === void 0 ? "" : `, then ${release}`}\u2026`;
402
+ }
403
+ function commandEnd(outcome) {
404
+ switch (outcome.kind) {
405
+ case "exited":
406
+ return `exited ${outcome.code}`;
407
+ case "signaled":
408
+ return `ended on ${outcome.signal}`;
409
+ case "no-exit-code":
410
+ return "ended without an exit code";
411
+ }
412
+ }
413
+ function noteText(note) {
414
+ switch (note.kind) {
415
+ case "cache-unreadable":
416
+ return `couldn't read the runner snapshot cache at ${note.failure.path}: ${note.failure.message}; treating it as empty`;
417
+ case "expired-entry-not-removed":
418
+ return `couldn't remove the expired cache entry for runner snapshot ${note.entry.snapshotId} at ${note.failure.path}: ${note.failure.message}`;
419
+ case "candidate-steps-failed":
420
+ return `not reusing cached runner snapshots of base ${short(note.base)}: runner.${note.path.join(".")} ${note.problem.replace(/\.$/, "")}`;
421
+ case "candidate-check-failed":
422
+ return `not reusing cached runner snapshots of base ${short(note.base)}: ${note.failure.message.replace(/\.$/, "")}`;
423
+ }
424
+ }
425
+ function preparedNoteTexts(prepared) {
426
+ return [
427
+ ...prepared.nestedRepositories.length === 0 ? [] : [`leaving out untracked nested Git repositories: ${prepared.nestedRepositories.join(", ")}`],
428
+ ...prepared.notes.map(noteText),
429
+ ...prepared.saveSkipped ? ["not saving a branch snapshot: HEAD is detached"] : []
430
+ ];
431
+ }
432
+ function cacheWriteFailureText(failure) {
433
+ return `couldn't record the runner snapshot in the cache at ${failure.path}: ${failure.message}; later runs won't reuse it`;
434
+ }
435
+
436
+ // src/commands/exec/live-view.ts
437
+ var SPINNER = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
438
+ var INDENT = " ".repeat(LANE_WIDTH + 5);
439
+ function laneHead(glyph, lane) {
440
+ return ` ${glyph} ${lane.padEnd(LANE_WIDTH)} `;
441
+ }
442
+ function activePhase(state) {
443
+ if (state.cleanup !== void 0) return "cleanup";
444
+ if (state.command !== void 0) return "tests";
445
+ if (state.lanesStartedAt !== void 0 && state.runner !== void 0) return "lanes";
446
+ if (Object.keys(state.resources).length > 0 && state.runner === void 0) return "resources";
447
+ if (state.mint !== void 0) return "credential";
448
+ return void 0;
449
+ }
450
+ function heldLanes(state) {
451
+ const held = state.lanes;
452
+ return RESOURCE_PRESENTATIONS.lanes.filter(({ lane }) => held?.includes(lane) ?? true);
453
+ }
454
+ function headerLine(state, paint2) {
455
+ const version = state.version === void 0 ? "" : versionText(state.version.version, state.version.commit);
456
+ const header = [
457
+ `storm ${version}`.trimEnd(),
458
+ ...state.base === void 0 ? [] : [`base ${short(state.base.sha)} (merge-base ${state.base.ref})`]
459
+ ].join(" \xB7 ");
460
+ return paint2.strong(header);
461
+ }
462
+ function phaseFrame(state, phase, now, width, paint2) {
463
+ const view = {
464
+ now,
465
+ width,
466
+ paint: paint2,
467
+ glyph: (status) => statusGlyph(status, now, paint2),
468
+ // A live row is cut to the width: one that wrapped would take a row the next redraw doesn't erase.
469
+ row: (left, right) => spread(left, right, width),
470
+ line: (text) => truncate(text, width)
471
+ };
472
+ switch (phase) {
473
+ case "credential":
474
+ return state.mint === void 0 ? [] : [credentialLine(state.mint, view)];
475
+ case "lanes":
476
+ return lanesFrame(state, view);
477
+ case "resources":
478
+ return localResourcesFrame(state, view);
479
+ case "tests":
480
+ return testsFrame(state, view);
481
+ case "cleanup":
482
+ return state.cleanup === void 0 ? [] : [cleanupLine(state.cleanup, state.runner, view, false)];
483
+ }
484
+ }
485
+ function phaseRecord(state, phase, width, paint2) {
486
+ const view = {
487
+ now: void 0,
488
+ width,
489
+ paint: paint2,
490
+ glyph: (status) => statusGlyph(status === "running" ? "stopped" : status, 0, paint2),
491
+ row: (left, right) => visibleLength(left) + visibleLength(right) + 1 <= width ? spread(left, right, width) : `${left}${right === "" ? "" : ` ${right}`}`,
492
+ line: (text) => text
493
+ };
494
+ switch (phase) {
495
+ case "credential":
496
+ return state.mint === void 0 ? [] : [credentialLine(state.mint, view)];
497
+ case "lanes":
498
+ return lanesRecord(state, view);
499
+ case "resources":
500
+ return localResourcesRecord(state, view);
501
+ case "tests":
502
+ return state.command === void 0 ? [] : [testsLine(state, state.command, view, false)];
503
+ case "cleanup":
504
+ return state.cleanup === void 0 ? [] : [cleanupLine(state.cleanup, state.runner, view, true)];
505
+ }
506
+ }
507
+ function laneDraw(view) {
508
+ return {
509
+ now: view.now,
510
+ paint: view.paint,
511
+ glyph: view.glyph,
512
+ line: view.line,
513
+ elapsed: (from, to) => elapsed(view, from, to),
514
+ seconds
515
+ };
516
+ }
517
+ function elapsed(view, from, to) {
518
+ const end = to ?? view.now;
519
+ return from === void 0 || end === void 0 ? "" : seconds(end - from);
520
+ }
521
+ function credentialLine(mint, view) {
522
+ return view.row(
523
+ ` ${view.glyph(mint.status)} credential ${mintTargetText(mint.target)}`,
524
+ elapsed(view, mint.startedAt, mint.endedAt)
525
+ );
526
+ }
527
+ function lanesFrame(state, view) {
528
+ const { runner } = state;
529
+ if (runner === void 0) return [];
530
+ const { paint: paint2 } = view;
531
+ const stopping = (status) => state.stopping && status === "running";
532
+ const draw = laneDraw(view);
533
+ const resourceRows = heldLanes(state).map((lane) => {
534
+ const { status, text, right } = lane.lanesRow(state.resources, draw, {
535
+ stopping: state.stopping,
536
+ runnerRunning: runner.status === "running"
537
+ });
538
+ return view.row(`${laneHead(view.glyph(status ?? "running"), lane.lane)}${text}`, right);
539
+ });
540
+ const current = runner.steps.find(({ status }) => status === "running") ?? [...runner.steps].filter((step) => step.status !== "pending" && step.endedAt !== void 0).toSorted((a, b) => (a.endedAt ?? 0) - (b.endedAt ?? 0)).at(-1);
541
+ const currentText = current === void 0 ? "" : [
542
+ `${current.name}${stepLabel(current, runner) === "" ? "" : ` \xB7 ${stepLabel(current, runner)}`}`,
543
+ current.startedAt === current.endedAt ? "" : elapsed(view, current.startedAt, current.endedAt),
544
+ current.status === "failed" || current.status === "stopped" ? view.glyph(current.status) : ""
545
+ ].filter((part) => part !== "").join(" ");
546
+ const crumbs = stepsText(
547
+ runner.steps.filter((step) => step !== current),
548
+ view
549
+ );
550
+ const runnerText = stopping(runner.status) ? `stopping \xB7 ${currentText}` : currentText;
551
+ const runnerRow = view.row(
552
+ `${laneHead(runnerGlyph(runner, view), "runner")}${runnerText}${crumbs === "" ? "" : ` ${paint2.faint(crumbs)}`}`,
553
+ elapsed(view, runner.startedAt, runner.endedAt)
554
+ );
555
+ const running = runner.steps.find(({ status }) => status === "running");
556
+ const latest = running === void 0 ? void 0 : latestLine(running, runner);
557
+ const output = activityText(runner) ?? (latest === "" ? void 0 : latest);
558
+ return [...resourceRows, runnerRow, output === void 0 ? "" : view.line(`${INDENT}${paint2.faint(output)}`)];
559
+ }
560
+ function lanesRecord(state, view) {
561
+ const { runner } = state;
562
+ const lines = [];
563
+ const draw = laneDraw(view);
564
+ for (const lane of RESOURCE_PRESENTATIONS.lanes) {
565
+ const record = lane.record(state.resources, draw);
566
+ if (record === void 0) continue;
567
+ const { span } = record;
568
+ const waited = span.status === "done" && span.endedAt !== void 0 && runner?.endedAt !== void 0 && runner.endedAt > span.endedAt ? ` \xB7 waited ${seconds(runner.endedAt - span.endedAt)}` : "";
569
+ lines.push(
570
+ view.row(
571
+ `${laneHead(view.glyph(span.status), lane.lane)}${record.text}`,
572
+ `${elapsed(view, span.startedAt, span.endedAt)}${waited}`
573
+ ),
574
+ ...record.lines
575
+ );
576
+ }
577
+ if (runner !== void 0) {
578
+ const snapshot = runner.steps.find(({ name }) => name === "snapshot");
579
+ const parts = [
580
+ ...runner.sandbox === void 0 ? [] : [`${runner.sandbox.name} \xB7 ${runner.sandbox.region} \xB7 ${runner.sandbox.vcpus} vCPU`],
581
+ ...snapshot === void 0 || snapshot.status === "pending" ? [] : [snapshotText(snapshot, runner)],
582
+ ...runner.status === "failed" || runner.status === "stopped" ? [runner.status] : []
583
+ ];
584
+ lines.push(
585
+ view.row(
586
+ `${laneHead(runnerGlyph(runner, view), "runner")}${parts.join(" \xB7 ")}`,
587
+ elapsed(view, runner.startedAt, runner.endedAt)
588
+ )
589
+ );
590
+ const steps = stepsText(runner.steps, view);
591
+ if (steps !== "") lines.push(view.line(`${INDENT}${steps}`));
592
+ }
593
+ return lines;
594
+ }
595
+ function runnerGlyph(runner, view) {
596
+ return view.glyph(runner.steps.some(({ status }) => status === "failed") ? "failed" : runner.status);
597
+ }
598
+ function snapshotText(step, runner) {
599
+ if (runner.snapshot?.kind === "reused" || runner.snapshot?.kind === "built")
600
+ return `snapshot ${runner.snapshot.kind}`;
601
+ return `snapshot build ${step.status === "running" ? "stopped" : step.status}`;
602
+ }
603
+ function stepLabel(step, runner) {
604
+ if (step.name === "snapshot") {
605
+ const { snapshot } = runner;
606
+ if (snapshot === void 0) return step.label;
607
+ if (snapshot.kind !== "building") return `${snapshot.id} ${snapshot.kind}`;
608
+ return step.label === "" ? `building: ${snapshot.summary}` : step.label;
609
+ }
610
+ if (step.name === "upload" && runner.uploadBytes !== void 0) return megabytesText(runner.uploadBytes);
611
+ return step.label;
612
+ }
613
+ function latestLine(step, runner) {
614
+ if (step.latest !== void 0) return step.latest.trim();
615
+ if (step.name === "snapshot" && step.label === "" && runner.buildSandbox !== void 0)
616
+ return `build sandbox ${runner.buildSandbox} started`;
617
+ return void 0;
618
+ }
619
+ function activityText(runner) {
620
+ switch (runner.activity) {
621
+ case "saving-snapshot":
622
+ return "saving the build sandbox as a runner snapshot";
623
+ case "waiting-for-snapshot":
624
+ return WAITING_FOR_SNAPSHOT;
625
+ case void 0:
626
+ return void 0;
627
+ }
628
+ }
629
+ var WAITING_FOR_SNAPSHOT = "waiting for the runner snapshot still saving";
630
+ function stepsText(steps, view) {
631
+ return steps.filter(
632
+ (step) => step.status !== "pending" && step.status !== "running" && step.startedAt !== void 0 && step.endedAt !== void 0 && (step.endedAt > step.startedAt || step.status !== "done")
633
+ ).map((step) => {
634
+ const mark = step.status === "done" ? "" : ` ${view.glyph(step.status)}`;
635
+ return `${step.name} ${seconds((step.endedAt ?? 0) - (step.startedAt ?? 0))}${mark}`;
636
+ }).join(" \xB7 ");
637
+ }
638
+ function localResourcesFrame(state, view) {
639
+ const { mint } = state;
640
+ const draw = laneDraw(view);
641
+ const mintRow = mint !== void 0 && mint.status === "running" ? view.row(
642
+ ` ${view.glyph("running")} minting a credential for ${mintTargetText(mint.target)}`,
643
+ elapsed(view, mint.startedAt, mint.endedAt)
644
+ ) : void 0;
645
+ const rows = RESOURCE_PRESENTATIONS.lanes.flatMap((lane) => {
646
+ const row = lane.localRow(state.resources, draw);
647
+ return row === void 0 ? [] : [{ lane: lane.lane, ...row }];
648
+ });
649
+ return rows.flatMap(({ lane, span, text, below }, index) => [
650
+ view.row(`${laneHead(view.glyph(span.status), lane)}${text}`, elapsed(view, span.startedAt, span.endedAt)),
651
+ index === 0 && mintRow !== void 0 ? mintRow : below !== void 0 ? view.line(` ${view.glyph("running")} ${below}`) : ""
652
+ ]);
653
+ }
654
+ function localResourcesRecord(state, view) {
655
+ const { mint } = state;
656
+ const draw = laneDraw(view);
657
+ const lanes = RESOURCE_PRESENTATIONS.lanes.flatMap((lane) => {
658
+ const record = lane.record(state.resources, draw);
659
+ if (record === void 0) return [];
660
+ const { span } = record;
661
+ return [
662
+ view.row(
663
+ `${laneHead(view.glyph(span.status), lane.lane)}${record.text}`,
664
+ elapsed(view, span.startedAt, span.endedAt)
665
+ ),
666
+ ...record.lines
667
+ ];
668
+ });
669
+ if (lanes.length === 0) return [];
670
+ return [...mint === void 0 ? [] : [credentialLine(mint, view)], ...lanes];
671
+ }
672
+ function testsFrame(state, view) {
673
+ return state.command === void 0 ? [] : [testsLine(state, state.command, view, true)];
674
+ }
675
+ var LONG_FILE_MS = 1e4;
676
+ function testsLine(state, command, view, live) {
677
+ const { tests } = state;
678
+ const end = command.outcome === void 0 ? void 0 : endText(command.outcome);
679
+ const parts = [command.argv.join(" ")];
680
+ if (end !== void 0) parts.push(end);
681
+ else if (live && state.stopping) parts.push("stopping");
682
+ const head = ` ${view.glyph(command.status)} tests `;
683
+ const time = elapsed(view, command.startedAt, command.endedAt);
684
+ const text = live && end === void 0 && !state.stopping && tests !== void 0 ? testsProgress(tests, view, view.width - visibleLength(head) - visibleLength(time) - 1) : parts.join(" ");
685
+ return view.row(`${head}${text}`, time);
686
+ }
687
+ function testsProgress(tests, view, room) {
688
+ const { paint: paint2, now } = view;
689
+ const running = tests.workers.filter((worker) => worker.file !== void 0 || worker.containerSince !== void 0);
690
+ const waiting = tests.workers.filter((worker) => worker.containerSince !== void 0).length;
691
+ const longest = [...running].toSorted((a, b) => (a.fileStartedAt ?? 0) - (b.fileStartedAt ?? 0))[0];
692
+ const longestMs = longest?.fileStartedAt === void 0 || now === void 0 ? void 0 : now - longest.fileStartedAt;
693
+ const text = (showWaiting) => [
694
+ `${tests.passed} passed`,
695
+ ...tests.failed === 0 ? [] : [paint2.failed(`${tests.failed} failed`)],
696
+ `${tests.filesDone} ${tests.filesDone === 1 ? "file" : "files"} done`,
697
+ `${running.length} running${waiting === 0 || !showWaiting ? "" : ` (${waiting} waiting on a container)`}`,
698
+ ...longest?.file === void 0 || longestMs === void 0 || longestMs < LONG_FILE_MS ? [] : [`longest: ${shortFile(longest.file)} ${seconds(longestMs)}`]
699
+ ].join(" \xB7 ");
700
+ const full = text(true);
701
+ return visibleLength(full) <= room ? full : text(false);
702
+ }
703
+ function cleanupLine(cleanup, runner, view, record) {
704
+ const done = record || cleanup.status !== "running";
705
+ const releases = RESOURCE_PRESENTATIONS.releaseTexts(cleanup.holdings, done ? "done" : "doing");
706
+ const release = releases.length === 0 ? void 0 : releases.join(", ");
707
+ const { runnerSandbox } = cleanup;
708
+ const text = !done && cleanup.waiting ? `${WAITING_FOR_SNAPSHOT}\u2026` : runnerSandbox === null ? release ?? "nothing to release" : `${runnerSandboxText(runnerSandbox, runner, done)}${release === void 0 ? "" : `, ${release}`}`;
709
+ const leftBehind = cleanupProblems(cleanup);
710
+ const ending = done ? leftBehind === 0 ? "" : `: ${leftBehind} left behind` : "\u2026";
711
+ return view.row(
712
+ ` ${view.glyph(cleanup.status)} cleanup ${text}${!done && cleanup.waiting ? "" : ending}`,
713
+ elapsed(view, cleanup.startedAt, cleanup.endedAt)
714
+ );
715
+ }
716
+ function runnerSandboxText(sandbox, runner, done) {
717
+ const kept = runner?.kept;
718
+ if (kept !== void 0) return `kept the runner sandbox until ${isoSecondsText(kept.stopsAt)}`;
719
+ const removed = `${done ? "stopped and deleted" : "stopping and deleting"} the runner sandbox`;
720
+ switch (sandbox.kind) {
721
+ case "keep":
722
+ return !done && sandbox.ms > 0 ? `keeping the runner sandbox running ${keepTimeText(sandbox.ms)}` : removed;
723
+ case "save": {
724
+ const save = runner?.save;
725
+ if (save?.kind === "saved") return `saved branch snapshot ${save.id} of ${save.branch}`;
726
+ return !done && save?.kind !== "not-saved" ? `saving a branch snapshot of ${sandbox.branch}` : removed;
727
+ }
728
+ }
729
+ }
730
+ function statusGlyph(status, now, paint2) {
731
+ switch (status) {
732
+ case "pending":
733
+ return paint2.faint("\xB7");
734
+ case "running":
735
+ return paint2.active(SPINNER[Math.floor(now / 90) % SPINNER.length] ?? "\xB7");
736
+ case "done":
737
+ return paint2.done("\u2713");
738
+ case "failed":
739
+ return paint2.failed("\u2717");
740
+ case "stopped":
741
+ return paint2.stopped("\u25A0");
742
+ }
743
+ }
744
+ function endText(outcome) {
745
+ return outcome === "stopped" ? "stopped" : commandEnd(outcome);
746
+ }
747
+
748
+ // src/commands/exec/view.ts
749
+ var PLAIN_WIDTH = 80;
750
+ function runView(options) {
751
+ const { presentation, progress, context } = options;
752
+ if (progress === void 0)
753
+ return {
754
+ observer: { observe: async () => {
755
+ } },
756
+ runnerTerminal: context.runnerTerminal,
757
+ width: PLAIN_WIDTH,
758
+ paint: paint(false),
759
+ finish: async () => {
760
+ }
761
+ };
762
+ if (presentation.kind === "plain") {
763
+ const writer = droppingWriter(progress);
764
+ return {
765
+ observer: lineProgress(writer, { github: presentation.github, verbose: options.verbose }),
766
+ runnerTerminal: context.runnerTerminal,
767
+ width: Math.min(Math.max(presentation.columns ?? PLAIN_WIDTH, 60), 120),
768
+ paint: paint(presentation.color),
769
+ finish: async (summary) => {
770
+ for (const line of summary) await writer(line);
771
+ }
772
+ };
773
+ }
774
+ return liveView(context, paint(presentation.color), {
775
+ showOutput: options.showOutput || options.verbose,
776
+ verbose: options.verbose
777
+ });
778
+ }
779
+ function droppingWriter(write) {
780
+ let failed = false;
781
+ return async (line) => {
782
+ if (failed) return;
783
+ try {
784
+ await write(line);
785
+ } catch {
786
+ failed = true;
787
+ }
788
+ };
789
+ }
790
+ function liveView(context, colors, options) {
791
+ const { showOutput } = options;
792
+ const terminal = context.progressTerminal;
793
+ let state = EMPTY_RUN_STATE;
794
+ let phase;
795
+ let headerPrinted = false;
796
+ let live = false;
797
+ let finished = false;
798
+ const width = () => terminal.columns() - 1;
799
+ const frame = () => phase === void 0 || finished ? [] : phaseFrame(state, phase, context.clock.now().getTime(), width(), colors);
800
+ const print = (lines) => {
801
+ if (lines.length > 0) terminal.print("stderr", lines.map((line) => `${line}
802
+ `).join(""));
803
+ };
804
+ const header = () => {
805
+ if (headerPrinted) return [];
806
+ headerPrinted = true;
807
+ return [headerLine(state, colors)];
808
+ };
809
+ return {
810
+ observer: {
811
+ observe: async (timed) => {
812
+ if (finished) return;
813
+ state = applyStormRunEvent(state, timed);
814
+ const next = activePhase(state);
815
+ if (next !== phase) {
816
+ print([
817
+ ...next === void 0 ? [] : header(),
818
+ ...phase === void 0 ? [] : phaseRecord(state, phase, width(), colors)
819
+ ]);
820
+ phase = next;
821
+ }
822
+ print(noticeLines(timed, state.origin ?? timed.at.getTime(), options.verbose));
823
+ const { event } = timed;
824
+ if (showOutput && event.kind === "runner" && event.event.kind === "step-output") print([event.event.line]);
825
+ if (!live) {
826
+ terminal.show(frame);
827
+ live = true;
828
+ }
829
+ }
830
+ },
831
+ runnerTerminal: {
832
+ color: context.runnerTerminal.color,
833
+ writeStdout: (text) => terminal.print("stdout", text),
834
+ writeStderr: (text) => terminal.print("stderr", text)
835
+ },
836
+ // The terminal may have been resized by the time the summary prints.
837
+ get width() {
838
+ return terminal.columns();
839
+ },
840
+ paint: colors,
841
+ finish: async (summary) => {
842
+ if (finished) return;
843
+ finished = true;
844
+ print([...header(), ...phase === void 0 ? [] : phaseRecord(state, phase, width(), colors), ...summary]);
845
+ terminal.settle();
846
+ }
847
+ };
848
+ }
849
+ function noticeLines(timed, origin, verbose) {
850
+ const line = (lane, text) => progressLine(timed.at.getTime() - origin, lane, text);
851
+ const { event } = timed;
852
+ switch (event.kind) {
853
+ case "runner-prepared":
854
+ return preparedNoteTexts(event).map((text) => line("runner", text));
855
+ case "runner":
856
+ return runnerNoticeLines(event.event, line);
857
+ case "resource":
858
+ return RESOURCE_PRESENTATIONS.notices(event, { verbose }).map(({ lane, text }) => line(lane, text));
859
+ case "started":
860
+ case "requesting-token":
861
+ case "minting":
862
+ case "minted":
863
+ case "cleanup-started":
864
+ case "cleanup-finished":
865
+ case "command-started":
866
+ case "command-ended":
867
+ case "lanes-started":
868
+ case "lane-started":
869
+ case "lane-ended":
870
+ case "test":
871
+ case "test-event-unreadable":
872
+ case "test-events-incomplete":
873
+ return [];
874
+ }
875
+ }
876
+ function runnerNoticeLines(event, line) {
877
+ switch (event.kind) {
878
+ case "snapshot-entry-not-written":
879
+ return [line("runner", cacheWriteFailureText(event.failure))];
880
+ case "branch-snapshots-dropped":
881
+ case "branch-snapshots-not-dropped":
882
+ return [line("runner", branchSnapshotsDropText(event))];
883
+ case "branch-snapshot-saved":
884
+ case "branch-snapshot-not-saved":
885
+ return [line("cleanup", branchSnapshotSaveText(event))];
886
+ // The live view's phases show the rest.
887
+ case "snapshot-reused":
888
+ case "snapshot-build-started":
889
+ case "runner-sandbox-starting":
890
+ case "sandbox-started":
891
+ case "output-started":
892
+ case "output-ended":
893
+ case "step-started":
894
+ case "step-output":
895
+ case "step-finished":
896
+ case "snapshot-saving":
897
+ case "snapshot-built":
898
+ case "uploading":
899
+ case "uploaded":
900
+ case "command-output-started":
901
+ case "command-stopped":
902
+ case "stopping":
903
+ case "waiting-for-snapshot":
904
+ case "sandbox-kept":
905
+ case "branch-snapshot-saving":
906
+ return [];
907
+ }
908
+ }
909
+
910
+ // src/commands/exec/redaction.ts
911
+ function redactor(secrets) {
912
+ const kept = secrets.filter((secret) => secret !== "");
913
+ return kept.length === 0 ? (text) => text : (text) => redactSecrets(text, kept);
914
+ }
915
+ function redactStrings(value, redact) {
916
+ if (typeof value === "string") return redact(value);
917
+ if (Array.isArray(value)) return value.map((each) => redactStrings(each, redact));
918
+ if (typeof value === "object" && value !== null) {
919
+ const prototype = Object.getPrototypeOf(value);
920
+ if (prototype !== Object.prototype && prototype !== null) return value;
921
+ return Object.fromEntries(
922
+ Object.entries(value).map(([key, each]) => [key, redactStrings(each, redact)])
923
+ );
924
+ }
925
+ return value;
926
+ }
927
+ function redactingObserver(observer, redact) {
928
+ return {
929
+ observe: async (timed) => await observer.observe({ event: redactStrings(timed.event, redact), at: timed.at })
930
+ };
931
+ }
932
+ function redactingTerminal(terminal, redact) {
933
+ return {
934
+ color: terminal.color,
935
+ writeStdout: (text) => terminal.writeStdout(redact(text)),
936
+ writeStderr: (text) => terminal.writeStderr(redact(text))
937
+ };
938
+ }
939
+
940
+ // src/commands/exec/run-collector.ts
941
+ function runCollector(directory) {
942
+ let state = EMPTY_RUN_STATE;
943
+ const events = [];
944
+ let unreadable = 0;
945
+ let incomplete;
946
+ let workerOffsetMs = Infinity;
947
+ const collect = (event) => {
948
+ directory?.appendTestEvent(testEventLine(event));
949
+ events.push(summaryEvent(event));
950
+ };
951
+ return {
952
+ observer: {
953
+ observe: async (timed) => {
954
+ const { event } = timed;
955
+ if (event.kind === "runner" && event.event.kind === "step-output") return;
956
+ state = applyStormRunEvent(state, timed);
957
+ if (event.kind === "test") {
958
+ collect(event.event);
959
+ if (event.event.kind !== "test-result")
960
+ workerOffsetMs = Math.min(workerOffsetMs, timed.at.getTime() - event.event.at);
961
+ } else if (event.kind === "test-event-unreadable") unreadable += 1;
962
+ else if (event.kind === "test-events-incomplete") incomplete ??= event.message;
963
+ }
964
+ },
965
+ readLocal: async (localDirectory, redact) => {
966
+ const read = await localDirectory.readTestEvents((line) => {
967
+ const event = parseTestEvent(line);
968
+ if (event === void 0) unreadable += 1;
969
+ else collect(redactStrings(event, redact));
970
+ });
971
+ if (!read.ok) incomplete ??= read.failure.message;
972
+ },
973
+ finish: () => ({
974
+ state,
975
+ tests: { events, unreadable, incomplete },
976
+ workerOffsetMs: workerOffsetMs === Infinity ? 0 : workerOffsetMs
977
+ })
978
+ };
979
+ }
980
+ function summaryEvent(event) {
981
+ if (event.kind !== "test-result") return event;
982
+ return {
983
+ kind: event.kind,
984
+ id: event.id,
985
+ file: event.file,
986
+ test: event.test,
987
+ state: event.state,
988
+ retryCount: event.retryCount,
989
+ flaky: event.flaky,
990
+ at: event.at
991
+ };
992
+ }
993
+
994
+ // src/commands/exec/run-command.ts
995
+ var RUN_REQUEST_FIELDS = {
996
+ set: z.array(z.string()).default([]),
997
+ testserverSandboxes: z.number().optional(),
998
+ testserverBuild: z.string().optional(),
999
+ testserverMinTimeLeft: z.string().optional(),
1000
+ testserverTtl: z.string().optional(),
1001
+ testserverNoCreate: z.boolean().optional(),
1002
+ scope: z.string().min(1).optional(),
1003
+ project: z.string().min(1).optional(),
1004
+ credential: z.enum(["mint", "github-actions"]).optional(),
1005
+ local: z.boolean().default(false),
1006
+ rebuildSnapshot: z.boolean().default(false),
1007
+ saveSnapshot: z.boolean().default(false),
1008
+ showOutput: z.boolean().default(false),
1009
+ keepSandbox: z.string().optional(),
1010
+ verbose: z.boolean().default(false)
1011
+ };
1012
+ var RUN_CLI_OPTIONS = { project: { short: "p" } };
1013
+ var runRequestSchema = z.object(RUN_REQUEST_FIELDS);
1014
+ async function runCommand({ app, ui, signal }, request, spec) {
1015
+ const sets = parseSetFlags(request.set, RESOURCE_CONFIGS, TESTSERVER_OWN_FLAGS);
1016
+ if (!sets.ok) throw new Error(`--set should have been refused: ${sets.problems.join("; ")}`);
1017
+ const settled = await settleRun(app, { ...request, given: withTestserverFlags(sets.values, request) });
1018
+ if (!settled.ok) return settled.refusal;
1019
+ const secrets = [
1020
+ ...settled.settlement.secrets,
1021
+ ...settled.where.kind === "runner" ? Object.values(settled.where.secrets) : []
1022
+ ];
1023
+ const redact = redactor(secrets);
1024
+ const ready = await spec.prepare(settled, signal);
1025
+ if (signal.aborted) return canceledBeforeStart();
1026
+ if (!ready.ok) return secrets.length === 0 ? ready.refusal : redactStrings(ready.refusal, redact);
1027
+ const { argv, plan } = ready;
1028
+ const { configFile, options, where, settlement } = ready.settled;
1029
+ if (settlement.secrets !== settled.settlement.secrets || where !== settled.where)
1030
+ throw new Error("spec.prepare changed the run's secrets");
1031
+ const base = {
1032
+ argv,
1033
+ // A resource can name host variables that could point the command at something else than the run payload
1034
+ // names, so the command never sees one.
1035
+ env: Object.fromEntries(
1036
+ Object.entries(app.env).filter(([name]) => !RESOURCE_REPORTS.hostVariablesToDrop.includes(name))
1037
+ ),
1038
+ version: app.version,
1039
+ commit: app.commit,
1040
+ configFile,
1041
+ verbose: request.verbose
1042
+ };
1043
+ let run;
1044
+ if (where.kind === "local")
1045
+ run = {
1046
+ ...base,
1047
+ resources: settlement.requests,
1048
+ ...where.credential === void 0 ? {} : { credential: where.credential }
1049
+ };
1050
+ else {
1051
+ const prepared = await prepareRunner(app.context, {
1052
+ cwd: app.cwd,
1053
+ recipe: where.recipe,
1054
+ resources: RESOURCE_REPORTS.runnerResources(options),
1055
+ rebuild: request.rebuildSnapshot,
1056
+ saveSnapshot: request.saveSnapshot
1057
+ });
1058
+ if (prepared.kind !== "ok") {
1059
+ const refusal = prepareRefusal(prepared, configFile);
1060
+ return secrets.length === 0 ? refusal : redactStrings(refusal, redact);
1061
+ }
1062
+ const { save } = prepared.prepared;
1063
+ run = {
1064
+ ...base,
1065
+ resources: settlement.requests,
1066
+ runner: {
1067
+ prepared: prepared.prepared,
1068
+ target: where.target,
1069
+ user: app.user,
1070
+ secrets: where.secrets,
1071
+ sandbox: save?.kind === "branch" ? { kind: "save", branch: save.branch } : { kind: "keep", ms: keepSandboxMinutes(request.keepSandbox, where.recipe, app.env) * 6e4 }
1072
+ }
1073
+ };
1074
+ }
1075
+ const terminate = new AbortController();
1076
+ const forward = () => {
1077
+ const reason = signal.reason;
1078
+ if (reason instanceof NodeSignalCancellation && reason.signal === "SIGTERM") terminate.abort(reason);
1079
+ };
1080
+ if (run.runner === void 0) {
1081
+ if (signal.aborted) forward();
1082
+ else signal.addEventListener("abort", forward, { once: true });
1083
+ }
1084
+ const view = runView({
1085
+ presentation: app.presentation,
1086
+ progress: ui.progress,
1087
+ context: app.context,
1088
+ showOutput: request.showOutput,
1089
+ verbose: request.verbose
1090
+ });
1091
+ const git = await checkoutGit(app.context.checkout, app.cwd);
1092
+ const startedAt = app.context.clock.now();
1093
+ const record = redactStrings(
1094
+ {
1095
+ version: 1,
1096
+ startedAt: startedAt.toISOString(),
1097
+ cwd: app.cwd,
1098
+ configFile,
1099
+ argv,
1100
+ ...plan === void 0 ? {} : { plan },
1101
+ where: run.runner === void 0 ? { kind: "local" } : startedWhere(run.runner),
1102
+ git
1103
+ },
1104
+ redact
1105
+ );
1106
+ const opened = await app.context.runDirectories.open({
1107
+ startedAt,
1108
+ keep: RUN_DIRECTORIES_KEPT,
1109
+ run: runRecordText(record)
1110
+ });
1111
+ const directory = opened.ok ? opened.directory : void 0;
1112
+ const collector = runCollector(directory);
1113
+ const observers = [collector.observer, view.observer];
1114
+ if (directory !== void 0) observers.push(runDirectoryObserver(directory));
1115
+ const observer = observeAll(...observers);
1116
+ const terminal = teeTerminal(view.runnerTerminal, directory);
1117
+ let outcome;
1118
+ try {
1119
+ const ended = await executeRun(
1120
+ RESOURCES,
1121
+ { ...app.context, runnerTerminal: secrets.length === 0 ? terminal : redactingTerminal(terminal, redact) },
1122
+ run.runner === void 0 && directory !== void 0 ? { ...run, testEvents: testEventsPath(directory.path) } : run,
1123
+ { signal, terminate: terminate.signal },
1124
+ timedProgress(app.context.clock, secrets.length === 0 ? observer : redactingObserver(observer, redact))
1125
+ );
1126
+ outcome = secrets.length === 0 ? ended : redactStrings(ended, redact);
1127
+ } catch (error) {
1128
+ await view.finish([]);
1129
+ await directory?.close();
1130
+ throw error;
1131
+ }
1132
+ signal.removeEventListener("abort", forward);
1133
+ const ran = await summarize(app, {
1134
+ command: spec.name,
1135
+ view,
1136
+ collector,
1137
+ opened,
1138
+ local: run.runner === void 0,
1139
+ redact,
1140
+ record,
1141
+ outcome,
1142
+ requests: run.resources
1143
+ });
1144
+ switch (outcome.kind) {
1145
+ case "ran": {
1146
+ app.exit.status = commandExitStatus(outcome.command);
1147
+ const { command } = outcome;
1148
+ return spec.ran(
1149
+ {
1150
+ version: app.version,
1151
+ commit: app.commit,
1152
+ configFile,
1153
+ resources: RESOURCE_REPORTS.ranFacts(outcome.resources, run.resources),
1154
+ cleanup: RUN_CLEANUP.facts(outcome),
1155
+ command: command.kind === "exited" ? { exitCode: command.code, signal: null } : command.kind === "signaled" ? { exitCode: null, signal: command.signal } : { exitCode: null, signal: null },
1156
+ runner: outcome.runner === void 0 ? null : {
1157
+ snapshotId: outcome.runner.snapshotId,
1158
+ base: outcome.runner.base,
1159
+ snapshotBranch: outcome.runner.snapshotBranch,
1160
+ snapshotHead: outcome.runner.snapshotHead,
1161
+ built: outcome.runner.built,
1162
+ vcpus: outcome.runner.vcpus,
1163
+ region: outcome.runner.region,
1164
+ runtime: outcome.runner.runtime,
1165
+ buildMs: outcome.runner.buildMs,
1166
+ save: outcome.runner.save
1167
+ },
1168
+ timeline: timelineFacts(ran),
1169
+ runId: directory?.id ?? null
1170
+ },
1171
+ plan
1172
+ );
1173
+ }
1174
+ case "resource-unprepared":
1175
+ return RESOURCE_COMMANDS.unpreparedError(outcome);
1176
+ case "resource-refused":
1177
+ return RESOURCE_COMMANDS.refusedError(outcome, RUN_CLEANUP.facts(outcome));
1178
+ // The run's mint: in a runner run for the runner sandbox, in a local run for a resource that needed it.
1179
+ case "mint-failed":
1180
+ return mintFailedErrors.mintFailed({
1181
+ ...outcome.target,
1182
+ ...describeMintFailure(outcome.failure, outcome.target),
1183
+ runner: outcome.runner,
1184
+ cleanup: RUN_CLEANUP.facts(outcome)
1185
+ });
1186
+ case "spawn-failed":
1187
+ return runErrors.spawnFailed({
1188
+ executable: outcome.executable,
1189
+ message: outcome.message,
1190
+ // Only a local run spawns its command on this machine, so it holds no runner sandbox.
1191
+ cleanup: RUN_CLEANUP.facts({ runnerCleanup: null, resourceCleanup: outcome.resourceCleanup })
1192
+ });
1193
+ case "canceled":
1194
+ return outcomes.canceled({ changed: canceledChanges(outcome) });
1195
+ case "runner-failed":
1196
+ return runErrors.runnerFailed({
1197
+ failure: runnerFailureFacts(outcome.failure),
1198
+ cleanup: RUN_CLEANUP.facts(outcome)
1199
+ });
1200
+ case "snapshot-gone":
1201
+ return runErrors.snapshotGone({
1202
+ snapshotId: outcome.entry.snapshotId,
1203
+ base: outcome.entry.base,
1204
+ removal: outcome.removal === void 0 ? null : { ...outcome.removal },
1205
+ cleanup: RUN_CLEANUP.facts(outcome)
1206
+ });
1207
+ }
1208
+ }
1209
+ function runProblems({
1210
+ set,
1211
+ credential,
1212
+ local,
1213
+ rebuildSnapshot,
1214
+ saveSnapshot,
1215
+ showOutput,
1216
+ keepSandbox,
1217
+ ...rest
1218
+ }) {
1219
+ return [
1220
+ ...setProblems(set).map((problem) => ({ field: "set", message: `${problem}.` })),
1221
+ ...testserverFlagProblems(rest),
1222
+ ...rebuildSnapshot && local ? [{ field: "rebuildSnapshot", message: "--rebuild-snapshot builds a runner snapshot; drop it or --local." }] : [],
1223
+ ...!local && credential === "github-actions" ? [
1224
+ {
1225
+ field: "credential",
1226
+ message: "A runner run needs the mint: the runner sandbox uses a minted Vercel token. Add --local, or drop --credential github-actions."
1227
+ }
1228
+ ] : [],
1229
+ ...showOutput && local ? [{ field: "showOutput", message: "--show-output prints a runner run's step output; drop it or --local." }] : [],
1230
+ ...keepSandbox !== void 0 && parseKeepTime(keepSandbox) === void 0 ? [
1231
+ {
1232
+ field: "keepSandbox",
1233
+ message: `--keep-sandbox takes 0, or a whole number of minutes or hours up to 5h, such as 30m or 2h, not ${JSON.stringify(keepSandbox)}.`
1234
+ }
1235
+ ] : [],
1236
+ ...keepSandbox !== void 0 && local ? [{ field: "keepSandbox", message: "--keep-sandbox keeps a runner run's runner sandbox; drop it or --local." }] : [],
1237
+ ...saveSnapshot && local ? [{ field: "saveSnapshot", message: "--save-snapshot saves a runner run's runner sandbox; drop it or --local." }] : [],
1238
+ ...saveSnapshot && keepSandbox !== void 0 && (parseKeepTime(keepSandbox) ?? 0) > 0 ? [
1239
+ {
1240
+ field: "saveSnapshot",
1241
+ message: "--save-snapshot saves the runner sandbox instead of keeping it; drop --keep-sandbox or set it to 0."
1242
+ }
1243
+ ] : []
1244
+ ];
1245
+ }
1246
+ function prepareRefusal(prepared, configFile) {
1247
+ switch (prepared.kind) {
1248
+ case "no-base-ref":
1249
+ return runErrors.noBaseRef({ refs: prepared.refs.map(({ ref, reason }) => ({ ref, reason })) });
1250
+ case "submodules":
1251
+ return runErrors.submodulesRefused({ paths: [...prepared.paths] });
1252
+ case "invalid-recipe":
1253
+ return invalidConfig(configFile ?? "", [
1254
+ { key: ["runner", ...prepared.path].join("."), location: null, problem: prepared.problem }
1255
+ ]);
1256
+ case "checkout-failed":
1257
+ return checkoutFailedRefusal(prepared.failure);
1258
+ }
1259
+ }
1260
+ function canceledBeforeStart() {
1261
+ return outcomes.canceled({ changed: "The command didn't run.\nNothing was minted, leased or started." });
1262
+ }
1263
+ function checkoutFailedRefusal(failure) {
1264
+ return runErrors.runnerFailed({
1265
+ failure: runnerFailureFacts({ kind: "checkout-failed", failure }),
1266
+ cleanup: RUN_CLEANUP.facts(NOTHING_HELD)
1267
+ });
1268
+ }
1269
+ async function summarize(app, run) {
1270
+ const { view, opened } = run;
1271
+ const directory = opened.ok ? opened.directory : void 0;
1272
+ if (run.local && directory !== void 0) await run.collector.readLocal(directory, run.redact);
1273
+ const collected = run.collector.finish();
1274
+ const { state, tests } = collected;
1275
+ const ran = stormTimeline(state);
1276
+ directory?.publishTestEvents();
1277
+ directory?.writeTimeline(JSON.stringify(ran, null, 2));
1278
+ directory?.writeRun(
1279
+ runRecordText({
1280
+ ...run.record,
1281
+ where: endedWhere(
1282
+ run.record.where,
1283
+ state.runner,
1284
+ run.outcome.kind === "ran" ? run.outcome.runner?.save ?? null : null
1285
+ ),
1286
+ ended: runEnd(run.outcome, state.command, tests, run.requests)
1287
+ })
1288
+ );
1289
+ const writeFailure = await directory?.close();
1290
+ const failed = tests.events.some((event) => event.kind === "test-result" && event.state === "fail");
1291
+ const testsLines = testsSummaryLines(tests.events, tests.unreadable, tests.incomplete);
1292
+ const stepLogs = failedStepLogs(ran, directory?.path, app.env);
1293
+ const clock = workerClock(ran, collected, run.local);
1294
+ const charted = clock === void 0 ? void 0 : testsChart(tests.events, tests.unreadable, clock, tests.incomplete);
1295
+ const summarized = await app.context.jobSummary.appendJobSummary(
1296
+ jobSummaryMarkdown(ran, { command: run.command, logs: directory?.path, details: [...testsLines, ...stepLogs] })
1297
+ );
1298
+ await view.finish(
1299
+ waterfallLines(ran, {
1300
+ width: view.width,
1301
+ paint: view.paint,
1302
+ logs: logsText(opened, writeFailure, app.env, failed),
1303
+ ...charted === void 0 ? {} : { workers: charted.lanes },
1304
+ details: [
1305
+ ...charted?.notes ?? testsLines,
1306
+ ...stepLogs,
1307
+ ...summarized.kind === "failed" ? [` couldn't append to the job summary at ${summarized.failure.path}: ${summarized.failure.message}`] : []
1308
+ ]
1309
+ })
1310
+ );
1311
+ return ran;
1312
+ }
1313
+ function workerClock(ran, collected, local) {
1314
+ const tests = ran.rows.find((row) => row.name === "tests");
1315
+ if (tests === void 0) return void 0;
1316
+ return { runStartedAt: Date.parse(ran.startedAt), offsetMs: local ? 0 : collected.workerOffsetMs, tests };
1317
+ }
1318
+ function teeTerminal(terminal, directory) {
1319
+ if (directory === void 0) return terminal;
1320
+ return {
1321
+ color: terminal.color,
1322
+ writeStdout: (text) => {
1323
+ directory.appendCommandOutput(text);
1324
+ terminal.writeStdout(text);
1325
+ },
1326
+ writeStderr: (text) => {
1327
+ directory.appendCommandOutput(text);
1328
+ terminal.writeStderr(text);
1329
+ }
1330
+ };
1331
+ }
1332
+ function displayPath(path, env) {
1333
+ const home = env["HOME"];
1334
+ if (home === void 0 || home === "" || !path.startsWith(`${home}/`)) return path;
1335
+ return `~${path.slice(home.length)}`;
1336
+ }
1337
+ function logsText(opened, writeFailure, env, failed) {
1338
+ if (!opened.ok) return `none: couldn't make ${opened.failure.path}: ${opened.failure.message}`;
1339
+ const path = `${displayPath(opened.directory.path, env)}/`;
1340
+ const problems = [
1341
+ ...writeFailure === void 0 ? [] : [`couldn't write ${writeFailure.path}: ${writeFailure.message}`],
1342
+ ...opened.pruneFailures.slice(0, 1).map((failure) => `couldn't remove ${failure.path}: ${failure.message}`)
1343
+ ];
1344
+ const show = `storm runs show ${opened.directory.id}${failed ? " --failed" : ""}`;
1345
+ return `${problems.length === 0 ? path : `${path} (${problems.join("; ")})`} \xB7 ${show}`;
1346
+ }
1347
+ function runEnd(outcome, ran, tests, requests) {
1348
+ const command = outcome.kind === "ran" ? outcome.command : void 0;
1349
+ const ms = ran?.outcome === void 0 || ran.outcome === "stopped" || ran.endedAt === void 0 ? null : ran.endedAt - ran.startedAt;
1350
+ return {
1351
+ outcome: outcome.kind,
1352
+ exitCode: command === void 0 ? null : commandExitStatus(command),
1353
+ signal: command?.kind === "signaled" ? command.signal : null,
1354
+ ms,
1355
+ tests: testTotals(tests.events),
1356
+ testsIncomplete: tests.incomplete ?? null,
1357
+ resources: outcome.kind === "ran" ? RESOURCE_REPORTS.ranFacts(outcome.resources, requests) : null
1358
+ };
1359
+ }
1360
+ async function checkoutGit(checkout, cwd) {
1361
+ const root = await checkout.repositoryRoot({ cwd });
1362
+ if (!root.ok) return null;
1363
+ const head = await checkout.head({ repoRoot: root.value });
1364
+ return head.ok ? { ...head.value } : null;
1365
+ }
1366
+ var DEFAULT_KEEP_SANDBOX_MINUTES = 30;
1367
+ function keepSandboxMinutes(flag, recipe, env) {
1368
+ const fromFlag = flag === void 0 ? void 0 : parseKeepTime(flag);
1369
+ return fromFlag ?? recipe.keepSandboxMinutes ?? (isCi(env) ? 0 : DEFAULT_KEEP_SANDBOX_MINUTES);
1370
+ }
1371
+ function isCi(env) {
1372
+ const ci = env["CI"];
1373
+ return ci !== void 0 && ci !== "" && ci !== "0" && ci.toLowerCase() !== "false";
1374
+ }
1375
+ function startedWhere(runner) {
1376
+ const { prepared, target } = runner;
1377
+ return {
1378
+ kind: "runner",
1379
+ team: target.team,
1380
+ project: target.project,
1381
+ region: prepared.recipe.region,
1382
+ runtime: prepared.recipe.runtime,
1383
+ vcpus: prepared.vcpus,
1384
+ base: prepared.base,
1385
+ baseRef: prepared.baseRef,
1386
+ sandbox: null,
1387
+ snapshot: null,
1388
+ keptUntil: null,
1389
+ save: null
1390
+ };
1391
+ }
1392
+ function endedWhere(where, runner, save) {
1393
+ if (where.kind === "local") return where;
1394
+ const snapshot = runner?.snapshot;
1395
+ return {
1396
+ ...where,
1397
+ sandbox: runner?.sandbox?.name ?? null,
1398
+ snapshot: snapshot === void 0 || snapshot.kind === "building" ? null : {
1399
+ id: snapshot.id,
1400
+ base: snapshot.base,
1401
+ built: snapshot.kind === "built",
1402
+ branch: snapshot.branch,
1403
+ head: snapshot.head
1404
+ },
1405
+ keptUntil: runner?.kept?.stopsAt ?? null,
1406
+ save
1407
+ };
1408
+ }
1409
+ function failedStepLogs(ran, directory, env) {
1410
+ if (directory === void 0) return [];
1411
+ const runner = ran.rows.find((row) => row.name === "runner");
1412
+ return (runner?.steps ?? []).filter((step) => step.outcome === "failed").flatMap((step) => {
1413
+ const log = stepLog(directory, step.name);
1414
+ return log === void 0 ? [] : [` failed ${step.name}, whole output: ${displayPath(log, env)}`];
1415
+ });
1416
+ }
1417
+ function timelineFacts(ran) {
1418
+ return {
1419
+ ...ran,
1420
+ rows: ran.rows.map((row) => ({ ...row, steps: row.steps.map((step) => ({ ...step })) })),
1421
+ criticalPath: [...ran.criticalPath]
1422
+ };
1423
+ }
1424
+ function runnerFailureFacts(failure) {
1425
+ switch (failure.kind) {
1426
+ case "snapshot-build-step-failed":
1427
+ case "apply-failed":
1428
+ case "install-failed":
1429
+ case "build-failed":
1430
+ return { kind: failure.kind, label: failure.label, exitCode: failure.exitCode, tail: [...failure.tail] };
1431
+ case "sandbox-api-failed":
1432
+ return { kind: failure.kind, operation: failure.operation, status: failure.status, message: failure.message };
1433
+ case "checkout-failed":
1434
+ return { kind: failure.kind, message: failure.failure.message, command: failure.failure.displayCommand ?? null };
1435
+ case "credential-claims-missing":
1436
+ return { kind: failure.kind, ...failure.target };
1437
+ }
1438
+ }
1439
+ var NOTHING_HELD = { runnerCleanup: null, resourceCleanup: {} };
1440
+ function setProblems(texts) {
1441
+ const parsed = parseSetFlags(texts, RESOURCE_CONFIGS, TESTSERVER_OWN_FLAGS);
1442
+ return parsed.ok ? [] : parsed.problems;
1443
+ }
1444
+ async function settleRun(app, request) {
1445
+ const file = await loadSettingsFile(app.context.config, app.cwd, RESOURCE_CONFIGS);
1446
+ if (!file.ok) return file;
1447
+ const configFile = file.path;
1448
+ const resolved = settleResourceOptions(file, request.given);
1449
+ if (!resolved.ok) return resolved;
1450
+ const { options } = resolved;
1451
+ const takesCredential = RESOURCE_COMMANDS.takesCredential(options);
1452
+ if (request.credential !== void 0 && !takesCredential)
1453
+ return refused(runErrors.credentialUnused({ flags: ["--credential"], configFile }));
1454
+ const settings = fileSettings(file, request);
1455
+ let where;
1456
+ if (!request.local) {
1457
+ if (settings.runner === void 0) return refused(runErrors.missingRunner({ configFile }));
1458
+ const required = requireTarget(settings.scope, settings.project);
1459
+ if (!required.ok) return required;
1460
+ const recipe = settings.runner.value;
1461
+ const secrets = readRunnerSecrets(recipe, app.env);
1462
+ if (!secrets.ok)
1463
+ return refused(
1464
+ runErrors.runnerSecretsInvalid({
1465
+ variables: secrets.variables.map(({ name, problem }) => ({ name, problem })),
1466
+ minLength: RUNNER_SECRET_MIN_LENGTH,
1467
+ configFile
1468
+ })
1469
+ );
1470
+ where = { kind: "runner", recipe, target: required.target, secrets: secrets.values };
1471
+ } else if (takesCredential) {
1472
+ const chosen = settleCredential(request.credential ?? "mint", settings.scope, settings.project);
1473
+ if (!chosen.ok) return chosen;
1474
+ where = { kind: "local", credential: chosen.credential };
1475
+ } else where = { kind: "local", credential: void 0 };
1476
+ const settlement = RESOURCE_COMMANDS.settle(options, app.env, configFile);
1477
+ if (!settlement.ok) return settlement;
1478
+ return { ok: true, configFile, file, options, where, settlement };
1479
+ }
1480
+ function canceledChanges(outcome) {
1481
+ const { commandStopped } = outcome;
1482
+ const lines = [
1483
+ commandStopped === true ? "The command was stopped in the runner sandbox." : "The command didn't run."
1484
+ ];
1485
+ const cleanup = RUN_CLEANUP.facts(outcome).runner;
1486
+ if (cleanup !== null) lines.push(...runnerCleanupLines(cleanup));
1487
+ lines.push(...RESOURCE_COMMANDS.canceledLines(outcome.resources, outcome.resourceCleanup));
1488
+ return lines.join("\n");
1489
+ }
1490
+ function runnerCleanupLines({ kept, notKept, notStopped, notDeleted }) {
1491
+ const problems = [
1492
+ ...notKept === null ? [] : [notKeptText(notKept)],
1493
+ ...notStopped.map(notStoppedText),
1494
+ ...notDeleted.map(notDeletedText)
1495
+ ];
1496
+ if (kept === null)
1497
+ return problems.length === 0 ? ["Every sandbox the runner started is stopped and deleted."] : problems;
1498
+ return [
1499
+ keptText(kept),
1500
+ ...problems.length === 0 ? ["Every other sandbox the runner started is stopped and deleted."] : problems
1501
+ ];
1502
+ }
1503
+
1504
+ export {
1505
+ testserverSandboxesSource,
1506
+ RUN_REQUEST_FIELDS,
1507
+ RUN_CLI_OPTIONS,
1508
+ runCommand,
1509
+ runProblems,
1510
+ canceledBeforeStart,
1511
+ checkoutFailedRefusal
1512
+ };