@testsprite/testsprite-cli 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +39 -30
  2. package/dist/commands/agent.js +44 -42
  3. package/dist/commands/doctor.d.ts +1 -1
  4. package/dist/commands/doctor.js +4 -7
  5. package/dist/commands/project.js +3 -2
  6. package/dist/commands/schedule.d.ts +120 -0
  7. package/dist/commands/schedule.js +487 -0
  8. package/dist/commands/test.d.ts +55 -1
  9. package/dist/commands/test.js +714 -183
  10. package/dist/commands/testlist.d.ts +88 -0
  11. package/dist/commands/testlist.js +747 -0
  12. package/dist/index.js +6 -2
  13. package/dist/lib/agent-targets.d.ts +13 -4
  14. package/dist/lib/agent-targets.js +11 -2
  15. package/dist/lib/conflict-reason.d.ts +30 -0
  16. package/dist/lib/conflict-reason.js +45 -0
  17. package/dist/lib/credentials.js +42 -1
  18. package/dist/lib/cron.d.ts +40 -0
  19. package/dist/lib/cron.js +190 -0
  20. package/dist/lib/dry-run/samples.js +177 -55
  21. package/dist/lib/errors.d.ts +9 -0
  22. package/dist/lib/errors.js +11 -0
  23. package/dist/lib/gh-output.d.ts +51 -4
  24. package/dist/lib/gh-output.js +149 -19
  25. package/dist/lib/http.d.ts +25 -0
  26. package/dist/lib/http.js +201 -3
  27. package/dist/lib/junit-report.d.ts +20 -2
  28. package/dist/lib/junit-report.js +38 -5
  29. package/dist/lib/poll.js +72 -36
  30. package/dist/lib/proxy.d.ts +16 -0
  31. package/dist/lib/proxy.js +19 -1
  32. package/dist/lib/response-schemas.d.ts +7 -0
  33. package/dist/lib/response-schemas.js +46 -14
  34. package/dist/lib/runs.types.d.ts +8 -3
  35. package/dist/lib/secret-file.d.ts +15 -0
  36. package/dist/lib/secret-file.js +82 -0
  37. package/dist/lib/target-url-preflight.d.ts +91 -0
  38. package/dist/lib/target-url-preflight.js +259 -0
  39. package/dist/lib/target-url.d.ts +22 -5
  40. package/dist/lib/target-url.js +60 -28
  41. package/dist/lib/testlist.types.d.ts +77 -0
  42. package/dist/lib/testlist.types.js +9 -0
  43. package/dist/lib/v3-advisory.d.ts +37 -4
  44. package/dist/lib/v3-advisory.js +47 -4
  45. package/dist/lib/wait-exit.d.ts +29 -0
  46. package/dist/lib/wait-exit.js +103 -0
  47. package/dist/version-guard.d.ts +10 -7
  48. package/dist/version-guard.js +37 -9
  49. package/dist/version.d.ts +1 -1
  50. package/dist/version.js +1 -1
  51. package/package.json +2 -1
@@ -0,0 +1,747 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { Command } from 'commander';
3
+ import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
4
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, localValidationError, } from '../lib/errors.js';
5
+ import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, } from '../lib/http.js';
6
+ import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
7
+ import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
8
+ import { emitCiArtifacts, summarizeAcceptedPayload } from '../lib/gh-output.js';
9
+ import { describeConflict, summarizeConflicts } from '../lib/conflict-reason.js';
10
+ import { createTicker } from '../lib/ticker.js';
11
+ import { buildJUnitReport, parseJUnitReportFormat, writeJUnitReportFile, } from '../lib/junit-report.js';
12
+ import { renderTextTable, resolveTextColumns } from '../lib/text-table.js';
13
+ import { assertIdempotencyKey } from '../lib/validate.js';
14
+ import { resolveWaitFailure } from '../lib/wait-exit.js';
15
+ // ── helpers ──────────────────────────────────────────────────────────────────
16
+ function resolveCommonOptions(command) {
17
+ const g = command.optsWithGlobals();
18
+ return {
19
+ profile: g.profile ?? 'default',
20
+ output: resolveOutputMode(g.output),
21
+ endpointUrl: g.endpointUrl,
22
+ debug: g.debug ?? false,
23
+ verbose: g.verbose ?? false,
24
+ dryRun: g.dryRun ?? false,
25
+ requestTimeoutMs: parseRequestTimeoutFlag(g.requestTimeout),
26
+ };
27
+ }
28
+ function makeClient(opts, deps) {
29
+ return makeHttpClient(opts, {
30
+ env: deps.env,
31
+ credentialsPath: deps.credentialsPath,
32
+ fetchImpl: deps.fetchImpl,
33
+ stderr: deps.stderr,
34
+ });
35
+ }
36
+ function makeOutput(mode, deps) {
37
+ return new Output(mode, { stdout: deps.stdout, stderr: deps.stderr });
38
+ }
39
+ function emitIdempotencyKey(opts, deps, key, supplied) {
40
+ if (supplied === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
41
+ const stderr = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
42
+ stderr(`idempotency-key: ${key}`);
43
+ }
44
+ }
45
+ /**
46
+ * Parse a repeatable `--project-env <projectId>:<environmentName>` flag. Splits
47
+ * on the FIRST `:` so an environment name containing `:` still round-trips
48
+ * (project ids are UUIDs and never contain one). Raises a typed
49
+ * VALIDATION_ERROR (exit 5) on a malformed pair.
50
+ */
51
+ function parseProjectEnvs(pairs) {
52
+ if (pairs === undefined || pairs.length === 0)
53
+ return undefined;
54
+ return pairs.map(raw => {
55
+ const idx = raw.indexOf(':');
56
+ if (idx <= 0 || idx === raw.length - 1) {
57
+ throw localValidationError('project-env', 'expected <projectId>:<environmentName>', raw);
58
+ }
59
+ return { projectId: raw.slice(0, idx), environmentName: raw.slice(idx + 1) };
60
+ });
61
+ }
62
+ const collectRepeatable = (value, acc) => [...acc, value];
63
+ function dryRunStderr(deps) {
64
+ return deps.stderr ?? (line => process.stderr.write(`${line}\n`));
65
+ }
66
+ // Canned `--dry-run` samples (offline, no network) — the global `--dry-run`
67
+ // contract promises a shape-accurate sample for every command.
68
+ const DRY_RUN_LIST = {
69
+ id: 'tl_dryrun',
70
+ name: 'dry-run test list',
71
+ orgId: 'org_dryrun',
72
+ caseCount: 0,
73
+ projectEnvironments: [],
74
+ lastExecutionId: null,
75
+ createdAt: '2026-05-16T00:00:00.000Z',
76
+ updatedAt: '2026-05-16T00:00:00.000Z',
77
+ };
78
+ const DRY_RUN_DETAIL = {
79
+ ...DRY_RUN_LIST,
80
+ cases: [],
81
+ stats: { total: 0, passed: 0, failed: 0, blocked: 0, running: 0 },
82
+ lastExecutionCreated: null,
83
+ };
84
+ // ── run functions (called directly by tests) ─────────────────────────────────
85
+ export async function runTestlistList(opts, deps = {}) {
86
+ const out = makeOutput(opts.output, deps);
87
+ if (opts.output === 'text' && opts.columns !== undefined) {
88
+ resolveTextColumns(opts.columns, TESTLIST_COLUMNS); // validate up front (exit 5 on a bad key)
89
+ }
90
+ if (opts.dryRun) {
91
+ emitDryRunBanner(dryRunStderr(deps));
92
+ out.print([DRY_RUN_LIST], data => renderTestListListText(data, opts));
93
+ return [DRY_RUN_LIST];
94
+ }
95
+ const client = makeClient(opts, deps);
96
+ const resp = await client.get('/testlist');
97
+ out.print(resp.items, data => renderTestListListText(data, opts));
98
+ return resp.items;
99
+ }
100
+ export async function runTestlistGet(opts, deps = {}) {
101
+ const out = makeOutput(opts.output, deps);
102
+ if (opts.dryRun) {
103
+ emitDryRunBanner(dryRunStderr(deps));
104
+ out.print(DRY_RUN_DETAIL, data => renderTestListDetailText(data));
105
+ return DRY_RUN_DETAIL;
106
+ }
107
+ const client = makeClient(opts, deps);
108
+ const detail = await client.get(`/testlist/${encodeURIComponent(opts.listId)}`);
109
+ out.print(detail, data => renderTestListDetailText(data));
110
+ return detail;
111
+ }
112
+ export async function runTestlistCreate(opts, deps = {}) {
113
+ const out = makeOutput(opts.output, deps);
114
+ if (opts.name === undefined || opts.name.trim() === '') {
115
+ throw localValidationError('name', 'is required');
116
+ }
117
+ if (opts.idempotencyKey !== undefined)
118
+ assertIdempotencyKey(opts.idempotencyKey);
119
+ const projectEnvironments = parseProjectEnvs(opts.projectEnv);
120
+ const idempotencyKey = opts.idempotencyKey ?? `cli-testlist-create-${randomUUID()}`;
121
+ emitIdempotencyKey(opts, deps, idempotencyKey, opts.idempotencyKey);
122
+ if (opts.dryRun) {
123
+ emitDryRunBanner(dryRunStderr(deps));
124
+ const sample = { ...DRY_RUN_DETAIL, name: opts.name };
125
+ out.print(sample, data => renderTestListDetailText(data));
126
+ return sample;
127
+ }
128
+ const client = makeClient(opts, deps);
129
+ const detail = await client.post('/testlist', {
130
+ body: { name: opts.name, ...(projectEnvironments ? { projectEnvironments } : {}) },
131
+ headers: { 'idempotency-key': idempotencyKey },
132
+ });
133
+ out.print(detail, data => renderTestListDetailText(data));
134
+ return detail;
135
+ }
136
+ export async function runTestlistUpdate(opts, deps = {}) {
137
+ const out = makeOutput(opts.output, deps);
138
+ const hasProjectEnv = opts.projectEnv !== undefined && opts.projectEnv.length > 0;
139
+ if (opts.clearProjectEnv && hasProjectEnv) {
140
+ throw localValidationError('clear-project-env', 'cannot be combined with --project-env');
141
+ }
142
+ if (opts.name === undefined && !hasProjectEnv && !opts.clearProjectEnv) {
143
+ throw localValidationError('name', 'pass --name, --project-env, or --clear-project-env');
144
+ }
145
+ if (opts.idempotencyKey !== undefined)
146
+ assertIdempotencyKey(opts.idempotencyKey);
147
+ // `[]` (clear) vs the parsed array vs `undefined` (leave untouched) — the
148
+ // three cases the V3 update contract distinguishes.
149
+ const projectEnvironments = opts.clearProjectEnv ? [] : parseProjectEnvs(opts.projectEnv);
150
+ const idempotencyKey = opts.idempotencyKey ?? `cli-testlist-update-${randomUUID()}`;
151
+ emitIdempotencyKey(opts, deps, idempotencyKey, opts.idempotencyKey);
152
+ if (opts.dryRun) {
153
+ emitDryRunBanner(dryRunStderr(deps));
154
+ const sample = { ...DRY_RUN_DETAIL, ...(opts.name !== undefined ? { name: opts.name } : {}) };
155
+ out.print(sample, data => renderTestListDetailText(data));
156
+ return sample;
157
+ }
158
+ const client = makeClient(opts, deps);
159
+ const detail = await client.put(`/testlist/${encodeURIComponent(opts.listId)}`, {
160
+ body: {
161
+ ...(opts.name !== undefined ? { name: opts.name } : {}),
162
+ ...(projectEnvironments !== undefined ? { projectEnvironments } : {}),
163
+ },
164
+ headers: { 'idempotency-key': idempotencyKey },
165
+ });
166
+ out.print(detail, data => renderTestListDetailText(data));
167
+ return detail;
168
+ }
169
+ export async function runTestlistDelete(opts, deps = {}) {
170
+ const out = makeOutput(opts.output, deps);
171
+ // Destructive: deleting a list also deletes its schedules (and reaps their
172
+ // EventBridge triggers). Require explicit --confirm — matches the CLI's
173
+ // project/test delete convention and prevents accidental CI/shell deletion.
174
+ // --dry-run is exempt (it never touches the server).
175
+ if (!opts.confirm && !opts.dryRun) {
176
+ throw localValidationError('confirm', 'required for a destructive delete (deletes the list and its schedules); re-run with --confirm, or use --dry-run', undefined, 'flag');
177
+ }
178
+ if (opts.idempotencyKey !== undefined)
179
+ assertIdempotencyKey(opts.idempotencyKey);
180
+ const idempotencyKey = opts.idempotencyKey ?? `cli-testlist-delete-${randomUUID()}`;
181
+ emitIdempotencyKey(opts, deps, idempotencyKey, opts.idempotencyKey);
182
+ if (opts.dryRun) {
183
+ emitDryRunBanner(dryRunStderr(deps));
184
+ const sample = { listId: opts.listId };
185
+ out.print(sample, data => `Deleted test list ${data.listId}`);
186
+ return sample;
187
+ }
188
+ const client = makeClient(opts, deps);
189
+ const resp = await client.delete(`/testlist/${encodeURIComponent(opts.listId)}`, { headers: { 'idempotency-key': idempotencyKey } });
190
+ out.print(resp, data => `Deleted test list ${data.listId}`);
191
+ return resp;
192
+ }
193
+ async function mutateCases(verb, opts, deps) {
194
+ const out = makeOutput(opts.output, deps);
195
+ if (opts.testIds.length === 0) {
196
+ throw localValidationError('test-id', 'at least one test id is required', undefined, 'field');
197
+ }
198
+ if (opts.idempotencyKey !== undefined)
199
+ assertIdempotencyKey(opts.idempotencyKey);
200
+ const idempotencyKey = opts.idempotencyKey ?? `cli-testlist-${verb}-${randomUUID()}`;
201
+ emitIdempotencyKey(opts, deps, idempotencyKey, opts.idempotencyKey);
202
+ if (opts.dryRun) {
203
+ emitDryRunBanner(dryRunStderr(deps));
204
+ out.print(DRY_RUN_DETAIL, data => renderTestListDetailText(data));
205
+ return DRY_RUN_DETAIL;
206
+ }
207
+ const path = verb === 'add'
208
+ ? `/testlist/${encodeURIComponent(opts.listId)}/cases`
209
+ : `/testlist/${encodeURIComponent(opts.listId)}/cases/delete`;
210
+ const client = makeClient(opts, deps);
211
+ const detail = await client.post(path, {
212
+ body: { testIds: opts.testIds },
213
+ headers: { 'idempotency-key': idempotencyKey },
214
+ });
215
+ out.print(detail, data => renderTestListDetailText(data));
216
+ return detail;
217
+ }
218
+ export const runTestlistAdd = (opts, deps = {}) => mutateCases('add', opts, deps);
219
+ export const runTestlistRemove = (opts, deps = {}) => mutateCases('remove', opts, deps);
220
+ // ── run ────────────────────────────────────────────────────────────────────
221
+ const MAX_TESTLIST_RUN_CONCURRENCY = 50;
222
+ const DEFAULT_TESTLIST_RUN_CONCURRENCY = 10;
223
+ const DEFAULT_TESTLIST_RUN_TIMEOUT_SECONDS = 600;
224
+ const WAIT_REQUEST_TIMEOUT_CUSHION_MS = 5_000;
225
+ /**
226
+ * Under `--wait`, raise the per-request HTTP timeout to cover `--timeout` so a
227
+ * slow trigger / long-poll on a large list isn't cut short by the default 120s
228
+ * request deadline and mis-reported as a member timeout. Mirrors
229
+ * `test run`'s `resolveWaitRequestTimeoutMs` (reimplemented locally to keep this
230
+ * file off the `test.ts` module — see the security-lint note on `run`).
231
+ */
232
+ export function waitRequestTimeoutMs(opts) {
233
+ if (opts.wait !== true || opts.timeoutSeconds === undefined)
234
+ return opts.requestTimeoutMs;
235
+ const base = opts.requestTimeoutMs ?? REQUEST_TIMEOUT_DEFAULT_MS;
236
+ const cover = Math.min(opts.timeoutSeconds * 1000 + WAIT_REQUEST_TIMEOUT_CUSHION_MS, REQUEST_TIMEOUT_MAX_MS);
237
+ return Math.max(base, cover);
238
+ }
239
+ /** Parse `--timeout <s>` (1–3600, default 600). Mirrors `test run`'s bounds. */
240
+ function parseTestlistTimeoutFlag(raw) {
241
+ if (raw === undefined)
242
+ return DEFAULT_TESTLIST_RUN_TIMEOUT_SECONDS;
243
+ const n = Number(raw);
244
+ if (!Number.isInteger(n) || n < 1 || n > 3600) {
245
+ throw localValidationError('timeout', 'must be an integer between 1 and 3600', raw);
246
+ }
247
+ return n;
248
+ }
249
+ /** Parse `--max-concurrency <n>` (≥1, default 10). Upper bound is enforced in `runTestlistRun`. */
250
+ function parseTestlistConcurrencyFlag(raw) {
251
+ if (raw === undefined)
252
+ return DEFAULT_TESTLIST_RUN_CONCURRENCY;
253
+ const n = Number(raw);
254
+ if (!Number.isInteger(n) || n < 1) {
255
+ throw localValidationError('max-concurrency', 'must be a positive integer', raw);
256
+ }
257
+ return n;
258
+ }
259
+ /**
260
+ * Rate-deferred members were never dispatched → the batch is incomplete (exit 7),
261
+ * mirroring `test run --all`. The backend applies the same per-key run-rate
262
+ * soft-fold as `POST /tests/batch/run` and returns the overflow here, so a
263
+ * partial dispatch surfaces as a non-zero exit instead of silently passing CI.
264
+ */
265
+ function assertNoDeferred(resp) {
266
+ if (resp.deferred.length === 0)
267
+ return;
268
+ const ids = resp.deferred.map(d => d.testId).join(' ');
269
+ throw new CLIError(`Batch run incomplete: ${resp.deferred.length} test(s) rate-deferred (per-key run budget) — retry after ~60s: ${ids}`, 7);
270
+ }
271
+ /**
272
+ * A partial `--case` miss (some ids are not members of the list) means the run
273
+ * did not cover everything the operator asked for → exit non-zero (4, NOT_FOUND)
274
+ * so a mistyped/renamed id fails the CI step instead of passing green. Checked
275
+ * AFTER the poll gates, so a genuine failure/timeout on the matched subset is
276
+ * reported first; the ids were already surfaced on stderr the moment they were
277
+ * known. A FULL miss is a 404 upstream and never reaches this command.
278
+ */
279
+ function assertNoNotFound(resp) {
280
+ if (!resp.notFound || resp.notFound.length === 0)
281
+ return;
282
+ throw new CLIError(`${resp.notFound.length} --case id(s) not in this list: ${resp.notFound.join(' ')}`, 4);
283
+ }
284
+ /**
285
+ * `testlist run` — dispatch the list's cases (optionally a `--case` subset) and,
286
+ * with `--wait`, poll every returned runId to a verdict, optionally writing a
287
+ * JUnit XML report (`--report junit`). testlist run is V3-only.
288
+ */
289
+ export async function runTestlistRun(opts, deps = {}) {
290
+ const out = makeOutput(opts.output, deps);
291
+ const stderrFn = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
292
+ if (opts.idempotencyKey !== undefined)
293
+ assertIdempotencyKey(opts.idempotencyKey);
294
+ if (!Number.isInteger(opts.maxConcurrency) ||
295
+ opts.maxConcurrency < 1 ||
296
+ opts.maxConcurrency > MAX_TESTLIST_RUN_CONCURRENCY) {
297
+ throw localValidationError('max-concurrency', `must be an integer between 1 and ${MAX_TESTLIST_RUN_CONCURRENCY}`);
298
+ }
299
+ if (opts.report === 'junit' && opts.reportFile === undefined) {
300
+ throw localValidationError('report-file', 'required when --report junit is set');
301
+ }
302
+ if (opts.report === 'junit' && !opts.wait) {
303
+ throw localValidationError('report', '--report junit requires --wait (verdicts come from the poll)');
304
+ }
305
+ // --gh-output / --summary-file reduce a --wait run's per-member results into the
306
+ // CI summary. They require --wait (without it the command returns after dispatch,
307
+ // before any terminal result exists) — reject loudly, same rule as --report junit
308
+ // above and the sibling `test run` flags. Gate only the EXPLICIT flags; the
309
+ // GITHUB_ACTIONS auto-enable must stay silent without --wait, same as `test run`.
310
+ if (opts.ghOutput === true && !opts.wait) {
311
+ throw localValidationError('gh-output', '--gh-output requires --wait (it reduces the terminal run result). Add --wait.');
312
+ }
313
+ if (opts.summaryFile !== undefined && !opts.wait) {
314
+ throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
315
+ }
316
+ const idempotencyKey = opts.idempotencyKey ?? `cli-testlist-run-${randomUUID()}`;
317
+ emitIdempotencyKey(opts, deps, idempotencyKey, opts.idempotencyKey);
318
+ if (opts.dryRun) {
319
+ emitDryRunBanner(dryRunStderr(deps));
320
+ const sample = { accepted: [], conflicts: [], deferred: [] };
321
+ out.print(sample, () => 'dry-run: no runs dispatched');
322
+ return sample;
323
+ }
324
+ // Under --wait, raise the per-request timeout to cover --timeout (see helper).
325
+ const client = makeClient({ ...opts, requestTimeoutMs: waitRequestTimeoutMs(opts) }, deps);
326
+ const resp = await client.triggerTestListRun(opts.listId, opts.cases && opts.cases.length > 0 ? { testIds: opts.cases } : {}, { idempotencyKey });
327
+ // Partial `--case` miss: some ids were not members of this list. The matched
328
+ // subset still dispatched; a FULL miss is a 404 upstream and never reaches
329
+ // here. Warn on stderr so JSON stdout stays the machine payload (the ids are
330
+ // also carried on `resp.notFound`).
331
+ if (resp.notFound && resp.notFound.length > 0) {
332
+ stderrFn(`warning: ${resp.notFound.length} --case id(s) not in this list, skipped: ${resp.notFound.join(' ')}`);
333
+ }
334
+ // All-conflict: nothing new dispatched because every targeted case is already
335
+ // in flight → exit 6, for BOTH --wait and non-wait (a --wait over zero accepted
336
+ // would otherwise no-op straight to exit 0). Distinct from the empty/no-match
337
+ // case (accepted AND conflicts both empty), which is a legitimate success and
338
+ // flows through the tail below so its CI artifacts are still emitted.
339
+ if (resp.accepted.length === 0 && resp.conflicts.length > 0) {
340
+ out.print(resp, () => renderRunAcceptedText(resp));
341
+ // Surface the exit-6 in CI too (only under --wait, the CI-artifact contract):
342
+ // an all-conflict re-run — every targeted case already in flight — otherwise
343
+ // exits 6 with no ::error:: annotation and no summary file. The conflicts fold
344
+ // into the summary as non-passed rows. The non-wait path never emits CI
345
+ // artifacts, matching the main tail below.
346
+ if (opts.wait) {
347
+ emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify({
348
+ accepted: [],
349
+ conflicts: resp.conflicts,
350
+ deferred: resp.deferred,
351
+ // Include notFound too: a mixed `--case` selection can be
352
+ // all-conflict on its matched ids AND carry not-in-list ids, and the
353
+ // CI summary must report the whole requested set (same reason the
354
+ // main --wait envelope threads it). Undefined ⇒ JSON.stringify drops it.
355
+ notFound: resp.notFound,
356
+ }), { notFoundNote: 'not a member of this list (not dispatched)' }), opts, {
357
+ env: deps.env ?? process.env,
358
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
359
+ stderr: stderrFn,
360
+ }, 'testlist run');
361
+ }
362
+ const pollIds = resp.conflicts
363
+ .map(c => c.currentRunId)
364
+ .filter((id) => Boolean(id));
365
+ // Name the causes instead of blanket "already in flight" — a list pinned to
366
+ // a local env or a view-only project is not something to poll. The poll hint
367
+ // is emitted only for the cases that actually have an in-flight run.
368
+ throw new CLIError(`Nothing dispatched — ${resp.conflicts.length} conflict(s): ${summarizeConflicts(resp.conflicts)}` +
369
+ (pollIds.length > 0
370
+ ? `. Poll in-flight runs: testsprite test wait ${pollIds.join(' ')}`
371
+ : ''), 6);
372
+ }
373
+ if (!opts.wait) {
374
+ // Print what dispatched, or the empty/no-match reason. Exit 0.
375
+ out.print(resp, () => resp.accepted.length > 0
376
+ ? renderRunAcceptedText(resp)
377
+ : `No runs dispatched${resp.reason ? ` (${resp.reason})` : ''}.`);
378
+ assertNoDeferred(resp);
379
+ assertNoNotFound(resp);
380
+ return resp;
381
+ }
382
+ // --wait beyond this point. An empty/no-match run (zero accepted, zero
383
+ // conflicts) is NOT short-circuited: it flows through the fan-out (a no-op) and
384
+ // the report tail so an explicitly-requested --report junit still emits an
385
+ // empty-suite report rather than nothing.
386
+ // --- --wait fan-out ---
387
+ const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
388
+ const batchDeadlineMs = Date.now() + opts.timeoutSeconds * 1000;
389
+ const results = [];
390
+ async function pollOne(entry) {
391
+ const remainingMs = batchDeadlineMs - Date.now();
392
+ if (remainingMs <= 0) {
393
+ return {
394
+ testId: entry.testId,
395
+ runId: entry.runId,
396
+ status: 'timeout',
397
+ error: {
398
+ code: 'UNSUPPORTED',
399
+ message: `Timed out after ${opts.timeoutSeconds}s`,
400
+ exitCode: 7,
401
+ },
402
+ };
403
+ }
404
+ try {
405
+ // testlist run is V3-only; V3 run rows (FE and BE) finalize via the
406
+ // execution completion path, so the run-surface poll resolves without the
407
+ // V2 BE-orphan-row fallback that `test run` needs.
408
+ const finalRun = await pollRunUntilTerminal(client, entry.runId, {
409
+ timeoutSeconds: Math.ceil(remainingMs / 1000),
410
+ sleep: deps.sleep,
411
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
412
+ onTick: (run, elapsedMs) => {
413
+ const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
414
+ ticker.update(`Run ${run.runId} (${entry.testId}) — ${run.status} (${s.completed}/${s.total} steps elapsed=${Math.round(elapsedMs / 1000)}s)`);
415
+ },
416
+ });
417
+ return {
418
+ testId: entry.testId,
419
+ runId: entry.runId,
420
+ projectId: finalRun.projectId,
421
+ status: finalRun.status,
422
+ // Carry the run's dashboard link so the ::error:: annotations and the
423
+ // job-summary Run column are clickable (parity with `test run --all`).
424
+ // Use the SERVER's dashboardUrl, not a client-built resolvePortalUrl:
425
+ // testlist run is V3-only, and the client helper emits the V2 route
426
+ // shape (`/dashboard/tests/...`) which 404s for a V3 project.
427
+ ...(typeof finalRun.dashboardUrl === 'string'
428
+ ? { dashboardUrl: finalRun.dashboardUrl }
429
+ : {}),
430
+ };
431
+ }
432
+ catch (err) {
433
+ if (err instanceof TimeoutError) {
434
+ return {
435
+ testId: entry.testId,
436
+ runId: entry.runId,
437
+ status: 'timeout',
438
+ error: {
439
+ code: 'UNSUPPORTED',
440
+ message: `Timed out after ${opts.timeoutSeconds}s`,
441
+ exitCode: 7,
442
+ },
443
+ };
444
+ }
445
+ // Interrupt must reject the whole fan-out (never flatten to a per-member
446
+ // outcome that would swallow the 128+signum exit).
447
+ if (err instanceof InterruptError)
448
+ throw err;
449
+ if (err instanceof RequestTimeoutError) {
450
+ return {
451
+ testId: entry.testId,
452
+ runId: entry.runId,
453
+ status: 'timeout',
454
+ error: { code: 'UNSUPPORTED', message: err.message, exitCode: err.exitCode },
455
+ };
456
+ }
457
+ if (err instanceof ApiError) {
458
+ // Preserve the real code/exit (AUTH_INVALID=3, NOT_FOUND=4, …) rather
459
+ // than flattening every member failure to a generic 1.
460
+ return {
461
+ testId: entry.testId,
462
+ runId: entry.runId,
463
+ status: 'error',
464
+ error: { code: err.code, message: err.message, exitCode: err.exitCode },
465
+ };
466
+ }
467
+ throw err;
468
+ }
469
+ }
470
+ // Bounded-concurrency fan-out (self-contained; deliberately kept separate from
471
+ // `runTestRunAll`'s inline driver rather than extracting a shared helper).
472
+ let pollIdx = 0;
473
+ let inFlight = 0;
474
+ await new Promise((resolve, reject) => {
475
+ function startNext() {
476
+ while (inFlight < opts.maxConcurrency && pollIdx < resp.accepted.length) {
477
+ const entry = resp.accepted[pollIdx++];
478
+ inFlight++;
479
+ pollOne(entry)
480
+ .then(r => {
481
+ results.push(r);
482
+ inFlight--;
483
+ startNext();
484
+ if (inFlight === 0 && pollIdx >= resp.accepted.length)
485
+ resolve();
486
+ })
487
+ .catch(reject);
488
+ }
489
+ }
490
+ startNext();
491
+ if (resp.accepted.length === 0)
492
+ resolve();
493
+ });
494
+ ticker.finalize();
495
+ const passed = results.filter(r => r.status === 'passed').length;
496
+ const failed = results.filter(r => r.status !== 'passed' && r.status !== 'timeout').length;
497
+ const timedOut = results.filter(r => r.status === 'timeout').length;
498
+ stderrFn(`Test-list run complete: ${passed}/${resp.accepted.length} passed, ${failed} failed/blocked, ${timedOut} timed out`);
499
+ const jsonPayload = {
500
+ accepted: results,
501
+ conflicts: resp.conflicts,
502
+ deferred: resp.deferred,
503
+ // Not members of this list (partial `--case` miss). Threaded into the
504
+ // envelope so `summarizeAcceptedPayload` folds them as non-passed rows
505
+ // (gh-output.ts) — without this a `1 accepted passed + 1 not-found` run
506
+ // read as "1/1 passed" in the CI summary while the command exits 4.
507
+ ...(resp.notFound && resp.notFound.length > 0 ? { notFound: resp.notFound } : {}),
508
+ // Present only on a nothing-dispatched run (empty list / no-match --case);
509
+ // surfaced here so the --wait envelope explains a zero-run report.
510
+ ...(resp.reason ? { reason: resp.reason } : {}),
511
+ summary: {
512
+ passed,
513
+ failed,
514
+ timedOut,
515
+ deferred: resp.deferred.length,
516
+ conflicts: resp.conflicts.length,
517
+ total: resp.accepted.length,
518
+ },
519
+ };
520
+ if (opts.report === 'junit' && opts.reportFile !== undefined) {
521
+ // Multi-project list: name the suite/classname by the LIST, not one project
522
+ // (`resolveBatchReportProjectId`'s single-project assumption doesn't hold).
523
+ const suiteName = opts.reportSuiteName ?? `testsprite:testlist:${opts.listId}`;
524
+ const xml = buildJUnitReport({ suiteName, classname: `testlist:${opts.listId}`, results });
525
+ await writeJUnitReportFile(opts.reportFile, xml);
526
+ }
527
+ out.print(jsonPayload, () => results.map(r => `${r.runId} ${r.status}`).join('\n'));
528
+ // CI-native output parity with `test run` (--gh-output / --summary-file):
529
+ // auto-enable under GITHUB_ACTIONS. Emit BEFORE the exit-code gates below so a
530
+ // failing/timed-out/deferred run still gets its ::error:: annotations + the
531
+ // job-summary table. `emitCiArtifacts` is the shared helper the sibling run
532
+ // paths use, keyed off the identical reduced envelope.
533
+ emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(jsonPayload), {
534
+ notFoundNote: 'not a member of this list (not dispatched)',
535
+ }), opts, {
536
+ env: deps.env ?? process.env,
537
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
538
+ stderr: stderrFn,
539
+ }, 'testlist run');
540
+ // Rate-deferred → incomplete batch (exit 7), checked before the timeout/failed
541
+ // gates so the operator learns to retry the deferred set (mirrors test run --all).
542
+ assertNoDeferred(resp);
543
+ // Shared exit-code precedence (auth 3 → typed operational ApiError → timeout 7
544
+ // → generic fail 1) so `testlist run` and `test run` can't drift.
545
+ const failure = resolveWaitFailure(results, { timeoutSeconds: opts.timeoutSeconds });
546
+ if (failure)
547
+ throw failure;
548
+ assertNoNotFound(resp);
549
+ return resp;
550
+ }
551
+ function renderRunAcceptedText(resp) {
552
+ const lines = [];
553
+ for (const a of resp.accepted)
554
+ lines.push(`${a.runId} ${a.testId} dispatched`);
555
+ for (const c of resp.conflicts) {
556
+ // Reason-aware: a view-only / un-runnable / not-found case is no longer
557
+ // mislabelled "already-in-flight" (see describeConflict).
558
+ lines.push(`${c.currentRunId ?? '(none)'} ${c.testId} ${describeConflict(c)}`);
559
+ }
560
+ if (lines.length === 0)
561
+ return 'No runs dispatched.';
562
+ return lines.join('\n');
563
+ }
564
+ // ── text renderers ───────────────────────────────────────────────────────────
565
+ const TESTLIST_COLUMNS = [
566
+ { header: 'ID', width: rows => Math.max(2, ...rows.map(r => r.id.length)), render: r => r.id },
567
+ {
568
+ header: 'NAME',
569
+ width: rows => Math.max(4, ...rows.map(r => r.name.length)),
570
+ render: r => r.name,
571
+ },
572
+ { header: 'CASES', width: 5, render: r => String(r.caseCount) },
573
+ // Fixed 36 (a UUID); `width: 0` (skip-padding) is only valid on the LAST
574
+ // column, and UPDATED is last — a `width: 0` here would leave LAST_EXEC
575
+ // unpadded and drift UPDATED per row (UUID 36 chars vs "(none)" 6 chars).
576
+ { header: 'LAST_EXEC', width: 36, render: r => r.lastExecutionId ?? '(none)' },
577
+ { header: 'UPDATED', width: 0, render: r => r.updatedAt },
578
+ ];
579
+ function renderTestListListText(items, options = {}) {
580
+ if (items.length === 0)
581
+ return 'No test lists.';
582
+ return renderTextTable(items, TESTLIST_COLUMNS, {
583
+ columns: options.columns,
584
+ noHeader: options.noHeader,
585
+ });
586
+ }
587
+ function renderTestListDetailText(d) {
588
+ const lines = [
589
+ `ID: ${d.id}`,
590
+ `Name: ${d.name}`,
591
+ `Cases: ${d.stats.total} (passed ${d.stats.passed}, failed ${d.stats.failed}, blocked ${d.stats.blocked}, running ${d.stats.running})`,
592
+ ];
593
+ if (d.projectEnvironments.length > 0) {
594
+ lines.push(`Envs: ${d.projectEnvironments.map(e => `${e.projectId}:${e.environmentName}`).join(', ')}`);
595
+ }
596
+ lines.push(`Last exec: ${d.lastExecutionId ?? '(none)'}`);
597
+ lines.push(`Updated: ${d.updatedAt}`);
598
+ if (d.cases.length > 0) {
599
+ lines.push('');
600
+ const caseTable = renderTextTable(d.cases, [
601
+ {
602
+ header: 'TEST_ID',
603
+ width: rows => Math.max(7, ...rows.map(c => c.testId.length)),
604
+ render: c => c.testId,
605
+ },
606
+ { header: 'TYPE', width: 8, render: c => c.type },
607
+ {
608
+ header: 'TITLE',
609
+ width: rows => Math.max(5, ...rows.map(c => (c.title ?? '').length)),
610
+ render: c => c.title ?? '',
611
+ },
612
+ { header: 'STATUS', width: 0, render: c => c.status ?? '' },
613
+ ]);
614
+ lines.push(caseTable);
615
+ }
616
+ return lines.join('\n');
617
+ }
618
+ // ── command wiring ───────────────────────────────────────────────────────────
619
+ export function createTestListCommand(deps = {}) {
620
+ const testlist = new Command('testlist').description('Manage test lists (groups of tests)');
621
+ testlist
622
+ .command('list')
623
+ .description('List test lists visible to the API key')
624
+ .option('--columns <list>', 'select/reorder text table columns (comma-separated keys)')
625
+ .option('--no-header', 'suppress the text table header row')
626
+ .addHelpText('after', GLOBAL_OPTS_HINT)
627
+ .action(async (cmdOpts, command) => {
628
+ await runTestlistList({
629
+ ...resolveCommonOptions(command),
630
+ columns: cmdOpts.columns,
631
+ noHeader: cmdOpts.header === false,
632
+ }, deps);
633
+ });
634
+ testlist
635
+ .command('get <list-id>')
636
+ .description('Get a test list with its cases')
637
+ .addHelpText('after', GLOBAL_OPTS_HINT)
638
+ .action(async (listId, _cmdOpts, command) => {
639
+ await runTestlistGet({ ...resolveCommonOptions(command), listId }, deps);
640
+ });
641
+ testlist
642
+ .command('create')
643
+ .description('Create a test list')
644
+ .option('--name <name>', 'test-list name (required)')
645
+ .option('--project-env <projectId:env>', 'project+environment pair the list runs against (repeatable)', collectRepeatable, [])
646
+ .option('--idempotency-key <key>', 'caller-supplied idempotency key (1-256 chars)')
647
+ .addHelpText('after', GLOBAL_OPTS_HINT)
648
+ .action(async (cmdOpts, command) => {
649
+ await runTestlistCreate({
650
+ ...resolveCommonOptions(command),
651
+ name: cmdOpts.name,
652
+ projectEnv: cmdOpts.projectEnv,
653
+ idempotencyKey: cmdOpts.idempotencyKey,
654
+ }, deps);
655
+ });
656
+ testlist
657
+ .command('update <list-id>')
658
+ .description('Update a test list (name and/or environments)')
659
+ .option('--name <name>', 'new name')
660
+ .option('--project-env <projectId:env>', 'replace the env mapping with these pairs (repeatable)', collectRepeatable, [])
661
+ .option('--clear-project-env', 'remove all environment mappings from the list')
662
+ .option('--idempotency-key <key>', 'caller-supplied idempotency key (1-256 chars)')
663
+ .addHelpText('after', GLOBAL_OPTS_HINT)
664
+ .action(async (listId, cmdOpts, command) => {
665
+ await runTestlistUpdate({
666
+ ...resolveCommonOptions(command),
667
+ listId,
668
+ name: cmdOpts.name,
669
+ projectEnv: cmdOpts.projectEnv,
670
+ clearProjectEnv: cmdOpts.clearProjectEnv,
671
+ idempotencyKey: cmdOpts.idempotencyKey,
672
+ }, deps);
673
+ });
674
+ testlist
675
+ .command('delete <list-id>')
676
+ .description('Delete a test list and its schedules (requires --confirm)')
677
+ .option('--confirm', 'confirm the destructive delete (required unless --dry-run)')
678
+ .option('--idempotency-key <key>', 'caller-supplied idempotency key (1-256 chars)')
679
+ .addHelpText('after', GLOBAL_OPTS_HINT)
680
+ .action(async (listId, cmdOpts, command) => {
681
+ await runTestlistDelete({
682
+ ...resolveCommonOptions(command),
683
+ listId,
684
+ confirm: cmdOpts.confirm,
685
+ idempotencyKey: cmdOpts.idempotencyKey,
686
+ }, deps);
687
+ });
688
+ testlist
689
+ .command('add <list-id> <test-id...>')
690
+ .description('Add one or more tests to a test list')
691
+ .option('--idempotency-key <key>', 'caller-supplied idempotency key (1-256 chars)')
692
+ .addHelpText('after', GLOBAL_OPTS_HINT)
693
+ .action(async (listId, testIds, cmdOpts, command) => {
694
+ await runTestlistAdd({
695
+ ...resolveCommonOptions(command),
696
+ listId,
697
+ testIds,
698
+ idempotencyKey: cmdOpts.idempotencyKey,
699
+ }, deps);
700
+ });
701
+ testlist
702
+ .command('remove <list-id> <test-id...>')
703
+ .description('Remove one or more tests from a test list')
704
+ .option('--idempotency-key <key>', 'caller-supplied idempotency key (1-256 chars)')
705
+ .addHelpText('after', GLOBAL_OPTS_HINT)
706
+ .action(async (listId, testIds, cmdOpts, command) => {
707
+ await runTestlistRemove({
708
+ ...resolveCommonOptions(command),
709
+ listId,
710
+ testIds,
711
+ idempotencyKey: cmdOpts.idempotencyKey,
712
+ }, deps);
713
+ });
714
+ testlist
715
+ .command('run <list-id>')
716
+ .description('Run a test list (dispatch its cases and return pollable run ids)')
717
+ .option('--case <test-id>', 'run only this case (repeatable; default: every case in the list)', collectRepeatable, [])
718
+ .option('--wait', 'poll every dispatched run until terminal or --timeout', false)
719
+ .option('--timeout <s>', 'with --wait, max seconds to wait (1–3600, default 600)')
720
+ .option('--max-concurrency <n>', `with --wait, max in-flight polls at once (1-${MAX_TESTLIST_RUN_CONCURRENCY}, default ${DEFAULT_TESTLIST_RUN_CONCURRENCY})`)
721
+ .option('--idempotency-key <key>', 'caller-supplied idempotency key (1-256 chars)')
722
+ .option('--report <format>', 'with --wait: write a JUnit XML sidecar after polling (accepted: junit)')
723
+ .option('--report-file <path>', 'output path for --report (atomic write)')
724
+ .option('--report-suite-name <name>', 'JUnit <testsuite name=...> override (default: testsprite:testlist:<listId>)')
725
+ .option('--gh-output', 'with --wait: emit GitHub-native output (::error:: annotations per non-passed member; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
726
+ .option('--summary-file <path>', 'with --wait: also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
727
+ .addHelpText('after', GLOBAL_OPTS_HINT)
728
+ .action(async (listId, cmdOpts, command) => {
729
+ const wait = cmdOpts.wait === true;
730
+ await runTestlistRun({
731
+ ...resolveCommonOptions(command),
732
+ listId,
733
+ cases: cmdOpts.case,
734
+ wait,
735
+ timeoutSeconds: parseTestlistTimeoutFlag(cmdOpts.timeout),
736
+ maxConcurrency: parseTestlistConcurrencyFlag(cmdOpts.maxConcurrency),
737
+ idempotencyKey: cmdOpts.idempotencyKey,
738
+ report: parseJUnitReportFormat(cmdOpts.report),
739
+ reportFile: cmdOpts.reportFile,
740
+ reportSuiteName: cmdOpts.reportSuiteName,
741
+ ghOutput: cmdOpts.ghOutput,
742
+ summaryFile: cmdOpts.summaryFile,
743
+ }, deps);
744
+ });
745
+ return testlist;
746
+ }
747
+ //# sourceMappingURL=testlist.js.map