@testsprite/testsprite-cli 0.2.0 → 0.3.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 (55) hide show
  1. package/README.md +34 -26
  2. package/dist/commands/agent.d.ts +43 -0
  3. package/dist/commands/agent.js +200 -18
  4. package/dist/commands/auth.js +29 -27
  5. package/dist/commands/doctor.d.ts +49 -0
  6. package/dist/commands/doctor.js +211 -0
  7. package/dist/commands/init.d.ts +1 -1
  8. package/dist/commands/init.js +24 -14
  9. package/dist/commands/project.d.ts +50 -1
  10. package/dist/commands/project.js +252 -43
  11. package/dist/commands/test.d.ts +188 -1
  12. package/dist/commands/test.js +1088 -81
  13. package/dist/commands/usage.js +13 -12
  14. package/dist/index.js +33 -2
  15. package/dist/lib/agent-targets.d.ts +72 -6
  16. package/dist/lib/agent-targets.js +188 -6
  17. package/dist/lib/bundle.d.ts +34 -0
  18. package/dist/lib/bundle.js +44 -10
  19. package/dist/lib/client-factory.d.ts +25 -0
  20. package/dist/lib/client-factory.js +47 -0
  21. package/dist/lib/config.d.ts +2 -0
  22. package/dist/lib/config.js +11 -2
  23. package/dist/lib/credentials.js +10 -1
  24. package/dist/lib/dry-run/samples.d.ts +5 -0
  25. package/dist/lib/dry-run/samples.js +28 -0
  26. package/dist/lib/flaky.d.ts +80 -0
  27. package/dist/lib/flaky.js +76 -0
  28. package/dist/lib/http.d.ts +20 -0
  29. package/dist/lib/http.js +216 -132
  30. package/dist/lib/interrupt.d.ts +61 -0
  31. package/dist/lib/interrupt.js +97 -0
  32. package/dist/lib/junit-report.d.ts +58 -0
  33. package/dist/lib/junit-report.js +210 -0
  34. package/dist/lib/output.d.ts +16 -1
  35. package/dist/lib/output.js +24 -2
  36. package/dist/lib/pagination.d.ts +4 -3
  37. package/dist/lib/pagination.js +34 -6
  38. package/dist/lib/prompt.js +52 -8
  39. package/dist/lib/proxy.d.ts +29 -0
  40. package/dist/lib/proxy.js +30 -0
  41. package/dist/lib/render-error.js +3 -1
  42. package/dist/lib/skill-nudge.d.ts +2 -2
  43. package/dist/lib/skill-nudge.js +13 -4
  44. package/dist/lib/target-url.js +8 -1
  45. package/dist/lib/ticker.d.ts +11 -1
  46. package/dist/lib/ticker.js +33 -1
  47. package/dist/lib/update-check.d.ts +67 -0
  48. package/dist/lib/update-check.js +246 -0
  49. package/dist/version-guard.d.ts +33 -0
  50. package/dist/version-guard.js +39 -0
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +3 -2
  54. package/skills/testsprite-onboard.skill.md +21 -0
  55. package/skills/testsprite-verify.skill.md +33 -0
@@ -371,28 +371,52 @@ async function freshTmpDir(dir) {
371
371
  * caught reading the dir during it sees no meta and refuses to consume
372
372
  * (per §7.3). That's what we want.
373
373
  */
374
+ /**
375
+ * Whether a top-level directory entry belongs to the bundle format —
376
+ * i.e. something a prior `writeBundle` could have produced and this
377
+ * commit is therefore allowed to clean up. `code.<ext>` is matched by
378
+ * pattern (not the current run's extension) so a stale `code.py` is
379
+ * still swept when the new bundle writes `code.ts`. Everything else in
380
+ * the directory is the user's and must never be deleted (`--out` can
381
+ * point at a pre-existing, populated directory).
382
+ */
383
+ export function isBundleOwnedEntry(entry) {
384
+ if (entry === 'result.json' ||
385
+ entry === 'failure.json' ||
386
+ entry === 'video.mp4' ||
387
+ entry === 'meta.json' ||
388
+ entry === 'steps' ||
389
+ entry === '.tmp' ||
390
+ entry === '.partial') {
391
+ return true;
392
+ }
393
+ return /^code\.[A-Za-z0-9]+$/.test(entry);
394
+ }
374
395
  async function commitBundle(tmpDir, dir, files) {
375
396
  // (1) Remove the prior bundle's completion signal FIRST.
376
397
  await unlink(join(dir, 'meta.json')).catch(() => undefined);
377
398
  // (2) Sweep stale top-level files that the new bundle won't write.
378
399
  // If the prior run wrote `video.mp4` and the new run has no video,
379
- // an in-place rename leaves the old video lingering. Enumerate
380
- // current top-level entries and remove anything that isn't being
381
- // freshly renamed in.
400
+ // an in-place rename leaves the old video lingering. Only entries the
401
+ // bundle format OWNS are candidates: `--out` may point at a directory
402
+ // that also holds the user's unrelated files, and those must survive
403
+ // the commit (deleting them would be silent data loss).
382
404
  const topLevel = files.filter(f => !f.startsWith('steps/'));
383
405
  const newTopLevelSet = new Set(topLevel);
384
406
  newTopLevelSet.add('meta.json'); // about to land last, do not delete
385
407
  const existing = await readdir(dir).catch(() => []);
386
408
  for (const entry of existing) {
387
409
  // Preserve the writer's own scratch dir + the .partial marker
388
- // (we'll re-evaluate .partial at the end of commit). Anything else
389
- // not-listed in the new bundle is stale.
410
+ // (we'll re-evaluate .partial at the end of commit). Any other
411
+ // bundle-owned entry not-listed in the new bundle is stale.
390
412
  if (entry === '.tmp' || entry === '.partial')
391
413
  continue;
392
414
  if (newTopLevelSet.has(entry))
393
415
  continue;
394
416
  if (entry === 'steps')
395
417
  continue; // handled below
418
+ if (!isBundleOwnedEntry(entry))
419
+ continue; // foreign file — never touch
396
420
  await rm(join(dir, entry), { recursive: true, force: true });
397
421
  }
398
422
  // (3) Replace `<dir>/steps/` with `<tmp>/steps/`.
@@ -545,10 +569,11 @@ function sidecarExtension(kind) {
545
569
  */
546
570
  export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
547
571
  const sleepFn = deps?.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
572
+ const artifactUrl = redactArtifactUrlForDetails(url);
548
573
  for (let attempt = 1; attempt <= STREAM_URL_MAX_RETRIES; attempt++) {
549
574
  let response;
550
575
  try {
551
- response = await fetchImpl(url);
576
+ response = await fetchImpl(url, { redirect: 'error' });
552
577
  }
553
578
  catch (err) {
554
579
  const message = err instanceof Error ? err.message : String(err);
@@ -556,7 +581,7 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
556
581
  await sleepFn(STREAM_URL_RETRY_DELAY_MS);
557
582
  continue;
558
583
  }
559
- throw new TransportError(`Failed to download presigned URL ${url}: ${message}`);
584
+ throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
560
585
  }
561
586
  if (!response.ok) {
562
587
  // Non-2xx: the URL itself is bad (expired, unauthorized, not found).
@@ -567,7 +592,7 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
567
592
  message: `Failed to download presigned URL (HTTP ${response.status}).`,
568
593
  nextAction: 'Re-run `testsprite test failure get`. Presigned URLs in the bundle expire after 15 minutes.',
569
594
  requestId: 'local',
570
- details: { status: response.status, url },
595
+ details: { status: response.status, artifactUrl },
571
596
  },
572
597
  });
573
598
  }
@@ -588,7 +613,7 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
588
613
  await sleepFn(STREAM_URL_RETRY_DELAY_MS);
589
614
  continue;
590
615
  }
591
- throw new TransportError(`Failed to download presigned URL ${url}: ${message}`);
616
+ throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
592
617
  }
593
618
  }
594
619
  await mkdir(dirname(filePath), { recursive: true });
@@ -611,10 +636,19 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
611
636
  await sleepFn(STREAM_URL_RETRY_DELAY_MS);
612
637
  continue;
613
638
  }
614
- throw new TransportError(`Failed mid-download of ${url}: ${message}`);
639
+ throw new TransportError(`Failed mid-download of ${artifactUrl}: ${message}`);
615
640
  }
616
641
  }
617
642
  }
643
+ function redactArtifactUrlForDetails(url) {
644
+ try {
645
+ const parsed = new URL(url);
646
+ return `${parsed.origin}${parsed.pathname}`;
647
+ }
648
+ catch {
649
+ return '<invalid-url>';
650
+ }
651
+ }
618
652
  function isPresignedUrl(value) {
619
653
  return value.startsWith('https://');
620
654
  }
@@ -87,4 +87,29 @@ export declare function resolveRequestTimeoutMs(opts: Pick<CommonOptions, 'reque
87
87
  * assuming the flag.
88
88
  */
89
89
  export declare function assertValidEndpointUrl(rawUrl: string): void;
90
+ export declare function assertValidApiKeyHeaderValue(apiKey: string): void;
91
+ /**
92
+ * Parse the `--request-timeout <seconds>` flag value into milliseconds.
93
+ *
94
+ * Returns `undefined` when the flag was omitted (the factory then falls back to
95
+ * the `TESTSPRITE_REQUEST_TIMEOUT_MS` env var, else the 120s default).
96
+ *
97
+ * A supplied-but-invalid value (non-numeric, zero, or negative) throws a typed
98
+ * VALIDATION_ERROR (exit 5) rather than being silently dropped. An explicit
99
+ * `--request-timeout 30s` typo previously resolved to `undefined` and the
100
+ * command ran with the default 120s deadline — the operator believed they had
101
+ * set a timeout but had not, with no signal. Failing loudly here is consistent
102
+ * with every other validated flag (`--page-size`, `--output`, `--type`).
103
+ *
104
+ * Out-of-range but positive values are intentionally NOT rejected — they flow
105
+ * through to {@link resolveRequestTimeoutMs}, which clamps to
106
+ * `[REQUEST_TIMEOUT_MIN_MS, REQUEST_TIMEOUT_MAX_MS]`. The env-var path stays
107
+ * lenient by design (a stray global env var should not hard-fail every
108
+ * command); only the explicit per-invocation flag is strict.
109
+ *
110
+ * This single definition replaces five byte-identical copies that previously
111
+ * lived in `auth`, `project`, `usage`, `init`, and `test` — drift between them
112
+ * would have silently changed timeout behaviour depending on the command.
113
+ */
114
+ export declare function parseRequestTimeoutFlag(raw: string | undefined): number | undefined;
90
115
  export declare function makeHttpClient(opts: CommonOptions, deps?: ClientFactoryDeps): HttpClient;
@@ -109,6 +109,52 @@ export function assertValidEndpointUrl(rawUrl) {
109
109
  `(e.g. https://api.testsprite.com)`, undefined, 'field');
110
110
  }
111
111
  }
112
+ export function assertValidApiKeyHeaderValue(apiKey) {
113
+ const reason = 'must be a non-empty HTTP header value; paste the raw key without smart punctuation, emoji, or line breaks';
114
+ if (apiKey.trim().length === 0) {
115
+ throw localValidationError('api-key', reason, undefined, 'field');
116
+ }
117
+ for (let i = 0; i < apiKey.length; i += 1) {
118
+ const code = apiKey.charCodeAt(i);
119
+ if (code < 0x20 || code === 0x7f || code > 0xff) {
120
+ throw localValidationError('api-key', reason, undefined, 'field');
121
+ }
122
+ }
123
+ }
124
+ /**
125
+ * Parse the `--request-timeout <seconds>` flag value into milliseconds.
126
+ *
127
+ * Returns `undefined` when the flag was omitted (the factory then falls back to
128
+ * the `TESTSPRITE_REQUEST_TIMEOUT_MS` env var, else the 120s default).
129
+ *
130
+ * A supplied-but-invalid value (non-numeric, zero, or negative) throws a typed
131
+ * VALIDATION_ERROR (exit 5) rather than being silently dropped. An explicit
132
+ * `--request-timeout 30s` typo previously resolved to `undefined` and the
133
+ * command ran with the default 120s deadline — the operator believed they had
134
+ * set a timeout but had not, with no signal. Failing loudly here is consistent
135
+ * with every other validated flag (`--page-size`, `--output`, `--type`).
136
+ *
137
+ * Out-of-range but positive values are intentionally NOT rejected — they flow
138
+ * through to {@link resolveRequestTimeoutMs}, which clamps to
139
+ * `[REQUEST_TIMEOUT_MIN_MS, REQUEST_TIMEOUT_MAX_MS]`. The env-var path stays
140
+ * lenient by design (a stray global env var should not hard-fail every
141
+ * command); only the explicit per-invocation flag is strict.
142
+ *
143
+ * This single definition replaces five byte-identical copies that previously
144
+ * lived in `auth`, `project`, `usage`, `init`, and `test` — drift between them
145
+ * would have silently changed timeout behaviour depending on the command.
146
+ */
147
+ export function parseRequestTimeoutFlag(raw) {
148
+ if (raw === undefined)
149
+ return undefined;
150
+ const n = Number(raw);
151
+ if (!Number.isFinite(n) || n <= 0) {
152
+ // Surface the offending value in the message (same as assertValidEndpointUrl)
153
+ // so the operator sees exactly what they typed.
154
+ throw localValidationError('request-timeout', `"${raw}" is not valid — must be a positive number of seconds`);
155
+ }
156
+ return Math.round(n * 1000); // seconds → milliseconds
157
+ }
112
158
  export function makeHttpClient(opts, deps = {}) {
113
159
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
114
160
  const env = deps.env ?? process.env;
@@ -142,6 +188,7 @@ export function makeHttpClient(opts, deps = {}) {
142
188
  assertValidEndpointUrl(config.apiUrl);
143
189
  if (!config.apiKey)
144
190
  throw ApiError.authRequired();
191
+ assertValidApiKeyHeaderValue(config.apiKey);
145
192
  return new HttpClient({
146
193
  baseUrl: facadeBaseUrl(config.apiUrl),
147
194
  apiKey: config.apiKey,
@@ -9,6 +9,8 @@ export interface LoadConfigOptions {
9
9
  env?: NodeJS.ProcessEnv;
10
10
  credentialsPath?: string;
11
11
  }
12
+ /** Treat empty / whitespace-only env values as unset for `??` resolution chains. */
13
+ export declare function normalizeEnvVar(value: string | undefined): string | undefined;
12
14
  export declare function defaultConfigPath(): string;
13
15
  /**
14
16
  * Resolves the active profile name and its (apiUrl, apiKey) pair.
@@ -2,6 +2,10 @@ import { homedir } from 'node:os';
2
2
  import { join } from 'node:path';
3
3
  import { DEFAULT_PROFILE, defaultCredentialsPath, readProfile } from './credentials.js';
4
4
  const DEFAULT_API_URL = 'https://api.testsprite.com';
5
+ /** Treat empty / whitespace-only env values as unset for `??` resolution chains. */
6
+ export function normalizeEnvVar(value) {
7
+ return value?.trim() || undefined;
8
+ }
5
9
  export function defaultConfigPath() {
6
10
  return join(homedir(), '.testsprite', 'config');
7
11
  }
@@ -21,9 +25,14 @@ export function loadConfig(options = {}) {
21
25
  const profile = options.profile ?? env.TESTSPRITE_PROFILE ?? DEFAULT_PROFILE;
22
26
  const credentialsPath = options.credentialsPath ?? defaultCredentialsPath();
23
27
  const fileEntry = readProfile(profile, { path: credentialsPath });
28
+ // Empty / whitespace-only env vars are treated as unset so they do not
29
+ // short-circuit the `??` chain (e.g. `export TESTSPRITE_API_URL=` in a shell
30
+ // profile). Matches the normalization in auth configure and init/setup.
31
+ const envApiUrl = normalizeEnvVar(env.TESTSPRITE_API_URL);
32
+ const envApiKey = normalizeEnvVar(env.TESTSPRITE_API_KEY);
24
33
  return {
25
- apiUrl: options.endpointUrl ?? env.TESTSPRITE_API_URL ?? fileEntry?.apiUrl ?? DEFAULT_API_URL,
26
- apiKey: env.TESTSPRITE_API_KEY ?? fileEntry?.apiKey,
34
+ apiUrl: options.endpointUrl ?? envApiUrl ?? fileEntry?.apiUrl ?? DEFAULT_API_URL,
35
+ apiKey: envApiKey ?? fileEntry?.apiKey,
27
36
  profile,
28
37
  };
29
38
  }
@@ -93,7 +93,16 @@ export function serializeCredentials(file) {
93
93
  const value = entry[field];
94
94
  if (value === undefined || value === '')
95
95
  continue;
96
- lines.push(`${FIELD_TO_FILE_KEY[field]} = ${value}`);
96
+ // Guard against INI injection: a value containing newline characters
97
+ // would be serialized across multiple lines, allowing an attacker to
98
+ // inject arbitrary key-value pairs (or new section headers) into the
99
+ // credentials file. A valid API key or URL never contains \n or \r.
100
+ // Strip them so a compromised env var or MITM'd backend response
101
+ // cannot override the stored api_key on subsequent reads.
102
+ const sanitized = value.replace(/[\r\n]/g, '');
103
+ if (sanitized === '')
104
+ continue;
105
+ lines.push(`${FIELD_TO_FILE_KEY[field]} = ${sanitized}`);
97
106
  }
98
107
  lines.push('');
99
108
  }
@@ -1,5 +1,10 @@
1
1
  export declare const SAMPLE_RUN_ID = "run_abc";
2
2
  export declare const SAMPLE_DRY_RUN_REQUEST_ID = "req_dry-run";
3
+ /**
4
+ * Canned JUnit XML for batch `--wait --report junit --dry-run`. Mirrors the
5
+ * fresh batch-run sample ids so agents can learn the sidecar shape offline.
6
+ */
7
+ export declare function sampleJUnitReportXml(projectId?: string, reportSuiteName?: string): string;
3
8
  /**
4
9
  * Dry-run sample lookup keyed by OpenAPI operationId. Order matters in
5
10
  * {@link findSample}: more specific patterns must precede their generic
@@ -1,3 +1,4 @@
1
+ import { buildJUnitReport } from '../junit-report.js';
1
2
  const SAMPLE_USER_ID = '11111111-1111-4111-8111-111111111111';
2
3
  const SAMPLE_KEY_ID = 'key_dryrun_2026';
3
4
  const SAMPLE_PROJECT_ID = 'project_b3c91efa';
@@ -25,6 +26,33 @@ const SAMPLE_SNAPSHOT_ID = 'snap_2026_05_05_b2f9a1c8';
25
26
  const SAMPLE_TARGET_URL = 'https://staging.example.com/checkout';
26
27
  const SAMPLE_REQUEST_ID = 'req_dry-run';
27
28
  export const SAMPLE_DRY_RUN_REQUEST_ID = SAMPLE_REQUEST_ID;
29
+ /**
30
+ * Canned JUnit XML for batch `--wait --report junit --dry-run`. Mirrors the
31
+ * fresh batch-run sample ids so agents can learn the sidecar shape offline.
32
+ */
33
+ export function sampleJUnitReportXml(projectId = SAMPLE_PROJECT_ID, reportSuiteName) {
34
+ return buildJUnitReport({
35
+ suiteName: reportSuiteName ?? `testsprite:${projectId}`,
36
+ classname: projectId,
37
+ results: [
38
+ {
39
+ testId: SAMPLE_TEST_ID_FRESH_1,
40
+ runId: SAMPLE_BATCH_FRESH_RUN_ID_1,
41
+ status: 'passed',
42
+ },
43
+ {
44
+ testId: SAMPLE_TEST_ID_FRESH_2,
45
+ runId: SAMPLE_BATCH_FRESH_RUN_ID_2,
46
+ status: 'failed',
47
+ error: {
48
+ code: 'ASSERTION',
49
+ message: 'Expected checkout heading to be visible',
50
+ exitCode: 1,
51
+ },
52
+ },
53
+ ],
54
+ });
55
+ }
28
56
  const me = {
29
57
  userId: SAMPLE_USER_ID,
30
58
  keyId: SAMPLE_KEY_ID,
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Pure aggregation + rendering for `test flaky` — the repeat-run flaky-test
3
+ * detector. This module performs no I/O: the orchestrator in
4
+ * `commands/test.ts` feeds it the per-attempt outcomes, and it returns a
5
+ * machine-readable stability report plus the text rendering and exit code.
6
+ *
7
+ * Keeping the scoring logic pure makes it trivially unit-testable in isolation
8
+ * (deterministic, no network / credentials), matching the repo's mock-based
9
+ * test convention.
10
+ */
11
+ /**
12
+ * Outcome of a single flaky-detector attempt. The first four mirror the
13
+ * terminal `RunStatus` values; `timeout` and `error` are orchestration
14
+ * outcomes (per-attempt deadline exceeded, or a non-fatal trigger/transport
15
+ * error that was recorded rather than aborting the whole probe).
16
+ */
17
+ export type FlakyOutcome = 'passed' | 'failed' | 'blocked' | 'cancelled' | 'timeout' | 'error';
18
+ /** Overall stability verdict across all observed attempts. */
19
+ export type FlakyVerdict = 'stable' | 'flaky' | 'failing';
20
+ /** One recorded attempt in a flaky run. */
21
+ export interface FlakyAttempt {
22
+ /** 1-based attempt index. */
23
+ attempt: number;
24
+ /** The runId of this attempt, or `null` when the trigger never returned one. */
25
+ runId: string | null;
26
+ outcome: FlakyOutcome;
27
+ /**
28
+ * Server `failureKind` for non-passing runs (or the error code for `error`
29
+ * outcomes). `null` / omitted when the attempt passed or the kind is unknown.
30
+ */
31
+ failureKind?: string | null;
32
+ }
33
+ /** A single non-passing attempt as surfaced in the report. */
34
+ export interface FlakyFailure {
35
+ attempt: number;
36
+ runId: string | null;
37
+ outcome: FlakyOutcome;
38
+ failureKind: string | null;
39
+ }
40
+ /**
41
+ * Machine-readable stability report. This is also the exact `--output json`
42
+ * shape, so dashboards / agents / CI can consume it directly.
43
+ */
44
+ export interface FlakyReport {
45
+ testId: string;
46
+ /**
47
+ * Attempts actually observed. May be fewer than requested when
48
+ * `--until-fail` short-circuits on the first non-passing attempt.
49
+ */
50
+ runs: number;
51
+ passed: number;
52
+ failed: number;
53
+ /** `passed / runs`, rounded to 4 decimal places. `0` when `runs === 0`. */
54
+ stableRatio: number;
55
+ verdict: FlakyVerdict;
56
+ /** Non-passing attempts, in attempt order. */
57
+ failures: FlakyFailure[];
58
+ }
59
+ /**
60
+ * Aggregate per-attempt outcomes into a stability report.
61
+ *
62
+ * Verdict rules:
63
+ * - every attempt passed → `stable`
64
+ * - no attempt passed → `failing`
65
+ * - a mix of pass and non-pass → `flaky`
66
+ * An empty attempt list (no runs observed) is reported as `failing` with a
67
+ * `0` ratio — there is no evidence the test is stable.
68
+ */
69
+ export declare function summarizeFlaky(testId: string, attempts: FlakyAttempt[]): FlakyReport;
70
+ /**
71
+ * Exit code for the command: `0` only when the verdict is `stable` (every
72
+ * observed attempt passed). Anything else is non-zero so CI can gate a merge
73
+ * on flakiness (`testsprite test flaky <id> --runs 5 || exit 1`).
74
+ */
75
+ export declare function flakyExitCode(report: FlakyReport): number;
76
+ /**
77
+ * Render a report to human-readable text. JSON-mode callers ship the report
78
+ * verbatim via `out.print`; this is the text-mode rendering.
79
+ */
80
+ export declare function renderFlakyText(report: FlakyReport): string;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Pure aggregation + rendering for `test flaky` — the repeat-run flaky-test
3
+ * detector. This module performs no I/O: the orchestrator in
4
+ * `commands/test.ts` feeds it the per-attempt outcomes, and it returns a
5
+ * machine-readable stability report plus the text rendering and exit code.
6
+ *
7
+ * Keeping the scoring logic pure makes it trivially unit-testable in isolation
8
+ * (deterministic, no network / credentials), matching the repo's mock-based
9
+ * test convention.
10
+ */
11
+ /**
12
+ * Aggregate per-attempt outcomes into a stability report.
13
+ *
14
+ * Verdict rules:
15
+ * - every attempt passed → `stable`
16
+ * - no attempt passed → `failing`
17
+ * - a mix of pass and non-pass → `flaky`
18
+ * An empty attempt list (no runs observed) is reported as `failing` with a
19
+ * `0` ratio — there is no evidence the test is stable.
20
+ */
21
+ export function summarizeFlaky(testId, attempts) {
22
+ const runs = attempts.length;
23
+ const passed = attempts.filter(a => a.outcome === 'passed').length;
24
+ const failed = runs - passed;
25
+ const stableRatio = runs === 0 ? 0 : Math.round((passed / runs) * 10000) / 10000;
26
+ const verdict = runs > 0 && passed === runs ? 'stable' : passed === 0 ? 'failing' : 'flaky';
27
+ const failures = attempts
28
+ .filter(a => a.outcome !== 'passed')
29
+ .map(a => ({
30
+ attempt: a.attempt,
31
+ runId: a.runId,
32
+ outcome: a.outcome,
33
+ failureKind: a.failureKind ?? null,
34
+ }));
35
+ return { testId, runs, passed, failed, stableRatio, verdict, failures };
36
+ }
37
+ /**
38
+ * Exit code for the command: `0` only when the verdict is `stable` (every
39
+ * observed attempt passed). Anything else is non-zero so CI can gate a merge
40
+ * on flakiness (`testsprite test flaky <id> --runs 5 || exit 1`).
41
+ */
42
+ export function flakyExitCode(report) {
43
+ return report.verdict === 'stable' ? 0 : 1;
44
+ }
45
+ /** Human-readable label for a verdict. */
46
+ function verdictLabel(verdict) {
47
+ switch (verdict) {
48
+ case 'stable':
49
+ return 'STABLE';
50
+ case 'flaky':
51
+ return 'FLAKY';
52
+ case 'failing':
53
+ return 'FAILING';
54
+ }
55
+ }
56
+ /**
57
+ * Render a report to human-readable text. JSON-mode callers ship the report
58
+ * verbatim via `out.print`; this is the text-mode rendering.
59
+ */
60
+ export function renderFlakyText(report) {
61
+ const pct = Math.round(report.stableRatio * 100);
62
+ const lines = [
63
+ `Ran ${report.testId} ${report.runs}x — ${report.passed} passed, ${report.failed} failed → ` +
64
+ `${verdictLabel(report.verdict)} (${pct}% stable)`,
65
+ ];
66
+ if (report.failures.length > 0) {
67
+ lines.push(' failed attempts:');
68
+ for (const f of report.failures) {
69
+ const kind = f.failureKind ? ` failureKind=${f.failureKind}` : '';
70
+ const rid = f.runId ?? '(no runId)';
71
+ lines.push(` #${f.attempt} ${rid} ${f.outcome}${kind}`);
72
+ }
73
+ }
74
+ return lines.join('\n');
75
+ }
76
+ //# sourceMappingURL=flaky.js.map
@@ -1,4 +1,5 @@
1
1
  import type { ErrorCode } from './errors.js';
2
+ import { ApiError } from './errors.js';
2
3
  import type { TriggerRunBody, TriggerRunResponse, RunResponse, RerunRequest, RerunResponse, BatchRerunRequest, BatchRerunResponse, BatchRunFreshRequest, BatchRunFreshResponse, ListRunsQuery, ListRunsResponse } from './runs.types.js';
3
4
  export type FetchImpl = typeof globalThis.fetch;
4
5
  export type DebugEventKind = 'request' | 'response' | 'retry' | 'error';
@@ -252,4 +253,23 @@ export declare class HttpClient {
252
253
  request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
253
254
  }
254
255
  export declare function buildUrl(baseUrl: string, path: string, query?: Record<string, string | number | boolean | undefined>): string;
256
+ /**
257
+ * Build a typed error for a successful response whose body could not be parsed
258
+ * as JSON.
259
+ *
260
+ * The CLI expects every API response to be a JSON envelope. When a `200 OK`
261
+ * carries a non-JSON body — a misconfigured endpoint, a proxy / captive-portal
262
+ * / SSO login page returning HTML with a success status, or an empty body —
263
+ * `response.json()` throws a raw `SyntaxError`. Left unhandled it escapes to
264
+ * the top-level handler in `index.ts`, which prints a bare
265
+ * `{"error":"<parse message>"}` under `--output json` (breaking the
266
+ * typed-envelope contract every other error honors) and gives the operator no
267
+ * actionable context.
268
+ *
269
+ * This wraps it in a typed `INTERNAL` `ApiError` (exit 1, unchanged) that
270
+ * carries the `requestId`, names the likely cause, and points the operator at
271
+ * their endpoint configuration. `details` includes the HTTP status, the
272
+ * response `content-type` (when present), and the underlying parse message.
273
+ */
274
+ export declare function malformedResponseError(response: Response, requestId: string, cause: unknown): ApiError;
255
275
  export declare function parseRetryAfter(headerValue: string | null): number | undefined;