@testsprite/testsprite-cli 0.3.0 → 0.5.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 (63) hide show
  1. package/README.md +55 -29
  2. package/dist/commands/agent.js +17 -6
  3. package/dist/commands/auth.d.ts +51 -0
  4. package/dist/commands/auth.js +46 -2
  5. package/dist/commands/completion.d.ts +36 -0
  6. package/dist/commands/completion.js +111 -0
  7. package/dist/commands/doctor.js +56 -16
  8. package/dist/commands/init.d.ts +32 -1
  9. package/dist/commands/init.js +40 -10
  10. package/dist/commands/project.d.ts +102 -4
  11. package/dist/commands/project.js +250 -47
  12. package/dist/commands/test.d.ts +253 -11
  13. package/dist/commands/test.js +1822 -390
  14. package/dist/commands/usage.d.ts +56 -17
  15. package/dist/commands/usage.js +144 -29
  16. package/dist/index.js +172 -29
  17. package/dist/lib/browser.d.ts +6 -0
  18. package/dist/lib/browser.js +54 -0
  19. package/dist/lib/bundle.d.ts +32 -31
  20. package/dist/lib/bundle.js +144 -84
  21. package/dist/lib/client-factory.d.ts +29 -0
  22. package/dist/lib/client-factory.js +49 -1
  23. package/dist/lib/config.js +7 -3
  24. package/dist/lib/credentials.d.ts +17 -1
  25. package/dist/lib/credentials.js +175 -16
  26. package/dist/lib/dry-run/samples.js +51 -1
  27. package/dist/lib/errors.d.ts +33 -1
  28. package/dist/lib/errors.js +110 -19
  29. package/dist/lib/failing-fe-resolver.d.ts +15 -0
  30. package/dist/lib/failing-fe-resolver.js +49 -1
  31. package/dist/lib/flaky.d.ts +12 -1
  32. package/dist/lib/flaky.js +7 -12
  33. package/dist/lib/gh-output.d.ts +62 -0
  34. package/dist/lib/gh-output.js +99 -0
  35. package/dist/lib/http.d.ts +86 -16
  36. package/dist/lib/http.js +181 -11
  37. package/dist/lib/interrupt.d.ts +65 -10
  38. package/dist/lib/interrupt.js +94 -9
  39. package/dist/lib/org-render.d.ts +52 -0
  40. package/dist/lib/org-render.js +59 -0
  41. package/dist/lib/poll.d.ts +11 -0
  42. package/dist/lib/poll.js +71 -6
  43. package/dist/lib/render-error.d.ts +14 -0
  44. package/dist/lib/render-error.js +30 -0
  45. package/dist/lib/response-schemas.d.ts +83 -0
  46. package/dist/lib/response-schemas.js +272 -0
  47. package/dist/lib/runs.types.d.ts +62 -8
  48. package/dist/lib/skill-nudge.d.ts +17 -0
  49. package/dist/lib/skill-nudge.js +19 -0
  50. package/dist/lib/telemetry.d.ts +90 -0
  51. package/dist/lib/telemetry.js +171 -0
  52. package/dist/lib/text-table.d.ts +14 -0
  53. package/dist/lib/text-table.js +45 -0
  54. package/dist/lib/v3-advisory.d.ts +22 -0
  55. package/dist/lib/v3-advisory.js +32 -0
  56. package/dist/lib/version-notice.d.ts +37 -0
  57. package/dist/lib/version-notice.js +87 -0
  58. package/dist/version.d.ts +1 -1
  59. package/dist/version.js +1 -1
  60. package/package.json +16 -5
  61. package/schemas/plan.schema.json +61 -0
  62. package/skills/testsprite-verify.codex.md +8 -2
  63. package/skills/testsprite-verify.skill.md +18 -7
@@ -38,6 +38,19 @@ export interface RerunClosure {
38
38
  addedTeardowns: string[];
39
39
  clearedCaptured: number;
40
40
  }
41
+ /**
42
+ * A machine-readable note that a requested option was forwarded to the
43
+ * execution engine but is not yet honored there. Emitted ONLY on a
44
+ * V3-routed rerun when the caller explicitly requested `autoHeal:false` —
45
+ * absent otherwise, including every V2 response and every V3 response that
46
+ * did not request an opt-out.
47
+ */
48
+ export interface RerunAdvisory {
49
+ /** Machine-readable feature name the advisory concerns (e.g. "autoHeal"). */
50
+ feature: string;
51
+ /** Human-readable explanation of the current limitation. */
52
+ message: string;
53
+ }
41
54
  /**
42
55
  * Response from `POST /api/cli/v1/tests/{testId}/runs/rerun`.
43
56
  * FE shape: no `closure`. BE shape: includes `closure` with per-member runIds.
@@ -58,6 +71,12 @@ export interface RerunResponse {
58
71
  * the `!!closure` truthy check in the CLI already handles both).
59
72
  */
60
73
  closure?: RerunClosure | null;
74
+ /**
75
+ * Present only when this rerun was routed to V3 execution AND the caller
76
+ * explicitly requested `autoHeal:false` (see {@link RerunAdvisory}). Absent
77
+ * on every other response, including older backends that predate the field.
78
+ */
79
+ advisories?: RerunAdvisory[];
61
80
  }
62
81
  /**
63
82
  * Body sent to `POST /api/cli/v1/tests/batch/rerun`.
@@ -106,6 +125,10 @@ export interface BatchRerunClosure {
106
125
  * Present when the server supports partial-accept (SOME ids bad → 200 with accepted+notFound).
107
126
  * When ALL ids are bad the server returns 404 (caught separately in the catch block).
108
127
  * Optional for back-compat with older backends that don't send this field.
128
+ * `advisories` = present only when at least one FE test in the batch was routed to V3
129
+ * execution AND explicitly requested `autoHeal:false` (see {@link RerunAdvisory}).
130
+ * Absent on every other response. The CLI aggregates + dedupes this field across
131
+ * chunked dispatch requests (see `dedupeRerunAdvisories` in `commands/test.ts`).
109
132
  */
110
133
  export interface BatchRerunResponse {
111
134
  accepted: BatchRerunAccepted[];
@@ -113,6 +136,7 @@ export interface BatchRerunResponse {
113
136
  conflicts: BatchRerunConflict[];
114
137
  closure: BatchRerunClosure;
115
138
  notFound?: string[];
139
+ advisories?: RerunAdvisory[];
116
140
  }
117
141
  /**
118
142
  * Response from `POST /api/cli/v1/tests/{testId}/runs`.
@@ -174,8 +198,19 @@ export interface RunResponse {
174
198
  createdAt: string;
175
199
  startedAt: string | null;
176
200
  finishedAt: string | null;
177
- codeVersion: string;
178
- targetUrl: string;
201
+ /**
202
+ * Code version stamped at trigger time. `null` on pre-M3.1 rows and on
203
+ * runs whose test has no stored code body (e.g. a plan-driven frontend
204
+ * test), per the server contract (`RunEnvelope.codeVersion` is
205
+ * `[string, 'null']`).
206
+ */
207
+ codeVersion: string | null;
208
+ /**
209
+ * Target URL stamped at trigger time. `null` for backend runs and for any
210
+ * run whose execution backend does not record one, per the server contract
211
+ * (`RunEnvelope.targetUrl` is `[string, 'null']`).
212
+ */
213
+ targetUrl: string | null;
179
214
  createdFrom: string | null;
180
215
  failedStepIndex: number | null;
181
216
  failureKind: string | null;
@@ -186,12 +221,21 @@ export interface RunResponse {
186
221
  /** Optional hint from the server; honored by the polling loop. */
187
222
  retryAfterSeconds?: number;
188
223
  /**
189
- * CLIENT-synthesized Portal deep link — never sent by the server. The CLI
190
- * adds it to terminal run output (`test run --wait`, `test wait`,
191
- * `test rerun --wait`) when projectId+testId are present and the API
192
- * endpoint maps to a known portal host (see `resolvePortalUrl`).
224
+ * Portal deep link for this run's test.
225
+ *
226
+ * **Server-provided when present, client-synthesized otherwise.** Newer
227
+ * backends send this field on `GET /runs/{runId}` because only the server
228
+ * knows which store answered the read (a V3-served run's page is a different
229
+ * route family, and the V2 route it replaces cannot render for a V3-native
230
+ * project) and only the server can resolve the portal origin outside prod.
231
+ *
232
+ * A server `null` means "no correct link exists for this run" — the CLI
233
+ * treats it as absent for rendering and does NOT substitute its own guess.
234
+ * A missing field (older backend) reopens the client path: `resolvePortalUrl`
235
+ * from projectId+testId when the endpoint maps to a known portal host. See
236
+ * `withRunDashboardUrl` in `commands/test.ts`.
193
237
  */
194
- dashboardUrl?: string;
238
+ dashboardUrl?: string | null;
195
239
  /**
196
240
  * Full ordered step list. Only present when the request includes
197
241
  * `?includeSteps=true`. Absent (undefined) when the flag was not sent.
@@ -203,6 +247,15 @@ export interface RunResponse {
203
247
  */
204
248
  steps?: RunStepDto[] | null;
205
249
  }
250
+ /**
251
+ * Response from `POST /api/cli/v1/runs/{runId}/cancel`.
252
+ * Same shape as `GET /runs/{runId}` (`status: "cancelled"`, verdict
253
+ * untouched) plus `alreadyCancelled` distinguishing a fresh cancel
254
+ * (naturally idempotent) from a no-op re-cancel.
255
+ */
256
+ export interface CancelRunResponse extends RunResponse {
257
+ alreadyCancelled: boolean;
258
+ }
206
259
  /** Terminal states from the RunStatus union. */
207
260
  export declare const TERMINAL_RUN_STATUSES: ReadonlySet<RunStatus>;
208
261
  export declare function isTerminalStatus(status: RunStatus): boolean;
@@ -233,7 +286,8 @@ export interface RunHistoryItem {
233
286
  /** May be null — backend doesn't always stamp it. */
234
287
  startedAt: string | null;
235
288
  finishedAt: string | null;
236
- codeVersion: string;
289
+ /** May be null — not stamped on pre-M3.2 rows or on tests with no code body. */
290
+ codeVersion: string | null;
237
291
  /** Null when the run passed. */
238
292
  failureKind: string | null;
239
293
  /**
@@ -21,6 +21,23 @@ export declare const SKILL_NUDGE_COMMANDS: ReadonlySet<string>;
21
21
  * the CLI by hand without wiring a coding agent.
22
22
  */
23
23
  export declare const SKILL_NUDGE_OPT_OUT_ENV = "TESTSPRITE_NO_SKILL_WARNING";
24
+ /**
25
+ * True when this invocation is `test create --plan-template`, a
26
+ * pure-local/informational flag (prints the plan-file skeleton and exits)
27
+ * that must be treated like `setup` / `agent install`: exempt from BOTH the
28
+ * missing-skill nudge above AND the update-registry check
29
+ * (`src/lib/update-check.ts`'s `maybeNotifyUpdate`, which hits the network
30
+ * and writes `~/.testsprite/update-check.json` — both contradict "no
31
+ * network" for this flag). Neither allowlist (`SKILL_NUDGE_COMMANDS` here,
32
+ * the unconditional call site in `src/index.ts`) tracks individual flags,
33
+ * only whole commands, so `src/index.ts`'s `preAction` hook filters this one
34
+ * case via this pure, independently-testable helper instead of teaching
35
+ * either module about flags. Exported from `skill-nudge.ts` (rather than
36
+ * `src/index.ts`, which executes `program.parse()` at import time and so
37
+ * cannot be safely imported by a unit test) purely so it has a home that
38
+ * supports direct unit testing.
39
+ */
40
+ export declare function isPlanTemplateInvocation(commandPath: string, planTemplate: boolean | undefined): boolean;
24
41
  export interface SkillPresenceDeps {
25
42
  existsSync?: (p: string) => boolean;
26
43
  readFileSync?: (p: string) => string;
@@ -31,6 +31,25 @@ export const SKILL_NUDGE_COMMANDS = new Set([
31
31
  * the CLI by hand without wiring a coding agent.
32
32
  */
33
33
  export const SKILL_NUDGE_OPT_OUT_ENV = 'TESTSPRITE_NO_SKILL_WARNING';
34
+ /**
35
+ * True when this invocation is `test create --plan-template`, a
36
+ * pure-local/informational flag (prints the plan-file skeleton and exits)
37
+ * that must be treated like `setup` / `agent install`: exempt from BOTH the
38
+ * missing-skill nudge above AND the update-registry check
39
+ * (`src/lib/update-check.ts`'s `maybeNotifyUpdate`, which hits the network
40
+ * and writes `~/.testsprite/update-check.json` — both contradict "no
41
+ * network" for this flag). Neither allowlist (`SKILL_NUDGE_COMMANDS` here,
42
+ * the unconditional call site in `src/index.ts`) tracks individual flags,
43
+ * only whole commands, so `src/index.ts`'s `preAction` hook filters this one
44
+ * case via this pure, independently-testable helper instead of teaching
45
+ * either module about flags. Exported from `skill-nudge.ts` (rather than
46
+ * `src/index.ts`, which executes `program.parse()` at import time and so
47
+ * cannot be safely imported by a unit test) purely so it has a home that
48
+ * supports direct unit testing.
49
+ */
50
+ export function isPlanTemplateInvocation(commandPath, planTemplate) {
51
+ return commandPath === 'test create' && planTemplate === true;
52
+ }
34
53
  /**
35
54
  * True if the `testsprite-verify` skill is installed for ANY supported agent in
36
55
  * `dir`. own-file targets (claude/cursor/cline/antigravity): the landing file
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Max time the flush-before-exit will wait on the beacon POST. Kept short so a
3
+ * slow/unreachable backend adds at most this to a command's exit (including
4
+ * Ctrl-C); a healthy POST completes in well under it, and when it doesn't,
5
+ * dropping the event is the correct best-effort behavior.
6
+ */
7
+ export declare const TELEMETRY_TIMEOUT_MS = 1000;
8
+ export type TelemetryOutcome = 'success' | 'error' | 'abort';
9
+ export interface TelemetryOutcomeInput {
10
+ /** Leaf command path that ran, e.g. `test run`. Empty → skip (no command). */
11
+ command: string;
12
+ outcome: TelemetryOutcome;
13
+ exitCode: number;
14
+ /** Stable machine error code (e.g. `VALIDATION_ERROR`) — never a message. */
15
+ errorCode?: string;
16
+ durationMs: number;
17
+ /** Global flags, used to resolve config + fill context. */
18
+ profile?: string;
19
+ endpointUrl?: string;
20
+ output?: string;
21
+ dryRun?: boolean;
22
+ }
23
+ export interface TelemetryDeps {
24
+ env?: NodeJS.ProcessEnv;
25
+ credentialsPath?: string;
26
+ fetchImpl?: typeof globalThis.fetch;
27
+ /** Test seam for TTY detection (CI/non-interactive context prop). */
28
+ isTTY?: boolean;
29
+ /**
30
+ * Auth pre-resolved by the caller (the preAction hook). When present,
31
+ * recordOutcome uses it verbatim instead of re-reading the credentials file —
32
+ * so a command that mutates that file (`auth remove` deletes the profile) is
33
+ * still reported on the key it ran under.
34
+ */
35
+ resolvedAuth?: ResolvedTelemetryAuth;
36
+ }
37
+ /** The (apiKey, apiUrl) pair telemetry needs, resolved once per invocation. */
38
+ export interface ResolvedTelemetryAuth {
39
+ apiKey?: string;
40
+ apiUrl: string;
41
+ }
42
+ /** The exact wire body — a flat allowlist mirroring the backend DTO. */
43
+ export interface TelemetryEvent {
44
+ command: string;
45
+ outcome: TelemetryOutcome;
46
+ exitCode?: number;
47
+ errorCode?: string;
48
+ durationMs?: number;
49
+ cliVersion?: string;
50
+ os?: string;
51
+ nodeVersion?: string;
52
+ output?: string;
53
+ ci?: boolean;
54
+ }
55
+ /**
56
+ * Map a thrown CLI error to its telemetry disposition — mirrors the exit-code
57
+ * mapping in `index.ts`'s top-level catch so telemetry and the process exit
58
+ * code never disagree. Pure; safe to unit-test.
59
+ */
60
+ export declare function classifyCliError(err: unknown): {
61
+ outcome: TelemetryOutcome;
62
+ exitCode: number;
63
+ errorCode?: string;
64
+ };
65
+ /** True when the operator has opted out via either supported env var. */
66
+ export declare function isTelemetryOptedOut(env: NodeJS.ProcessEnv): boolean;
67
+ /** Assemble the allowlisted wire event. No URL / message / flag value ever. */
68
+ export declare function buildTelemetryEvent(input: TelemetryOutcomeInput, env: NodeJS.ProcessEnv, isTTY: boolean): TelemetryEvent;
69
+ /**
70
+ * Resolve just the (apiKey, apiUrl) pair telemetry needs. Called once from the
71
+ * `index.ts` preAction hook — BEFORE the command's own action runs — so a
72
+ * command that mutates the credentials file (`auth remove` deletes the profile)
73
+ * is still reported on the key it ran under. The hook only calls this for a
74
+ * telemetry-eligible, non-opted-out, non-dry-run invocation, so a gated-out or
75
+ * opted-out call never reads the credentials file.
76
+ */
77
+ export declare function resolveTelemetryAuth(opts: {
78
+ profile?: string;
79
+ endpointUrl?: string;
80
+ }, deps?: {
81
+ env?: NodeJS.ProcessEnv;
82
+ credentialsPath?: string;
83
+ }): ResolvedTelemetryAuth;
84
+ /**
85
+ * Fire one command-outcome event to the beacon. Awaited by `index.ts` before
86
+ * `process.exit` (the flush) — bounded and fully best-effort, so it can neither
87
+ * hang nor throw. Skips silently when opted out, under dry-run, with no leaf
88
+ * command, or when no api-key is configured.
89
+ */
90
+ export declare function recordOutcome(input: TelemetryOutcomeInput, deps?: TelemetryDeps): Promise<void>;
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Client-side telemetry: one "command outcome" event per CLI invocation,
3
+ * fired to the backend beacon (`POST /api/cli/v1/telemetry`), which forwards it
4
+ * to PostHog server-side. The CLI ships no PostHog SDK / write-key.
5
+ *
6
+ * Contract:
7
+ * - Best-effort: every failure is swallowed; telemetry NEVER changes a
8
+ * command's behavior, output, or exit code.
9
+ * - Bounded: the POST is aborted after {@link TELEMETRY_TIMEOUT_MS}, so the
10
+ * flush-before-exit can add at most that long to a slow/unreachable-backend
11
+ * invocation (normal case is a sub-200ms POST).
12
+ * - Authenticated-only: skipped when no api-key is configured (the backend
13
+ * keys the event on the api-key's user; anonymous events are out of scope).
14
+ * - Opt-out: skipped when `TESTSPRITE_NO_TELEMETRY` or the cross-tool
15
+ * `DO_NOT_TRACK` is set. Also skipped under `--dry-run` (no network) and
16
+ * when no leaf command actually ran (bare `--help` / parse errors).
17
+ * - Never on abort (SIGINT/SIGTERM): Ctrl-C must exit immediately, so the
18
+ * abort path emits nothing (awaiting would delay shutdown; fire-and-forget
19
+ * would be cut off before delivery anyway).
20
+ *
21
+ * Privacy: the event is a fixed allowlist of low-cardinality, PII-free fields.
22
+ * It NEVER carries target URLs, api keys, flag values, arg values, or error
23
+ * messages — `errorCode` is a stable machine code, never the human message.
24
+ */
25
+ import { CommanderError } from 'commander';
26
+ import { loadConfig } from './config.js';
27
+ import { defaultCredentialsPath } from './credentials.js';
28
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError } from './errors.js';
29
+ import { facadeBaseUrl } from './facade.js';
30
+ import { VERSION } from '../version.js';
31
+ /**
32
+ * Max time the flush-before-exit will wait on the beacon POST. Kept short so a
33
+ * slow/unreachable backend adds at most this to a command's exit (including
34
+ * Ctrl-C); a healthy POST completes in well under it, and when it doesn't,
35
+ * dropping the event is the correct best-effort behavior.
36
+ */
37
+ export const TELEMETRY_TIMEOUT_MS = 1000;
38
+ /**
39
+ * Map a thrown CLI error to its telemetry disposition — mirrors the exit-code
40
+ * mapping in `index.ts`'s top-level catch so telemetry and the process exit
41
+ * code never disagree. Pure; safe to unit-test.
42
+ */
43
+ export function classifyCliError(err) {
44
+ if (err instanceof InterruptError) {
45
+ return { outcome: 'abort', exitCode: err.exitCode, errorCode: 'INTERRUPTED' };
46
+ }
47
+ if (err instanceof RequestTimeoutError) {
48
+ return { outcome: 'error', exitCode: err.exitCode, errorCode: 'REQUEST_TIMEOUT' };
49
+ }
50
+ if (err instanceof ApiError) {
51
+ return { outcome: 'error', exitCode: err.exitCode, errorCode: err.code };
52
+ }
53
+ if (err instanceof CommanderError) {
54
+ // Help / version are user-requested successes (exit 0); everything else
55
+ // Commander throws is a parse/validation error (exit 5).
56
+ if (err.code === 'commander.helpDisplayed' ||
57
+ err.code === 'commander.help' ||
58
+ err.code === 'commander.version') {
59
+ return { outcome: 'success', exitCode: 0 };
60
+ }
61
+ return { outcome: 'error', exitCode: 5, errorCode: 'VALIDATION_ERROR' };
62
+ }
63
+ if (err instanceof CLIError) {
64
+ return { outcome: 'error', exitCode: err.exitCode };
65
+ }
66
+ return { outcome: 'error', exitCode: 1 };
67
+ }
68
+ /** True when the operator has opted out via either supported env var. */
69
+ export function isTelemetryOptedOut(env) {
70
+ return isTruthyEnv(env.TESTSPRITE_NO_TELEMETRY) || isTruthyEnv(env.DO_NOT_TRACK);
71
+ }
72
+ function isTruthyEnv(v) {
73
+ if (v === undefined)
74
+ return false;
75
+ const t = v.trim().toLowerCase();
76
+ return t !== '' && t !== '0' && t !== 'false';
77
+ }
78
+ /** Assemble the allowlisted wire event. No URL / message / flag value ever. */
79
+ export function buildTelemetryEvent(input, env, isTTY) {
80
+ return {
81
+ command: input.command,
82
+ outcome: input.outcome,
83
+ exitCode: input.exitCode,
84
+ ...(input.errorCode ? { errorCode: input.errorCode } : {}),
85
+ durationMs: input.durationMs,
86
+ cliVersion: VERSION,
87
+ os: process.platform,
88
+ nodeVersion: process.versions.node,
89
+ ...(input.output === 'json' || input.output === 'text' ? { output: input.output } : {}),
90
+ ci: isTruthyEnv(env.CI) || !isTTY,
91
+ };
92
+ }
93
+ /**
94
+ * Resolve just the (apiKey, apiUrl) pair telemetry needs. Called once from the
95
+ * `index.ts` preAction hook — BEFORE the command's own action runs — so a
96
+ * command that mutates the credentials file (`auth remove` deletes the profile)
97
+ * is still reported on the key it ran under. The hook only calls this for a
98
+ * telemetry-eligible, non-opted-out, non-dry-run invocation, so a gated-out or
99
+ * opted-out call never reads the credentials file.
100
+ */
101
+ export function resolveTelemetryAuth(opts, deps = {}) {
102
+ const config = loadConfig({
103
+ profile: opts.profile ?? 'default',
104
+ endpointUrl: opts.endpointUrl,
105
+ env: deps.env ?? process.env,
106
+ credentialsPath: deps.credentialsPath ?? defaultCredentialsPath(),
107
+ });
108
+ return { apiKey: config.apiKey, apiUrl: config.apiUrl };
109
+ }
110
+ /**
111
+ * Fire one command-outcome event to the beacon. Awaited by `index.ts` before
112
+ * `process.exit` (the flush) — bounded and fully best-effort, so it can neither
113
+ * hang nor throw. Skips silently when opted out, under dry-run, with no leaf
114
+ * command, or when no api-key is configured.
115
+ */
116
+ export async function recordOutcome(input, deps = {}) {
117
+ try {
118
+ const env = deps.env ?? process.env;
119
+ if (isTelemetryOptedOut(env))
120
+ return;
121
+ if (input.dryRun)
122
+ return;
123
+ if (!input.command)
124
+ return; // no leaf command ran (bare --help / parse error)
125
+ // Never on the abort path: Ctrl-C / SIGTERM must exit immediately. Awaiting
126
+ // a beacon post here would delay shutdown by up to the bounded timeout, and
127
+ // a fire-and-forget post would be cut off by process.exit before delivery —
128
+ // so the event would be unreliable anyway. Aborts are simply not reported.
129
+ if (input.outcome === 'abort')
130
+ return;
131
+ // Prefer auth the preAction hook already resolved (before a command like
132
+ // `auth remove` could delete the profile); fall back to a fresh read.
133
+ const config = deps.resolvedAuth ??
134
+ loadConfig({
135
+ profile: input.profile ?? 'default',
136
+ endpointUrl: input.endpointUrl,
137
+ env,
138
+ credentialsPath: deps.credentialsPath ?? defaultCredentialsPath(),
139
+ });
140
+ if (!config.apiKey)
141
+ return; // authenticated-only
142
+ const url = `${facadeBaseUrl(config.apiUrl)}/telemetry`;
143
+ const isTTY = deps.isTTY ?? process.stderr.isTTY === true;
144
+ const body = buildTelemetryEvent(input, env, isTTY);
145
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
146
+ const controller = new AbortController();
147
+ const timer = setTimeout(() => controller.abort(), TELEMETRY_TIMEOUT_MS);
148
+ // Don't keep the event loop alive just for the timer.
149
+ if (typeof timer.unref === 'function')
150
+ timer.unref();
151
+ try {
152
+ await fetchImpl(url, {
153
+ method: 'POST',
154
+ headers: {
155
+ 'content-type': 'application/json',
156
+ 'x-api-key': config.apiKey,
157
+ 'user-agent': `testsprite-cli/${VERSION}`,
158
+ },
159
+ body: JSON.stringify(body),
160
+ signal: controller.signal,
161
+ });
162
+ }
163
+ finally {
164
+ clearTimeout(timer);
165
+ }
166
+ }
167
+ catch {
168
+ // Best-effort: telemetry must never affect the command.
169
+ }
170
+ }
171
+ //# sourceMappingURL=telemetry.js.map
@@ -0,0 +1,14 @@
1
+ export interface TextTableColumn<T> {
2
+ header: string;
3
+ width: number | ((rows: readonly T[]) => number);
4
+ render: (row: T) => string;
5
+ }
6
+ export interface TextTableOptions {
7
+ columns?: string;
8
+ noHeader?: boolean;
9
+ separator?: boolean;
10
+ }
11
+ export declare function renderTextTable<T>(rows: readonly T[], columns: readonly TextTableColumn<T>[], options?: TextTableOptions): string;
12
+ export declare function resolveTextColumns<T>(raw: string | undefined, columns: readonly TextTableColumn<T>[]): readonly TextTableColumn<T>[];
13
+ export declare function measureTextColumns<T>(rows: readonly T[], columns: readonly TextTableColumn<T>[]): number[];
14
+ export declare function formatTextTableRow(values: readonly string[], widths: readonly number[]): string;
@@ -0,0 +1,45 @@
1
+ import { localValidationError } from './errors.js';
2
+ export function renderTextTable(rows, columns, options = {}) {
3
+ const selected = resolveTextColumns(options.columns, columns);
4
+ const widths = measureTextColumns(rows, selected);
5
+ const body = rows.map(row => formatTextTableRow(selected.map(column => column.render(row)), widths));
6
+ if (options.noHeader === true)
7
+ return body.join('\n');
8
+ const header = formatTextTableRow(selected.map(column => column.header), widths);
9
+ return [header, ...(options.separator === true ? ['-'.repeat(header.length)] : []), ...body].join('\n');
10
+ }
11
+ export function resolveTextColumns(raw, columns) {
12
+ if (raw === undefined || raw.trim() === '')
13
+ return columns;
14
+ const byKey = new Map(columns.map(column => [textColumnKey(column.header), column]));
15
+ const validKeys = columns.map(column => textColumnKey(column.header));
16
+ const requested = raw.split(',').map(token => token.trim());
17
+ if (requested.some(token => token.length === 0)) {
18
+ throw localValidationError('columns', `must be a comma-separated list of: ${validKeys.join(', ')}`, validKeys);
19
+ }
20
+ return requested.map(token => {
21
+ const key = textColumnKey(token);
22
+ const column = byKey.get(key);
23
+ if (column === undefined) {
24
+ throw localValidationError('columns', `unknown column "${token}"; must be one of: ${validKeys.join(', ')}`, validKeys);
25
+ }
26
+ return column;
27
+ });
28
+ }
29
+ export function measureTextColumns(rows, columns) {
30
+ return columns.map(column => typeof column.width === 'function' ? column.width(rows) : column.width);
31
+ }
32
+ export function formatTextTableRow(values, widths) {
33
+ return values
34
+ .map((value, index) => (index === values.length - 1 ? value : pad(value, widths[index] ?? 0)))
35
+ .join(' ');
36
+ }
37
+ function textColumnKey(value) {
38
+ return value.toLowerCase().replace(/[^a-z0-9]/g, '');
39
+ }
40
+ function pad(value, width) {
41
+ if (value.length >= width)
42
+ return value;
43
+ return value + ' '.repeat(width - value.length);
44
+ }
45
+ //# sourceMappingURL=text-table.js.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Shared V3-routing text surfaces for `auth status` and `doctor`.
3
+ *
4
+ * `v3Enabled` on the `/me` response is the authoritative routing bit. When it
5
+ * is on, some commands behave differently while the V3 gaps stay open — the
6
+ * advisory names them. Copy lives here so both commands stay in sync.
7
+ */
8
+ /** One-word routing label for the text card. */
9
+ export declare function routingLabel(v3Enabled: boolean): 'v3' | 'v2';
10
+ /**
11
+ * Consolidated advisory (stderr) emitted when V3 routing is on.
12
+ *
13
+ * Only genuinely-open gaps belong here. Two originally-listed items have
14
+ * shipped and were removed: `test cancel` works on V3 runs, and `test delete`
15
+ * mirrors into Postgres instead of leaving a runnable, billable row behind.
16
+ * An advisory that warns about fixed behavior is worse than none — it teaches
17
+ * users to distrust the whole block, and it sends them chasing a failure that
18
+ * cannot happen.
19
+ */
20
+ export declare const V3_ROUTING_ADVISORY: string[];
21
+ /** Write the advisory to a stderr sink, one line per call. */
22
+ export declare function emitV3RoutingAdvisory(stderr: (line: string) => void): void;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Shared V3-routing text surfaces for `auth status` and `doctor`.
3
+ *
4
+ * `v3Enabled` on the `/me` response is the authoritative routing bit. When it
5
+ * is on, some commands behave differently while the V3 gaps stay open — the
6
+ * advisory names them. Copy lives here so both commands stay in sync.
7
+ */
8
+ /** One-word routing label for the text card. */
9
+ export function routingLabel(v3Enabled) {
10
+ return v3Enabled ? 'v3' : 'v2';
11
+ }
12
+ /**
13
+ * Consolidated advisory (stderr) emitted when V3 routing is on.
14
+ *
15
+ * Only genuinely-open gaps belong here. Two originally-listed items have
16
+ * shipped and were removed: `test cancel` works on V3 runs, and `test delete`
17
+ * mirrors into Postgres instead of leaving a runnable, billable row behind.
18
+ * An advisory that warns about fixed behavior is worse than none — it teaches
19
+ * users to distrust the whole block, and it sends them chasing a failure that
20
+ * cannot happen.
21
+ */
22
+ export const V3_ROUTING_ADVISORY = [
23
+ '[advisory] V3 routing is on for this account. While these gaps are open:',
24
+ ' - `--target-url` is ignored on frontend runs (the run uses the project environment)',
25
+ ' - a frontend rerun replays the run it was pointed at, not necessarily the latest saved code',
26
+ ];
27
+ /** Write the advisory to a stderr sink, one line per call. */
28
+ export function emitV3RoutingAdvisory(stderr) {
29
+ for (const line of V3_ROUTING_ADVISORY)
30
+ stderr(line);
31
+ }
32
+ //# sourceMappingURL=v3-advisory.js.map
@@ -0,0 +1,37 @@
1
+ /** Version-compatibility signal observed on a backend response (the floor). */
2
+ export interface ServerVersionInfo {
3
+ minVersion?: string;
4
+ }
5
+ export interface VersionNoticeDeps {
6
+ /** Version the running binary reports. Defaults to the built-in `VERSION`. */
7
+ currentVersion?: string;
8
+ env?: NodeJS.ProcessEnv;
9
+ /** Whether stderr is an interactive terminal. */
10
+ isTTY?: boolean;
11
+ /** The command's `--output` mode; `'json'` suppresses the advisory. */
12
+ outputMode?: string;
13
+ /** Suppress under `--dry-run` (the dry-run fetch returns no real headers). */
14
+ dryRun?: boolean;
15
+ /** Sink for the single advisory line. */
16
+ stderr?: (line: string) => void;
17
+ }
18
+ /**
19
+ * True when every gate passes and the running version is strictly below the
20
+ * advertised floor. Gates mirror the update notice: opt-out env, JSON output,
21
+ * dry-run, and non-TTY all suppress. Pure — no side effects, no process state.
22
+ */
23
+ export declare function shouldWarnBelowFloor(info: ServerVersionInfo, deps?: VersionNoticeDeps): boolean;
24
+ /**
25
+ * The single advisory line. Names the floor (the backend's authority) and the
26
+ * upgrade command — it deliberately does NOT name a target release; the npm
27
+ * update-notice is the single source of truth for the newest version.
28
+ */
29
+ export declare function formatBelowFloorNotice(currentVersion: string, minVersion: string): string;
30
+ /** Test-only: reset the once-per-process guard between cases. */
31
+ export declare function resetBelowFloorNoticeState(): void;
32
+ /**
33
+ * Emit the below-floor advisory at most once per process. Wired to the HTTP
34
+ * client's `onServerVersion` hook. Never throws — an advisory must not break or
35
+ * delay the command it rides along with.
36
+ */
37
+ export declare function noteServerVersion(info: ServerVersionInfo, deps?: VersionNoticeDeps): void;