@testsprite/testsprite-cli 0.13.0 → 0.15.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 (81) hide show
  1. package/README.md +54 -49
  2. package/dist/commands/ci.d.ts +66 -17
  3. package/dist/commands/ci.js +466 -104
  4. package/dist/commands/doctor.d.ts +3 -0
  5. package/dist/commands/doctor.js +62 -20
  6. package/dist/commands/init.js +17 -3
  7. package/dist/commands/project-env.d.ts +11 -1
  8. package/dist/commands/project-env.js +399 -61
  9. package/dist/commands/project-sign-in.d.ts +60 -0
  10. package/dist/commands/project-sign-in.js +289 -0
  11. package/dist/commands/project.d.ts +9 -0
  12. package/dist/commands/project.js +82 -28
  13. package/dist/commands/schedule.d.ts +12 -0
  14. package/dist/commands/schedule.js +175 -5
  15. package/dist/commands/test.d.ts +126 -30
  16. package/dist/commands/test.js +1928 -447
  17. package/dist/commands/testlist.d.ts +10 -5
  18. package/dist/commands/testlist.js +170 -30
  19. package/dist/commands/tunnel.js +11 -5
  20. package/dist/index.js +17 -38
  21. package/dist/lib/agent-targets.d.ts +8 -3
  22. package/dist/lib/agent-targets.js +15 -4
  23. package/dist/lib/ci-run.d.ts +11 -0
  24. package/dist/lib/ci-run.js +34 -0
  25. package/dist/lib/client-factory.d.ts +35 -1
  26. package/dist/lib/client-factory.js +21 -10
  27. package/dist/lib/config.d.ts +1 -0
  28. package/dist/lib/config.js +1 -1
  29. package/dist/lib/credentials.d.ts +0 -1
  30. package/dist/lib/credentials.js +51 -14
  31. package/dist/lib/dry-run/samples.js +95 -1
  32. package/dist/lib/environment-tunnel.d.ts +109 -0
  33. package/dist/lib/environment-tunnel.js +465 -0
  34. package/dist/lib/errors.js +12 -1
  35. package/dist/lib/first-suite-hint.d.ts +55 -0
  36. package/dist/lib/first-suite-hint.js +101 -0
  37. package/dist/lib/gh-output.d.ts +62 -4
  38. package/dist/lib/gh-output.js +152 -7
  39. package/dist/lib/github-context.d.ts +21 -0
  40. package/dist/lib/github-context.js +153 -0
  41. package/dist/lib/http.d.ts +12 -1
  42. package/dist/lib/http.js +9 -1
  43. package/dist/lib/junit-report.d.ts +11 -7
  44. package/dist/lib/junit-report.js +13 -7
  45. package/dist/lib/local-target.d.ts +13 -3
  46. package/dist/lib/local-target.js +47 -12
  47. package/dist/lib/output.js +15 -1
  48. package/dist/lib/plan-poll.js +3 -4
  49. package/dist/lib/plans.types.d.ts +1 -1
  50. package/dist/lib/redact.d.ts +38 -0
  51. package/dist/lib/redact.js +140 -0
  52. package/dist/lib/render-error.d.ts +19 -5
  53. package/dist/lib/render-error.js +31 -0
  54. package/dist/lib/response-schemas.d.ts +5 -1
  55. package/dist/lib/response-schemas.js +54 -0
  56. package/dist/lib/runs.types.d.ts +115 -1
  57. package/dist/lib/target-url.js +5 -5
  58. package/dist/lib/telemetry.d.ts +31 -8
  59. package/dist/lib/telemetry.js +55 -7
  60. package/dist/lib/testlist.types.d.ts +1 -0
  61. package/dist/lib/ticker.d.ts +9 -0
  62. package/dist/lib/ticker.js +18 -0
  63. package/dist/lib/tunnel-session.d.ts +3 -4
  64. package/dist/lib/tunnel-session.js +3 -4
  65. package/dist/lib/v3-advisory.js +0 -1
  66. package/dist/vendor/tunnel-client/client.d.ts +15 -8
  67. package/dist/vendor/tunnel-client/client.js +477 -407
  68. package/dist/vendor/tunnel-client/config.d.ts +5 -5
  69. package/dist/vendor/tunnel-client/config.js +5 -5
  70. package/dist/vendor/tunnel-client/index.d.ts +4 -4
  71. package/dist/vendor/tunnel-client/index.js +4 -4
  72. package/dist/vendor/tunnel-client/types.d.ts +19 -34
  73. package/dist/vendor/tunnel-client/types.js +1 -0
  74. package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
  75. package/dist/vendor/tunnel-client/ws-compat.js +70 -12
  76. package/dist/version.d.ts +1 -1
  77. package/dist/version.js +1 -1
  78. package/package.json +1 -1
  79. package/schemas/plan.schema.json +2 -2
  80. package/skills/testsprite-ci.skill.md +154 -0
  81. package/skills/testsprite-onboard.skill.md +4 -4
@@ -32,7 +32,7 @@
32
32
  */
33
33
  export declare const LOOPBACK_HOSTS: readonly ["localhost", "127.0.0.1", "::1"];
34
34
  export type LoopbackHost = (typeof LOOPBACK_HOSTS)[number];
35
- /** Default `--local-host`. An IP literal, so no resolver is involved at all. */
35
+ /** Default host for a new `--local <port>` shorthand target. */
36
36
  export declare const DEFAULT_LOCAL_HOST: LoopbackHost;
37
37
  /**
38
38
  * Per-candidate dial budget. Deliberately short: this is a loopback connect on
@@ -68,6 +68,13 @@ export declare function parseLocalPort(raw: string): number;
68
68
  * caller's own machine and nothing else, so a non-loopback value here is a
69
69
  * misunderstanding to correct immediately, not a request to forward.
70
70
  */
71
+ /**
72
+ * The loopback spelling a host string names, or `undefined` when it names
73
+ * anything else. Accepts bracketed IPv6 (`[::1]`, as `URL.hostname` renders
74
+ * it) and any letter case. This is the membership question; callers that
75
+ * need a refusal on a miss use {@link normalizeLocalHost}.
76
+ */
77
+ export declare function loopbackHost(raw: string): LoopbackHost | undefined;
71
78
  export declare function normalizeLocalHost(raw: string | undefined): LoopbackHost;
72
79
  /**
73
80
  * `normalizeLocalHost` for a command whose alternative to `--local` is `--url`
@@ -80,13 +87,15 @@ export interface StoredLocalTarget {
80
87
  host: LoopbackHost;
81
88
  port: number;
82
89
  }
90
+ /** Parse a loopback origin that the stored-target API and tunnel can reach. */
91
+ export declare function parseLoopbackTargetUrl(raw: string, field?: string): StoredLocalTarget | undefined;
83
92
  /**
84
93
  * Parse the `--local` / `--local-host` / `--url` trio a stored-target write
85
94
  * takes. `--local` and `--url` are two spellings of one field, so both is a
86
95
  * contradiction; `--local-host` only means something next to `--local`; the
87
96
  * port is validated strictly because it becomes part of a URL runs are billed
88
- * against. Returns the local target, or `undefined` when `--url` (or nothing)
89
- * was given.
97
+ * against. Returns the local target for either shorthand or loopback URL input,
98
+ * or `undefined` for a public URL (or no target).
90
99
  */
91
100
  export declare function parseStoredLocalTarget(opts: {
92
101
  local?: string;
@@ -124,4 +133,5 @@ export declare function probeLocalPort(host: string, port: number, deps?: LocalP
124
133
  */
125
134
  export declare function assertLocalPortListening(host: LoopbackHost | string, port: number, opts: {
126
135
  skipPreflight?: boolean;
136
+ environmentName?: string;
127
137
  }, _stderrFn: (line: string) => void, deps?: LocalPortProbeDeps): Promise<void>;
@@ -34,8 +34,8 @@ import { resolveDialCandidates } from '../vendor/tunnel-client/index.js';
34
34
  * value this rejects but the server accepts is a capability silently withheld.
35
35
  */
36
36
  export const LOOPBACK_HOSTS = ['localhost', '127.0.0.1', '::1'];
37
- /** Default `--local-host`. An IP literal, so no resolver is involved at all. */
38
- export const DEFAULT_LOCAL_HOST = '127.0.0.1';
37
+ /** Default host for a new `--local <port>` shorthand target. */
38
+ export const DEFAULT_LOCAL_HOST = 'localhost';
39
39
  /**
40
40
  * Per-candidate dial budget. Deliberately short: this is a loopback connect on
41
41
  * the caller's own machine, where a live listener answers in microseconds. A
@@ -60,12 +60,21 @@ export function parseLocalPort(raw) {
60
60
  * caller's own machine and nothing else, so a non-loopback value here is a
61
61
  * misunderstanding to correct immediately, not a request to forward.
62
62
  */
63
+ /**
64
+ * The loopback spelling a host string names, or `undefined` when it names
65
+ * anything else. Accepts bracketed IPv6 (`[::1]`, as `URL.hostname` renders
66
+ * it) and any letter case. This is the membership question; callers that
67
+ * need a refusal on a miss use {@link normalizeLocalHost}.
68
+ */
69
+ export function loopbackHost(raw) {
70
+ const unbracketed = raw.startsWith('[') && raw.endsWith(']') ? raw.slice(1, -1) : raw;
71
+ const candidate = unbracketed.trim().toLowerCase();
72
+ return LOOPBACK_HOSTS.find(host => host === candidate);
73
+ }
63
74
  export function normalizeLocalHost(raw) {
64
75
  if (raw === undefined)
65
76
  return DEFAULT_LOCAL_HOST;
66
- const unbracketed = raw.startsWith('[') && raw.endsWith(']') ? raw.slice(1, -1) : raw;
67
- const candidate = unbracketed.trim().toLowerCase();
68
- const match = LOOPBACK_HOSTS.find(host => host === candidate);
77
+ const match = loopbackHost(raw);
69
78
  if (match === undefined) {
70
79
  throw localValidationError('local-host', `must name your own machine — one of ${LOOPBACK_HOSTS.join(', ')}. ` +
71
80
  'A tunnel only reaches the machine running this CLI; to test a reachable ' +
@@ -89,13 +98,34 @@ export function normalizeStoredLocalHost(raw) {
89
98
  throw err;
90
99
  }
91
100
  }
101
+ /** Parse a loopback origin that the stored-target API and tunnel can reach. */
102
+ export function parseLoopbackTargetUrl(raw, field = 'target-url') {
103
+ let parsed;
104
+ try {
105
+ parsed = new URL(raw);
106
+ }
107
+ catch {
108
+ return undefined;
109
+ }
110
+ const host = loopbackHost(parsed.hostname);
111
+ if (host === undefined)
112
+ return undefined;
113
+ // Read the explicit port from the input: URL.port drops the default :80.
114
+ const match = /^http:\/\/(localhost|127\.0\.0\.1|\[::1\]):([0-9]+)\/?$/.exec(raw);
115
+ const port = match === null ? 0 : Number(match[2]);
116
+ if (match === null || !Number.isInteger(port) || port < 1 || port > 65535) {
117
+ throw localValidationError(field, 'loopback URLs must use http://localhost:<port>, http://127.0.0.1:<port>, or http://[::1]:<port>, with a port between 1 and 65535 and no path ' +
118
+ '(an optional trailing / is allowed), query, fragment, or credentials');
119
+ }
120
+ return { host, port };
121
+ }
92
122
  /**
93
123
  * Parse the `--local` / `--local-host` / `--url` trio a stored-target write
94
124
  * takes. `--local` and `--url` are two spellings of one field, so both is a
95
125
  * contradiction; `--local-host` only means something next to `--local`; the
96
126
  * port is validated strictly because it becomes part of a URL runs are billed
97
- * against. Returns the local target, or `undefined` when `--url` (or nothing)
98
- * was given.
127
+ * against. Returns the local target for either shorthand or loopback URL input,
128
+ * or `undefined` for a public URL (or no target).
99
129
  */
100
130
  export function parseStoredLocalTarget(opts) {
101
131
  if (opts.local !== undefined && opts.url !== undefined) {
@@ -104,8 +134,9 @@ export function parseStoredLocalTarget(opts) {
104
134
  if (opts.localHost !== undefined && opts.local === undefined) {
105
135
  throw flagPairError('--local-host requires --local');
106
136
  }
107
- if (opts.local === undefined)
108
- return undefined;
137
+ if (opts.local === undefined) {
138
+ return opts.url === undefined ? undefined : parseLoopbackTargetUrl(opts.url, 'url');
139
+ }
109
140
  if (!/^\d+$/.test(opts.local)) {
110
141
  throw flagPairError('--local must be a port number between 1 and 65535');
111
142
  }
@@ -243,9 +274,13 @@ export async function assertLocalPortListening(host, port, opts, _stderrFn, deps
243
274
  throw ApiError.fromEnvelope({
244
275
  error: {
245
276
  code: 'VALIDATION_ERROR',
246
- message: `Nothing is listening on ${host}:${port}, so a tunnel run would fail after being billed.`,
247
- nextAction: `Start your app on port ${port} first, or point --local at the port it is actually ` +
248
- `serving. ${SKIP_HINT}`,
277
+ message: opts.environmentName !== undefined
278
+ ? `Nothing is listening on ${host}:${port} (environment "${opts.environmentName}"). Start your app or run with --skip-preflight.`
279
+ : `Nothing is listening on ${host}:${port}, so a tunnel run would fail after being billed.`,
280
+ nextAction: opts.environmentName !== undefined
281
+ ? `Start your app on ${host}:${port} (environment "${opts.environmentName}") or run with --skip-preflight.`
282
+ : `Start your app on port ${port} first, or point --local at the port it is actually ` +
283
+ `serving. ${SKIP_HINT}`,
249
284
  requestId: 'local',
250
285
  details: {
251
286
  field: 'local',
@@ -1,4 +1,5 @@
1
1
  import { localValidationError } from './errors.js';
2
+ import { redactDeep } from './redact.js';
2
3
  /**
3
4
  * Help-text footer pointing at the global options surface so users
4
5
  * looking at any subcommand `--help` don't miss `--dry-run`, `--output`,
@@ -50,6 +51,15 @@ export class Output {
50
51
  this.rawStdoutWrite = streams.rawStdout ?? defaultRawStdout;
51
52
  }
52
53
  print(data, textRenderer) {
54
+ // Success data is the caller's OWN content — generated test code, plans,
55
+ // backend-test fixtures — and must round-trip byte-identical (`test code
56
+ // get --output json` -> edit -> `test code put`), even when it
57
+ // legitimately contains a literal `Authorization: Bearer …` header or a
58
+ // `password` fixture key. Never redacted here, in either mode. Secret
59
+ // redaction (see `redact.ts`) applies only at error and request-trace
60
+ // boundaries — `Output.error` below, the ApiError envelope in
61
+ // `index.ts`, and `--debug` tracing in `client-factory.ts` — never to a
62
+ // success payload.
53
63
  if (this.mode === 'json' || !textRenderer) {
54
64
  this.stdoutWrite(JSON.stringify(data, null, 2));
55
65
  return;
@@ -84,7 +94,11 @@ export class Output {
84
94
  message: input.message,
85
95
  nextAction: input.nextAction ?? '',
86
96
  requestId: input.requestId ?? 'local',
87
- details: input.details ?? {},
97
+ // Defence in depth: `details` from a server envelope is already
98
+ // redacted server-side and (for an ApiError) at construction — see
99
+ // `errors.ts` — but this render boundary redacts again so no path
100
+ // that builds an envelope by hand here can ever skip it.
101
+ details: redactDeep(input.details ?? {}),
88
102
  },
89
103
  };
90
104
  this.stderrWrite(JSON.stringify(envelope, null, 2));
@@ -370,10 +370,9 @@ async function ladderLoop(client, projectId, options) {
370
370
  throw ApiError.fromEnvelope({
371
371
  error: {
372
372
  code: 'INTERNAL',
373
- message: `Plan generation appears stuck: ${state.triggerPosts} trigger request(s) ` +
374
- `(${state.acceptedPosts} accepted) but the server still reports no staged ` +
375
- `proposals and nothing running.`,
376
- nextAction: 'Retry later or check the project in the Portal. If this persists, report the requestId to support@testsprite.com.',
373
+ message: `Plan generation is not making progress after ${state.triggerPosts} ` +
374
+ `${state.triggerPosts === 1 ? 'try' : 'tries'}: nothing new is staged and no stage is running.`,
375
+ nextAction: 'Wait a few minutes, then run the same command again. If this keeps happening, check the project in the Portal or contact support@testsprite.com.',
377
376
  requestId: 'local',
378
377
  details: {
379
378
  projectId,
@@ -58,7 +58,7 @@ export interface CliPlanProposal {
58
58
  proposalId: string;
59
59
  title: string;
60
60
  description: string;
61
- /** CLI priority vocabulary (`p1`..`p3`, mapped from V3 High/Medium/Low). */
61
+ /** Priority as the CLI shows it: `p0` (High), `p1` (Medium), `p2` (Low). */
62
62
  priority: string;
63
63
  category: string;
64
64
  feature: string;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Recursive, key-based secret redaction for CLI output.
3
+ *
4
+ * Before this module, the only redaction anywhere in the codebase was
5
+ * `tunnel-session.ts`'s `redactTunnelSecret` — a literal `String.replaceAll`
6
+ * of an ALREADY-KNOWN secret value out of a single log line. That only works
7
+ * when the caller already holds the plaintext to search for; it does nothing
8
+ * for an arbitrary server error `details` blob or a `--debug` trace, where
9
+ * the secret has to be found by its KEY name (`password`, `apiKey`, …), not
10
+ * by a value the caller can search for. This module fills that gap.
11
+ *
12
+ * Deliberately NOT applied to `Output.print`'s success data: generated test
13
+ * code, plans and backend-test fixtures are the user's OWN content and must
14
+ * round-trip byte-identical (`test code get --output json` -> edit ->
15
+ * `test code put`), even when they legitimately contain a literal
16
+ * `Authorization: Bearer …` header or a `password` fixture key — that is
17
+ * not a secret the CLI is leaking, it is the value the user is asking to see
18
+ * back. Applied instead at `Output.error`'s `details`, the hand-built
19
+ * ApiError envelope in `index.ts`, and the `--debug` / dry-run request
20
+ * tracing in `client-factory.ts` — server/error prose and request traces,
21
+ * never the user's stored data — and never at request-construction time (the
22
+ * real secret still has to go out on the wire). `--dry-run` previews that
23
+ * commands print are built from non-secret shapes (booleans such as
24
+ * `hasCredentials`, field names), so they never carry a secret to redact.
25
+ */
26
+ export declare const REDACTED = "[REDACTED]";
27
+ /**
28
+ * Deep-walk `value`, replacing:
29
+ * - the string value of any object key matching {@link isSecretKey}, at any
30
+ * depth, arrays included, with {@link REDACTED};
31
+ * - a `Bearer <token>` substring inside any other string, wherever it
32
+ * appears (key name irrelevant).
33
+ *
34
+ * Never mutates its input — returns a new tree. Plain data only (the values
35
+ * that ever reach here are parsed JSON or plain option objects); a `Date`,
36
+ * `Map`, etc. is returned unchanged rather than walked.
37
+ */
38
+ export declare function redactDeep<T>(value: T): T;
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Recursive, key-based secret redaction for CLI output.
3
+ *
4
+ * Before this module, the only redaction anywhere in the codebase was
5
+ * `tunnel-session.ts`'s `redactTunnelSecret` — a literal `String.replaceAll`
6
+ * of an ALREADY-KNOWN secret value out of a single log line. That only works
7
+ * when the caller already holds the plaintext to search for; it does nothing
8
+ * for an arbitrary server error `details` blob or a `--debug` trace, where
9
+ * the secret has to be found by its KEY name (`password`, `apiKey`, …), not
10
+ * by a value the caller can search for. This module fills that gap.
11
+ *
12
+ * Deliberately NOT applied to `Output.print`'s success data: generated test
13
+ * code, plans and backend-test fixtures are the user's OWN content and must
14
+ * round-trip byte-identical (`test code get --output json` -> edit ->
15
+ * `test code put`), even when they legitimately contain a literal
16
+ * `Authorization: Bearer …` header or a `password` fixture key — that is
17
+ * not a secret the CLI is leaking, it is the value the user is asking to see
18
+ * back. Applied instead at `Output.error`'s `details`, the hand-built
19
+ * ApiError envelope in `index.ts`, and the `--debug` / dry-run request
20
+ * tracing in `client-factory.ts` — server/error prose and request traces,
21
+ * never the user's stored data — and never at request-construction time (the
22
+ * real secret still has to go out on the wire). `--dry-run` previews that
23
+ * commands print are built from non-secret shapes (booleans such as
24
+ * `hasCredentials`, field names), so they never carry a secret to redact.
25
+ */
26
+ export const REDACTED = '[REDACTED]';
27
+ /**
28
+ * Key-name suffixes (case-insensitive, separators ignored) whose STRING
29
+ * value is replaced by {@link REDACTED}. A suffix match, not a substring or
30
+ * exact match: it has to catch the realistic compound names a server or a
31
+ * future field could use (`refreshToken`, `clientSecret`, `x-api-key`,
32
+ * `Set-Cookie`) while still excluding names that merely contain the word,
33
+ * such as `credentialsPath` (a filesystem path, ends in "path") or
34
+ * `tokenEndpoint` (a URL, ends in "endpoint").
35
+ *
36
+ * Only applied when the value is a `string`. Two real shapes in this
37
+ * codebase would otherwise break under a type-blind rule:
38
+ * - `ci init`'s JSON output has a top-level `secret: {name, attempted, set,
39
+ * reason}` object describing metadata ABOUT a GitHub secret, never the
40
+ * secret's value.
41
+ * - `CliProjectEnvironment.hasCredentials` is a boolean PRESENCE flag, not
42
+ * a credential.
43
+ * Both keys are left untouched by the string-only guard below, and their
44
+ * children are still walked recursively (so an object nested under a
45
+ * matching key can carry its own, separately-matched, leaf secret).
46
+ */
47
+ const SECRET_KEY_SUFFIXES = [
48
+ 'password',
49
+ 'secret',
50
+ 'apikey',
51
+ 'authorization',
52
+ 'cookie',
53
+ 'credential',
54
+ 'credentials',
55
+ ];
56
+ /**
57
+ * Exact (post-normalization) key names treated as an auth token — NOT a
58
+ * suffix rule like the list above. This CLI's own pagination continuation
59
+ * handles are also literally named "...Token" (`nextToken`, `startingToken`)
60
+ * and are opaque cursors, not secrets; a suffix match on "token" would blank
61
+ * them (`test result --history`'s `nextToken`, `project list`'s
62
+ * `startingToken`/`nextToken`). Add a new compound auth-token name here, not
63
+ * to the suffix list above.
64
+ */
65
+ const SECRET_TOKEN_KEYS = new Set([
66
+ 'token',
67
+ 'apitoken',
68
+ 'authtoken',
69
+ 'accesstoken',
70
+ 'refreshtoken',
71
+ 'bearertoken',
72
+ 'idtoken',
73
+ 'sessiontoken',
74
+ ]);
75
+ /** Lowercase and strip every non-alphanumeric character for key matching. */
76
+ function normalizeKey(key) {
77
+ return key.replace(/[^a-z0-9]/gi, '').toLowerCase();
78
+ }
79
+ function isSecretKey(key) {
80
+ const normalized = normalizeKey(key);
81
+ if (SECRET_TOKEN_KEYS.has(normalized))
82
+ return true;
83
+ return SECRET_KEY_SUFFIXES.some(suffix => normalized.endsWith(suffix));
84
+ }
85
+ /**
86
+ * A conservative check for a secret-shaped string VALUE regardless of its
87
+ * key name — a bearer token embedded in server/error prose (e.g. inside a
88
+ * free-form `message`/`nextAction` string) has no key to match on.
89
+ * Deliberately narrow: only the `Bearer <token>` wire form, and only when
90
+ * the run of token characters contains an actual DIGIT, so an ordinary
91
+ * hyphenated or dotted phrase — "a Bearer authentication header", "Bearer
92
+ * token-based auth" — is left alone. A separator alone used to be enough
93
+ * (any of `._~+/=-`), which let the `{8,}` scan's greedy, position-blind
94
+ * match swallow a whole compound word merely because it contained a hyphen
95
+ * — a broader entropy/length heuristic would also flag long environment
96
+ * names, test ids, or UUIDs, which must never be redacted.
97
+ */
98
+ const BEARER_TOKEN_RE = /\bBearer\s+(?=[A-Za-z0-9._~+/=-]*[0-9])[A-Za-z0-9._~+/=-]{8,}/gi;
99
+ /**
100
+ * Keys whose object value is user-authored data shown back on purpose:
101
+ * environment `variables` are plaintext by design (a variable named
102
+ * `DB_PASSWORD` is the user's own fixture value), so they are never masked.
103
+ */
104
+ const VERBATIM_KEYS = new Set(['variables']);
105
+ /** Replace any `Bearer <token>` substring inside a free-form string. */
106
+ function redactSecretLookingSubstrings(value) {
107
+ return value.replace(BEARER_TOKEN_RE, `Bearer ${REDACTED}`);
108
+ }
109
+ /**
110
+ * Deep-walk `value`, replacing:
111
+ * - the string value of any object key matching {@link isSecretKey}, at any
112
+ * depth, arrays included, with {@link REDACTED};
113
+ * - a `Bearer <token>` substring inside any other string, wherever it
114
+ * appears (key name irrelevant).
115
+ *
116
+ * Never mutates its input — returns a new tree. Plain data only (the values
117
+ * that ever reach here are parsed JSON or plain option objects); a `Date`,
118
+ * `Map`, etc. is returned unchanged rather than walked.
119
+ */
120
+ export function redactDeep(value) {
121
+ if (Array.isArray(value)) {
122
+ return value.map(item => redactDeep(item));
123
+ }
124
+ if (typeof value === 'string') {
125
+ return redactSecretLookingSubstrings(value);
126
+ }
127
+ if (value !== null && typeof value === 'object' && value.constructor === Object) {
128
+ const result = {};
129
+ for (const [key, v] of Object.entries(value)) {
130
+ if (VERBATIM_KEYS.has(key) && v !== null && typeof v === 'object' && !Array.isArray(v)) {
131
+ result[key] = v;
132
+ continue;
133
+ }
134
+ result[key] = isSecretKey(key) && typeof v === 'string' ? REDACTED : redactDeep(v);
135
+ }
136
+ return result;
137
+ }
138
+ return value;
139
+ }
140
+ //# sourceMappingURL=redact.js.map
@@ -1,10 +1,24 @@
1
+ import type { InterruptError } from './errors.js';
2
+ import type { OutputMode } from './output.js';
3
+ /** The JSON-mode stderr envelope for a signal detach (errors.md §8.1). */
4
+ export interface InterruptEnvelope {
5
+ error: {
6
+ code: 'INTERRUPTED';
7
+ message: string;
8
+ nextAction: string;
9
+ requestId: 'local';
10
+ details: Record<string, unknown>;
11
+ };
12
+ }
1
13
  /**
2
- * Shared error rendering helpers for `src/index.ts`.
3
- *
4
- * Extracted so the output-interceptor rephrasing logic (P10) is
5
- * unit-testable without spawning a full CLI process.
14
+ * Build the `INTERRUPTED` envelope from whatever the interrupted command
15
+ * attached to the error. A tunnel run attaches `tunnelDetach` and
16
+ * `test plan generate` attaches `planDetach`; each carries its own
17
+ * `nextAction` so the envelope never contradicts the text line the catch
18
+ * block already printed. Otherwise a run wait gets the run-detach story
19
+ * (`test wait`) and any other request gets the generic check-state hint.
6
20
  */
7
- import type { OutputMode } from './output.js';
21
+ export declare function buildInterruptEnvelope(err: InterruptError): InterruptEnvelope;
8
22
  /**
9
23
  * Rephrase Commander's "unknown option '--foo'" error when `--foo` is
10
24
  * a known global flag that was placed after the subcommand.
@@ -1,3 +1,34 @@
1
+ /**
2
+ * Build the `INTERRUPTED` envelope from whatever the interrupted command
3
+ * attached to the error. A tunnel run attaches `tunnelDetach` and
4
+ * `test plan generate` attaches `planDetach`; each carries its own
5
+ * `nextAction` so the envelope never contradicts the text line the catch
6
+ * block already printed. Otherwise a run wait gets the run-detach story
7
+ * (`test wait`) and any other request gets the generic check-state hint.
8
+ */
9
+ export function buildInterruptEnvelope(err) {
10
+ const { tunnelDetach, planDetach } = err;
11
+ const nextAction = tunnelDetach?.nextAction ??
12
+ planDetach?.nextAction ??
13
+ (err.runWaitContext
14
+ ? 'The server-side run (if any) keeps executing and billing. ' +
15
+ 'Re-attach with: testsprite test wait <runId>, or stop it with: testsprite test cancel <runId> ' +
16
+ '(runId is in the partial JSON on stdout).'
17
+ : 'The request was interrupted. Check the current state before retrying; ' +
18
+ 'a multi-item command may have processed some items.');
19
+ const details = { signal: err.signal };
20
+ if (tunnelDetach) {
21
+ details.runId = tunnelDetach.runId;
22
+ details.cancelOutcome = tunnelDetach.cancel;
23
+ }
24
+ else if (planDetach) {
25
+ details.projectId = planDetach.projectId;
26
+ details.stagesRemaining = planDetach.stagesRemaining;
27
+ }
28
+ return {
29
+ error: { code: 'INTERRUPTED', message: err.message, nextAction, requestId: 'local', details },
30
+ };
31
+ }
1
32
  /**
2
33
  * Global flags that belong before the subcommand, not after it.
3
34
  *
@@ -36,7 +36,7 @@
36
36
  import * as v from 'valibot';
37
37
  import type { MeResponse } from '../commands/auth.js';
38
38
  import type { UsageResponse } from '../commands/usage.js';
39
- import type { BatchRerunResponse, BatchRunFreshResponse, CancelRunResponse, ListRunsResponse, RerunResponse, RunResponse, TriggerRunResponse } from './runs.types.js';
39
+ import type { BatchRerunResponse, BatchRunFreshResponse, CancelRunResponse, ListRunsResponse, RerunResponse, RunResponse, TriggerRunResponse, ExecutionReport, ExecutionReportResponse } from './runs.types.js';
40
40
  import type { CliTestListRunResponse } from './testlist.types.js';
41
41
  import type { TunnelListResponse, TunnelMintResponse, TunnelStatusResponse } from './tunnel.types.js';
42
42
  /** Mirrors `RunResponse` (runs.types.ts): `GET /api/cli/v1/runs/{runId}`. */
@@ -146,3 +146,7 @@ export declare const TUNNEL_MINT_RESPONSE_SCHEMA: v.GenericSchema<unknown, Tunne
146
146
  export declare const TUNNEL_STATUS_RESPONSE_SCHEMA: v.GenericSchema<unknown, TunnelStatusResponse>;
147
147
  /** Mirrors `TunnelListResponse`: a server may add status values or omit creation time. */
148
148
  export declare const TUNNEL_LIST_RESPONSE_SCHEMA: v.GenericSchema<unknown, TunnelListResponse>;
149
+ /** Mirrors `ExecutionReport` — the server's report model, kept loose so new fields pass through. */
150
+ export declare const EXECUTION_REPORT_SCHEMA: v.GenericSchema<unknown, ExecutionReport>;
151
+ /** Mirrors `ExecutionReportResponse`: `report`/`markdown` only travel with `ready: true`. */
152
+ export declare const EXECUTION_REPORT_RESPONSE_SCHEMA: v.GenericSchema<unknown, ExecutionReportResponse>;
@@ -110,6 +110,13 @@ export const RUN_RESPONSE_SCHEMA = v.looseObject({
110
110
  error: v.nullish(v.string(), null),
111
111
  videoUrl: v.nullish(v.string(), null),
112
112
  stepSummary: RUN_STEP_SUMMARY_SCHEMA,
113
+ // Optional with no default: absent on older backends. `reason` / `caveat` are
114
+ // `null` on the wire when the run carries no routing reason or caveat.
115
+ replay: v.optional(v.looseObject({
116
+ path: v.string(),
117
+ reason: v.nullish(v.string()),
118
+ caveat: v.nullish(v.string()),
119
+ })),
113
120
  retryAfterSeconds: v.optional(v.number()),
114
121
  // Portal link. Three-state wire contract (pinned): **absent** — an older
115
122
  // backend that predates this field, and cannot have produced a V3-native/
@@ -286,6 +293,8 @@ export const BATCH_RUN_FRESH_RESPONSE_SCHEMA = v.looseObject({
286
293
  runId: v.string(),
287
294
  enqueuedAt: v.string(),
288
295
  dashboardUrl: v.optional(v.string()),
296
+ // V3-served runs name their execution; an older backend omits it.
297
+ executionId: v.optional(v.string()),
289
298
  })),
290
299
  conflicts: v.array(v.looseObject({
291
300
  testId: v.string(),
@@ -296,6 +305,12 @@ export const BATCH_RUN_FRESH_RESPONSE_SCHEMA = v.looseObject({
296
305
  deferred: v.array(v.looseObject({ testId: v.string() })),
297
306
  skippedFrontend: v.array(v.string()),
298
307
  skippedIntegration: v.array(v.looseObject({ testId: v.string() })),
308
+ // Optional with no default: absent on older backends and frontend projects.
309
+ integration: v.optional(v.looseObject({
310
+ existing: v.number(),
311
+ runsAfterWave: v.boolean(),
312
+ mayGenerate: v.boolean(),
313
+ })),
299
314
  // Project-level closing link. Absent-key-preserving like `RUN_RESPONSE_SCHEMA`'s
300
315
  // `dashboardUrl` (see the note there): omitted stays ABSENT so the client
301
316
  // keeps computing its legacy template for an older backend / the V2 engine;
@@ -303,6 +318,10 @@ export const BATCH_RUN_FRESH_RESPONSE_SCHEMA = v.looseObject({
303
318
  dashboardUrl: v.nullish(v.string(), undefined),
304
319
  // An exact echo confirms that the backend read the target URL override.
305
320
  targetUrl: v.optional(v.string()),
321
+ // Same contract for the CI fields: a client that sent one and gets no
322
+ // echo was served by a backend that cut the batch / ran a plain override.
323
+ admission: v.optional(v.picklist(['budget', 'all'])),
324
+ previewName: v.optional(v.string()),
306
325
  });
307
326
  /**
308
327
  * `POST /api/cli/v1/testlist/{listId}/run`. Mirrors the batch-run-fresh shape so
@@ -466,4 +485,39 @@ export const TUNNEL_LIST_RESPONSE_SCHEMA = v.looseObject({
466
485
  createdAt: v.optional(v.nullable(v.string())),
467
486
  })),
468
487
  });
488
+ /** Mirrors `ExecutionReport` — the server's report model, kept loose so new fields pass through. */
489
+ export const EXECUTION_REPORT_SCHEMA = v.looseObject({
490
+ projectId: v.string(),
491
+ executionId: v.string(),
492
+ projectName: v.string(),
493
+ orgId: v.nullish(v.string(), null),
494
+ stats: v.looseObject({
495
+ passed: v.number(),
496
+ failed: v.number(),
497
+ blocked: v.number(),
498
+ total: v.number(),
499
+ }),
500
+ allPassed: v.boolean(),
501
+ narrative: v.nullish(v.string(), null),
502
+ whatCouldBeBetter: v.nullish(v.string(), null),
503
+ recommendedNextStep: v.nullish(v.string(), null),
504
+ tests: v.array(v.looseObject({
505
+ id: v.string(),
506
+ title: v.string(),
507
+ slug: v.nullish(v.string(), null),
508
+ status: openWireLiteral(),
509
+ screenshotUrl: v.nullish(v.string(), null),
510
+ error: v.nullish(v.string(), null),
511
+ fix: v.nullish(v.string(), null),
512
+ resultUrl: v.optional(v.string()),
513
+ })),
514
+ resultUrl: v.string(),
515
+ });
516
+ /** Mirrors `ExecutionReportResponse`: `report`/`markdown` only travel with `ready: true`. */
517
+ export const EXECUTION_REPORT_RESPONSE_SCHEMA = v.looseObject({
518
+ ready: v.boolean(),
519
+ retryAfterSeconds: v.optional(v.number()),
520
+ report: v.optional(EXECUTION_REPORT_SCHEMA),
521
+ markdown: v.optional(v.string()),
522
+ });
469
523
  //# sourceMappingURL=response-schemas.js.map