@testsprite/testsprite-cli 0.15.0 → 0.17.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 (207) hide show
  1. package/README.md +53 -141
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +55 -65
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +44 -56
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +297 -489
  8. package/dist/commands/completion.js +2 -1
  9. package/dist/commands/conversation.d.ts +27 -0
  10. package/dist/commands/conversation.js +702 -0
  11. package/dist/commands/doctor.d.ts +5 -1
  12. package/dist/commands/doctor.js +130 -34
  13. package/dist/commands/init.d.ts +4 -45
  14. package/dist/commands/init.js +116 -68
  15. package/dist/commands/project-env.d.ts +62 -2
  16. package/dist/commands/project-env.js +426 -53
  17. package/dist/commands/project-sign-in.d.ts +0 -48
  18. package/dist/commands/project-sign-in.js +1 -224
  19. package/dist/commands/project.d.ts +15 -186
  20. package/dist/commands/project.js +93 -921
  21. package/dist/commands/result.d.ts +10 -0
  22. package/dist/commands/result.js +215 -0
  23. package/dist/commands/schedule.d.ts +0 -29
  24. package/dist/commands/schedule.js +47 -97
  25. package/dist/commands/test.d.ts +315 -1824
  26. package/dist/commands/test.js +1962 -13733
  27. package/dist/commands/testlist.d.ts +128 -5
  28. package/dist/commands/testlist.js +269 -329
  29. package/dist/commands/tunnel.d.ts +2 -2
  30. package/dist/commands/tunnel.js +43 -41
  31. package/dist/commands/usage.d.ts +12 -45
  32. package/dist/commands/usage.js +51 -131
  33. package/dist/index.js +189 -108
  34. package/dist/lib/agent-detect.js +9 -5
  35. package/dist/lib/agent-targets.d.ts +21 -2
  36. package/dist/lib/agent-targets.js +88 -11
  37. package/dist/lib/args.d.ts +13 -0
  38. package/dist/lib/args.js +49 -0
  39. package/dist/lib/basic-auth.d.ts +3 -0
  40. package/dist/lib/basic-auth.js +15 -0
  41. package/dist/lib/billing-refusal.js +4 -3
  42. package/dist/lib/ci-linkage.d.ts +4 -82
  43. package/dist/lib/ci-linkage.js +4 -157
  44. package/dist/lib/ci-run.js +1 -1
  45. package/dist/lib/client-factory.d.ts +10 -2
  46. package/dist/lib/client-factory.js +38 -26
  47. package/dist/lib/commit-signal.d.ts +65 -0
  48. package/dist/lib/commit-signal.js +305 -0
  49. package/dist/lib/concurrency-limiter.d.ts +6 -0
  50. package/dist/lib/concurrency-limiter.js +29 -0
  51. package/dist/lib/config.js +10 -5
  52. package/dist/lib/conflict-reason.d.ts +31 -4
  53. package/dist/lib/conflict-reason.js +38 -4
  54. package/dist/lib/conversation/answers.d.ts +9 -0
  55. package/dist/lib/conversation/answers.js +49 -0
  56. package/dist/lib/conversation/api.d.ts +71 -0
  57. package/dist/lib/conversation/api.js +150 -0
  58. package/dist/lib/conversation/change.d.ts +31 -0
  59. package/dist/lib/conversation/change.js +124 -0
  60. package/dist/lib/conversation/context.d.ts +19 -0
  61. package/dist/lib/conversation/context.js +70 -0
  62. package/dist/lib/conversation/environment.d.ts +15 -0
  63. package/dist/lib/conversation/environment.js +33 -0
  64. package/dist/lib/conversation/follow.d.ts +24 -0
  65. package/dist/lib/conversation/follow.js +42 -0
  66. package/dist/lib/conversation/render.d.ts +33 -0
  67. package/dist/lib/conversation/render.js +315 -0
  68. package/dist/lib/conversation/title.d.ts +2 -0
  69. package/dist/lib/conversation/title.js +18 -0
  70. package/dist/lib/conversation/types.d.ts +156 -0
  71. package/dist/lib/conversation/types.js +6 -0
  72. package/dist/lib/credentials.js +67 -11
  73. package/dist/lib/cron.d.ts +1 -1
  74. package/dist/lib/cron.js +2 -2
  75. package/dist/lib/dispatch-stop.d.ts +20 -0
  76. package/dist/lib/dispatch-stop.js +30 -0
  77. package/dist/lib/download.d.ts +71 -0
  78. package/dist/lib/download.js +274 -0
  79. package/dist/lib/dry-run/fetch.d.ts +10 -0
  80. package/dist/lib/dry-run/fetch.js +20 -0
  81. package/dist/lib/dry-run/samples.d.ts +6 -34
  82. package/dist/lib/dry-run/samples.js +389 -751
  83. package/dist/lib/environment-tunnel.d.ts +16 -26
  84. package/dist/lib/environment-tunnel.js +161 -157
  85. package/dist/lib/errors.d.ts +20 -4
  86. package/dist/lib/errors.js +36 -16
  87. package/dist/lib/facade.d.ts +7 -29
  88. package/dist/lib/facade.js +7 -36
  89. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  90. package/dist/lib/failing-fe-resolver.js +47 -132
  91. package/dist/lib/first-suite-hint.d.ts +16 -22
  92. package/dist/lib/first-suite-hint.js +38 -47
  93. package/dist/lib/gh-output.d.ts +76 -21
  94. package/dist/lib/gh-output.js +171 -90
  95. package/dist/lib/git-utils.d.ts +56 -0
  96. package/dist/lib/git-utils.js +212 -0
  97. package/dist/lib/github-context.d.ts +2 -0
  98. package/dist/lib/github-context.js +40 -8
  99. package/dist/lib/history-retention.d.ts +6 -2
  100. package/dist/lib/history-retention.js +10 -7
  101. package/dist/lib/http.d.ts +58 -134
  102. package/dist/lib/http.js +352 -271
  103. package/dist/lib/interrupt.d.ts +14 -8
  104. package/dist/lib/interrupt.js +28 -10
  105. package/dist/lib/junit-report.d.ts +60 -4
  106. package/dist/lib/junit-report.js +209 -32
  107. package/dist/lib/local-target.d.ts +3 -3
  108. package/dist/lib/local-target.js +3 -3
  109. package/dist/lib/output.d.ts +0 -29
  110. package/dist/lib/output.js +10 -33
  111. package/dist/lib/pagination.d.ts +2 -5
  112. package/dist/lib/pagination.js +2 -5
  113. package/dist/lib/presigned-url.d.ts +22 -0
  114. package/dist/lib/presigned-url.js +90 -0
  115. package/dist/lib/prompt.js +36 -2
  116. package/dist/lib/proxy.js +2 -1
  117. package/dist/lib/redact.d.ts +2 -2
  118. package/dist/lib/redact.js +3 -4
  119. package/dist/lib/removed-commands.d.ts +18 -0
  120. package/dist/lib/removed-commands.js +154 -0
  121. package/dist/lib/render-error.d.ts +31 -6
  122. package/dist/lib/render-error.js +88 -25
  123. package/dist/lib/response-schemas.d.ts +38 -30
  124. package/dist/lib/response-schemas.js +210 -207
  125. package/dist/lib/result/api.d.ts +24 -0
  126. package/dist/lib/result/api.js +28 -0
  127. package/dist/lib/result/evidence.d.ts +71 -0
  128. package/dist/lib/result/evidence.js +420 -0
  129. package/dist/lib/result/render.d.ts +20 -0
  130. package/dist/lib/result/render.js +194 -0
  131. package/dist/lib/result/types.d.ts +122 -0
  132. package/dist/lib/result/types.js +19 -0
  133. package/dist/lib/run-output.d.ts +275 -0
  134. package/dist/lib/run-output.js +227 -0
  135. package/dist/lib/run-render.d.ts +101 -0
  136. package/dist/lib/run-render.js +183 -0
  137. package/dist/lib/run-wait.d.ts +192 -0
  138. package/dist/lib/run-wait.js +452 -0
  139. package/dist/lib/runs.types.d.ts +134 -367
  140. package/dist/lib/runs.types.js +0 -14
  141. package/dist/lib/secret-file.d.ts +1 -1
  142. package/dist/lib/secret-file.js +11 -2
  143. package/dist/lib/skill-nudge.d.ts +7 -27
  144. package/dist/lib/skill-nudge.js +9 -37
  145. package/dist/lib/target-path.d.ts +15 -0
  146. package/dist/lib/target-path.js +35 -0
  147. package/dist/lib/target-url-advisory.d.ts +19 -0
  148. package/dist/lib/target-url-advisory.js +31 -0
  149. package/dist/lib/target-url-preflight.d.ts +9 -0
  150. package/dist/lib/target-url-preflight.js +214 -106
  151. package/dist/lib/target-url.d.ts +1 -1
  152. package/dist/lib/target-url.js +6 -16
  153. package/dist/lib/telemetry.d.ts +32 -12
  154. package/dist/lib/telemetry.js +39 -8
  155. package/dist/lib/terminal-text.d.ts +41 -0
  156. package/dist/lib/terminal-text.js +127 -0
  157. package/dist/lib/testlist.types.d.ts +16 -8
  158. package/dist/lib/testlist.types.js +1 -1
  159. package/dist/lib/text-equality.d.ts +2 -0
  160. package/dist/lib/text-equality.js +5 -0
  161. package/dist/lib/text-file.d.ts +16 -0
  162. package/dist/lib/text-file.js +41 -0
  163. package/dist/lib/text-table.d.ts +46 -0
  164. package/dist/lib/text-table.js +72 -4
  165. package/dist/lib/ticker.d.ts +9 -2
  166. package/dist/lib/ticker.js +16 -3
  167. package/dist/lib/transport-failure.d.ts +22 -0
  168. package/dist/lib/transport-failure.js +126 -0
  169. package/dist/lib/tunnel-session.d.ts +7 -1
  170. package/dist/lib/tunnel-session.js +22 -9
  171. package/dist/lib/update-check.js +3 -2
  172. package/dist/lib/url-template.d.ts +43 -0
  173. package/dist/lib/url-template.js +151 -0
  174. package/dist/lib/validate.d.ts +0 -64
  175. package/dist/lib/validate.js +2 -131
  176. package/dist/lib/version-notice.js +4 -3
  177. package/dist/lib/wait-exit.d.ts +37 -2
  178. package/dist/lib/wait-exit.js +88 -30
  179. package/dist/lib/workspace-status.js +10 -2
  180. package/dist/version.d.ts +1 -1
  181. package/dist/version.js +1 -1
  182. package/package.json +3 -4
  183. package/skills/testsprite-ci.skill.md +48 -18
  184. package/skills/testsprite-onboard.skill.md +66 -151
  185. package/skills/testsprite-verify.codex.md +54 -56
  186. package/skills/testsprite-verify.skill.md +194 -358
  187. package/dist/lib/browser.d.ts +0 -6
  188. package/dist/lib/browser.js +0 -54
  189. package/dist/lib/bundle.d.ts +0 -234
  190. package/dist/lib/bundle.js +0 -781
  191. package/dist/lib/deprecate.d.ts +0 -10
  192. package/dist/lib/deprecate.js +0 -13
  193. package/dist/lib/flaky.d.ts +0 -91
  194. package/dist/lib/flaky.js +0 -71
  195. package/dist/lib/plan-poll.d.ts +0 -171
  196. package/dist/lib/plan-poll.js +0 -441
  197. package/dist/lib/plans.types.d.ts +0 -130
  198. package/dist/lib/plans.types.js +0 -31
  199. package/dist/lib/poll.d.ts +0 -100
  200. package/dist/lib/poll.js +0 -290
  201. package/dist/lib/rate-throttle.d.ts +0 -49
  202. package/dist/lib/rate-throttle.js +0 -75
  203. package/dist/lib/run-progress.d.ts +0 -41
  204. package/dist/lib/run-progress.js +0 -56
  205. package/dist/lib/v3-advisory.d.ts +0 -55
  206. package/dist/lib/v3-advisory.js +0 -74
  207. package/schemas/plan.schema.json +0 -61
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Waiting on one run: re-read `GET /results?run=<runId>` every 3 s until the
3
+ * server says the run has finished or the deadline passes, the way the Portal
4
+ * polls one run. One request per read, whatever the run's size.
5
+ *
6
+ * The run's own `status`, not its results, says when it is done: a backend
7
+ * run adds its integration results after its wave has settled, so "every
8
+ * listed result has settled" can be true while the run still has work to
9
+ * add. A listing without the run is from a server older than this CLI, and
10
+ * the wait refuses it rather than guess.
11
+ *
12
+ * The waiter reports; it never prints or picks an exit code. Its outcome
13
+ * says how the wait ended (`timedOut`, `error`) and holds the results as last
14
+ * listed. {@link resolveRunWaitFailure} judges one or more outcomes the way
15
+ * every `--wait` judges its results, including an ending no result carries (a
16
+ * run that timed out, or a listing that failed, after every listed result had
17
+ * settled); {@link toWaitMembers} gives the per-result rows it judges.
18
+ *
19
+ * Reads:
20
+ * - An outage (UNAVAILABLE) or a throttle (RATE_LIMITED) is read through
21
+ * until the deadline, from the first read on: the run keeps executing
22
+ * server-side. An outage still on at the deadline is the outcome's
23
+ * `error` (exit 10); a throttle still on is a plain timeout (exit 7). A
24
+ * 429 for a standing condition (`isStandingRateLimit`) is no throttle and
25
+ * ends the wait like any other error.
26
+ * - A server error (INTERNAL) is read again once, as the run poller does.
27
+ * - Until a read has been answered, any other error is thrown as it is (a
28
+ * second server error in a row too): a 404 with `details.resource` is a
29
+ * run the server does not know, one without is a server without the
30
+ * route. A 404 is thrown even on the read at the deadline.
31
+ * - Once a read has been answered, a second server error in a row, or any
32
+ * other `ApiError`, ends the wait as the outcome's `error`.
33
+ * - An interrupt (`InterruptError`), an abort of `signal`, and anything that
34
+ * is not an `ApiError` (a per-request timeout, say) are thrown as they are.
35
+ *
36
+ * The deadline runs on timers set once per wait: one at the deadline ends the
37
+ * sleep between reads, and one a grace later cuts a read still in flight.
38
+ * After the deadline the waiter reads once more, one attempt within that
39
+ * grace, so a result that finished during the last sleep gets its verdict.
40
+ * That read can only bring verdicts: if it fails, the wait ends as it stood
41
+ * (only a 404 before any answered read, or the failure of a first read made
42
+ * at the deadline, is thrown).
43
+ * A read cut by the grace (one in flight, or in the HTTP client's own retry
44
+ * back-off) ends the wait with no read after it.
45
+ *
46
+ * The shutdown scope is armed for the whole wait, the sleeps and `onRead`
47
+ * included, so a Ctrl-C between reads ends the wait at once instead of killing
48
+ * the process.
49
+ */
50
+ import { ApiError, CLIError } from './errors.js';
51
+ import { type HttpClient } from './http.js';
52
+ import type { ShutdownHandle } from './interrupt.js';
53
+ import { type ResultLine, type ResultRun } from './result/types.js';
54
+ import { type WaitMemberResult } from './wait-exit.js';
55
+ /** Time between two reads of a run. */
56
+ export declare const RUN_POLL_INTERVAL_MS = 3000;
57
+ /**
58
+ * How long past the deadline a read may still be answered: the read the
59
+ * waiter makes at the deadline, or one already in flight then.
60
+ */
61
+ export declare const RUN_WAIT_READ_GRACE_MS = 2000;
62
+ /** One read of the run: the run and its results in scope, oldest first. */
63
+ export interface RunWaitSnapshot {
64
+ run: ResultRun;
65
+ results: ResultLine[];
66
+ }
67
+ export interface RunWaitOptions {
68
+ /** When the wait gives up, in epoch ms: the command's one deadline. */
69
+ deadline: number;
70
+ /**
71
+ * The command's shutdown handle. The wait arms it for its whole length, and
72
+ * an interrupt ends the wait with its `InterruptError`.
73
+ */
74
+ shutdown?: ShutdownHandle;
75
+ /**
76
+ * Ends the wait at once when it aborts, with its reason thrown as it is (an
77
+ * interrupt still outranks it): a reason the caller has for stopping, such
78
+ * as a tunnel it found gone.
79
+ */
80
+ signal?: AbortSignal;
81
+ /**
82
+ * Wait only on these results of the run (a run another command started and
83
+ * this one joined): the others are neither reported nor waited on, and the
84
+ * wait ends once these have settled, or when the run finishes. Must name at
85
+ * least one result. The outcome is then marked `joined`.
86
+ */
87
+ onlyResultIds?: readonly string[];
88
+ /** Called once per result when it is first listed settled, a result first listed settled included. */
89
+ onSettled?: (line: ResultLine) => void;
90
+ /**
91
+ * Called after every read the server answered, after that read's
92
+ * `onSettled` calls, with its own copy of the results; the wait awaits it
93
+ * before it sleeps, so its time adds to the interval. It runs on the read
94
+ * that ends the wait too (the run finished, or the read at the deadline), so
95
+ * a hook that throws there turns that ending into its error. `signal`
96
+ * aborts on an interrupt, on the caller's `signal`, and when the deadline's
97
+ * grace ends, not at the deadline itself. A throw ends the wait with that
98
+ * error, thrown as it is (an interrupt or the caller's abort with their own
99
+ * reasons); an abort at the end of the grace ends it on that read instead,
100
+ * as a timeout unless the read finished the wait.
101
+ */
102
+ onRead?: (snapshot: RunWaitSnapshot, signal: AbortSignal) => void | Promise<void>;
103
+ /** Where a `--debug` line goes. */
104
+ debug?: (line: string) => void;
105
+ /** Injectable sleep; defaults to a timer that ends when its signal aborts. */
106
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
107
+ }
108
+ export interface RunWaitOutcome {
109
+ /** The run waited on. */
110
+ runId: string;
111
+ /** The run as last read; null when no read was answered before the deadline. */
112
+ run: ResultRun | null;
113
+ /** The results in scope as last listed, oldest first. */
114
+ results: ResultLine[];
115
+ /** Results `onlyResultIds` names that the listing never showed. */
116
+ missingResultIds: string[];
117
+ /** The deadline passed before the run finished (or before the given results settled). */
118
+ timedOut: boolean;
119
+ /**
120
+ * The wait was given `onlyResultIds`: the run is one this command joined and
121
+ * did not start, so cancelling it stops tests it did not start.
122
+ */
123
+ joined?: true;
124
+ /**
125
+ * The listing error that ended the wait, or the outage still on at the
126
+ * deadline. Absent when the wait ended on the run or on a plain timeout.
127
+ */
128
+ error?: ApiError;
129
+ }
130
+ /**
131
+ * Wait on run `runId` until the server reports it finished (or, with
132
+ * `onlyResultIds`, until those results have settled), or until the deadline.
133
+ *
134
+ * @throws An error before any read was answered, as it is, unless it is an
135
+ * outage, a throttle, or a first server error.
136
+ * @throws `ApiError` UNSUPPORTED (exit 7) when a listing has no run object
137
+ * (the server is older than this CLI) or one without a readable `runId` and
138
+ * `status`.
139
+ * @throws `InterruptError` on an interrupt, marked as a run wait's.
140
+ * @throws The reason of `signal` when it aborts, and whatever `onRead` throws.
141
+ */
142
+ export declare function waitForRun(client: HttpClient, runId: string, opts: RunWaitOptions): Promise<RunWaitOutcome>;
143
+ /** Results the CLI cancelled itself; see {@link RunWaitJudgeOptions.cancelledResultIds}. */
144
+ type CancelledResultIds = readonly string[] | ReadonlySet<string>;
145
+ /**
146
+ * The rows `resolveWaitFailure` judges, one per result in the outcome:
147
+ * - a settled result has its status, lower-cased (`passed`, `failed`, …);
148
+ * - a result still running has the outcome's `error` when there is one,
149
+ * `timeout` when the wait timed out, and otherwise `running` (a finished
150
+ * run with a result still running, which is not a pass);
151
+ * - a given result the listing never showed is a timeout or the outcome's
152
+ * error like a running one, and NOT_FOUND (exit 4) when the run finished
153
+ * without it;
154
+ * - a result in `cancelledResultIds` that the listing does not show with a
155
+ * verdict (it reads cancelled, still running, or not at all) timed out and
156
+ * was cancelled (`cancel: 'cancelled'`).
157
+ *
158
+ * Rows carry the result id as `resultId` and the execution as `runId`, the names
159
+ * `WaitMemberResult` reads them by, and `joined` when the outcome is. An
160
+ * ending no row carries is judged by {@link resolveRunWaitFailure}, not here.
161
+ */
162
+ export declare function toWaitMembers(outcome: RunWaitOutcome, opts?: {
163
+ cancelledResultIds?: CancelledResultIds;
164
+ }): Array<WaitMemberResult & {
165
+ resultId: string;
166
+ runId: string;
167
+ }>;
168
+ export interface RunWaitJudgeOptions {
169
+ timeoutSeconds: number;
170
+ /**
171
+ * Results the CLI cancelled itself when it stopped waiting for them (an
172
+ * owned tunnel's per-test timeout). Each timed out and was cancelled unless
173
+ * the listing shows it with a verdict, so the hints look it up by itself
174
+ * instead of offering to resume it, as for any result the CLI cancelled.
175
+ */
176
+ cancelledResultIds?: CancelledResultIds;
177
+ }
178
+ /**
179
+ * The failure a command exits with after waiting on these runs, or null when
180
+ * every run finished and every result in them passed. The rows
181
+ * ({@link toWaitMembers}) are judged by `resolveWaitFailure`, and with them,
182
+ * by the same precedence, each run's own ending that no row carries:
183
+ * - a listing error after every listed result had settled (or before any
184
+ * was read) is that error, as it is: no result failed;
185
+ * - a run that timed out with no result still running (every listed one had
186
+ * settled, or none was ever read) is a timeout (exit 7), which outranks
187
+ * only a generic failure. One timeout names every run left unfinished.
188
+ * On a tie the run's own ending wins: it says why the wait stopped. An outage
189
+ * (exit 10) re-attaches to every result and run left unfinished.
190
+ */
191
+ export declare function resolveRunWaitFailure(outcomes: readonly RunWaitOutcome[], opts: RunWaitJudgeOptions, requestFailure?: CLIError): CLIError | ApiError | null;
192
+ export {};
@@ -0,0 +1,452 @@
1
+ /**
2
+ * Waiting on one run: re-read `GET /results?run=<runId>` every 3 s until the
3
+ * server says the run has finished or the deadline passes, the way the Portal
4
+ * polls one run. One request per read, whatever the run's size.
5
+ *
6
+ * The run's own `status`, not its results, says when it is done: a backend
7
+ * run adds its integration results after its wave has settled, so "every
8
+ * listed result has settled" can be true while the run still has work to
9
+ * add. A listing without the run is from a server older than this CLI, and
10
+ * the wait refuses it rather than guess.
11
+ *
12
+ * The waiter reports; it never prints or picks an exit code. Its outcome
13
+ * says how the wait ended (`timedOut`, `error`) and holds the results as last
14
+ * listed. {@link resolveRunWaitFailure} judges one or more outcomes the way
15
+ * every `--wait` judges its results, including an ending no result carries (a
16
+ * run that timed out, or a listing that failed, after every listed result had
17
+ * settled); {@link toWaitMembers} gives the per-result rows it judges.
18
+ *
19
+ * Reads:
20
+ * - An outage (UNAVAILABLE) or a throttle (RATE_LIMITED) is read through
21
+ * until the deadline, from the first read on: the run keeps executing
22
+ * server-side. An outage still on at the deadline is the outcome's
23
+ * `error` (exit 10); a throttle still on is a plain timeout (exit 7). A
24
+ * 429 for a standing condition (`isStandingRateLimit`) is no throttle and
25
+ * ends the wait like any other error.
26
+ * - A server error (INTERNAL) is read again once, as the run poller does.
27
+ * - Until a read has been answered, any other error is thrown as it is (a
28
+ * second server error in a row too): a 404 with `details.resource` is a
29
+ * run the server does not know, one without is a server without the
30
+ * route. A 404 is thrown even on the read at the deadline.
31
+ * - Once a read has been answered, a second server error in a row, or any
32
+ * other `ApiError`, ends the wait as the outcome's `error`.
33
+ * - An interrupt (`InterruptError`), an abort of `signal`, and anything that
34
+ * is not an `ApiError` (a per-request timeout, say) are thrown as they are.
35
+ *
36
+ * The deadline runs on timers set once per wait: one at the deadline ends the
37
+ * sleep between reads, and one a grace later cuts a read still in flight.
38
+ * After the deadline the waiter reads once more, one attempt within that
39
+ * grace, so a result that finished during the last sleep gets its verdict.
40
+ * That read can only bring verdicts: if it fails, the wait ends as it stood
41
+ * (only a 404 before any answered read, or the failure of a first read made
42
+ * at the deadline, is thrown).
43
+ * A read cut by the grace (one in flight, or in the HTTP client's own retry
44
+ * back-off) ends the wait with no read after it.
45
+ *
46
+ * The shutdown scope is armed for the whole wait, the sleeps and `onRead`
47
+ * included, so a Ctrl-C between reads ends the wait at once instead of killing
48
+ * the process.
49
+ */
50
+ import { ApiError, CLIError, InterruptError } from './errors.js';
51
+ import { isStandingRateLimit } from './http.js';
52
+ import { defaultSleep, isAbortError, sleepUnlessInterrupted } from './poll-support.js';
53
+ import { resultApi } from './result/api.js';
54
+ import { ALL_RESULT_STATUSES, isResultRunning, } from './result/types.js';
55
+ import { launchIds } from './run-render.js';
56
+ import { resolveWaitFailure, unfinishedHint, WAIT_EXIT_PRIORITY, waitMemberError, } from './wait-exit.js';
57
+ /** Time between two reads of a run. */
58
+ export const RUN_POLL_INTERVAL_MS = 3_000;
59
+ /**
60
+ * How long past the deadline a read may still be answered: the read the
61
+ * waiter makes at the deadline, or one already in flight then.
62
+ */
63
+ export const RUN_WAIT_READ_GRACE_MS = 2_000;
64
+ /**
65
+ * Wait on run `runId` until the server reports it finished (or, with
66
+ * `onlyResultIds`, until those results have settled), or until the deadline.
67
+ *
68
+ * @throws An error before any read was answered, as it is, unless it is an
69
+ * outage, a throttle, or a first server error.
70
+ * @throws `ApiError` UNSUPPORTED (exit 7) when a listing has no run object
71
+ * (the server is older than this CLI) or one without a readable `runId` and
72
+ * `status`.
73
+ * @throws `InterruptError` on an interrupt, marked as a run wait's.
74
+ * @throws The reason of `signal` when it aborts, and whatever `onRead` throws.
75
+ */
76
+ export async function waitForRun(client, runId, opts) {
77
+ if (opts.onlyResultIds !== undefined && opts.onlyResultIds.length === 0) {
78
+ throw new Error('waitForRun: onlyResultIds names no result');
79
+ }
80
+ const disarm = opts.shutdown?.arm();
81
+ try {
82
+ return await readUntilDone(client, runId, opts);
83
+ }
84
+ catch (err) {
85
+ if (err instanceof InterruptError && opts.shutdown?.signal.aborted) {
86
+ err.runWaitContext = true;
87
+ }
88
+ throw err;
89
+ }
90
+ finally {
91
+ disarm?.();
92
+ }
93
+ }
94
+ async function readUntilDone(client, runId, opts) {
95
+ const api = resultApi(client);
96
+ const shutdownSignal = opts.shutdown?.signal;
97
+ const callerSignal = opts.signal;
98
+ const sleep = opts.sleep ?? defaultSleep;
99
+ const only = opts.onlyResultIds !== undefined ? new Set(opts.onlyResultIds) : undefined;
100
+ // One deadline, one grace, and their composed signals per wait, reused by
101
+ // every read and every sleep.
102
+ const remainingMs = Math.max(0, opts.deadline - Date.now());
103
+ const deadline = new AbortController();
104
+ const grace = new AbortController();
105
+ const deadlineTimer = Number.isFinite(remainingMs)
106
+ ? setTimeout(() => deadline.abort(), remainingMs)
107
+ : undefined;
108
+ const graceTimer = Number.isFinite(remainingMs)
109
+ ? setTimeout(() => grace.abort(), remainingMs + RUN_WAIT_READ_GRACE_MS)
110
+ : undefined;
111
+ const withEnds = (timer) => {
112
+ const sources = [timer, shutdownSignal, callerSignal].filter((source) => source !== undefined);
113
+ return sources.length === 1 ? timer : AbortSignal.any(sources);
114
+ };
115
+ const readSignal = withEnds(grace.signal);
116
+ const sleepSignal = withEnds(deadline.signal);
117
+ const pastDeadline = () => deadline.signal.aborted || Date.now() >= opts.deadline;
118
+ /** An interrupt, then the caller's abort, ends the wait with its own reason. */
119
+ const throwIfEnded = () => {
120
+ if (shutdownSignal?.aborted)
121
+ throw shutdownSignal.reason;
122
+ if (callerSignal?.aborted)
123
+ throw callerSignal.reason;
124
+ };
125
+ /** Sleep `ms`, or less when the deadline comes first. */
126
+ const pause = async (ms) => {
127
+ try {
128
+ const clamped = Math.max(0, Math.min(ms, opts.deadline - Date.now()));
129
+ await sleepUnlessInterrupted(sleep, clamped, sleepSignal);
130
+ }
131
+ catch (err) {
132
+ throwIfEnded();
133
+ if (deadline.signal.aborted)
134
+ return;
135
+ throw err;
136
+ }
137
+ };
138
+ let run = null;
139
+ let results = [];
140
+ // The last read's failure, and how many reads in a row failed with a
141
+ // server error; both cleared by a read the server answered.
142
+ let lastFailure;
143
+ let serverErrors = 0;
144
+ const settled = new Set();
145
+ const outcome = (timedOut) => {
146
+ const listed = new Set(results.map(line => line.resultId));
147
+ // At the deadline only an outage is reported: a throttle or a server
148
+ // error read again is a plain timeout.
149
+ const error = !timedOut || lastFailure?.code === 'UNAVAILABLE' ? lastFailure : undefined;
150
+ return {
151
+ runId,
152
+ run,
153
+ results,
154
+ missingResultIds: [...(only ?? [])].filter(resultId => !listed.has(resultId)),
155
+ timedOut,
156
+ ...(only !== undefined ? { joined: true } : {}),
157
+ ...(error !== undefined ? { error } : {}),
158
+ };
159
+ };
160
+ const done = (current) => {
161
+ if (current.status === 'finished')
162
+ return true;
163
+ if (only === undefined)
164
+ return false;
165
+ const byId = new Map(results.map(line => [line.resultId, line]));
166
+ return [...only].every(resultId => {
167
+ const line = byId.get(resultId);
168
+ return line !== undefined && !isResultRunning(line.testStatus);
169
+ });
170
+ };
171
+ try {
172
+ for (;;) {
173
+ throwIfEnded();
174
+ const final = pastDeadline();
175
+ let listed;
176
+ try {
177
+ // The read at the deadline is one attempt: a retry would spend the grace waiting.
178
+ listed = await api.listByRun(runId, ALL_RESULT_STATUSES, {
179
+ signal: readSignal,
180
+ retry: final ? false : undefined,
181
+ });
182
+ }
183
+ catch (err) {
184
+ if (err instanceof InterruptError)
185
+ throw err;
186
+ throwIfEnded();
187
+ // Cut at the end of the grace: the wait ends on what it read before.
188
+ if (isAbortError(err) && grace.signal.aborted)
189
+ return outcome(true);
190
+ if (!(err instanceof ApiError))
191
+ throw err;
192
+ // A 429 for a standing condition (a cap the caller must free) is no
193
+ // passing throttle: waiting cannot clear it. (This read charges
194
+ // nothing, so it never answers with a credit-depletion 429.)
195
+ const transient = err.code === 'UNAVAILABLE' || (err.code === 'RATE_LIMITED' && !isStandingRateLimit(err));
196
+ const unread = run === null;
197
+ // No read has shown the run: a 404 says it does not exist, even at the deadline.
198
+ if (unread && err.code === 'NOT_FOUND')
199
+ throw err;
200
+ if (final) {
201
+ // A first read made at the deadline keeps the first read's rule.
202
+ if (unread && lastFailure === undefined && !transient)
203
+ throw err;
204
+ // Otherwise the read at the deadline only brings verdicts: its
205
+ // failure changes nothing, and an outage before it stays the outcome's.
206
+ return outcome(true);
207
+ }
208
+ const readAgain = transient || (err.code === 'INTERNAL' && serverErrors === 0);
209
+ if (err.code === 'INTERNAL')
210
+ serverErrors += 1;
211
+ if (!readAgain && unread)
212
+ throw err;
213
+ lastFailure = err;
214
+ if (!readAgain)
215
+ return outcome(false);
216
+ await pause(Math.max(RUN_POLL_INTERVAL_MS, err.retryAfterMs ?? 0));
217
+ continue;
218
+ }
219
+ if (listed.run === undefined)
220
+ throw serverTooOld();
221
+ if (listed.run === null) {
222
+ opts.debug?.(`The listing of run ${runId} has a run object without a readable runId and status.`);
223
+ throw unreadableRun(runId);
224
+ }
225
+ lastFailure = undefined;
226
+ serverErrors = 0;
227
+ run = listed.run;
228
+ results = inOrder(only === undefined
229
+ ? listed.results
230
+ : listed.results.filter(line => only.has(line.resultId)));
231
+ for (const line of results) {
232
+ if (isResultRunning(line.testStatus) || settled.has(line.resultId))
233
+ continue;
234
+ settled.add(line.resultId);
235
+ opts.onSettled?.(line);
236
+ }
237
+ if (opts.onRead !== undefined) {
238
+ try {
239
+ await opts.onRead({ run, results: [...results] }, readSignal);
240
+ }
241
+ catch (err) {
242
+ throwIfEnded();
243
+ // Cut by the deadline grace: the wait ends on this read, as on a read cut there.
244
+ if (isAbortError(err) && grace.signal.aborted)
245
+ return outcome(!done(run));
246
+ throw err;
247
+ }
248
+ }
249
+ if (done(run))
250
+ return outcome(false);
251
+ if (final)
252
+ return outcome(true);
253
+ await pause(RUN_POLL_INTERVAL_MS);
254
+ }
255
+ }
256
+ finally {
257
+ clearTimeout(deadlineTimer);
258
+ clearTimeout(graceTimer);
259
+ }
260
+ }
261
+ /** Oldest first, then by id: the server lists newest first. */
262
+ function inOrder(lines) {
263
+ return [...lines].sort((a, b) => Date.parse(a.created) - Date.parse(b.created) ||
264
+ (a.resultId < b.resultId ? -1 : a.resultId > b.resultId ? 1 : 0));
265
+ }
266
+ /** Exit 7: the listing has no run object, so the server cannot say when a run has finished. */
267
+ function serverTooOld() {
268
+ return ApiError.fromEnvelope({
269
+ error: {
270
+ code: 'UNSUPPORTED',
271
+ message: 'This server does not say whether a run has finished, which waiting on a run needs.',
272
+ nextAction: 'The TestSprite service is older than this CLI: stay on CLI 0.16 until it is updated.',
273
+ requestId: 'local',
274
+ details: { reason: 'run_status_missing' },
275
+ },
276
+ });
277
+ }
278
+ /** Exit 7: the listing has a run object, but not one whose `runId` and `status` can be read. */
279
+ function unreadableRun(runId) {
280
+ return ApiError.fromEnvelope({
281
+ error: {
282
+ code: 'UNSUPPORTED',
283
+ message: `Whether run ${runId} has finished could not be read from the server's answer.`,
284
+ nextAction: 'Run the command again with --debug; if it persists, report it to support@testsprite.com.',
285
+ requestId: 'local',
286
+ details: { reason: 'run_status_unreadable', runId },
287
+ },
288
+ });
289
+ }
290
+ /**
291
+ * The rows `resolveWaitFailure` judges, one per result in the outcome:
292
+ * - a settled result has its status, lower-cased (`passed`, `failed`, …);
293
+ * - a result still running has the outcome's `error` when there is one,
294
+ * `timeout` when the wait timed out, and otherwise `running` (a finished
295
+ * run with a result still running, which is not a pass);
296
+ * - a given result the listing never showed is a timeout or the outcome's
297
+ * error like a running one, and NOT_FOUND (exit 4) when the run finished
298
+ * without it;
299
+ * - a result in `cancelledResultIds` that the listing does not show with a
300
+ * verdict (it reads cancelled, still running, or not at all) timed out and
301
+ * was cancelled (`cancel: 'cancelled'`).
302
+ *
303
+ * Rows carry the result id as `resultId` and the execution as `runId`, the names
304
+ * `WaitMemberResult` reads them by, and `joined` when the outcome is. An
305
+ * ending no row carries is judged by {@link resolveRunWaitFailure}, not here.
306
+ */
307
+ export function toWaitMembers(outcome, opts = {}) {
308
+ const cancelled = new Set(opts.cancelledResultIds ?? []);
309
+ const ids = (resultId) => ({
310
+ resultId,
311
+ runId: outcome.runId,
312
+ ...(outcome.joined ? { joined: true } : {}),
313
+ });
314
+ const cancelledByCli = { status: 'timeout', cancel: 'cancelled' };
315
+ const unfinished = () => outcome.error !== undefined
316
+ ? { status: 'error', error: waitMemberError(outcome.error) }
317
+ : outcome.timedOut
318
+ ? { status: 'timeout' }
319
+ : undefined;
320
+ const listed = outcome.results.map(line => {
321
+ const running = isResultRunning(line.testStatus);
322
+ const verdict = !running && line.testStatus.toUpperCase() !== 'CANCELLED';
323
+ return {
324
+ ...ids(line.resultId),
325
+ ...(line.caseKey !== null ? { testId: line.caseKey } : {}),
326
+ ...(cancelled.has(line.resultId) && !verdict
327
+ ? cancelledByCli
328
+ : running
329
+ ? (unfinished() ?? { status: 'running' })
330
+ : { status: line.testStatus.toLowerCase() }),
331
+ };
332
+ });
333
+ const missing = outcome.missingResultIds.map(resultId => ({
334
+ ...ids(resultId),
335
+ ...(cancelled.has(resultId)
336
+ ? cancelledByCli
337
+ : (unfinished() ?? {
338
+ status: 'error',
339
+ error: waitMemberError(notInRun(resultId, outcome.runId)),
340
+ })),
341
+ }));
342
+ return [...listed, ...missing];
343
+ }
344
+ /** Exit 4: a result the wait was given that its finished run never listed. */
345
+ function notInRun(resultId, runId) {
346
+ return ApiError.fromEnvelope({
347
+ error: {
348
+ code: 'NOT_FOUND',
349
+ message: `result ${resultId} is not in run ${runId}`,
350
+ nextAction: '',
351
+ requestId: 'local',
352
+ details: { resource: 'result', resultId, runId },
353
+ },
354
+ });
355
+ }
356
+ /** Where an exit code stands in the wait precedence; a code outside it is a generic failure. */
357
+ function rank(exitCode) {
358
+ const at = WAIT_EXIT_PRIORITY.indexOf(exitCode);
359
+ return at === -1 ? WAIT_EXIT_PRIORITY.indexOf(1) : at;
360
+ }
361
+ /**
362
+ * The failure a command exits with after waiting on these runs, or null when
363
+ * every run finished and every result in them passed. The rows
364
+ * ({@link toWaitMembers}) are judged by `resolveWaitFailure`, and with them,
365
+ * by the same precedence, each run's own ending that no row carries:
366
+ * - a listing error after every listed result had settled (or before any
367
+ * was read) is that error, as it is: no result failed;
368
+ * - a run that timed out with no result still running (every listed one had
369
+ * settled, or none was ever read) is a timeout (exit 7), which outranks
370
+ * only a generic failure. One timeout names every run left unfinished.
371
+ * On a tie the run's own ending wins: it says why the wait stopped. An outage
372
+ * (exit 10) re-attaches to every result and run left unfinished.
373
+ */
374
+ export function resolveRunWaitFailure(outcomes, opts, requestFailure) {
375
+ const cancelledResultIds = new Set(opts.cancelledResultIds ?? []);
376
+ const rows = [];
377
+ // A request timeout competes with completed sibling reads under the same
378
+ // precedence; it must not mask an authorization or transport refusal.
379
+ const runErrors = requestFailure ? [requestFailure] : [];
380
+ // Runs left unfinished with no row to say so: timed out, or cut off by an outage.
381
+ const unfinishedRuns = [];
382
+ for (const outcome of outcomes) {
383
+ const members = toWaitMembers(outcome, { cancelledResultIds });
384
+ rows.push(...members);
385
+ // Cancellation can end an execution between unit and integration phases,
386
+ // with every existing result passed. Borrowed subsets own only their results.
387
+ if (outcome.run?.cancelled === true && !outcome.joined) {
388
+ runErrors.push(new CLIError(`Run ${outcome.runId} was cancelled.`, 1));
389
+ }
390
+ const run = {
391
+ runId: outcome.runId,
392
+ ...(outcome.joined ? { joined: true } : {}),
393
+ status: 'timeout',
394
+ };
395
+ if (outcome.error !== undefined) {
396
+ runErrors.push(outcome.error);
397
+ if (outcome.error.code === 'UNAVAILABLE') {
398
+ unfinishedRuns.push({ ...run, status: 'error', error: waitMemberError(outcome.error) });
399
+ }
400
+ }
401
+ else if (outcome.timedOut &&
402
+ !members.some(row => row.status === 'timeout' || row.status === 'error')) {
403
+ unfinishedRuns.push(run);
404
+ }
405
+ }
406
+ const failure = resolveWaitFailure(rows, opts);
407
+ if (runErrors.length === 0 && unfinishedRuns.length === 0)
408
+ return failure;
409
+ const timedOutRuns = unfinishedRuns.filter(run => run.status === 'timeout');
410
+ const candidates = [
411
+ ...(failure !== null ? [failure] : []),
412
+ ...runErrors,
413
+ ...(timedOutRuns.length > 0
414
+ ? [runsTimedOut(failure, rows, timedOutRuns, opts.timeoutSeconds)]
415
+ : []),
416
+ ];
417
+ const chosen = candidates.reduce((best, next) => rank(next.exitCode) <= rank(best.exitCode) ? next : best);
418
+ return chosen;
419
+ }
420
+ /**
421
+ * Exit 7 for runs that did not finish in time: the results that timed out,
422
+ * whose own timeout (`rowFailure`, when it is one) speaks first, and the runs
423
+ * that timed out with none of theirs still running. Its details and hint are
424
+ * those of `resolveWaitFailure`'s own timeout, over both.
425
+ */
426
+ function runsTimedOut(rowFailure, rows, timedOutRuns, timeoutSeconds) {
427
+ const timedOutRows = rows.filter(row => row.status === 'timeout');
428
+ const unfinished = [...timedOutRows, ...timedOutRuns];
429
+ const runIds = launchIds(unfinished.filter(row => row.cancel !== 'cancelled'));
430
+ const resultIds = timedOutRows
431
+ .map(row => row.resultId)
432
+ .filter((id) => typeof id === 'string' && id.length > 0);
433
+ const named = timedOutRuns.map(run => run.runId).join(', ');
434
+ const runs = `${timedOutRuns.length === 1 ? 'Run' : 'Runs'} ${named} had not finished when the --timeout ended.`;
435
+ return ApiError.fromEnvelope({
436
+ error: {
437
+ code: 'UNSUPPORTED',
438
+ message: timedOutRows.length > 0 && rowFailure?.exitCode === 7
439
+ ? `${rowFailure.message} ${runs}`
440
+ : runs,
441
+ nextAction: unfinishedHint(unfinished),
442
+ requestId: 'local',
443
+ details: {
444
+ runId: runIds.length === 1 ? runIds[0] : null,
445
+ runIds,
446
+ timedOutResultIds: resultIds,
447
+ timeoutSeconds,
448
+ },
449
+ },
450
+ });
451
+ }
452
+ //# sourceMappingURL=run-wait.js.map