@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,1842 @@
1
+ import {
2
+ CREATE_CONCURRENCY,
3
+ checkBoolean,
4
+ credentialOriginRows,
5
+ describeValue,
6
+ optionKeyPath,
7
+ prBuildRefusalErrors,
8
+ prBuildRefusalFacts,
9
+ readBooleanText,
10
+ readTextAsIs,
11
+ rejectedCredentialFacts,
12
+ rejectedCredentialShape,
13
+ rejectedCredentialText,
14
+ testserverPoolConfig,
15
+ tokenRequestFailureFacts,
16
+ tokenRequestFailureShape,
17
+ wrongValue
18
+ } from "./chunk-OCZJE5XV.js";
19
+ import {
20
+ POOL_DIRECTORY_PATTERN,
21
+ POOL_SUBPATH,
22
+ TESTSERVER_REPO,
23
+ applyRunEvent,
24
+ bindCommands,
25
+ buildMatch,
26
+ createFailureText,
27
+ createPooledSandbox,
28
+ defineRefusals,
29
+ describeCreateFailure,
30
+ describeCredentialFailure,
31
+ describeTtl,
32
+ leaseUsable,
33
+ liveControlPlaneGateway,
34
+ liveHealthCheckGateway,
35
+ livePoolStoreGateway,
36
+ mayLeaveSandbox,
37
+ minutesSince,
38
+ parseBuildReference,
39
+ releaseLeases,
40
+ resolveBuild,
41
+ resolvePrBuild,
42
+ resolveStateDirectory,
43
+ resourcePresentations,
44
+ resourceReports,
45
+ runLimited,
46
+ secondsOf,
47
+ secondsText,
48
+ shortSha,
49
+ systemTimer,
50
+ timeline,
51
+ unavailablePoolStoreGateway
52
+ } from "./chunk-5CQCRX2L.js";
53
+ import {
54
+ testserverPoolCommandTree
55
+ } from "./chunk-S5NAIZYS.js";
56
+
57
+ // src/combine-errors.ts
58
+ function combineErrors(records) {
59
+ const combined = {};
60
+ for (const record of records)
61
+ for (const [key, error] of Object.entries(record)) {
62
+ if (Object.hasOwn(combined, key)) throw new Error(`Two resources define the error ${key}`);
63
+ combined[key] = error;
64
+ }
65
+ return combined;
66
+ }
67
+
68
+ // src/commands/exec/cleanup.ts
69
+ import { defineErrors } from "@vercel/clinkr";
70
+ import { z } from "zod";
71
+
72
+ // src/commands/dashboard.ts
73
+ function projectPage({ team, project }) {
74
+ return `https://vercel.com/${encodeURIComponent(team)}/${encodeURIComponent(project)}`;
75
+ }
76
+ function sandboxPage(where, name) {
77
+ return `${projectPage(where)}/sandboxes/${encodeURIComponent(name)}`;
78
+ }
79
+ function sandboxConnectPage(where, name) {
80
+ return `${sandboxPage(where, name)}/connect`;
81
+ }
82
+ function snapshotPage(where, id) {
83
+ return `${projectPage(where)}/sandboxes/snapshots/${encodeURIComponent(id)}`;
84
+ }
85
+
86
+ // src/commands/exec/text.ts
87
+ function seconds(ms) {
88
+ return secondsText(secondsOf(ms));
89
+ }
90
+ function keepTimeText(ms) {
91
+ const minutes = Math.round(ms / 6e4);
92
+ return minutes >= 60 && minutes % 60 === 0 ? `${minutes / 60}h` : `${minutes}m`;
93
+ }
94
+ function isoSecondsText(iso) {
95
+ return iso.replace(/\.\d+Z$/, "Z");
96
+ }
97
+ function short(sha) {
98
+ return sha.slice(0, 12);
99
+ }
100
+ function shortFile(file) {
101
+ const parts = file.split("/").filter((part) => part !== "");
102
+ return parts.slice(-2).join("/").replace(/\.(test|spec)\.[cm]?[jt]sx?$/, "").replace(/\.[cm]?[jt]sx?$/, "");
103
+ }
104
+ function median(values) {
105
+ const sorted = [...values].toSorted((a, b) => a - b);
106
+ if (sorted.length === 0) return void 0;
107
+ const middle = Math.floor(sorted.length / 2);
108
+ return sorted.length % 2 === 1 ? sorted[middle] : ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2;
109
+ }
110
+ var code = (open, close) => (text) => text === "" ? text : `\x1B[${open}m${text}\x1B[${close}m`;
111
+ function paint(color) {
112
+ if (!color) {
113
+ const none = (text) => text;
114
+ return { done: none, failed: none, stopped: none, active: none, faint: none, strong: none };
115
+ }
116
+ return {
117
+ done: code(32, 39),
118
+ failed: code(31, 39),
119
+ stopped: code(33, 39),
120
+ active: code(36, 39),
121
+ faint: code(2, 22),
122
+ strong: code(1, 22)
123
+ };
124
+ }
125
+ var COLOR_CODE = /\u001b\[[0-9;]*m/g;
126
+ function visibleLength(text) {
127
+ return Array.from(text.replace(COLOR_CODE, "")).length;
128
+ }
129
+ function truncate(text, width) {
130
+ if (visibleLength(text) <= width) return text;
131
+ const plain = Array.from(text.replace(COLOR_CODE, ""));
132
+ return width <= 0 ? "" : `${plain.slice(0, width - 1).join("")}\u2026`;
133
+ }
134
+ function spread(left, right, width) {
135
+ if (right === "") return truncate(left, width);
136
+ const room = width - visibleLength(right) - 1;
137
+ const fitted = truncate(left, Math.max(0, room));
138
+ return `${fitted}${" ".repeat(Math.max(1, width - visibleLength(fitted) - visibleLength(right)))}${right}`;
139
+ }
140
+
141
+ // src/commands/exec/cleanup.ts
142
+ var notStoppedSchema = z.object({
143
+ name: z.string(),
144
+ role: z.enum(["runner", "snapshot-build"]),
145
+ /** The sandbox's own timeout, in minutes, within which it stops. */
146
+ timeoutMinutes: z.number(),
147
+ message: z.string()
148
+ });
149
+ var notDeletedSchema = z.object({
150
+ name: z.string(),
151
+ role: z.enum(["runner", "snapshot-build"]),
152
+ message: z.string()
153
+ });
154
+ var keptSchema = z.object({
155
+ name: z.string(),
156
+ /** When its timeout stops it, as an ISO time: the keep time from when the run ended, or later. */
157
+ stopsAt: z.string(),
158
+ /** Its Connect page in the Vercel dashboard, which says how to open a shell in it. */
159
+ url: z.string()
160
+ });
161
+ var notKeptSchema = z.object({ name: z.string(), message: z.string() });
162
+ var runnerCleanupSchema = z.object({
163
+ kept: keptSchema.nullable(),
164
+ notKept: notKeptSchema.nullable(),
165
+ notStopped: z.array(notStoppedSchema),
166
+ notDeleted: z.array(notDeletedSchema)
167
+ });
168
+ function sandboxRole(role) {
169
+ return role === "runner" ? "runner sandbox" : "build sandbox";
170
+ }
171
+ function notStoppedText(sandbox) {
172
+ return `Couldn't stop the ${sandboxRole(sandbox.role)} ${sandbox.name}: ${sandbox.message}. Its own timeout stops it within ${sandbox.timeoutMinutes} minutes.`;
173
+ }
174
+ function notDeletedText(sandbox) {
175
+ return `Stopped the ${sandboxRole(sandbox.role)} ${sandbox.name}, but couldn't delete it: ${sandbox.message}. It stays listed in the Vercel project.`;
176
+ }
177
+ function keptText(kept) {
178
+ return `Kept the runner sandbox ${kept.name} running until ${isoSecondsText(kept.stopsAt)}, so you can connect to it: ${kept.url}`;
179
+ }
180
+ function notKeptText(sandbox) {
181
+ return `Couldn't keep the runner sandbox ${sandbox.name} running: ${sandbox.message}. Stopped and deleted it instead.`;
182
+ }
183
+ function runnerCleanupRows(cleanup) {
184
+ if (cleanup === null) return [];
185
+ const { kept, notKept } = cleanup;
186
+ return [
187
+ ...kept === null ? [] : [["Sandbox kept", [`${kept.name}, running until ${isoSecondsText(kept.stopsAt)}`, kept.url]]],
188
+ ...notKept === null ? [] : [["Sandbox not kept", notKeptText(notKept)]],
189
+ ...cleanup.notStopped.length === 0 ? [] : [["Sandboxes not stopped", cleanup.notStopped.map(notStoppedText)]],
190
+ ...cleanup.notDeleted.length === 0 ? [] : [["Sandboxes not deleted", cleanup.notDeleted.map(notDeletedText)]]
191
+ ];
192
+ }
193
+ function runnerCleanupWarnings(cleanup) {
194
+ if (cleanup === null) return [];
195
+ return [
196
+ ...cleanup.notKept === null ? [] : [{ reason: "runner_sandbox_not_kept", message: notKeptText(cleanup.notKept) }],
197
+ ...cleanup.notStopped.map((sandbox) => ({
198
+ reason: "runner_sandbox_not_stopped",
199
+ message: notStoppedText(sandbox)
200
+ })),
201
+ ...cleanup.notDeleted.map((sandbox) => ({
202
+ reason: "runner_sandbox_not_deleted",
203
+ message: notDeletedText(sandbox)
204
+ }))
205
+ ];
206
+ }
207
+ function runCleanupOf(reports) {
208
+ const schema4 = z.object({ runner: runnerCleanupSchema.nullable(), resources: reports.cleanupSchema });
209
+ const rows = (cleanup) => [
210
+ ...runnerCleanupRows(cleanup.runner),
211
+ ...reports.cleanupRows(cleanup.resources)
212
+ ];
213
+ return {
214
+ schema: schema4,
215
+ facts: ({ runnerCleanup, resourceCleanup }) => ({
216
+ runner: runnerCleanupFacts(runnerCleanup),
217
+ resources: reports.cleanupFacts(resourceCleanup)
218
+ }),
219
+ rows,
220
+ withCleanup: (definitions) => {
221
+ const extended = Object.fromEntries(
222
+ Object.entries(definitions).map(([key, own]) => {
223
+ const extendedSchema = z.object({ ...own.schema.shape, cleanup: schema4 });
224
+ const definition = {
225
+ ...own,
226
+ schema: extendedSchema,
227
+ render: (data) => {
228
+ const { rows: ownRows = [], ...content } = own.render(data);
229
+ const all = [...ownRows, ...rows(data.cleanup)];
230
+ return { ...content, ...all.length === 0 ? {} : { rows: all } };
231
+ }
232
+ };
233
+ return [key, definition];
234
+ })
235
+ );
236
+ const built = defineErrors(extended);
237
+ return {
238
+ // `defineErrors` keeps each key and its reason, and each schema is the definition's own with `cleanup` beside
239
+ // it.
240
+ errors: built,
241
+ build: ({ key, data }, cleanup) => {
242
+ const error = built[key];
243
+ if (error === void 0) throw new Error(`No refusal error is defined under ${key}`);
244
+ return error({ ...data, cleanup });
245
+ }
246
+ };
247
+ }
248
+ };
249
+ }
250
+ function runnerCleanupFacts(report) {
251
+ if (report === null) return null;
252
+ const { kept, target } = report;
253
+ return {
254
+ kept: kept === null ? null : { name: kept.name, stopsAt: kept.stopsAt, url: sandboxConnectPage(target, kept.name) },
255
+ notKept: report.notKept === null ? null : { ...report.notKept },
256
+ notStopped: report.notStopped.map(({ name, role, timeoutMinutes, message }) => ({
257
+ name,
258
+ role,
259
+ timeoutMinutes,
260
+ message
261
+ })),
262
+ notDeleted: report.notDeleted.map(({ name, role, message }) => ({ name, role, message }))
263
+ };
264
+ }
265
+
266
+ // src/resources/github/cleanup.ts
267
+ import { z as z2 } from "zod";
268
+ var schema = z2.object({
269
+ repo: z2.string(),
270
+ runPrefix: z2.string(),
271
+ deleted: z2.array(z2.string()),
272
+ failures: z2.array(z2.object({ branch: z2.string().nullable(), message: z2.string() }))
273
+ });
274
+ function fixtureRepoCleanupFailureText(cleanup, failure) {
275
+ return failure.branch === null ? `Couldn't list the branches under ${cleanup.runPrefix}/ in ${cleanup.repo}: ${failure.message}. Any there are left behind.` : `Couldn't delete branch ${failure.branch} in ${cleanup.repo}: ${failure.message}. It is left behind.`;
276
+ }
277
+ var githubFixtureRepoCleanupReport = {
278
+ schema,
279
+ facts: ({ repo, runPrefix, deleted, failures }) => ({
280
+ repo,
281
+ runPrefix,
282
+ deleted: [...deleted],
283
+ failures: failures.map(({ branch, message }) => ({ branch, message }))
284
+ }),
285
+ rows: (cleanup) => cleanup.failures.length === 0 ? [] : [["Branches left behind", cleanup.failures.map((failure) => fixtureRepoCleanupFailureText(cleanup, failure))]],
286
+ warnings: (cleanup) => cleanup.failures.map((failure) => ({
287
+ reason: failure.branch === null ? "github_branches_not_listed" : "github_branch_not_deleted",
288
+ message: fixtureRepoCleanupFailureText(cleanup, failure)
289
+ })),
290
+ // A failed list counts as one, since it can't say how many branches it left.
291
+ failuresText: (failures) => `${failures} GitHub fixture repository cleanup ${failures === 1 ? "failure" : "failures"}`
292
+ };
293
+
294
+ // src/resources/github/command.ts
295
+ import { defineErrors as defineErrors2, refused } from "@vercel/clinkr";
296
+ import { z as z3 } from "zod";
297
+ var OPTIONAL_KEY_PATH = optionKeyPath("githubFixtureRepo", "optional");
298
+ var githubFixtureRepoSettleErrors = defineErrors2({
299
+ githubTokenMissing: {
300
+ exitCode: 2,
301
+ description: "The run holds resources.githubFixtureRepo, required (optional is false: in the file, by --set resources.githubFixtureRepo.optional=false, or by default), and the host environment variable its tokenEnv names is unset or empty, so the run didn't start.",
302
+ schema: z3.object({
303
+ /** The variable that should hold the token, such as CNC_GITHUB_FIXTURE_TOKEN. */
304
+ tokenEnv: z3.string(),
305
+ /** The repository the token is for, as owner/name. */
306
+ repo: z3.string(),
307
+ /** The config file that applied; null when none did. */
308
+ configFile: z3.string().nullable(),
309
+ /**
310
+ * What made the resource required: `set`, --set resources.githubFixtureRepo.optional=false; `config`, the file's
311
+ * githubFixtureRepo({ … }) without optional: true, or the default.
312
+ */
313
+ requiredBy: z3.enum(["config", "set"])
314
+ }),
315
+ render: ({ tokenEnv, repo, requiredBy }) => ({
316
+ message: `${tokenEnv} is not set: resources.githubFixtureRepo needs a token for ${repo} from it. The run didn't start.`,
317
+ next: [
318
+ {
319
+ type: "text",
320
+ text: requiredBy === "set" ? `Set ${tokenEnv} to a token limited to ${repo}: --set ${OPTIONAL_KEY_PATH}=false makes the repository required for this run.` : `Set ${tokenEnv} to a token limited to ${repo}, or let runs go on without the repository with githubFixtureRepo({ \u2026, optional: true }) or --set ${OPTIONAL_KEY_PATH}=true.`
321
+ }
322
+ ]
323
+ })
324
+ }
325
+ });
326
+ function fixtureRepoCanceledLines(cleanup) {
327
+ if (cleanup === void 0) return [];
328
+ const facts = githubFixtureRepoCleanupReport.facts(cleanup);
329
+ if (facts.failures.length === 0) return [`Every branch under ${facts.runPrefix}/ in ${facts.repo} is deleted.`];
330
+ return facts.failures.map((failure) => fixtureRepoCleanupFailureText(facts, failure));
331
+ }
332
+ var githubFixtureRepoRefusalErrors = defineRefusals({
333
+ githubFixtureRepoUnavailable: {
334
+ exitCode: 1,
335
+ description: "The token from resources.githubFixtureRepo's tokenEnv couldn't read the repository (GET repos/{repo} failed), so the command didn't run.",
336
+ schema: z3.object({
337
+ /** The repository, as owner/name. */
338
+ repo: z3.string(),
339
+ /** The HTTP status GitHub answered with; null when it never answered. */
340
+ status: z3.number().nullable(),
341
+ /** What GitHub or the connection said. */
342
+ message: z3.string()
343
+ }),
344
+ render: ({ repo, status, message }) => ({
345
+ message: `Couldn't read the GitHub fixture repository ${repo}: ${status === null ? message : `HTTP ${status}: ${message}`}. The command didn't run.`,
346
+ next: [
347
+ {
348
+ type: "text",
349
+ text: `Check that the token in resources.githubFixtureRepo's tokenEnv can read ${repo}, then retry.`
350
+ }
351
+ ]
352
+ })
353
+ }
354
+ });
355
+ var githubFixtureRepoCommand = {
356
+ errors: githubFixtureRepoSettleErrors,
357
+ refusalErrors: githubFixtureRepoRefusalErrors,
358
+ settle: ({ options, env, configFile }) => {
359
+ const { repo, tokenEnv, optional } = options;
360
+ const token = env[tokenEnv] ?? "";
361
+ if (token !== "") return settled({ kind: "open", repo, token }, [token]);
362
+ if (optional.value) return settled({ kind: "omitted", repo, tokenEnv }, []);
363
+ return refused(
364
+ githubFixtureRepoSettleErrors.githubTokenMissing({
365
+ tokenEnv,
366
+ repo,
367
+ configFile,
368
+ requiredBy: optional.source === "flag" ? "set" : "config"
369
+ })
370
+ );
371
+ },
372
+ takesCredential: (_options) => false,
373
+ refusalFacts: ({ repo, failure }) => ({
374
+ key: "githubFixtureRepoUnavailable",
375
+ data: { repo, status: failure.status, message: failure.message }
376
+ }),
377
+ unpreparedError: void 0,
378
+ canceledLines: (_facts, released) => fixtureRepoCanceledLines(released)
379
+ };
380
+ function settled(request, secrets) {
381
+ return { ok: true, secrets, request };
382
+ }
383
+
384
+ // src/resources/github/config.ts
385
+ var REPO_NAME = /^[\w.-]+\/[\w.-]+$/;
386
+ var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
387
+ function repoName(value) {
388
+ return typeof value === "string" && REPO_NAME.test(value) ? { ok: true, value } : wrongValue(`must be a repository as owner/name, not ${describeValue(value)}`);
389
+ }
390
+ function envName(value) {
391
+ return typeof value === "string" && ENV_NAME.test(value) ? { ok: true, value } : wrongValue(`must be an environment variable's name, not ${describeValue(value)}`);
392
+ }
393
+ var KIND = "githubFixtureRepo";
394
+ var githubFixtureRepoConfig = {
395
+ name: "githubFixtureRepo",
396
+ factory: { kind: KIND, call: "githubFixtureRepo({ \u2026 })", subpath: "@vercel/storm/github" },
397
+ options: {
398
+ repo: { check: repoName, readText: readTextAsIs, required: true },
399
+ tokenEnv: { check: envName, readText: readTextAsIs, required: true },
400
+ optional: { check: checkBoolean, readText: readBooleanText, default: false }
401
+ },
402
+ resolve: ({ repo, tokenEnv, optional }) => ({
403
+ ok: true,
404
+ value: { repo: repo.value, tokenEnv: tokenEnv.value, optional }
405
+ })
406
+ };
407
+
408
+ // src/resources/github/fixture-repo.ts
409
+ var FIXTURE_RUN_PREFIX_ROOT = "run/";
410
+ function fixtureRunPrefix(startedAt, suffix) {
411
+ const stamp = startedAt.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
412
+ return `${FIXTURE_RUN_PREFIX_ROOT}${stamp}-${suffix}`;
413
+ }
414
+ async function openFixtureRepo(context, request, prefix) {
415
+ const read = await context.githubFixtureRepos.readRepo(request);
416
+ if (!read.ok) return { kind: "unavailable", repo: request.repo, failure: read.failure };
417
+ return {
418
+ kind: "opened",
419
+ held: {
420
+ repo: request.repo,
421
+ nameWithOwner: read.repo.nameWithOwner,
422
+ url: read.repo.cloneUrl,
423
+ token: request.token,
424
+ runPrefix: fixtureRunPrefix(prefix.startedAt, prefix.suffix)
425
+ }
426
+ };
427
+ }
428
+ async function cleanupFixtureRepo(context, held) {
429
+ const { repo, token, runPrefix } = held;
430
+ const listed = await context.githubFixtureRepos.listBranches({ repo, token, prefix: `${runPrefix}/` });
431
+ if (!listed.ok)
432
+ return { repo, runPrefix, deleted: [], failures: [{ branch: null, message: failureText(listed.failure) }] };
433
+ const deleted = [];
434
+ const failures = [];
435
+ for (const branch of listed.branches) {
436
+ const removed = await context.githubFixtureRepos.deleteBranch({ repo, token, branch });
437
+ if (removed.ok) deleted.push(branch);
438
+ else failures.push({ branch, message: failureText(removed.failure) });
439
+ }
440
+ return { repo, runPrefix, deleted, failures };
441
+ }
442
+ function failureText(failure) {
443
+ return failure.status === null ? failure.message : `HTTP ${failure.status}: ${failure.message}`;
444
+ }
445
+
446
+ // src/resources/github/live/fixture-repo-gateway.ts
447
+ import { z as z4 } from "zod";
448
+ var repoSchema = z4.object({ full_name: z4.string().min(1), clone_url: z4.string().min(1) });
449
+ var refsSchema = z4.array(z4.object({ ref: z4.string() }));
450
+ var errorSchema = z4.object({ message: z4.string() });
451
+ function liveGitHubFixtureRepoGateway(options) {
452
+ return {
453
+ readRepo: async ({ repo, token }) => {
454
+ const answered = await call(options, token, "GET", `repos/${repoPath(repo)}`);
455
+ if (!answered.ok) return answered;
456
+ const parsed = repoSchema.safeParse(answered.body);
457
+ if (!parsed.success) return { ok: false, failure: { status: answered.status, message: "unexpected answer" } };
458
+ return { ok: true, repo: { nameWithOwner: parsed.data.full_name, cloneUrl: parsed.data.clone_url } };
459
+ },
460
+ listBranches: async ({ repo, token, prefix }) => {
461
+ const answered = await call(
462
+ options,
463
+ token,
464
+ "GET",
465
+ `repos/${repoPath(repo)}/git/matching-refs/heads/${refPath(prefix)}`
466
+ );
467
+ if (!answered.ok) return answered;
468
+ const parsed = refsSchema.safeParse(answered.body);
469
+ if (!parsed.success) return { ok: false, failure: { status: answered.status, message: "unexpected answer" } };
470
+ const branches = parsed.data.map(({ ref }) => ref).filter((ref) => ref.startsWith("refs/heads/")).map((ref) => ref.slice("refs/heads/".length)).filter((branch) => branch.startsWith(prefix));
471
+ return { ok: true, branches };
472
+ },
473
+ deleteBranch: async ({ repo, token, branch }) => {
474
+ const answered = await call(
475
+ options,
476
+ token,
477
+ "DELETE",
478
+ `repos/${repoPath(repo)}/git/refs/heads/${refPath(branch)}`
479
+ );
480
+ return answered.ok ? { ok: true } : answered;
481
+ }
482
+ };
483
+ }
484
+ function repoPath(repo) {
485
+ return repo.split("/").map(encodeURIComponent).join("/");
486
+ }
487
+ function refPath(ref) {
488
+ return ref.split("/").map(encodeURIComponent).join("/");
489
+ }
490
+ async function call(options, token, method, path) {
491
+ const signal = AbortSignal.timeout(options.timeoutMs);
492
+ const hide = (text) => token === "" ? text : text.replaceAll(token, "<token>");
493
+ try {
494
+ const response = await fetch(`${options.origin}/${path}`, {
495
+ method,
496
+ headers: {
497
+ accept: "application/vnd.github+json",
498
+ authorization: `Bearer ${token}`,
499
+ "x-github-api-version": "2022-11-28",
500
+ "user-agent": "storm"
501
+ },
502
+ redirect: "manual",
503
+ signal
504
+ });
505
+ const text = await response.text();
506
+ if (response.status < 200 || response.status >= 300) {
507
+ let message = `HTTP ${response.status}`;
508
+ try {
509
+ const parsed = errorSchema.safeParse(JSON.parse(text));
510
+ if (parsed.success) message = parsed.data.message;
511
+ } catch {
512
+ }
513
+ return { ok: false, failure: { status: response.status, message: hide(message) } };
514
+ }
515
+ return { ok: true, status: response.status, body: text === "" ? null : JSON.parse(text) };
516
+ } catch (error) {
517
+ const message = signal.aborted ? `no answer within ${options.timeoutMs / 1e3}s` : error instanceof Error ? error.message : String(error);
518
+ return { ok: false, failure: { status: null, message: hide(message) } };
519
+ }
520
+ }
521
+
522
+ // src/resources/github/live/gateways.ts
523
+ import { randomBytes } from "node:crypto";
524
+ var GITHUB_API_ORIGIN = "https://api.github.com";
525
+ function liveGitHubFixtureRepoGateways(_host) {
526
+ return {
527
+ githubFixtureRepos: liveGitHubFixtureRepoGateway({ origin: GITHUB_API_ORIGIN, timeoutMs: 1e4 }),
528
+ randomSuffix: () => randomBytes(4).toString("hex")
529
+ };
530
+ }
531
+
532
+ // src/resources/github/provider.ts
533
+ var githubFixtureRepoRunProvider = {
534
+ name: "githubFixtureRepo",
535
+ lane: void 0,
536
+ requested: (request) => request.kind === "open" ? request : void 0,
537
+ prepare: async (_context, request, progress) => {
538
+ if (request.kind !== "omitted") return void 0;
539
+ const { repo, tokenEnv } = request;
540
+ await progress.emit({ kind: "omitted", repo, tokenEnv });
541
+ return void 0;
542
+ },
543
+ acquire: async ({ context, request, progress, owned }) => {
544
+ const opened = await openFixtureRepo(
545
+ context,
546
+ { repo: request.repo, token: request.token },
547
+ { startedAt: context.clock.now(), suffix: context.randomSuffix() }
548
+ );
549
+ if (opened.kind === "unavailable")
550
+ return {
551
+ kind: "refused",
552
+ refusal: { kind: "github-fixture-repo-unavailable", repo: opened.repo, failure: opened.failure }
553
+ };
554
+ owned.push(opened.held);
555
+ await progress.emit({ kind: "opened", repo: opened.held.nameWithOwner, runPrefix: opened.held.runPrefix });
556
+ return { kind: "acquired", connection: opened.held, facts: void 0 };
557
+ },
558
+ holding: ([held]) => held === void 0 ? void 0 : { runPrefix: held.runPrefix },
559
+ release: async (context, owned, progress) => {
560
+ const [held] = owned;
561
+ if (held === void 0) return void 0;
562
+ const cleaned = await cleanupFixtureRepo(context, held);
563
+ await progress.emit({
564
+ kind: "cleaned",
565
+ repo: held.nameWithOwner,
566
+ runPrefix: cleaned.runPrefix,
567
+ deleted: cleaned.deleted.length,
568
+ failures: cleaned.failures
569
+ });
570
+ return cleaned;
571
+ },
572
+ // A failed list counts as one, since it can't say how many branches it left.
573
+ failures: (cleanup) => cleanup.failures.length,
574
+ payload: (held) => ({
575
+ url: held.url,
576
+ nameWithOwner: held.nameWithOwner,
577
+ token: held.token,
578
+ runPrefix: held.runPrefix
579
+ })
580
+ };
581
+
582
+ // src/resources/github/presentation.ts
583
+ function fixtureRepoNotices(event) {
584
+ switch (event.kind) {
585
+ case "omitted":
586
+ return [
587
+ {
588
+ lane: "run",
589
+ text: `no GitHub fixture repository: ${event.tokenEnv} is unset and resources.githubFixtureRepo is optional, so the run goes on without ${event.repo}`
590
+ }
591
+ ];
592
+ case "opened":
593
+ return [
594
+ { lane: "run", text: `GitHub fixture repository ${event.repo}, the run's branches under ${event.runPrefix}/` }
595
+ ];
596
+ case "cleaned": {
597
+ const branches = event.deleted === 1 ? "1 branch" : `${event.deleted} branches`;
598
+ return [
599
+ `deleted ${branches} under ${event.runPrefix}/ in ${event.repo}`,
600
+ ...event.failures.map(
601
+ ({ branch, message }) => branch === null ? `warning: couldn't list the branches under ${event.runPrefix}/ in ${event.repo}: ${message}` : `warning: couldn't delete branch ${branch} in ${event.repo}: ${message}`
602
+ )
603
+ ].map((text) => ({ lane: "cleanup", text }));
604
+ }
605
+ }
606
+ }
607
+ var githubFixtureRepoPresentation = {
608
+ plain: () => fixtureRepoNotices,
609
+ notices: fixtureRepoNotices,
610
+ release: (holding, tense) => {
611
+ const verb = tense === "doing" ? "deleting" : "deleted";
612
+ return holding === void 0 ? `${verb} the run's branches` : `${verb} the branches under ${holding.runPrefix}/`;
613
+ },
614
+ lane: void 0
615
+ };
616
+
617
+ // src/resources/github/resource-provider.ts
618
+ var githubFixtureRepoProvider = {
619
+ name: "githubFixtureRepo",
620
+ run: githubFixtureRepoRunProvider,
621
+ command: githubFixtureRepoCommand,
622
+ config: githubFixtureRepoConfig,
623
+ cleanup: githubFixtureRepoCleanupReport,
624
+ ran: void 0,
625
+ lane: void 0,
626
+ presentation: githubFixtureRepoPresentation,
627
+ liveGateways: liveGitHubFixtureRepoGateways
628
+ };
629
+
630
+ // src/resources/testserver/cleanup.ts
631
+ import { z as z5 } from "zod";
632
+ var schema2 = z5.object({
633
+ /** Leases the run couldn't release: the lease file and what the OS said. */
634
+ releaseFailures: z5.array(z5.object({ path: z5.string(), message: z5.string() }))
635
+ });
636
+ var testserverPoolCleanupReport = {
637
+ schema: schema2,
638
+ facts: ({ releaseFailures }) => ({
639
+ releaseFailures: releaseFailures.map(({ path, message }) => ({ path, message }))
640
+ }),
641
+ rows: ({ releaseFailures }) => releaseFailures.length === 0 ? [] : [["Unreleased leases", releaseFailures.map(({ path, message }) => `${path}: ${message}`)]],
642
+ warnings: ({ releaseFailures }) => releaseFailures.map(({ path, message }) => ({
643
+ reason: "release_failed",
644
+ message: `Couldn't release the lease at ${path}: ${message}. A later run reclaims it once this one has exited.`
645
+ })),
646
+ failuresText: (failures) => `${failures} ${failures === 1 ? "lease" : "leases"} not released`
647
+ };
648
+
649
+ // src/resources/testserver/command.ts
650
+ import { defineErrors as defineErrors3 } from "@vercel/clinkr";
651
+ import { z as z7 } from "zod";
652
+
653
+ // src/resources/testserver/ran.ts
654
+ import { z as z6 } from "zod";
655
+ var createFailureKinds = [
656
+ "connect-failed",
657
+ "http-error",
658
+ "stream-error",
659
+ "stream-ended",
660
+ "dropped",
661
+ "timeout",
662
+ "malformed"
663
+ ];
664
+ var createFailureSchema = z6.object({
665
+ kind: z6.enum(createFailureKinds),
666
+ detail: z6.string().nullable()
667
+ });
668
+ var unpooledSchema = z6.object({ testserverUrl: z6.string(), path: z6.string(), message: z6.string() });
669
+ function unpooledFacts(unpooled) {
670
+ return unpooled.map(({ testserverUrl, failure }) => ({ testserverUrl, ...failure }));
671
+ }
672
+ function failedCreateFacts(failures) {
673
+ return failures.map((failure) => {
674
+ const { kind, detail } = describeCreateFailure(failure);
675
+ return { kind, detail };
676
+ });
677
+ }
678
+ var schema3 = z6.object({
679
+ /** What the build setting asked for and the build it resolved to. */
680
+ build: z6.object({
681
+ /** The build, build channel or PR build reference (pr:<N>) the build setting gave. */
682
+ requested: z6.string(),
683
+ /** The build it resolved to; null when a build channel couldn't be resolved and was matched as written. */
684
+ resolved: z6.string().nullable(),
685
+ /** For a PR build reference, the pull request and the head commit the resolved PR build was made from; null otherwise. */
686
+ pullRequest: z6.object({
687
+ /** The repository, vercel/api. */
688
+ repo: z6.string(),
689
+ number: z6.number(),
690
+ /** The pull request's head commit when the run started, 40 hex characters. */
691
+ headSha: z6.string()
692
+ }).nullable()
693
+ }),
694
+ /** The sandbox list: reused Testserver sandboxes first, freshest first, then created ones. */
695
+ sandboxes: z6.array(
696
+ z6.object({
697
+ testserverUrl: z6.string(),
698
+ logViewerUrl: z6.string(),
699
+ origin: z6.enum(["reused", "created"])
700
+ })
701
+ ),
702
+ reused: z6.number(),
703
+ created: z6.number(),
704
+ /** The creates that failed, which the run went on without. */
705
+ failedCreates: z6.array(createFailureSchema),
706
+ /** Created Testserver sandboxes the run used but couldn't add to the pool. */
707
+ unpooled: z6.array(unpooledSchema),
708
+ /** When the credential source failed with some Testserver sandboxes in hand: how many more weren't created, which source failed, and why. */
709
+ uncreated: z6.object({
710
+ count: z6.number(),
711
+ source: z6.enum(["mint", "github-actions"]),
712
+ cause: z6.string(),
713
+ fix: z6.string()
714
+ }).nullable(),
715
+ /** Under noCreate, how many of the requested Testserver sandboxes the pool couldn't supply, which the run didn't create; 0 otherwise. */
716
+ notCreated: z6.number()
717
+ });
718
+ var testserverPoolRanReport = {
719
+ schema: schema3,
720
+ facts: (facts, request) => {
721
+ const { resolution, sandboxes } = facts;
722
+ return {
723
+ build: {
724
+ requested: request.build,
725
+ resolved: resolution.kind === "as-written" ? null : resolution.build,
726
+ pullRequest: resolution.kind === "pull-request" ? { repo: TESTSERVER_REPO, number: resolution.pr, headSha: resolution.headSha } : null
727
+ },
728
+ sandboxes: sandboxes.map(({ testserverUrl, logViewerUrl, origin }) => ({ testserverUrl, logViewerUrl, origin })),
729
+ reused: sandboxes.filter((sandbox) => sandbox.origin === "reused").length,
730
+ created: sandboxes.filter((sandbox) => sandbox.origin === "created").length,
731
+ failedCreates: failedCreateFacts(facts.failedCreates),
732
+ unpooled: unpooledFacts(facts.unpooled),
733
+ uncreated: facts.uncreated === void 0 ? null : {
734
+ count: facts.uncreated.count,
735
+ source: facts.uncreated.failure.source,
736
+ ...describeCredentialFailure(facts.uncreated.failure)
737
+ },
738
+ notCreated: facts.notCreated
739
+ };
740
+ },
741
+ warnings: (ran) => [
742
+ ...ran.failedCreates.length === 0 ? [] : [
743
+ {
744
+ reason: "creates_failed",
745
+ message: `${ran.failedCreates.length} of ${ran.failedCreates.length + ran.created} creates failed (${ran.failedCreates.map(createFailureText).join("; ")}); the command ran on ${ran.sandboxes.length} Testserver sandboxes.`
746
+ }
747
+ ],
748
+ ...ran.unpooled.map(({ testserverUrl, message }) => ({
749
+ reason: "sandbox_not_pooled",
750
+ message: `Used the Testserver sandbox ${testserverUrl}, but couldn't add it to the pool: ${message}`
751
+ })),
752
+ ...ran.uncreated === null ? [] : [
753
+ ran.uncreated.source === "mint" ? {
754
+ reason: "mint_failed",
755
+ message: `Couldn't create ${ran.uncreated.count} more Testserver sandboxes: couldn't mint a credential: ${ran.uncreated.cause}. ${ran.uncreated.fix}`
756
+ } : {
757
+ reason: "token_request_failed",
758
+ message: `Couldn't create ${ran.uncreated.count} more Testserver sandboxes: couldn't request a GitHub Actions OIDC token: ${ran.uncreated.cause}. ${ran.uncreated.fix}`
759
+ }
760
+ ],
761
+ ...ran.notCreated === 0 ? [] : [
762
+ {
763
+ reason: "sandboxes_not_created",
764
+ message: `noCreate: ${ran.notCreated} of ${ran.notCreated + ran.sandboxes.length} Testserver sandboxes couldn't be leased, and none were created; the command ran on ${ran.sandboxes.length}.`
765
+ }
766
+ ]
767
+ ],
768
+ rows: (ran) => ran.sandboxes.length === 0 ? [] : [
769
+ [
770
+ "Testserver",
771
+ ran.sandboxes.flatMap(({ testserverUrl, logViewerUrl, origin }) => [
772
+ `${testserverUrl} (${origin})`,
773
+ ` logs ${logViewerUrl}`
774
+ ])
775
+ ]
776
+ ]
777
+ };
778
+
779
+ // src/resources/testserver/command.ts
780
+ function unpooledRows(unpooled) {
781
+ return unpooled.length === 0 ? [] : [
782
+ [
783
+ "Unpooled Testserver sandboxes",
784
+ unpooled.map(({ testserverUrl, message }) => `${testserverUrl}: ${message}`)
785
+ ]
786
+ ];
787
+ }
788
+ function sandboxMayExist(ttlMinutes) {
789
+ return `A create that reached the Testserver control plane may have left a Testserver sandbox anyway; nothing can delete it, and it expires within ${describeTtl(ttlMinutes)}.`;
790
+ }
791
+ var NOTHING_CANCELED = { pooled: 0, unpooled: [], failedCreates: [], ttlMinutes: void 0 };
792
+ function testserverPoolCanceledLines(facts, cleanup) {
793
+ if (cleanup === void 0) return [];
794
+ const { releaseFailures } = cleanup;
795
+ const { pooled, unpooled, failedCreates, ttlMinutes } = facts ?? NOTHING_CANCELED;
796
+ const ttl = ttlMinutes === void 0 ? "its TTL" : describeTtl(ttlMinutes);
797
+ const lines = [];
798
+ if (pooled > 0) {
799
+ const sandboxes = pooled === 1 ? "Testserver sandbox" : `${pooled} Testserver sandboxes`;
800
+ lines.push(
801
+ releaseFailures.length === 0 ? `The ${sandboxes} it created ${pooled === 1 ? "is" : "are"} free in the pool.` : `It added the ${sandboxes} it created to the pool.`
802
+ );
803
+ }
804
+ if (unpooled.length > 0) {
805
+ const one = unpooled.length === 1;
806
+ lines.push(
807
+ `It couldn't add ${one ? "a" : unpooled.length} Testserver ${one ? "sandbox" : "sandboxes"} it created to the pool; ${one ? "it expires" : "they expire"} within ${ttl}:`,
808
+ ...unpooled.map(({ testserverUrl, failure }) => ` ${testserverUrl}: ${failure.message}`)
809
+ );
810
+ }
811
+ if (failedCreates.some(mayLeaveSandbox))
812
+ lines.push(
813
+ `A create that reached the Testserver control plane may have left a Testserver sandbox; nothing can delete it, and it expires within ${ttl}.`
814
+ );
815
+ if (releaseFailures.length === 0) lines.push("The run holds no lease.");
816
+ else {
817
+ const one = releaseFailures.length === 1;
818
+ lines.push(
819
+ `It couldn't release ${one ? "a lease" : `${releaseFailures.length} leases`}; a later run reclaims ${one ? "it" : "each"} once this process has exited:`,
820
+ ...releaseFailures.map(({ path, message }) => ` ${path}: ${message}`)
821
+ );
822
+ }
823
+ return lines;
824
+ }
825
+ var NO_CREATE_KEY_PATH = optionKeyPath("testserverPool", "noCreate");
826
+ var testserverPoolPrepareErrors = defineErrors3({
827
+ poolUnavailable: {
828
+ exitCode: 1,
829
+ description: "storm couldn't use the pool, so it minted no credential and didn't run the command.",
830
+ schema: z7.object({
831
+ /** The pool directory that couldn't be made, or where the pool would live. */
832
+ path: z7.string(),
833
+ /** What the OS said, or why there is no place for the pool. */
834
+ message: z7.string()
835
+ }),
836
+ render: ({ path, message }) => ({
837
+ message: `Couldn't prepare the pool: ${message}`,
838
+ rows: [["Pool path", path]],
839
+ next: [{ type: "text", text: "Fix the pool path, then retry. The command didn't run." }]
840
+ })
841
+ }
842
+ });
843
+ var testserverPoolRefusalErrors = defineRefusals({
844
+ poolUnreadable: {
845
+ exitCode: 1,
846
+ description: "storm couldn't list the pool, so it didn't run the command.",
847
+ schema: z7.object({ path: z7.string(), message: z7.string() }),
848
+ render: ({ path, message }) => ({
849
+ message: `Couldn't read the pool: ${message}`,
850
+ rows: [["Pool path", path]],
851
+ next: [{ type: "text", text: "Fix the pool path, then retry. The command didn't run." }]
852
+ })
853
+ },
854
+ tokenRequestFailed: {
855
+ exitCode: 1,
856
+ description: "With --credential github-actions, the GitHub Actions OIDC token request failed, and the run had no usable Testserver sandbox, from the pool or created, so the command didn't run. It lists the creates that failed before the request did, and says when one may have left a Testserver sandbox.",
857
+ schema: z7.object({
858
+ ...tokenRequestFailureShape,
859
+ /** The TTL each create asked for, in minutes: how long a Testserver sandbox a failed create left lives. */
860
+ ttlMinutes: z7.number(),
861
+ /** The creates that failed before the token request did. */
862
+ failedCreates: z7.array(createFailureSchema),
863
+ /** Whether some failed create may have left a Testserver sandbox that nothing can delete. */
864
+ sandboxMayExist: z7.boolean()
865
+ }),
866
+ render: ({ detail, fix, ttlMinutes, failedCreates, sandboxMayExist: mayExist }) => ({
867
+ message: `Couldn't request a GitHub Actions OIDC token: ${detail}. The pool had no usable Testserver sandbox, so the command didn't run.`,
868
+ rows: failedCreates.length === 0 ? [] : [["Failed creates", failedCreates.map(createFailureText)]],
869
+ next: [
870
+ { type: "text", text: fix },
871
+ ...mayExist ? [{ type: "text", text: sandboxMayExist(ttlMinutes) }] : []
872
+ ]
873
+ })
874
+ },
875
+ credentialRejected: {
876
+ exitCode: 1,
877
+ description: "The Testserver control plane refused the credential, minted or a GitHub Actions OIDC token (a redirect to SSO, a 401 or a 403), so the command didn't run. It lists the other creates that failed and the created Testserver sandboxes it couldn't add to the pool, and says when some failed create may have left a Testserver sandbox.",
878
+ schema: z7.object({
879
+ ...rejectedCredentialShape,
880
+ status: z7.number(),
881
+ vercelId: z7.string().nullable(),
882
+ /** The TTL each create asked for, in minutes: how long a Testserver sandbox a failed create left lives. */
883
+ ttlMinutes: z7.number(),
884
+ /** The other creates that failed before the creates in flight settled. */
885
+ failedCreates: z7.array(createFailureSchema),
886
+ /** Created Testserver sandboxes the run couldn't add to the pool. Each expires when its TTL runs out. */
887
+ unpooled: z7.array(unpooledSchema),
888
+ /** Whether some failed create may have left a Testserver sandbox that nothing can delete. */
889
+ sandboxMayExist: z7.boolean()
890
+ }),
891
+ render: ({ origin, fix, status, vercelId, ttlMinutes, failedCreates, unpooled, sandboxMayExist: mayExist }) => ({
892
+ message: `The Testserver control plane rejected ${rejectedCredentialText(origin)} (HTTP ${status}, x-vercel-id ${vercelId ?? "unknown"}). The command didn't run.`,
893
+ rows: [
894
+ ...credentialOriginRows(origin),
895
+ ...unpooledRows(unpooled),
896
+ ...failedCreates.length === 0 ? [] : [["Failed creates", failedCreates.map(createFailureText)]]
897
+ ],
898
+ next: [
899
+ { type: "text", text: fix },
900
+ ...mayExist ? [{ type: "text", text: sandboxMayExist(ttlMinutes) }] : []
901
+ ]
902
+ })
903
+ },
904
+ noSandboxes: {
905
+ exitCode: 1,
906
+ description: "The pool had no usable Testserver sandbox and every create failed, so the command didn't run. When some failed create may have left a Testserver sandbox, it says so.",
907
+ schema: z7.object({
908
+ requested: z7.number(),
909
+ /** The TTL each create asked for, in minutes: how long a Testserver sandbox a failed create left lives. */
910
+ ttlMinutes: z7.number(),
911
+ failedCreates: z7.array(createFailureSchema),
912
+ /** Whether some failed create may have left a Testserver sandbox that nothing can delete. */
913
+ sandboxMayExist: z7.boolean()
914
+ }),
915
+ render: ({ requested, ttlMinutes, failedCreates, sandboxMayExist: mayExist }) => ({
916
+ message: `Got none of the ${requested} Testserver sandboxes asked for: the pool had no usable one, and all ${failedCreates.length} creates failed. The command didn't run.`,
917
+ rows: [["Failed creates", failedCreates.map(createFailureText)]],
918
+ ...mayExist ? { next: [{ type: "text", text: sandboxMayExist(ttlMinutes) }] } : {}
919
+ })
920
+ },
921
+ noUsableSandboxes: {
922
+ exitCode: 1,
923
+ description: "Under noCreate, the pool had no usable Testserver sandbox on the build, so the command didn't run. noCreate never creates one.",
924
+ schema: z7.object({
925
+ requested: z7.number(),
926
+ /** The build the run matched pool entries on: the one the build setting resolved to, or a build channel as written. */
927
+ build: z7.string()
928
+ }),
929
+ render: ({ requested, build }) => ({
930
+ message: `${requested === 1 ? "Got no Testserver sandbox" : `Got none of the ${requested} Testserver sandboxes asked for`}: the pool has no usable one on ${build}, and noCreate creates none. The command didn't run.`,
931
+ next: [
932
+ {
933
+ type: "text",
934
+ text: `Set ${NO_CREATE_KEY_PATH} to false to create Testserver sandboxes, or check the pool with storm pool list.`
935
+ }
936
+ ]
937
+ })
938
+ },
939
+ ...prBuildRefusalErrors("The command didn't run.")
940
+ });
941
+ var testserverPoolCommand = {
942
+ errors: testserverPoolPrepareErrors,
943
+ refusalErrors: testserverPoolRefusalErrors,
944
+ // Its request is the resolved options as they stand; a pool that creates gets the run's credential source.
945
+ settle: ({ options }) => ({ ok: true, secrets: [], request: options }),
946
+ takesCredential: (options) => options.provisioning.kind === "create",
947
+ unpreparedError: ({ failure }) => testserverPoolPrepareErrors.poolUnavailable({ ...failure }),
948
+ refusalFacts: (refusal) => {
949
+ switch (refusal.kind) {
950
+ case "pool-unreadable":
951
+ return { key: "poolUnreadable", data: { ...refusal.failure } };
952
+ case "token-request-failed":
953
+ return {
954
+ key: "tokenRequestFailed",
955
+ data: {
956
+ ...tokenRequestFailureFacts(refusal.failure),
957
+ ttlMinutes: refusal.ttlMinutes,
958
+ failedCreates: failedCreateFacts(refusal.failedCreates),
959
+ sandboxMayExist: refusal.failedCreates.some(mayLeaveSandbox)
960
+ }
961
+ };
962
+ case "credential-rejected":
963
+ return {
964
+ key: "credentialRejected",
965
+ data: {
966
+ ...rejectedCredentialFacts(refusal.origin),
967
+ ttlMinutes: refusal.ttlMinutes,
968
+ status: refusal.failure.status,
969
+ vercelId: refusal.failure.vercelId ?? null,
970
+ failedCreates: failedCreateFacts(refusal.failedCreates),
971
+ unpooled: unpooledFacts(refusal.unpooled),
972
+ sandboxMayExist: refusal.failedCreates.some(mayLeaveSandbox)
973
+ }
974
+ };
975
+ case "no-sandboxes":
976
+ return {
977
+ key: "noSandboxes",
978
+ data: {
979
+ requested: refusal.requested,
980
+ ttlMinutes: refusal.ttlMinutes,
981
+ failedCreates: failedCreateFacts(refusal.failedCreates),
982
+ sandboxMayExist: refusal.failedCreates.some(mayLeaveSandbox)
983
+ }
984
+ };
985
+ case "no-usable-sandboxes":
986
+ return {
987
+ key: "noUsableSandboxes",
988
+ data: {
989
+ requested: refusal.requested,
990
+ build: "resolvedBuild" in refusal.match ? refusal.match.resolvedBuild : refusal.match.requestedBuild
991
+ }
992
+ };
993
+ case "pull-request-unreadable":
994
+ case "pr-builds-unlisted":
995
+ case "pr-build-not-ready":
996
+ case "pr-build-expired":
997
+ return prBuildRefusalFacts(refusal);
998
+ }
999
+ },
1000
+ canceledLines: testserverPoolCanceledLines
1001
+ };
1002
+
1003
+ // src/resources/testserver/pull-request/live/github-rest.ts
1004
+ import { z as z8 } from "zod";
1005
+ var errorSchema2 = z8.object({ message: z8.string() });
1006
+ function headers(token) {
1007
+ return {
1008
+ accept: "application/vnd.github+json",
1009
+ authorization: `Bearer ${token}`,
1010
+ "x-github-api-version": "2022-11-28",
1011
+ "user-agent": "storm"
1012
+ };
1013
+ }
1014
+ function hideToken(text, token) {
1015
+ return token === "" ? text : text.replaceAll(token, "<token>");
1016
+ }
1017
+ async function getJson(options, token, path, schema4) {
1018
+ const signal = AbortSignal.timeout(options.timeoutMs);
1019
+ try {
1020
+ const response = await fetch(`${options.origin}/${path}`, { headers: headers(token), redirect: "manual", signal });
1021
+ const text = await response.text();
1022
+ if (response.status < 200 || response.status >= 300)
1023
+ return {
1024
+ ok: false,
1025
+ failure: statusFailure(response.status, hideToken(githubMessage(text, response.status), token))
1026
+ };
1027
+ let json;
1028
+ try {
1029
+ json = JSON.parse(text);
1030
+ } catch {
1031
+ return { ok: false, failure: { kind: "malformed", detail: "the answer isn't JSON" } };
1032
+ }
1033
+ const parsed = schema4.safeParse(json);
1034
+ if (!parsed.success) {
1035
+ const issue = parsed.error.issues[0];
1036
+ const where = issue === void 0 || issue.path.length === 0 ? "the answer" : issue.path.join(".");
1037
+ return {
1038
+ ok: false,
1039
+ failure: { kind: "malformed", detail: hideToken(`${where}: ${issue?.message ?? "unexpected"}`, token) }
1040
+ };
1041
+ }
1042
+ return { ok: true, value: parsed.data };
1043
+ } catch (error) {
1044
+ return { ok: false, failure: thrownFailure(error, signal, options, token) };
1045
+ }
1046
+ }
1047
+ async function getRedirectedText(options, token, path) {
1048
+ const signal = AbortSignal.timeout(options.timeoutMs);
1049
+ try {
1050
+ const response = await fetch(`${options.origin}/${path}`, { headers: headers(token), redirect: "manual", signal });
1051
+ if (response.status >= 200 && response.status < 300) return { ok: true, value: await response.text() };
1052
+ const location = response.headers.get("location");
1053
+ if (response.status < 300 || response.status >= 400 || location === null) {
1054
+ const text2 = await response.text();
1055
+ return {
1056
+ ok: false,
1057
+ failure: statusFailure(response.status, hideToken(githubMessage(text2, response.status), token))
1058
+ };
1059
+ }
1060
+ await response.body?.cancel().catch(() => {
1061
+ });
1062
+ const redirected = await fetch(location, { redirect: "follow", signal });
1063
+ const text = await redirected.text();
1064
+ if (!redirected.ok) return { ok: false, failure: statusFailure(redirected.status, `HTTP ${redirected.status}`) };
1065
+ return { ok: true, value: text };
1066
+ } catch (error) {
1067
+ return { ok: false, failure: thrownFailure(error, signal, options, token) };
1068
+ }
1069
+ }
1070
+ function statusFailure(status, message) {
1071
+ if (status === 404) return { kind: "not-found", status };
1072
+ if (status === 401 || status === 403) return { kind: "rejected", status, message };
1073
+ return { kind: "http-error", status, message };
1074
+ }
1075
+ function githubMessage(text, status) {
1076
+ try {
1077
+ const parsed = errorSchema2.safeParse(JSON.parse(text));
1078
+ if (parsed.success) return parsed.data.message;
1079
+ } catch {
1080
+ }
1081
+ return `HTTP ${status}`;
1082
+ }
1083
+ function thrownFailure(error, signal, options, token) {
1084
+ if (signal.aborted) return { kind: "timeout", seconds: options.timeoutMs / 1e3 };
1085
+ return { kind: "connect-failed", code: hideToken(errorCode(error), token) };
1086
+ }
1087
+ function errorCode(error) {
1088
+ if (!(error instanceof Error)) return String(error);
1089
+ const cause = error.cause;
1090
+ const code2 = typeof cause === "object" && cause !== null ? cause.code : void 0;
1091
+ return typeof code2 === "string" ? code2 : error.message;
1092
+ }
1093
+
1094
+ // src/resources/testserver/pull-request/live/github-token-gateway.ts
1095
+ import { execFile } from "node:child_process";
1096
+ var GH_TOKEN_TIMEOUT_MS = 5e3;
1097
+ function liveGitHubTokenGateway(options) {
1098
+ return {
1099
+ token: async () => {
1100
+ for (const origin of ["GITHUB_TOKEN", "GH_TOKEN"]) {
1101
+ const token2 = options.env[origin]?.trim();
1102
+ if (token2 !== void 0 && token2 !== "") return { token: token2, origin };
1103
+ }
1104
+ const token = await ghAuthToken(options.env);
1105
+ return token === void 0 ? void 0 : { token, origin: "gh auth token" };
1106
+ }
1107
+ };
1108
+ }
1109
+ function ghAuthToken(env) {
1110
+ return new Promise((resolve) => {
1111
+ try {
1112
+ execFile(
1113
+ "gh",
1114
+ ["auth", "token", "--hostname", "github.com"],
1115
+ { env: { ...env }, timeout: GH_TOKEN_TIMEOUT_MS, encoding: "utf8" },
1116
+ (error, stdout) => {
1117
+ const token = typeof stdout === "string" ? stdout.trim() : "";
1118
+ resolve(error === null && token !== "" ? token : void 0);
1119
+ }
1120
+ );
1121
+ } catch {
1122
+ resolve(void 0);
1123
+ }
1124
+ });
1125
+ }
1126
+
1127
+ // src/resources/testserver/pull-request/live/pull-request-gateway.ts
1128
+ import { z as z9 } from "zod";
1129
+ var pullSchema = z9.object({
1130
+ head: z9.object({ sha: z9.string().regex(/^[0-9a-f]{40}$/), ref: z9.string().min(1) }),
1131
+ state: z9.enum(["open", "closed"]),
1132
+ merged: z9.boolean()
1133
+ });
1134
+ function livePullRequestGateway(options) {
1135
+ return {
1136
+ head: async ({ repo, number, token }) => {
1137
+ const answered = await getJson(options, token, `repos/${repoPath2(repo)}/pulls/${number}`, pullSchema);
1138
+ if (!answered.ok) return answered;
1139
+ const { head, state, merged } = answered.value;
1140
+ return { ok: true, head: { headSha: head.sha, headRef: head.ref, state, merged } };
1141
+ }
1142
+ };
1143
+ }
1144
+ function repoPath2(repo) {
1145
+ return repo.split("/").map(encodeURIComponent).join("/");
1146
+ }
1147
+
1148
+ // src/resources/testserver/pull-request/live/testserver-workflow-gateway.ts
1149
+ import { z as z10 } from "zod";
1150
+ var TESTSERVER_WORKFLOW = "testserver-bundle-publish.yml";
1151
+ var BUNDLE_JOB = "Bundle & Publish";
1152
+ var RUNS_LISTED = 30;
1153
+ var BUNDLE_LINE = /📦 Bundle will be: builds\/pr-([1-9][0-9]*)\/([^\s/]+)/;
1154
+ var runsSchema = z10.object({
1155
+ workflow_runs: z10.array(
1156
+ z10.object({
1157
+ id: z10.number(),
1158
+ head_sha: z10.string().regex(/^[0-9a-f]{40}$/),
1159
+ created_at: z10.string().min(1)
1160
+ })
1161
+ )
1162
+ });
1163
+ var jobsSchema = z10.object({
1164
+ jobs: z10.array(z10.object({ id: z10.number(), name: z10.string(), conclusion: z10.string().nullable() }))
1165
+ });
1166
+ function liveTestserverWorkflowGateway(options) {
1167
+ return {
1168
+ runs: async ({ repo, branch, token }) => {
1169
+ const query = new URLSearchParams({ event: "pull_request", branch, per_page: String(RUNS_LISTED) });
1170
+ const answered = await getJson(
1171
+ options,
1172
+ token,
1173
+ `repos/${repoPath2(repo)}/actions/workflows/${TESTSERVER_WORKFLOW}/runs?${query.toString()}`,
1174
+ runsSchema
1175
+ );
1176
+ if (!answered.ok) return answered;
1177
+ const runs = answered.value.workflow_runs.map((run) => ({
1178
+ id: run.id,
1179
+ headSha: run.head_sha,
1180
+ createdAt: run.created_at
1181
+ }));
1182
+ return { ok: true, runs };
1183
+ },
1184
+ publishedBuild: async ({ repo, runId, token }) => {
1185
+ const jobs = await getJson(options, token, `repos/${repoPath2(repo)}/actions/runs/${runId}/jobs`, jobsSchema);
1186
+ if (!jobs.ok) return jobs;
1187
+ const job = jobs.value.jobs.find(({ name: name2 }) => name2 === BUNDLE_JOB);
1188
+ if (job === void 0 || job.conclusion !== "success") return { ok: true, build: void 0 };
1189
+ const log = await getRedirectedText(
1190
+ { origin: options.origin, timeoutMs: options.logTimeoutMs },
1191
+ token,
1192
+ `repos/${repoPath2(repo)}/actions/jobs/${job.id}/logs`
1193
+ );
1194
+ if (!log.ok) return log;
1195
+ const match = BUNDLE_LINE.exec(log.value);
1196
+ const [, pr, name] = match ?? [];
1197
+ return { ok: true, build: pr === void 0 || name === void 0 ? void 0 : { pr: Number(pr), name } };
1198
+ }
1199
+ };
1200
+ }
1201
+
1202
+ // src/resources/testserver/live/gateways.ts
1203
+ var TESTSERVER_ORIGIN = "https://testserver.vercel.sh";
1204
+ var GITHUB_API_ORIGIN2 = "https://api.github.com";
1205
+ function liveTestserverPoolGateways(host) {
1206
+ const directory = resolveStateDirectory(host.env, POOL_SUBPATH);
1207
+ return {
1208
+ controlPlane: liveControlPlaneGateway({
1209
+ origin: TESTSERVER_ORIGIN,
1210
+ streamTimeoutMs: 18e4,
1211
+ buildsTimeoutMs: 1e4
1212
+ }),
1213
+ healthChecks: liveHealthCheckGateway({ timeoutMs: 5e3 }),
1214
+ pool: directory.ok ? livePoolStoreGateway({ directory: directory.directory }) : unavailablePoolStoreGateway(POOL_DIRECTORY_PATTERN, directory.reason),
1215
+ timer: systemTimer,
1216
+ pullRequests: livePullRequestGateway({ origin: GITHUB_API_ORIGIN2, timeoutMs: 1e4 }),
1217
+ testserverWorkflow: liveTestserverWorkflowGateway({
1218
+ origin: GITHUB_API_ORIGIN2,
1219
+ timeoutMs: 1e4,
1220
+ logTimeoutMs: 3e4
1221
+ }),
1222
+ githubToken: liveGitHubTokenGateway({ env: host.env })
1223
+ };
1224
+ }
1225
+
1226
+ // src/resources/testserver/presentation.ts
1227
+ function seconds2(ms) {
1228
+ return secondsText(secondsOf(ms));
1229
+ }
1230
+ function line(text) {
1231
+ return { lane: "testserver", text };
1232
+ }
1233
+ function poolUpkeepTexts(report) {
1234
+ return [
1235
+ ...report.reclaimed.length === 0 ? [] : [`reclaimed ${count(report.reclaimed.length, "stale lease")}`],
1236
+ ...report.dropped.length === 0 ? [] : [`dropped ${count(report.dropped.length, "Testserver sandbox")} from the pool`],
1237
+ ...report.storeFailures.map(({ path, message }) => `a pool operation failed on ${path}: ${message}`)
1238
+ ];
1239
+ }
1240
+ function createFinishedText(event) {
1241
+ const which = `create ${event.index + 1} of ${event.count}`;
1242
+ const { outcome } = event;
1243
+ switch (outcome.kind) {
1244
+ case "pooled":
1245
+ return `${which} done: ${outcome.entry.testserverUrl}`;
1246
+ case "pool-write-failed":
1247
+ return `${which} done: ${outcome.entry.testserverUrl}, not added to the pool`;
1248
+ case "create-failed":
1249
+ return `${which} failed: ${describeCreateFailure(outcome.failure).text}`;
1250
+ }
1251
+ }
1252
+ function createProgressText(event) {
1253
+ return `create ${event.index + 1} of ${event.count}: ${event.message}`;
1254
+ }
1255
+ function unresolvedBuildText(event) {
1256
+ return `couldn't resolve ${event.channel} (${unresolvedWhy(event.reason)}); using Testserver sandboxes requested as ${event.channel}`;
1257
+ }
1258
+ function oldChannelResolutionText(event) {
1259
+ return event.ageMinutes < 0 ? `using ${event.channel}'s channel resolution, recorded later than now (noCreate)` : `using ${event.channel}'s channel resolution from ${age(event.ageMinutes)} ago (noCreate)`;
1260
+ }
1261
+ function prBuildResolvedText(event) {
1262
+ const pooled = event.from === "pool" ? " (from the pool)" : "";
1263
+ const merged = event.merged ? " (merged; latest_main or stable may have it)" : "";
1264
+ return `Build: ${TESTSERVER_REPO}#${event.pr} at ${shortSha(event.headSha)} \u2192 ${event.build}${pooled}${merged}`;
1265
+ }
1266
+ function unresolvedWhy(reason) {
1267
+ switch (reason.kind) {
1268
+ case "credential-failed": {
1269
+ const { cause } = describeCredentialFailure(reason.failure);
1270
+ return reason.failure.source === "mint" ? `couldn't mint a credential: ${cause}` : `couldn't request a GitHub Actions OIDC token: ${cause}`;
1271
+ }
1272
+ case "builds-failed":
1273
+ return `GET /builds failed: ${reason.failure.kind}`;
1274
+ case "no-build":
1275
+ return "the Testserver control plane names no build for it";
1276
+ case "not-recorded":
1277
+ return "no channel resolution is recorded, and noCreate doesn't ask the Testserver control plane";
1278
+ }
1279
+ }
1280
+ function age(minutes) {
1281
+ if (minutes < 60) return `${minutes}m`;
1282
+ if (minutes < 48 * 60) return `${Math.floor(minutes / 60)}h`;
1283
+ return `${Math.floor(minutes / (24 * 60))}d`;
1284
+ }
1285
+ function count(n, noun) {
1286
+ const plural = { "stale lease": "stale leases", "Testserver sandbox": "Testserver sandboxes" }[noun];
1287
+ return `${n} ${n === 1 ? noun : plural}`;
1288
+ }
1289
+ function onBuild(testserver) {
1290
+ return testserver.build === void 0 ? "" : ` on ${testserver.build}`;
1291
+ }
1292
+ function reusedCount(testserver) {
1293
+ return testserver.sandboxes.filter(({ origin }) => origin === "reused").length;
1294
+ }
1295
+ function originCounts(testserver) {
1296
+ const reused = reusedCount(testserver);
1297
+ return `${reused} reused, ${testserver.sandboxes.length - reused} created`;
1298
+ }
1299
+ function leasingText(testserver) {
1300
+ return testserver.requested === void 0 ? "resolving the build" : `leasing ${testserver.requested}${onBuild(testserver)}`;
1301
+ }
1302
+ function createsText(creates, paint2) {
1303
+ const failed = creates.failed === 0 ? "" : ` \xB7 ${paint2.failed(`${creates.failed} failed`)}`;
1304
+ return `creating ${creates.count} \xB7 ${creates.started} started \xB7 ${creates.finished - creates.failed} done${failed}`;
1305
+ }
1306
+ function creating(testserver) {
1307
+ const { creates } = testserver;
1308
+ return creates !== void 0 && creates.finished < creates.count && testserver.status === "running";
1309
+ }
1310
+ function testserverOutcome(testserver) {
1311
+ const counts = `${originCounts(testserver)}${onBuild(testserver)}`;
1312
+ return testserver.status === "done" ? counts : `${counts} \xB7 ${testserver.status}`;
1313
+ }
1314
+ function sandboxLines(testserver, draw) {
1315
+ return testserver.sandboxes.map(
1316
+ ({ testserverUrl, logViewerUrl }) => draw.line(` ${sandboxName(testserverUrl)} ${draw.paint.faint("logs")} ${logViewerUrl}`)
1317
+ );
1318
+ }
1319
+ function sandboxName(testserverUrl) {
1320
+ try {
1321
+ return new URL(testserverUrl).hostname.split(".")[0] ?? testserverUrl;
1322
+ } catch {
1323
+ return testserverUrl;
1324
+ }
1325
+ }
1326
+ var testserverPoolPresentation = {
1327
+ plain: ({ verbose }) => {
1328
+ let leasingAt;
1329
+ return (event, now) => {
1330
+ switch (event.kind) {
1331
+ case "build-unresolved":
1332
+ return [line(unresolvedBuildText(event))];
1333
+ case "old-channel-resolution":
1334
+ return [line(oldChannelResolutionText(event))];
1335
+ case "pr-build-resolved":
1336
+ return [line(prBuildResolvedText(event))];
1337
+ case "leasing":
1338
+ leasingAt = now;
1339
+ return [];
1340
+ case "leased": {
1341
+ const { report, requested } = event;
1342
+ const build = "resolvedBuild" in event.match ? event.match.resolvedBuild : event.match.requestedBuild;
1343
+ return [
1344
+ ...poolUpkeepTexts(report).map(line),
1345
+ line(
1346
+ `leased ${report.leased.length} of ${count(requested, "Testserver sandbox")} from the pool on ${build} (${seconds2(now - (leasingAt ?? now))})`
1347
+ )
1348
+ ];
1349
+ }
1350
+ case "creating":
1351
+ return [line(`creating ${count(event.count, "Testserver sandbox")} on ${event.build}\u2026`)];
1352
+ case "create-started":
1353
+ return [line(`create ${event.index + 1} of ${event.count} started`)];
1354
+ case "create-progress":
1355
+ return verbose ? [line(createProgressText(event))] : [];
1356
+ case "create-finished":
1357
+ return [line(createFinishedText(event))];
1358
+ case "sandbox-list":
1359
+ return event.sandboxes.map(
1360
+ ({ testserverUrl, logViewerUrl, origin }) => line(`${testserverUrl} logs ${logViewerUrl} (${origin})`)
1361
+ );
1362
+ }
1363
+ };
1364
+ },
1365
+ notices: (event, { verbose }) => {
1366
+ switch (event.kind) {
1367
+ case "build-unresolved":
1368
+ return [line(unresolvedBuildText(event))];
1369
+ case "old-channel-resolution":
1370
+ return [line(oldChannelResolutionText(event))];
1371
+ case "pr-build-resolved":
1372
+ return [line(prBuildResolvedText(event))];
1373
+ case "leased":
1374
+ return poolUpkeepTexts(event.report).map(line);
1375
+ case "create-finished":
1376
+ return event.outcome.kind === "create-failed" ? [line(createFinishedText(event))] : [];
1377
+ case "create-progress":
1378
+ return verbose ? [line(createProgressText(event))] : [];
1379
+ case "leasing":
1380
+ case "creating":
1381
+ case "create-started":
1382
+ case "sandbox-list":
1383
+ return [];
1384
+ }
1385
+ },
1386
+ release: (leases, tense) => {
1387
+ const verb = tense === "doing" ? "releasing" : "released";
1388
+ return leases === void 0 ? `${verb} the leases` : `${verb} ${leases} ${leases === 1 ? "lease" : "leases"}`;
1389
+ },
1390
+ lane: {
1391
+ label: "testserver-setup",
1392
+ steps: ["lease", "create"],
1393
+ lanesRow: (testserver, draw, run) => {
1394
+ if (testserver === void 0) return { text: "", right: "" };
1395
+ const text = run.stopping && testserver.status === "running" ? "stopping" : testserver.status !== "running" ? testserverOutcome(testserver) : creating(testserver) && testserver.creates !== void 0 ? createsText(testserver.creates, draw.paint) : leasingText(testserver);
1396
+ const waiting = testserver.status === "done" && run.runnerRunning && testserver.endedAt !== void 0 && draw.now !== void 0 ? `${draw.paint.faint(`waiting for runner +${seconds2(draw.now - testserver.endedAt)}`)} ` : "";
1397
+ return { text, right: `${waiting}${draw.elapsed(testserver.startedAt, testserver.endedAt)}` };
1398
+ },
1399
+ localRow: (testserver, draw) => ({
1400
+ text: testserver.status !== "running" ? testserverOutcome(testserver) : testserver.creates === void 0 ? leasingText(testserver) : `${reusedCount(testserver)} reused, creating ${testserver.creates.count}${onBuild(testserver)}`,
1401
+ ...creating(testserver) && testserver.creates !== void 0 ? { below: createsText(testserver.creates, draw.paint) } : {}
1402
+ }),
1403
+ record: (testserver, draw) => ({ text: testserverOutcome(testserver), lines: sandboxLines(testserver, draw) })
1404
+ }
1405
+ };
1406
+
1407
+ // src/resources/testserver/lane.ts
1408
+ var testserverPoolLane = {
1409
+ resource: "testserverPool",
1410
+ lane: "testserver",
1411
+ start: (startedAt) => ({
1412
+ status: "running",
1413
+ startedAt,
1414
+ endedAt: void 0,
1415
+ build: void 0,
1416
+ requested: void 0,
1417
+ sandboxes: [],
1418
+ creates: void 0,
1419
+ steps: { lease: void 0, create: void 0 }
1420
+ }),
1421
+ apply: (testserver, event, at) => applyTestserverEvent(testserver, event, at),
1422
+ ended: (testserver, outcome, at) => {
1423
+ const status = outcome === "ready" ? "done" : outcome;
1424
+ const settle = (span) => settled2(span, outcome, status, at);
1425
+ return {
1426
+ ...testserver,
1427
+ status,
1428
+ endedAt: at,
1429
+ steps: { lease: settle(testserver.steps.lease), create: settle(testserver.steps.create) }
1430
+ };
1431
+ },
1432
+ row: (testserver) => {
1433
+ const reused = testserver.sandboxes.filter(({ origin }) => origin === "reused").length;
1434
+ const { lease, create } = testserver.steps;
1435
+ return {
1436
+ steps: [
1437
+ ...lease === void 0 ? [] : [{ name: "lease", span: lease }],
1438
+ ...create === void 0 ? [] : [{ name: "create", span: create }]
1439
+ ],
1440
+ sandboxes: { reused, created: testserver.sandboxes.length - reused }
1441
+ };
1442
+ }
1443
+ };
1444
+ function applyTestserverEvent(testserver, event, at) {
1445
+ switch (event.kind) {
1446
+ // Resolving the build is part of the lane, but changes nothing it shows.
1447
+ case "build-unresolved":
1448
+ case "old-channel-resolution":
1449
+ case "pr-build-resolved":
1450
+ case "create-progress":
1451
+ return testserver;
1452
+ case "leasing":
1453
+ return {
1454
+ ...testserver,
1455
+ build: buildName(event.match),
1456
+ requested: event.requested,
1457
+ steps: { ...testserver.steps, lease: { status: "running", startedAt: at, endedAt: void 0 } }
1458
+ };
1459
+ case "leased":
1460
+ return {
1461
+ ...testserver,
1462
+ sandboxes: event.report.leased.map(({ entry }) => ({
1463
+ testserverUrl: entry.testserverUrl,
1464
+ logViewerUrl: entry.logViewerUrl,
1465
+ origin: "reused"
1466
+ })),
1467
+ steps: { ...testserver.steps, lease: ended(testserver.steps.lease, "done", at) }
1468
+ };
1469
+ case "creating":
1470
+ return {
1471
+ ...testserver,
1472
+ creates: { count: event.count, started: 0, finished: 0, failed: 0 },
1473
+ steps: { ...testserver.steps, create: { status: "running", startedAt: at, endedAt: void 0 } }
1474
+ };
1475
+ case "create-started":
1476
+ return {
1477
+ ...testserver,
1478
+ creates: testserver.creates === void 0 ? void 0 : { ...testserver.creates, started: testserver.creates.started + 1 }
1479
+ };
1480
+ case "create-finished": {
1481
+ const { outcome } = event;
1482
+ const creates = testserver.creates === void 0 ? void 0 : {
1483
+ ...testserver.creates,
1484
+ finished: testserver.creates.finished + 1,
1485
+ failed: testserver.creates.failed + (outcome.kind === "create-failed" ? 1 : 0)
1486
+ };
1487
+ const create = testserver.steps.create;
1488
+ return {
1489
+ ...testserver,
1490
+ sandboxes: outcome.kind === "create-failed" ? testserver.sandboxes : [
1491
+ ...testserver.sandboxes,
1492
+ {
1493
+ testserverUrl: outcome.entry.testserverUrl,
1494
+ logViewerUrl: outcome.entry.logViewerUrl,
1495
+ origin: "created"
1496
+ }
1497
+ ],
1498
+ creates,
1499
+ steps: {
1500
+ ...testserver.steps,
1501
+ // The create step ends with the last create; until then it runs, its end at the latest create's.
1502
+ create: create === void 0 ? void 0 : {
1503
+ ...create,
1504
+ endedAt: at,
1505
+ status: creates !== void 0 && creates.finished >= creates.count ? "done" : create.status
1506
+ }
1507
+ }
1508
+ };
1509
+ }
1510
+ case "sandbox-list":
1511
+ return {
1512
+ ...testserver,
1513
+ sandboxes: event.sandboxes.map(({ testserverUrl, logViewerUrl, origin }) => ({
1514
+ testserverUrl,
1515
+ logViewerUrl,
1516
+ origin
1517
+ }))
1518
+ };
1519
+ }
1520
+ }
1521
+ function settled2(span, outcome, status, at) {
1522
+ return outcome === "ready" || span === void 0 || span.status !== "running" ? span : ended(span, status, at);
1523
+ }
1524
+ function ended(span, status, at) {
1525
+ return span === void 0 ? void 0 : { ...span, status, endedAt: at };
1526
+ }
1527
+ function buildName(match) {
1528
+ return "resolvedBuild" in match ? match.resolvedBuild : match.requestedBuild;
1529
+ }
1530
+
1531
+ // src/resources/testserver/provider.ts
1532
+ var testserverPoolRunProvider = {
1533
+ name: "testserverPool",
1534
+ lane: "testserver",
1535
+ requested: (request) => request,
1536
+ prepare: async (context) => {
1537
+ const prepared = await context.pool.prepare();
1538
+ return prepared.ok ? void 0 : { kind: "pool-unavailable", failure: prepared.failure };
1539
+ },
1540
+ acquire: async ({ context, request, signal, progress, owned, credential }) => {
1541
+ const provisioned = await provision(context, request, createWith(request, credential), signal, progress, owned);
1542
+ if (provisioned.kind === "canceled") {
1543
+ const { kind: _kind2, ...facts2 } = provisioned;
1544
+ return { kind: "canceled", facts: facts2 };
1545
+ }
1546
+ if (provisioned.kind === "mint-failed") return provisioned;
1547
+ if (provisioned.kind !== "provisioned") return { kind: "refused", refusal: provisioned };
1548
+ const { kind: _kind, ...facts } = provisioned;
1549
+ return { kind: "acquired", connection: facts.sandboxes, facts };
1550
+ },
1551
+ ready: async ({ connection, progress }) => {
1552
+ await progress.emit({ kind: "sandbox-list", sandboxes: connection });
1553
+ },
1554
+ // The leases it holds, as its presentation counts them.
1555
+ holding: (owned) => owned.length === 0 ? void 0 : owned.length,
1556
+ release: async (context, owned) => ({ releaseFailures: await releaseLeases(context, owned) }),
1557
+ failures: (cleanup) => cleanup.releaseFailures.length,
1558
+ payload: (sandboxes) => ({
1559
+ sandboxes: [...new Set(sandboxes.map((sandbox) => sandbox.testserverUrl))].map((url) => ({ url }))
1560
+ }),
1561
+ canceledFacts: (request, facts) => {
1562
+ const ttlMinutes = request.provisioning.kind === "create" ? request.provisioning.ttlMinutes : void 0;
1563
+ if (facts !== void 0) return canceledAfter(facts, ttlMinutes);
1564
+ return { pooled: 0, unpooled: [], failedCreates: [], ttlMinutes };
1565
+ }
1566
+ };
1567
+ function createWith(request, credential) {
1568
+ const { provisioning } = request;
1569
+ if (provisioning.kind === "no-create") return void 0;
1570
+ if (credential === void 0)
1571
+ throw new Error("A Testserver pool that creates takes the credential, so its run settles a credential choice.");
1572
+ return { source: credential, ttlMinutes: provisioning.ttlMinutes };
1573
+ }
1574
+ function credentialFailed(failure, ttlMinutes, failedCreates) {
1575
+ return failure.source === "mint" ? { kind: "mint-failed", failure: failure.failure, target: failure.target } : { kind: "token-request-failed", failure: failure.failure, ttlMinutes, failedCreates };
1576
+ }
1577
+ function canceledAfter(facts, ttlMinutes) {
1578
+ const created = facts.sandboxes.filter((sandbox) => sandbox.origin === "created").length;
1579
+ return {
1580
+ pooled: created - facts.unpooled.length,
1581
+ unpooled: facts.unpooled,
1582
+ failedCreates: facts.failedCreates,
1583
+ ttlMinutes
1584
+ };
1585
+ }
1586
+ async function provision(context, request, create, signal, progress, held) {
1587
+ let tally = { created: [], failedCreates: [], unpooled: [] };
1588
+ const canceled = () => ({
1589
+ kind: "canceled",
1590
+ pooled: tally.created.length - tally.unpooled.length,
1591
+ unpooled: tally.unpooled,
1592
+ failedCreates: tally.failedCreates,
1593
+ ttlMinutes: create?.ttlMinutes
1594
+ });
1595
+ if (signal.aborted) return canceled();
1596
+ const reference = parseBuildReference(request.build);
1597
+ let resolution;
1598
+ if (reference.ok && reference.reference.kind === "pull-request") {
1599
+ const resolved = await resolvePullRequestBuild(context, reference.reference.number, progress);
1600
+ if (resolved.kind !== "resolved") return resolved;
1601
+ resolution = resolved.resolution;
1602
+ } else {
1603
+ resolution = await resolveBuild(context, { build: request.build, credential: create?.source });
1604
+ if (resolution.kind === "as-written")
1605
+ await progress.emit({ kind: "build-unresolved", channel: resolution.channel, reason: resolution.reason });
1606
+ if (resolution.kind === "old-channel-resolution")
1607
+ await progress.emit({
1608
+ kind: "old-channel-resolution",
1609
+ channel: resolution.channel,
1610
+ build: resolution.build,
1611
+ ageMinutes: minutesSince(resolution.learnedAt, context.clock.now())
1612
+ });
1613
+ }
1614
+ if (signal.aborted) return canceled();
1615
+ const match = buildMatch(resolution);
1616
+ await progress.emit({ kind: "leasing", match, requested: request.sandboxes });
1617
+ const leasedOutcome = await leaseUsable(context, {
1618
+ match,
1619
+ count: request.sandboxes,
1620
+ minTimeLeftMinutes: request.minTimeLeftMinutes
1621
+ });
1622
+ if (!leasedOutcome.ok) return { kind: "pool-unreadable", failure: leasedOutcome.failure };
1623
+ const { report } = leasedOutcome;
1624
+ held.push(...report.leased.map(({ host }) => host));
1625
+ await progress.emit({ kind: "leased", match, requested: request.sandboxes, report });
1626
+ const reused = report.leased.map(({ entry }) => ({
1627
+ testserverUrl: entry.testserverUrl,
1628
+ logViewerUrl: entry.logViewerUrl,
1629
+ origin: "reused"
1630
+ }));
1631
+ let uncreated;
1632
+ let notCreated = 0;
1633
+ const missing = request.sandboxes - reused.length;
1634
+ if (missing > 0 && create === void 0) {
1635
+ if (reused.length === 0) return { kind: "no-usable-sandboxes", requested: request.sandboxes, match };
1636
+ notCreated = missing;
1637
+ } else if (missing > 0 && create !== void 0) {
1638
+ if (signal.aborted) return canceled();
1639
+ const { rejected, credentialFailure, uncreatedCount, ...made } = await createMissing(
1640
+ context,
1641
+ {
1642
+ source: create.source,
1643
+ target: createTarget(request.build, resolution),
1644
+ ttlMinutes: create.ttlMinutes,
1645
+ count: missing
1646
+ },
1647
+ signal,
1648
+ progress,
1649
+ held
1650
+ );
1651
+ tally = made;
1652
+ if (rejected !== void 0)
1653
+ return {
1654
+ kind: "credential-rejected",
1655
+ failure: rejected.failure,
1656
+ origin: create.source.origin(rejected.credential),
1657
+ ttlMinutes: create.ttlMinutes,
1658
+ failedCreates: tally.failedCreates,
1659
+ unpooled: tally.unpooled
1660
+ };
1661
+ if (signal.aborted) return canceled();
1662
+ if (credentialFailure !== void 0) {
1663
+ if (reused.length === 0 && tally.created.length === 0)
1664
+ return credentialFailed(credentialFailure, create.ttlMinutes, tally.failedCreates);
1665
+ uncreated = { count: uncreatedCount, failure: credentialFailure };
1666
+ }
1667
+ if (reused.length === 0 && tally.created.length === 0)
1668
+ return {
1669
+ kind: "no-sandboxes",
1670
+ requested: request.sandboxes,
1671
+ ttlMinutes: create.ttlMinutes,
1672
+ failedCreates: tally.failedCreates
1673
+ };
1674
+ }
1675
+ const sandboxes = [...reused, ...tally.created];
1676
+ if (signal.aborted) return canceled();
1677
+ return {
1678
+ kind: "provisioned",
1679
+ resolution,
1680
+ sandboxes,
1681
+ failedCreates: tally.failedCreates,
1682
+ unpooled: tally.unpooled,
1683
+ uncreated,
1684
+ notCreated
1685
+ };
1686
+ }
1687
+ async function resolvePullRequestBuild(context, pr, progress) {
1688
+ const outcome = await resolvePrBuild(context, { pr });
1689
+ if (!outcome.ok) return outcome.refusal;
1690
+ const { resolution } = outcome;
1691
+ const { headSha, build, merged, from } = resolution;
1692
+ await progress.emit({ kind: "pr-build-resolved", pr, headSha, build, merged, from });
1693
+ return { kind: "resolved", resolution };
1694
+ }
1695
+ function createTarget(requestedBuild, resolution) {
1696
+ return resolution.kind === "pull-request" ? { build: resolution.build, requestedBuild, headSha: resolution.headSha } : { build: requestedBuild, requestedBuild };
1697
+ }
1698
+ async function createMissing(context, request, signal, progress, held) {
1699
+ const { source, target, ttlMinutes, count: count2 } = request;
1700
+ const first = await source.get();
1701
+ if (!first.ok)
1702
+ return {
1703
+ created: [],
1704
+ failedCreates: [],
1705
+ unpooled: [],
1706
+ rejected: void 0,
1707
+ credentialFailure: first.failure,
1708
+ uncreatedCount: count2
1709
+ };
1710
+ await progress.emit({ kind: "creating", count: count2, build: target.build });
1711
+ let rejected;
1712
+ let credentialFailure;
1713
+ const mayCreate = () => rejected === void 0 && credentialFailure === void 0 && !signal.aborted;
1714
+ const outcomes = await runLimited(
1715
+ count2,
1716
+ CREATE_CONCURRENCY,
1717
+ mayCreate,
1718
+ async (index) => {
1719
+ const got = await source.get();
1720
+ if (!got.ok) {
1721
+ credentialFailure ??= got.failure;
1722
+ return void 0;
1723
+ }
1724
+ if (!mayCreate()) return void 0;
1725
+ const { credential } = got;
1726
+ await progress.emit({ kind: "create-started", index, count: count2 });
1727
+ const outcome = await createPooledSandbox(
1728
+ context,
1729
+ { credential, ...target, ttlMinutes, lease: true },
1730
+ { onProgress: (message) => progress.emit({ kind: "create-progress", index, count: count2, message }) }
1731
+ );
1732
+ if (outcome.kind === "pooled") held.push(outcome.host);
1733
+ if (outcome.kind === "create-failed" && outcome.failure.kind === "rejected")
1734
+ rejected ??= { failure: outcome.failure, credential };
1735
+ await progress.emit({ kind: "create-finished", index, count: count2, outcome });
1736
+ return outcome;
1737
+ }
1738
+ );
1739
+ const created = [];
1740
+ const failedCreates = [];
1741
+ const unpooled = [];
1742
+ let uncreatedCount = 0;
1743
+ for (const outcome of outcomes) {
1744
+ if (outcome === void 0) {
1745
+ uncreatedCount += 1;
1746
+ continue;
1747
+ }
1748
+ if (outcome.kind === "create-failed") {
1749
+ const { failure } = outcome;
1750
+ if (failure.kind !== "rejected") failedCreates.push(failure);
1751
+ continue;
1752
+ }
1753
+ const { testserverUrl, logViewerUrl } = outcome.entry;
1754
+ created.push({ testserverUrl, logViewerUrl, origin: "created" });
1755
+ if (outcome.kind === "pool-write-failed") unpooled.push({ testserverUrl, failure: outcome.failure });
1756
+ }
1757
+ return { created, failedCreates, unpooled, rejected, credentialFailure, uncreatedCount };
1758
+ }
1759
+
1760
+ // src/resources/testserver/run-sandbox.ts
1761
+ var STALE_TESTSERVER_VARIABLES = ["TESTSERVER_BASES", "TESTSERVER_BASE"];
1762
+
1763
+ // src/resources/testserver/resource-provider.ts
1764
+ var testserverPoolProvider = {
1765
+ name: "testserverPool",
1766
+ run: testserverPoolRunProvider,
1767
+ command: testserverPoolCommand,
1768
+ config: testserverPoolConfig,
1769
+ cleanup: testserverPoolCleanupReport,
1770
+ ran: testserverPoolRanReport,
1771
+ lane: testserverPoolLane,
1772
+ presentation: testserverPoolPresentation,
1773
+ liveGateways: liveTestserverPoolGateways,
1774
+ hostVariablesToDrop: STALE_TESTSERVER_VARIABLES,
1775
+ runnerResources: ({ sandboxes }) => ({ testserverPool: { sandboxes } }),
1776
+ commands: testserverPoolCommandTree
1777
+ };
1778
+
1779
+ // src/resources.ts
1780
+ var PROVIDERS = [githubFixtureRepoProvider, testserverPoolProvider];
1781
+ var PROVIDER_LIST = PROVIDERS;
1782
+ var RESOURCES = PROVIDERS.map(({ run }) => run);
1783
+ var RESOURCE_LANES = PROVIDERS.flatMap(
1784
+ ({ lane }) => lane === void 0 ? [] : [lane]
1785
+ );
1786
+ var RESOURCE_CONFIGS = PROVIDERS.map(
1787
+ ({ config }) => config
1788
+ );
1789
+ var RESOURCE_REPORTS = resourceReports(PROVIDER_LIST);
1790
+ var RESOURCE_PRESENTATIONS = resourcePresentations(PROVIDER_LIST);
1791
+ var RUN_CLEANUP = runCleanupOf(RESOURCE_REPORTS);
1792
+ var REFUSALS = RUN_CLEANUP.withCleanup(combineErrors(PROVIDERS.map(({ command }) => command.refusalErrors)));
1793
+ var RESOURCE_ERRORS = combineErrors([
1794
+ combineErrors(PROVIDERS.map(({ command }) => command.errors)),
1795
+ REFUSALS.errors
1796
+ ]);
1797
+ var BOUND = bindCommands(PROVIDER_LIST);
1798
+ var RESOURCE_COMMANDS = {
1799
+ ...BOUND,
1800
+ refusedError: (outcome, cleanup) => REFUSALS.build(BOUND.refusalFacts(outcome), cleanup)
1801
+ };
1802
+ function liveResourceGateways(host) {
1803
+ let gateways = {};
1804
+ for (const provider of PROVIDERS) gateways = { ...gateways, ...provider.liveGateways(host) };
1805
+ return gateways;
1806
+ }
1807
+ function applyStormRunEvent(state, timed) {
1808
+ return applyRunEvent(RESOURCE_LANES, state, timed);
1809
+ }
1810
+ function stormTimeline(state) {
1811
+ return timeline(RESOURCE_LANES, state);
1812
+ }
1813
+
1814
+ export {
1815
+ sandboxPage,
1816
+ snapshotPage,
1817
+ seconds,
1818
+ keepTimeText,
1819
+ isoSecondsText,
1820
+ short,
1821
+ shortFile,
1822
+ median,
1823
+ paint,
1824
+ visibleLength,
1825
+ truncate,
1826
+ spread,
1827
+ notStoppedText,
1828
+ notDeletedText,
1829
+ keptText,
1830
+ notKeptText,
1831
+ runnerCleanupWarnings,
1832
+ RESOURCES,
1833
+ RESOURCE_CONFIGS,
1834
+ RESOURCE_REPORTS,
1835
+ RESOURCE_PRESENTATIONS,
1836
+ RUN_CLEANUP,
1837
+ RESOURCE_ERRORS,
1838
+ RESOURCE_COMMANDS,
1839
+ liveResourceGateways,
1840
+ applyStormRunEvent,
1841
+ stormTimeline
1842
+ };