@testsprite/testsprite-cli 0.1.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/LICENSE +201 -0
  2. package/README.md +190 -0
  3. package/dist/assets/agent-skill/testsprite-verify.codex.md +119 -0
  4. package/dist/assets/agent-skill/testsprite-verify.skill.md +423 -0
  5. package/dist/commands/agent.d.ts +51 -0
  6. package/dist/commands/agent.js +552 -0
  7. package/dist/commands/auth.d.ts +38 -0
  8. package/dist/commands/auth.js +247 -0
  9. package/dist/commands/init.d.ts +63 -0
  10. package/dist/commands/init.js +350 -0
  11. package/dist/commands/project.d.ts +72 -0
  12. package/dist/commands/project.js +400 -0
  13. package/dist/commands/test.d.ts +1245 -0
  14. package/dist/commands/test.js +6214 -0
  15. package/dist/commands/usage.d.ts +63 -0
  16. package/dist/commands/usage.js +156 -0
  17. package/dist/index.d.ts +2 -0
  18. package/dist/index.js +146 -0
  19. package/dist/lib/agent-targets.d.ts +50 -0
  20. package/dist/lib/agent-targets.js +99 -0
  21. package/dist/lib/bundle.d.ts +178 -0
  22. package/dist/lib/bundle.js +600 -0
  23. package/dist/lib/client-factory.d.ts +72 -0
  24. package/dist/lib/client-factory.js +120 -0
  25. package/dist/lib/config.d.ts +24 -0
  26. package/dist/lib/config.js +30 -0
  27. package/dist/lib/credentials.d.ts +17 -0
  28. package/dist/lib/credentials.js +122 -0
  29. package/dist/lib/dry-run/fetch.d.ts +18 -0
  30. package/dist/lib/dry-run/fetch.js +52 -0
  31. package/dist/lib/dry-run/samples.d.ts +50 -0
  32. package/dist/lib/dry-run/samples.js +676 -0
  33. package/dist/lib/errors.d.ts +118 -0
  34. package/dist/lib/errors.js +388 -0
  35. package/dist/lib/facade.d.ts +48 -0
  36. package/dist/lib/facade.js +104 -0
  37. package/dist/lib/failing-fe-resolver.d.ts +60 -0
  38. package/dist/lib/failing-fe-resolver.js +103 -0
  39. package/dist/lib/http.d.ts +255 -0
  40. package/dist/lib/http.js +608 -0
  41. package/dist/lib/output.d.ts +55 -0
  42. package/dist/lib/output.js +70 -0
  43. package/dist/lib/pagination.d.ts +56 -0
  44. package/dist/lib/pagination.js +81 -0
  45. package/dist/lib/poll.d.ts +88 -0
  46. package/dist/lib/poll.js +221 -0
  47. package/dist/lib/prompt.d.ts +8 -0
  48. package/dist/lib/prompt.js +97 -0
  49. package/dist/lib/rate-throttle.d.ts +49 -0
  50. package/dist/lib/rate-throttle.js +75 -0
  51. package/dist/lib/render-error.d.ts +15 -0
  52. package/dist/lib/render-error.js +44 -0
  53. package/dist/lib/runs.types.d.ts +344 -0
  54. package/dist/lib/runs.types.js +25 -0
  55. package/dist/lib/target-url.d.ts +25 -0
  56. package/dist/lib/target-url.js +127 -0
  57. package/dist/lib/ticker.d.ts +37 -0
  58. package/dist/lib/ticker.js +63 -0
  59. package/dist/lib/validate.d.ts +82 -0
  60. package/dist/lib/validate.js +165 -0
  61. package/dist/version.d.ts +1 -0
  62. package/dist/version.js +2 -0
  63. package/package.json +65 -0
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Sliding-window rate throttle for the `create-batch --run` fan-out.
3
+ *
4
+ * Tracks the wall-clock timestamps of `acquire()` calls inside a rolling
5
+ * time window (`windowMs`). When the number of acquired slots in the window
6
+ * reaches `maxPerWindow`, `acquire()` returns the number of milliseconds the
7
+ * caller should sleep before proceeding, such that the oldest slot in the
8
+ * window will have aged out by the time the caller resumes.
9
+ *
10
+ * This is intentionally a simple in-process sliding-window counter — it does
11
+ * NOT coordinate across separate CLI processes. Cross-process collisions are
12
+ * handled by the per-trigger `RATE_LIMITED` retry path in `runBatchRun`.
13
+ *
14
+ * @example
15
+ * const throttle = new RateThrottle(50, 60_000);
16
+ * const waitMs = throttle.acquire();
17
+ * if (waitMs > 0) await sleep(waitMs);
18
+ * // … fire the trigger …
19
+ */
20
+ export class RateThrottle {
21
+ maxPerWindow;
22
+ windowMs;
23
+ /** Timestamps (Date.now()) of each acquired slot, oldest first. */
24
+ slots = [];
25
+ now;
26
+ constructor(maxPerWindow, windowMs, now) {
27
+ if (maxPerWindow < 1)
28
+ throw new Error('maxPerWindow must be ≥ 1');
29
+ if (windowMs < 1)
30
+ throw new Error('windowMs must be ≥ 1');
31
+ this.maxPerWindow = maxPerWindow;
32
+ this.windowMs = windowMs;
33
+ this.now = now ?? Date.now;
34
+ }
35
+ /**
36
+ * Request a slot in the rate window.
37
+ *
38
+ * Prunes expired slots (older than `windowMs` ago), then:
39
+ * - If there is headroom (slots in window < maxPerWindow): records the
40
+ * current timestamp and returns `0` (no delay needed).
41
+ * - If the window is full: returns the delay in milliseconds until the
42
+ * oldest slot ages out. Does NOT record a new slot — the caller must
43
+ * call `acquire()` again after sleeping to claim the freed slot.
44
+ *
45
+ * This means callers should loop:
46
+ *
47
+ * ```ts
48
+ * let wait: number;
49
+ * while ((wait = throttle.acquire()) > 0) {
50
+ * await sleep(wait);
51
+ * }
52
+ * ```
53
+ *
54
+ * Returns `0` when a slot was successfully acquired.
55
+ */
56
+ acquire() {
57
+ const ts = this.now();
58
+ const cutoff = ts - this.windowMs;
59
+ // Prune slots older than the window.
60
+ while (this.slots.length > 0 && this.slots[0] <= cutoff) {
61
+ this.slots.shift();
62
+ }
63
+ if (this.slots.length < this.maxPerWindow) {
64
+ // Slot available — record and proceed.
65
+ this.slots.push(ts);
66
+ return 0;
67
+ }
68
+ // Window full — compute how long until the oldest slot ages out.
69
+ const oldestTs = this.slots[0];
70
+ const ageoutMs = oldestTs + this.windowMs - ts;
71
+ // Add a 50 ms buffer so we land solidly after the cutoff.
72
+ return Math.max(0, ageoutMs + 50);
73
+ }
74
+ }
75
+ //# sourceMappingURL=rate-throttle.js.map
@@ -0,0 +1,15 @@
1
+ /**
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.
6
+ */
7
+ /**
8
+ * Rephrase Commander's "unknown option '--foo'" error when `--foo` is
9
+ * a known global flag that was placed after the subcommand.
10
+ *
11
+ * Returns the rephrased string when the pattern matches, or `null` when
12
+ * it is an ordinary unknown flag that should fall through to the original
13
+ * Commander output.
14
+ */
15
+ export declare function rephraseUnknownOption(raw: string): string | null;
@@ -0,0 +1,44 @@
1
+ /**
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.
6
+ */
7
+ /**
8
+ * Global flags that belong before the subcommand, not after it.
9
+ *
10
+ * `boolean` flags (--dry-run, --debug, --verbose) take no value; emit
11
+ * example without a placeholder. `value` flags (--output, --profile,
12
+ * --endpoint-url) take a single argument; emit example with `<value>`.
13
+ */
14
+ const GLOBAL_FLAG_ARITY = {
15
+ 'dry-run': 'boolean',
16
+ output: 'value',
17
+ profile: 'value',
18
+ 'endpoint-url': 'value',
19
+ debug: 'boolean',
20
+ verbose: 'boolean',
21
+ };
22
+ /**
23
+ * Rephrase Commander's "unknown option '--foo'" error when `--foo` is
24
+ * a known global flag that was placed after the subcommand.
25
+ *
26
+ * Returns the rephrased string when the pattern matches, or `null` when
27
+ * it is an ordinary unknown flag that should fall through to the original
28
+ * Commander output.
29
+ */
30
+ export function rephraseUnknownOption(raw) {
31
+ // Commander emits: "error: unknown option '--foo'"
32
+ const match = /unknown option\s+'--([^']+)'/.exec(raw);
33
+ if (!match)
34
+ return null;
35
+ const name = match[1];
36
+ const arity = GLOBAL_FLAG_ARITY[name];
37
+ if (arity === undefined)
38
+ return null;
39
+ const example = arity === 'value'
40
+ ? `testsprite --${name} <value> <subcommand> ...`
41
+ : `testsprite --${name} <subcommand> ...`;
42
+ return (`error: '--${name}' is a global flag; place it before the subcommand.\n` + `Example: ${example}`);
43
+ }
44
+ //# sourceMappingURL=render-error.js.map
@@ -0,0 +1,344 @@
1
+ /**
2
+ * Types for M3.3 piece-3 — `test run` / `test wait` commands.
3
+ * Extended by M3.4 piece-3 — `test rerun` command.
4
+ * Extended by M3.4 piece-5 — `test result --history` command.
5
+
6
+ */
7
+ /** Literal body sent to `POST /api/cli/v1/tests/{testId}/runs`. */
8
+ export interface TriggerRunBody {
9
+ /** Fixed source literal for CLI-triggered runs. */
10
+ source: 'cli';
11
+ /** Optional override for the project's configured target URL. */
12
+ targetUrl?: string;
13
+ }
14
+ /**
15
+ * Body sent to `POST /api/cli/v1/tests/{testId}/runs/rerun`.
16
+ * No `targetUrl` — rerun replays against the project's configured URL.
17
+ * `source` must be "cli" (not "cli-rerun" — that is not a valid RUN_SOURCES value).
18
+ */
19
+ export interface RerunRequest {
20
+ source: 'cli';
21
+ /** Opt into AI heal-on-drift. Paid + FE only. Server tier-gates and echoes effective value. */
22
+ autoHeal?: boolean;
23
+ /** BE only: rerun only the named test without expanding the producer/teardown closure. */
24
+ skipDependencies?: boolean;
25
+ }
26
+ /** One closure member returned in `RerunResponse.closure.members[]`. */
27
+ export interface RerunClosureMember {
28
+ testId: string;
29
+ /** The runId minted synchronously (claimRunSlotOrThrow) for this member. Never null. */
30
+ runId: string;
31
+ /** Role of this test in the closure: 'selected' | 'producer' | 'teardown'. */
32
+ role: 'selected' | 'producer' | 'teardown';
33
+ }
34
+ /** Closure breakdown returned for BE reruns. */
35
+ export interface RerunClosure {
36
+ members: RerunClosureMember[];
37
+ addedProducers: string[];
38
+ addedTeardowns: string[];
39
+ clearedCaptured: number;
40
+ }
41
+ /**
42
+ * Response from `POST /api/cli/v1/tests/{testId}/runs/rerun`.
43
+ * FE shape: no `closure`. BE shape: includes `closure` with per-member runIds.
44
+ * `runId` is always non-null (minted synchronously before async invoke).
45
+ */
46
+ export interface RerunResponse {
47
+ /** The named test's runId (minted synchronously before async Lambda invoke). */
48
+ runId: string;
49
+ status: 'queued';
50
+ enqueuedAt: string;
51
+ codeVersion: string;
52
+ /** Effective autoHeal value after the server tier-gate (Free → always false). */
53
+ autoHeal: boolean;
54
+ /**
55
+ * Present for BE reruns only. Contains per-member runIds.
56
+ * G1c: backend always sends this field; FE reruns send `null`.
57
+ * `undefined` means pre-G1c backend (treated identically to `null` —
58
+ * the `!!closure` truthy check in the CLI already handles both).
59
+ */
60
+ closure?: RerunClosure | null;
61
+ }
62
+ /**
63
+ * Body sent to `POST /api/cli/v1/tests/batch/rerun`.
64
+ * Mixed FE/BE testIds allowed; BE closure deduped server-side per project.
65
+ */
66
+ export interface BatchRerunRequest {
67
+ source: 'cli';
68
+ testIds: string[];
69
+ autoHeal?: boolean;
70
+ skipDependencies?: boolean;
71
+ }
72
+ /** One accepted run in the batch rerun response. */
73
+ export interface BatchRerunAccepted {
74
+ testId: string;
75
+ /** runId minted synchronously (claimRunSlotOrThrow). Never null. */
76
+ runId: string;
77
+ enqueuedAt: string;
78
+ }
79
+ /** One rate-deferred testId in the batch rerun response. */
80
+ export interface BatchRerunDeferred {
81
+ testId: string;
82
+ reason: string;
83
+ }
84
+ /** One conflicted (already in-flight) testId in the batch rerun response. */
85
+ export interface BatchRerunConflict {
86
+ testId: string;
87
+ currentRunId: string;
88
+ }
89
+ /** Per-project closure summary in the batch rerun response. */
90
+ export interface BatchRerunClosureByProject {
91
+ projectId: string;
92
+ testIds: string[];
93
+ addedProducers: string[];
94
+ addedTeardowns: string[];
95
+ clearedCaptured: number;
96
+ }
97
+ export interface BatchRerunClosure {
98
+ byProject: BatchRerunClosureByProject[];
99
+ }
100
+ /**
101
+ * Response from `POST /api/cli/v1/tests/batch/rerun`.
102
+ * `accepted` carries one entry per dispatched run (incl. BE closure members), each with its runId.
103
+ * `deferred` = rate-limited this window; retry later (C1).
104
+ * `conflicts` = already in-flight, skipped.
105
+ * `notFound` = ids that were unknown, cross-tenant, or never completed a clean run (D2-CLI).
106
+ * Present when the server supports partial-accept (SOME ids bad → 200 with accepted+notFound).
107
+ * When ALL ids are bad the server returns 404 (caught separately in the catch block).
108
+ * Optional for back-compat with older backends that don't send this field.
109
+ */
110
+ export interface BatchRerunResponse {
111
+ accepted: BatchRerunAccepted[];
112
+ deferred: BatchRerunDeferred[];
113
+ conflicts: BatchRerunConflict[];
114
+ closure: BatchRerunClosure;
115
+ notFound?: string[];
116
+ }
117
+ /**
118
+ * Response from `POST /api/cli/v1/tests/{testId}/runs`.
119
+ * All fields are stamped at trigger time and cannot change for this runId.
120
+ */
121
+ export interface TriggerRunResponse {
122
+ runId: string;
123
+ status: 'queued';
124
+ enqueuedAt: string;
125
+ /** codeVersion resolved at trigger time from the test row. */
126
+ codeVersion: string;
127
+ /** Resolved target URL (project default when --target-url absent). */
128
+ targetUrl: string;
129
+ }
130
+ /**
131
+ * Public run-status values.
132
+ * `queued` and `running` are non-terminal; the rest are terminal.
133
+ */
134
+ export type RunStatus = 'queued' | 'running' | 'passed' | 'failed' | 'blocked' | 'cancelled';
135
+ /**
136
+ * Lightweight step summary returned inside `GET /api/cli/v1/runs/{runId}`.
137
+ * Full step records arrive via `/runs/{runId}/failure`.
138
+ */
139
+ export interface RunStepSummary {
140
+ total: number;
141
+ completed: number;
142
+ passedCount: number;
143
+ failedCount: number;
144
+ }
145
+ /**
146
+ * One step row returned when `GET /api/cli/v1/runs/{runId}?includeSteps=true`.
147
+ * Mirrors the backend's `RunStepDto` / `TestRunStepEntity` public fields.
148
+ *
149
+ * Note: `stepIndex` is a zero-padded string on the wire (SK of `TestRunStep`);
150
+ * parse with `parseInt` when a numeric index is needed. `createdAt` is the
151
+ * timestamp the step was recorded (no separate `updatedAt` for run-scoped steps).
152
+ */
153
+ export interface RunStepDto {
154
+ stepIndex: string;
155
+ type: 'action' | 'assertion';
156
+ action: string;
157
+ status: 'passed' | 'failed' | null;
158
+ description: string | null;
159
+ error: string | null;
160
+ screenshotUrl: string | null;
161
+ htmlSnapshotUrl: string | null;
162
+ createdAt: string;
163
+ }
164
+ /**
165
+ * Response from `GET /api/cli/v1/runs/{runId}`.
166
+ */
167
+ export interface RunResponse {
168
+ runId: string;
169
+ testId: string;
170
+ projectId: string;
171
+ userId: string;
172
+ status: RunStatus;
173
+ source: string;
174
+ createdAt: string;
175
+ startedAt: string | null;
176
+ finishedAt: string | null;
177
+ codeVersion: string;
178
+ targetUrl: string;
179
+ createdFrom: string | null;
180
+ failedStepIndex: number | null;
181
+ failureKind: string | null;
182
+ /** Raw error text for failed/blocked runs. Matches `GetRunResponseDto.error`. */
183
+ error: string | null;
184
+ videoUrl: string | null;
185
+ stepSummary: RunStepSummary;
186
+ /** Optional hint from the server; honored by the polling loop. */
187
+ retryAfterSeconds?: number;
188
+ /**
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`).
193
+ */
194
+ dashboardUrl?: string;
195
+ /**
196
+ * Full ordered step list. Only present when the request includes
197
+ * `?includeSteps=true`. Absent (undefined) when the flag was not sent.
198
+ * Null means the server returned the field explicitly as null (treated
199
+ * the same as absent for rendering purposes).
200
+ *
201
+ * Per M3.4 piece-4: default (absent/false) is byte-identical to the M3.3
202
+ * summary shape — the cheap `test wait` polling path is unaffected.
203
+ */
204
+ steps?: RunStepDto[] | null;
205
+ }
206
+ /** Terminal states from the RunStatus union. */
207
+ export declare const TERMINAL_RUN_STATUSES: ReadonlySet<RunStatus>;
208
+ export declare function isTerminalStatus(status: RunStatus): boolean;
209
+ /**
210
+ * Valid trigger source values for filtering run history.
211
+ * "cli-rerun" is NOT a valid source — reruns have source="cli" and
212
+ * createdFrom starting with "rerun:" (surfaced as `isRerun: true`).
213
+ */
214
+ export type RunSource = 'cli' | 'portal' | 'mcp' | 'schedule' | 'github_action';
215
+ /** The valid RUN_SOURCES values as an array for CLI flag validation. */
216
+ export declare const RUN_SOURCES: ReadonlyArray<RunSource>;
217
+ /**
218
+ * One row in a `GET /api/cli/v1/tests/{testId}/runs` response.
219
+ *
220
+ * `isRerun` is a derived field: `createdFrom?.startsWith('rerun:')` on the
221
+ * backend. Reruns always have `source: 'cli'`; the `isRerun` flag + the
222
+ * `createdFrom` lineage string together identify them.
223
+ */
224
+ export interface RunHistoryItem {
225
+ runId: string;
226
+ status: RunStatus;
227
+ source: RunSource;
228
+ /** Derived by backend: true when `createdFrom` starts with "rerun:". */
229
+ isRerun: boolean;
230
+ /** Lineage pointer; `null` for fresh runs. For reruns: `"rerun:<priorRunId>"`. */
231
+ createdFrom: string | null;
232
+ createdAt: string;
233
+ /** May be null — backend doesn't always stamp it. */
234
+ startedAt: string | null;
235
+ finishedAt: string | null;
236
+ codeVersion: string;
237
+ /** Null when the run passed. */
238
+ failureKind: string | null;
239
+ /**
240
+ * G1b — the resolved target URL for this specific run. `null` when the
241
+ * backend could not determine the URL (pre-G1b rows, or `targetUrlSource`
242
+ * is `'unresolved'`). Optional on the wire for back-compat with older
243
+ * backends that don't ship the field.
244
+ */
245
+ targetUrl?: string | null;
246
+ /**
247
+ * G1b — provenance of `targetUrl`.
248
+ * - `'run'`: stamped at run-trigger time (authoritative).
249
+ * - `'unresolved'`: backend could not resolve a URL for this run.
250
+ * - `null` / absent: pre-G1b backend; treat as unknown.
251
+ */
252
+ targetUrlSource?: 'run' | 'unresolved' | null;
253
+ }
254
+ /**
255
+ * Pre-cutover metadata block present when the test has no CLI-tracked
256
+ * history (created before 2026-05-14).
257
+ */
258
+ export interface RunHistoryMeta {
259
+ testKind?: 'frontend' | 'backend';
260
+ /**
261
+ * ISO date the history window starts at.
262
+ * Present on pre-cutover responses (when `runs` is empty because no
263
+ * TestRun rows exist for this test).
264
+ */
265
+ historyStartsAt?: string;
266
+ /**
267
+ * Human-readable note from the backend.
268
+ * Rendered in CLI text mode instead of a blank table for pre-cutover tests.
269
+ */
270
+ note?: string;
271
+ /** Portal URL where older run history can be viewed. */
272
+ portalUrl?: string;
273
+ }
274
+ /**
275
+ * Response from `GET /api/cli/v1/tests/{testId}/runs`.
276
+ *
277
+ * Pre-cutover shape: `runs: []`, `nextCursor: null`, `meta` has
278
+ * `historyStartsAt` + `note` + `portalUrl`.
279
+ */
280
+ export interface ListRunsResponse {
281
+ runs: RunHistoryItem[];
282
+ /** Opaque cursor for the next page; `null` when no more pages. */
283
+ nextCursor: string | null;
284
+ meta: RunHistoryMeta;
285
+ }
286
+ /** Query parameters for `GET /api/cli/v1/tests/{testId}/runs`. */
287
+ export interface ListRunsQuery {
288
+ cursor?: string;
289
+ pageSize?: number;
290
+ source?: RunSource;
291
+ /** ISO timestamp (after client-side duration parsing). */
292
+ since?: string;
293
+ }
294
+ /**
295
+ * Body sent to `POST /api/cli/v1/tests/batch/run`.
296
+ * BE-only engine — FE tests in the set are skipped server-side (advisory only).
297
+ * `testIds` absent / empty → run ALL BE tests in the project.
298
+ */
299
+ export interface BatchRunFreshRequest {
300
+ projectId: string;
301
+ testIds?: string[];
302
+ source: 'cli';
303
+ }
304
+ /** One accepted run in the batch fresh-run response. */
305
+ export interface BatchRunFreshAccepted {
306
+ testId: string;
307
+ /**
308
+ * runId minted synchronously by `claimRunSlotOrThrow`. The backend partitions
309
+ * any member whose slot-claim failed into `conflicts[]`, so every entry that
310
+ * lands in `accepted[]` always carries a real runId (never undefined). The CLI
311
+ * polls each one under `--wait`.
312
+ */
313
+ runId: string;
314
+ enqueuedAt: string;
315
+ /**
316
+ * CLIENT-synthesized Portal deep link — never sent by the server. Added by
317
+ * `test run --all` (projectId from the request, testId per item) when the
318
+ * API endpoint maps to a known portal host.
319
+ */
320
+ dashboardUrl?: string;
321
+ }
322
+ /**
323
+ * Response from `POST /api/cli/v1/tests/batch/run`.
324
+ * `accepted` carries per-test runIds. `conflicts`/`deferred`/`skippedFrontend`/
325
+ * `skippedIntegration` enumerate everything NOT dispatched, so a JSON consumer
326
+ * reading `accepted` alone can never silently undercount.
327
+ * - `conflicts` — BE test already executing (slot-claim conflict)
328
+ * - `deferred` — per-key run budget exhausted this window; retry later
329
+ * - `skippedFrontend` — FE tests in the set (BE-only wave engine)
330
+ * - `skippedIntegration` — assembled integration tests (run via the portal)
331
+ */
332
+ export interface BatchRunFreshResponse {
333
+ accepted: BatchRunFreshAccepted[];
334
+ conflicts: Array<{
335
+ testId: string;
336
+ }>;
337
+ deferred: Array<{
338
+ testId: string;
339
+ }>;
340
+ skippedFrontend: string[];
341
+ skippedIntegration: Array<{
342
+ testId: string;
343
+ }>;
344
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Types for M3.3 piece-3 — `test run` / `test wait` commands.
3
+ * Extended by M3.4 piece-3 — `test rerun` command.
4
+ * Extended by M3.4 piece-5 — `test result --history` command.
5
+
6
+ */
7
+ /** Terminal states from the RunStatus union. */
8
+ export const TERMINAL_RUN_STATUSES = new Set([
9
+ 'passed',
10
+ 'failed',
11
+ 'blocked',
12
+ 'cancelled',
13
+ ]);
14
+ export function isTerminalStatus(status) {
15
+ return TERMINAL_RUN_STATUSES.has(status);
16
+ }
17
+ /** The valid RUN_SOURCES values as an array for CLI flag validation. */
18
+ export const RUN_SOURCES = [
19
+ 'cli',
20
+ 'portal',
21
+ 'mcp',
22
+ 'schedule',
23
+ 'github_action',
24
+ ];
25
+ //# sourceMappingURL=runs.types.js.map
@@ -0,0 +1,25 @@
1
+ /**
2
+ * CLI-side pre-flight guard for `--target-url`.
3
+ *
4
+ * Defense-in-depth: the backend is the trust boundary and performs DNS
5
+ * resolution. This guard does **string/literal-only** checks to give a
6
+ * fast, friendly error before sending the request. It cannot detect
7
+ * DNS rebinding (a public hostname that resolves to a private IP) — the
8
+ * backend catches that.
9
+ *
10
+ * CLI-side target-url guard (exit 5 on any rejection):
11
+ * - Reject non-http(s) schemes
12
+ * - Reject `localhost`, `127.0.0.0/8`, `0.0.0.0`, and IPv6 loopback/unspecified (`::1`, `::`)
13
+ * - Reject `169.254.0.0/16` link-local and the `169.254.169.254` metadata address
14
+ * - Reject RFC1918 literal IPv4 (10.x, 172.16-31.x, 192.168.x)
15
+ * - Reject IPv4-mapped IPv6 (`::ffff:…`), IPv6 link-local (`fe80::/10`), unique-local (`fc00::/7`)
16
+ * - Hostnames that resolve to private IPs are the backend's concern.
17
+ */
18
+ /**
19
+ * Throws a local `VALIDATION_ERROR` (exit 5) when `rawUrl` is a
20
+ * disallowed target — localhost, RFC1918 literal IP, link-local, or
21
+ * metadata-service address. Also rejects non-http(s) schemes.
22
+ *
23
+ * Silently returns on allowed URLs.
24
+ */
25
+ export declare function assertNotLocal(rawUrl: string): void;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * CLI-side pre-flight guard for `--target-url`.
3
+ *
4
+ * Defense-in-depth: the backend is the trust boundary and performs DNS
5
+ * resolution. This guard does **string/literal-only** checks to give a
6
+ * fast, friendly error before sending the request. It cannot detect
7
+ * DNS rebinding (a public hostname that resolves to a private IP) — the
8
+ * backend catches that.
9
+ *
10
+ * CLI-side target-url guard (exit 5 on any rejection):
11
+ * - Reject non-http(s) schemes
12
+ * - Reject `localhost`, `127.0.0.0/8`, `0.0.0.0`, and IPv6 loopback/unspecified (`::1`, `::`)
13
+ * - Reject `169.254.0.0/16` link-local and the `169.254.169.254` metadata address
14
+ * - Reject RFC1918 literal IPv4 (10.x, 172.16-31.x, 192.168.x)
15
+ * - Reject IPv4-mapped IPv6 (`::ffff:…`), IPv6 link-local (`fe80::/10`), unique-local (`fc00::/7`)
16
+ * - Hostnames that resolve to private IPs are the backend's concern.
17
+ */
18
+ import { ApiError } from './errors.js';
19
+ const LOCAL_DEV_HINT = 'Local-dev tests are out of scope for the CLI; use testsprite-mcp-plugin for the local tunnel.';
20
+ /**
21
+ * Throws a local `VALIDATION_ERROR` (exit 5) when `rawUrl` is a
22
+ * disallowed target — localhost, RFC1918 literal IP, link-local, or
23
+ * metadata-service address. Also rejects non-http(s) schemes.
24
+ *
25
+ * Silently returns on allowed URLs.
26
+ */
27
+ export function assertNotLocal(rawUrl) {
28
+ let parsed;
29
+ try {
30
+ parsed = new URL(rawUrl);
31
+ }
32
+ catch {
33
+ throw localTargetError('target-url', 'must be a valid URL');
34
+ }
35
+ // Scheme check.
36
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
37
+ throw localTargetError('target-url', 'must use http or https scheme');
38
+ }
39
+ const host = parsed.hostname.toLowerCase();
40
+ // Loopback / unspecified.
41
+ if (host === 'localhost' || host === '0.0.0.0') {
42
+ throw localTargetError('target-url', 'localhost targets are not allowed', LOCAL_DEV_HINT);
43
+ }
44
+ // IPv6 literals. Node's URL parser wraps IPv6 hosts in brackets and
45
+ // normalizes IPv4-mapped forms to hex (`http://[::ffff:127.0.0.1]` →
46
+ // hostname `[::ffff:7f00:1]`). A dotted-form string check alone would miss
47
+ // the normalized variant, so we strip the brackets and classify the
48
+ // address family explicitly.
49
+ if (host.startsWith('[') && host.endsWith(']')) {
50
+ assertNotLocalIpv6(host.slice(1, -1));
51
+ }
52
+ // 127.0.0.0/8 loopback range.
53
+ if (/^127\.\d+\.\d+\.\d+$/.test(host)) {
54
+ throw localTargetError('target-url', 'loopback addresses are not allowed', LOCAL_DEV_HINT);
55
+ }
56
+ // AWS instance-metadata service (168 and 169 prefixes used for IMDS).
57
+ if (host === '169.254.169.254') {
58
+ throw localTargetError('target-url', '169.254.169.254 (AWS metadata service) is not allowed', LOCAL_DEV_HINT);
59
+ }
60
+ // 169.254.x.x link-local (IPv4).
61
+ if (/^169\.254\.\d+\.\d+$/.test(host)) {
62
+ throw localTargetError('target-url', 'link-local addresses are not allowed', LOCAL_DEV_HINT);
63
+ }
64
+ // RFC1918 literal IP addresses only — hostnames that resolve to private
65
+ // IPs are the backend's concern (DNS resolution is expensive CLI-side).
66
+ if (isRfc1918Literal(host)) {
67
+ throw localTargetError('target-url', 'private/RFC1918 addresses are not allowed', LOCAL_DEV_HINT);
68
+ }
69
+ }
70
+ function isRfc1918Literal(host) {
71
+ // 10.0.0.0/8
72
+ if (/^10\.\d+\.\d+\.\d+$/.test(host))
73
+ return true;
74
+ // 192.168.0.0/16
75
+ if (/^192\.168\.\d+\.\d+$/.test(host))
76
+ return true;
77
+ // 172.16.0.0/12 (172.16.x.x – 172.31.x.x)
78
+ const m = host.match(/^172\.(\d+)\.\d+\.\d+$/);
79
+ if (m) {
80
+ const second = parseInt(m[1], 10);
81
+ if (second >= 16 && second <= 31)
82
+ return true;
83
+ }
84
+ return false;
85
+ }
86
+ /**
87
+ * Reject disallowed IPv6 literals: loopback (`::1`), unspecified (`::`),
88
+ * IPv4-mapped (`::ffff:…`), link-local (`fe80::/10`), and unique-local
89
+ * (`fc00::/7`). `inner` is the bracket-stripped, lowercased host.
90
+ *
91
+ * The IPv4-mapped class is rejected wholesale rather than decoding the
92
+ * embedded v4 address: no legitimate target is expressed as a mapped
93
+ * literal, and the hex-normalized form (`::ffff:7f00:1`) is error-prone to
94
+ * decode. This closes the `http://[::ffff:127.0.0.1]` SSRF-guard bypass.
95
+ */
96
+ function assertNotLocalIpv6(inner) {
97
+ // Loopback (::1) and unspecified (::).
98
+ if (inner === '::1' || inner === '::') {
99
+ throw localTargetError('target-url', 'localhost targets are not allowed', LOCAL_DEV_HINT);
100
+ }
101
+ // IPv4-mapped IPv6 (`::ffff:a.b.c.d`, normalized to `::ffff:hhhh:hhhh`).
102
+ if (inner.startsWith('::ffff:')) {
103
+ throw localTargetError('target-url', 'IPv4-mapped IPv6 addresses are not allowed; use the IPv4 form or a hostname', LOCAL_DEV_HINT);
104
+ }
105
+ // Link-local fe80::/10 (first hextet fe80–febf).
106
+ if (/^fe[89ab][0-9a-f]:/.test(inner)) {
107
+ throw localTargetError('target-url', 'link-local addresses are not allowed', LOCAL_DEV_HINT);
108
+ }
109
+ // Unique-local fc00::/7 (first hextet fc00–fdff).
110
+ if (/^f[cd][0-9a-f]{2}:/.test(inner)) {
111
+ throw localTargetError('target-url', 'unique-local (private) addresses are not allowed', LOCAL_DEV_HINT);
112
+ }
113
+ }
114
+ function localTargetError(field, reason, hint) {
115
+ return ApiError.fromEnvelope({
116
+ error: {
117
+ code: 'VALIDATION_ERROR',
118
+ message: `Field \`${field}\` is invalid: ${reason}.`,
119
+ nextAction: hint
120
+ ? hint + ' See `testsprite test run --help` for accepted values.'
121
+ : `See \`testsprite test run --help\` for accepted values.`,
122
+ requestId: 'local',
123
+ details: { field, reason, ...(hint ? { hint } : {}) },
124
+ },
125
+ });
126
+ }
127
+ //# sourceMappingURL=target-url.js.map