@testsprite/testsprite-cli 0.5.0 → 0.7.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 (51) hide show
  1. package/README.md +39 -30
  2. package/dist/commands/agent.js +44 -42
  3. package/dist/commands/doctor.d.ts +1 -1
  4. package/dist/commands/doctor.js +4 -7
  5. package/dist/commands/project.js +3 -2
  6. package/dist/commands/schedule.d.ts +120 -0
  7. package/dist/commands/schedule.js +487 -0
  8. package/dist/commands/test.d.ts +55 -1
  9. package/dist/commands/test.js +714 -183
  10. package/dist/commands/testlist.d.ts +88 -0
  11. package/dist/commands/testlist.js +747 -0
  12. package/dist/index.js +6 -2
  13. package/dist/lib/agent-targets.d.ts +13 -4
  14. package/dist/lib/agent-targets.js +11 -2
  15. package/dist/lib/conflict-reason.d.ts +30 -0
  16. package/dist/lib/conflict-reason.js +45 -0
  17. package/dist/lib/credentials.js +42 -1
  18. package/dist/lib/cron.d.ts +40 -0
  19. package/dist/lib/cron.js +190 -0
  20. package/dist/lib/dry-run/samples.js +177 -55
  21. package/dist/lib/errors.d.ts +9 -0
  22. package/dist/lib/errors.js +11 -0
  23. package/dist/lib/gh-output.d.ts +51 -4
  24. package/dist/lib/gh-output.js +149 -19
  25. package/dist/lib/http.d.ts +25 -0
  26. package/dist/lib/http.js +201 -3
  27. package/dist/lib/junit-report.d.ts +20 -2
  28. package/dist/lib/junit-report.js +38 -5
  29. package/dist/lib/poll.js +72 -36
  30. package/dist/lib/proxy.d.ts +16 -0
  31. package/dist/lib/proxy.js +19 -1
  32. package/dist/lib/response-schemas.d.ts +7 -0
  33. package/dist/lib/response-schemas.js +46 -14
  34. package/dist/lib/runs.types.d.ts +8 -3
  35. package/dist/lib/secret-file.d.ts +15 -0
  36. package/dist/lib/secret-file.js +82 -0
  37. package/dist/lib/target-url-preflight.d.ts +91 -0
  38. package/dist/lib/target-url-preflight.js +259 -0
  39. package/dist/lib/target-url.d.ts +22 -5
  40. package/dist/lib/target-url.js +60 -28
  41. package/dist/lib/testlist.types.d.ts +77 -0
  42. package/dist/lib/testlist.types.js +9 -0
  43. package/dist/lib/v3-advisory.d.ts +37 -4
  44. package/dist/lib/v3-advisory.js +47 -4
  45. package/dist/lib/wait-exit.d.ts +29 -0
  46. package/dist/lib/wait-exit.js +103 -0
  47. package/dist/version-guard.d.ts +10 -7
  48. package/dist/version-guard.js +37 -9
  49. package/dist/version.d.ts +1 -1
  50. package/dist/version.js +1 -1
  51. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -6,7 +6,9 @@ import { createCompletionCommand } from './commands/completion.js';
6
6
  import { createDoctorCommand } from './commands/doctor.js';
7
7
  import { addSetupOptions, createDeprecatedInitCommand, createSetupCommand, runConfigureViaSetup, } from './commands/init.js';
8
8
  import { createProjectCommand } from './commands/project.js';
9
+ import { createScheduleCommand } from './commands/schedule.js';
9
10
  import { createTestCommand } from './commands/test.js';
11
+ import { createTestListCommand } from './commands/testlist.js';
10
12
  import { createUsageCommand } from './commands/usage.js';
11
13
  import { TARGETS } from './lib/agent-targets.js';
12
14
  import { ApiError, CLIError, InterruptError, RequestTimeoutError } from './lib/errors.js';
@@ -18,11 +20,11 @@ import { isPlanTemplateInvocation, maybeEmitSkillNudge } from './lib/skill-nudge
18
20
  import { classifyCliError, isTelemetryOptedOut, recordOutcome, resolveTelemetryAuth, } from './lib/telemetry.js';
19
21
  import { maybeNotifyUpdate } from './lib/update-check.js';
20
22
  import { VERSION } from './version.js';
21
- import { shouldRejectNodeVersion } from './version-guard.js';
23
+ import { SUPPORTED_NODE_RANGE, shouldRejectNodeVersion } from './version-guard.js';
22
24
  // Guard: exit early with a clear message on unsupported Node.js versions,
23
25
  // rather than failing later with a cryptic ESM/runtime error.
24
26
  if (shouldRejectNodeVersion(process.versions.node)) {
25
- process.stderr.write(`Error: testsprite requires Node.js >= 20 (found ${process.versions.node}).\nInstall the latest LTS from https://nodejs.org\n`);
27
+ process.stderr.write(`Error: testsprite requires Node.js ${SUPPORTED_NODE_RANGE} (found ${process.versions.node}).\nInstall a supported Node.js release from https://nodejs.org\n`);
26
28
  process.exit(1);
27
29
  }
28
30
  const program = new Command();
@@ -65,6 +67,8 @@ addSetupOptions(authCommand.command('configure', { hidden: true }), authConfigur
65
67
  program.addCommand(authCommand);
66
68
  program.addCommand(createProjectCommand({}));
67
69
  program.addCommand(createTestCommand());
70
+ program.addCommand(createTestListCommand());
71
+ program.addCommand(createScheduleCommand({}));
68
72
  program.addCommand(createAgentCommand({}));
69
73
  program.addCommand(createUsageCommand());
70
74
  program.addCommand(createDoctorCommand());
@@ -16,10 +16,12 @@ export interface TargetSpec {
16
16
  mode: 'own-file' | 'managed-section';
17
17
  /**
18
18
  * When true, render the budget-friendly body (see {@link compactBodyFor})
19
- * instead of the full own-file skill body. Used for own-file targets whose
20
- * rule files are size-capped — currently `windsurf` (`.windsurf/rules/*.md`
21
- * files cap at ~12 K characters and Cascade silently truncates beyond that,
22
- * which would cut the full ~22 KB verify skill in half).
19
+ * instead of the full own-file skill body. Set for own-file targets that must
20
+ * keep their rule file small: `windsurf` (hard ~12 K-char cap, silently
21
+ * truncated beyond) and `copilot` (no cap, but `applyTo: '**'` injects it into
22
+ * every request, so context cost is the constraint).
23
+ *
24
+ * Read it via {@link ownFileBodyFor}, never by testing target names (DEV-672).
23
25
  */
24
26
  compactBody?: boolean;
25
27
  /**
@@ -148,6 +150,13 @@ export declare function loadSkillBodyFor(skill: string, read?: ReadFn): string;
148
150
  * used.
149
151
  */
150
152
  export declare function compactBodyFor(skill: string, read?: ReadFn): string;
153
+ /**
154
+ * The canonical own-file body for a (target, skill) pair, and therefore the body
155
+ * the install marker's hash covers. Every producer AND consumer of an own-file
156
+ * body must resolve through here — install and status keeping separate copies of
157
+ * this rule is what caused DEV-672.
158
+ */
159
+ export declare function ownFileBodyFor(target: AgentTarget, skill: string, read?: ReadFn): string;
151
160
  /**
152
161
  * Resolve a skill's codex (AGENTS.md) contribution as a Markdown string.
153
162
  * 'full' → read the `*.codex.md` asset; 'line' → the inline one-liner; 'none' → ''.
@@ -284,6 +284,15 @@ export function compactBodyFor(skill, read = defaultRead) {
284
284
  ? readSkillAsset(spec.codex.file, read)
285
285
  : loadSkillBodyFor(skill, read);
286
286
  }
287
+ /**
288
+ * The canonical own-file body for a (target, skill) pair, and therefore the body
289
+ * the install marker's hash covers. Every producer AND consumer of an own-file
290
+ * body must resolve through here — install and status keeping separate copies of
291
+ * this rule is what caused DEV-672.
292
+ */
293
+ export function ownFileBodyFor(target, skill, read = defaultRead) {
294
+ return TARGETS[target].compactBody ? compactBodyFor(skill, read) : loadSkillBodyFor(skill, read);
295
+ }
287
296
  /**
288
297
  * Resolve a skill's codex (AGENTS.md) contribution as a Markdown string.
289
298
  * 'full' → read the `*.codex.md` asset; 'line' → the inline one-liner; 'none' → ''.
@@ -367,7 +376,7 @@ export function renderOwnFileWithMarker(target, skill, markerLine, body) {
367
376
  const skillSpec = SKILLS[skill];
368
377
  if (!skillSpec)
369
378
  throw new Error(`unknown skill: ${skill}`);
370
- const resolvedBody = body !== undefined ? body : loadSkillBodyFor(skill);
379
+ const resolvedBody = body !== undefined ? body : ownFileBodyFor(target, skill);
371
380
  return injectMarkerLine(spec.wrap(skillSpec.name, skillSpec.description, resolvedBody), markerLine);
372
381
  }
373
382
  /**
@@ -393,7 +402,7 @@ export function renderForTarget(t, skill, body) {
393
402
  const resolvedBody = body !== undefined ? body : codexContentFor(skill);
394
403
  return { path, content: spec.wrap(skillSpec.name, skillSpec.description, resolvedBody) };
395
404
  }
396
- const resolvedBody = body !== undefined ? body : spec.compactBody ? compactBodyFor(skill) : loadSkillBodyFor(skill);
405
+ const resolvedBody = body !== undefined ? body : ownFileBodyFor(t, skill);
397
406
  return {
398
407
  path,
399
408
  content: renderOwnFileWithMarker(t, skill, buildSkillMarker(skill, resolvedBody), resolvedBody),
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Why a case landed in a run response's `conflicts[]` instead of dispatching.
3
+ * The backend (`batchRunFresh` / `dispatchTestListGroups`) tags each conflict so
4
+ * the CLI stops rendering every non-dispatch as "already in flight" — which is
5
+ * wrong for a view-only mirror, an un-runnable environment, or an unknown id.
6
+ *
7
+ * Absent ⇒ a legacy / pre-discriminator backend: treated as `in_flight` (the
8
+ * historical rendering) for backward compatibility.
9
+ */
10
+ export type ConflictReason = 'in_flight' | 'mcp_view_only' | 'local_address' | 'not_found' | 'error';
11
+ /** A conflict entry on a run response. `message` carries actionable detail for
12
+ * `local_address` / `error` (the backend env guard's nextAction). */
13
+ export interface RunConflict {
14
+ testId: string;
15
+ currentRunId?: string;
16
+ reason?: ConflictReason;
17
+ message?: string;
18
+ }
19
+ /**
20
+ * Short human label for a conflict's cause — the reason a case did NOT dispatch.
21
+ * Absent reason renders as the legacy "already in flight" so an old backend's
22
+ * bare `{testId, currentRunId?}` conflicts read exactly as they did before.
23
+ */
24
+ export declare function describeConflict(c: RunConflict): string;
25
+ /**
26
+ * One-line summary of a conflict set grouped by reason, e.g.
27
+ * `2 already in flight, 1 environment not runnable`. Used where a single line
28
+ * must stand in for the whole `conflicts[]` (exit-message / advisory).
29
+ */
30
+ export declare function summarizeConflicts(conflicts: readonly RunConflict[]): string;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Short human label for a conflict's cause — the reason a case did NOT dispatch.
3
+ * Absent reason renders as the legacy "already in flight" so an old backend's
4
+ * bare `{testId, currentRunId?}` conflicts read exactly as they did before.
5
+ */
6
+ export function describeConflict(c) {
7
+ switch (c.reason) {
8
+ case 'mcp_view_only':
9
+ return 'project is view-only (MCP-mirrored) — not runnable';
10
+ case 'local_address':
11
+ return c.message || 'environment not runnable (local/private/unresolvable URL)';
12
+ case 'not_found':
13
+ return 'not found in this workspace';
14
+ case 'error':
15
+ return c.message || 'dispatch failed';
16
+ case 'in_flight':
17
+ default:
18
+ return c.currentRunId ? `already in flight (run ${c.currentRunId})` : 'already in flight';
19
+ }
20
+ }
21
+ /**
22
+ * One-line summary of a conflict set grouped by reason, e.g.
23
+ * `2 already in flight, 1 environment not runnable`. Used where a single line
24
+ * must stand in for the whole `conflicts[]` (exit-message / advisory).
25
+ */
26
+ export function summarizeConflicts(conflicts) {
27
+ const labels = {
28
+ in_flight: 'already in flight',
29
+ mcp_view_only: 'view-only (MCP) project',
30
+ local_address: 'environment not runnable',
31
+ not_found: 'not found',
32
+ error: 'dispatch error',
33
+ };
34
+ const counts = new Map();
35
+ for (const c of conflicts) {
36
+ const reason = c.reason ?? 'in_flight';
37
+ counts.set(reason, (counts.get(reason) ?? 0) + 1);
38
+ }
39
+ // A future/unknown reason the loose wire schema admits (describeConflict covers
40
+ // it via its default arm) must not render as "N undefined" here.
41
+ return [...counts.entries()]
42
+ .map(([reason, n]) => `${n} ${labels[reason] ?? 'not dispatched'}`)
43
+ .join(', ');
44
+ }
45
+ //# sourceMappingURL=conflict-reason.js.map
@@ -248,6 +248,34 @@ function acquireCredentialsLock(path) {
248
248
  }
249
249
  }
250
250
  }
251
+ /**
252
+ * Age is normally read from the lock body's own `createdAt` (unchanged from
253
+ * before — this is what lets a legitimately abandoned lock from a crashed
254
+ * process, or a test simulating one, report an age older than the file's own
255
+ * mtime). It is ONLY when the body cannot be read/parsed that this falls back
256
+ * to the lock file's filesystem mtime (`statSync`) rather than treating an
257
+ * unreadable body as `Number.POSITIVE_INFINITY` (i.e. "infinitely stale"), as
258
+ * an earlier version of this function did.
259
+ *
260
+ * That fallback-to-infinity was the bug: a transient, benign read/parse
261
+ * failure — e.g. this reader's `readFileSync` landing in the brief window
262
+ * where the current holder is rewriting or releasing the file — was
263
+ * indistinguishable from "no `createdAt` at all", which always cleared the
264
+ * staleness check regardless of true age. That could unlink a lock that was
265
+ * milliseconds old and actively held, so the real owner's later
266
+ * `assertHeld()` call failed with "lost ownership" even though nothing had
267
+ * actually gone stale — reproduced locally under concurrent-writer load
268
+ * (multiple `writeProfile` calls racing for the same credentials file) and
269
+ * matches the failure signature seen under CI contention. `statSync` is a
270
+ * single atomic syscall, so — unlike reading-then-parsing a small file — it
271
+ * cannot itself be fooled by a torn write; when it also fails (ENOENT because
272
+ * the holder already released it, or a transient EPERM/EBUSY on Windows
273
+ * while a handle is still closing) that is treated as "nothing to safely
274
+ * reclaim right now" rather than "definitely gone" — the acquire loop's own
275
+ * retry/deadline handles the ordinary case of the file being gone by simply
276
+ * succeeding on the next `wx` attempt, so there is no need for this function
277
+ * to draw that conclusion itself.
278
+ */
251
279
  function reclaimStaleCredentialsLock(lockPath) {
252
280
  let lockInfo;
253
281
  try {
@@ -257,7 +285,20 @@ function reclaimStaleCredentialsLock(lockPath) {
257
285
  lockInfo = undefined;
258
286
  }
259
287
  const createdAt = typeof lockInfo?.createdAt === 'number' ? lockInfo.createdAt : undefined;
260
- const ageMs = createdAt === undefined ? Number.POSITIVE_INFINITY : Date.now() - createdAt;
288
+ let ageMs;
289
+ if (createdAt !== undefined) {
290
+ ageMs = Date.now() - createdAt;
291
+ }
292
+ else {
293
+ try {
294
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- `lockPath` is `${credentialsPath}.lock`, derived internally from the same credentials-file path this whole module already operates on (default `~/.testsprite/credentials`, or the caller-supplied path in `CredentialsOptions.path`) — the identical, already-baselined risk profile as this file's other lock/credentials fs calls, not new external input.
295
+ ageMs = Date.now() - statSync(lockPath).mtimeMs;
296
+ }
297
+ catch {
298
+ // Already gone (or otherwise inaccessible) — nothing to reclaim.
299
+ return;
300
+ }
301
+ }
261
302
  const pid = typeof lockInfo?.pid === 'number' ? lockInfo.pid : undefined;
262
303
  if (ageMs <= CREDENTIALS_LOCK_STALE_MS && (pid === undefined || isProcessAlive(pid))) {
263
304
  return;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Cron helpers for the `schedule` commands.
3
+ *
4
+ * Everything here produces human-facing text only — none of it affects when a
5
+ * schedule fires.
6
+ *
7
+ * Field order is standard 5-field cron: minute hour day-of-month month day-of-week.
8
+ * That is the format the API takes on `schedule create`/`update` and hands back
9
+ * on `schedule get`, so an expression read from one command is valid input to
10
+ * the other.
11
+ */
12
+ /**
13
+ * Approximate number of times a cron fires per month, or null when the
14
+ * expression is not a 5-field cron we can read.
15
+ *
16
+ * Every field is counted, so a cron that pins a coarse field and leaves a finer
17
+ * one open (`* 3 * * *` — every minute of 03:00) is not mistaken for its coarse
18
+ * unit. day-of-month and day-of-week are OR'd when both are restricted, which
19
+ * is what standard cron does.
20
+ */
21
+ export declare function runsPerMonth(cron: string): number | null;
22
+ /**
23
+ * Human phrasing for a cron, or the expression itself when it names no exact
24
+ * time — a wrong description is worse than the raw expression.
25
+ */
26
+ export declare function describeCron(cron: string): string;
27
+ /**
28
+ * Advisory shown before a schedule is created: how often it will run, and that
29
+ * each run is a full test run.
30
+ *
31
+ * States frequency only. Credit cost is deliberately not quoted — the API does
32
+ * not expose a per-action rate for the workspace wallet, and a figure derived
33
+ * from anything else would be wrong. Same reason `usage` does not print a
34
+ * "~N runs" estimate.
35
+ *
36
+ * An expression we cannot read still gets the advisory, without a frequency —
37
+ * the server is the authority on the cron, so refusing to say anything about a
38
+ * schedule we are about to create would be worse than saying less.
39
+ */
40
+ export declare function formatScheduleFrequencyAdvisory(cron: string): string;
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Cron helpers for the `schedule` commands.
3
+ *
4
+ * Everything here produces human-facing text only — none of it affects when a
5
+ * schedule fires.
6
+ *
7
+ * Field order is standard 5-field cron: minute hour day-of-month month day-of-week.
8
+ * That is the format the API takes on `schedule create`/`update` and hands back
9
+ * on `schedule get`, so an expression read from one command is valid input to
10
+ * the other.
11
+ */
12
+ const FIELD_COUNT = 5;
13
+ /** 365/12, which makes an hourly cron come out at exactly 730 runs/month. */
14
+ const DAYS_PER_MONTH = 365 / 12;
15
+ const WEEKS_PER_MONTH = DAYS_PER_MONTH / 7;
16
+ const MONTHS_PER_YEAR = 12;
17
+ const MINUTE = { min: 0, max: 59 };
18
+ const HOUR = { min: 0, max: 23 };
19
+ const DAY_OF_MONTH = { min: 1, max: 31 };
20
+ const MONTH = { min: 1, max: 12 };
21
+ /** 0 and 7 both mean Sunday, so wrap folds them together. */
22
+ const DAY_OF_WEEK = { min: 0, max: 7, wrap: 7 };
23
+ const DAYS_IN_MONTH_FIELD = DAY_OF_MONTH.max - DAY_OF_MONTH.min + 1;
24
+ const DAYS_IN_WEEK = 7;
25
+ function fields(cron) {
26
+ return cron.trim().split(/\s+/);
27
+ }
28
+ /** True for a field naming one value, e.g. `3`. */
29
+ function isPinned(field) {
30
+ return field !== undefined && /^\d+$/.test(field);
31
+ }
32
+ /** True for a field that varies rather than naming one value. */
33
+ function isWildcard(field) {
34
+ return field === undefined || field === '*';
35
+ }
36
+ /**
37
+ * The values a single cron field matches, or null when the field is not a shape
38
+ * we read (month/day names, the `L`/`W`/`#` extensions, a 6-field Quartz cron).
39
+ *
40
+ * A set rather than a count, so overlapping lists (`1-5,3`) and the two
41
+ * spellings of Sunday (`0,7`) are each counted once and steps are exact.
42
+ */
43
+ function expand(field, range) {
44
+ if (field === undefined)
45
+ return null;
46
+ const out = new Set();
47
+ for (const part of field.split(',')) {
48
+ const segments = part.split('/');
49
+ if (segments.length > 2)
50
+ return null;
51
+ const [spec, stepText] = segments;
52
+ let step = 1;
53
+ if (stepText !== undefined) {
54
+ if (!/^\d+$/.test(stepText))
55
+ return null;
56
+ step = Number(stepText);
57
+ if (step < 1)
58
+ return null;
59
+ }
60
+ let lo;
61
+ let hi;
62
+ if (spec === '*') {
63
+ lo = range.min;
64
+ hi = range.max;
65
+ }
66
+ else if (spec !== undefined && /^\d+$/.test(spec)) {
67
+ lo = Number(spec);
68
+ // A step on a single value means "from here to the end of the range".
69
+ hi = stepText === undefined ? lo : range.max;
70
+ }
71
+ else {
72
+ const bounds = /^(\d+)-(\d+)$/.exec(spec ?? '');
73
+ if (!bounds)
74
+ return null;
75
+ lo = Number(bounds[1]);
76
+ hi = Number(bounds[2]);
77
+ }
78
+ if (lo < range.min || hi > range.max || lo > hi)
79
+ return null;
80
+ for (let value = lo; value <= hi; value += step) {
81
+ out.add(range.wrap === undefined ? value : value % range.wrap);
82
+ }
83
+ }
84
+ return out.size > 0 ? out : null;
85
+ }
86
+ /**
87
+ * Approximate number of times a cron fires per month, or null when the
88
+ * expression is not a 5-field cron we can read.
89
+ *
90
+ * Every field is counted, so a cron that pins a coarse field and leaves a finer
91
+ * one open (`* 3 * * *` — every minute of 03:00) is not mistaken for its coarse
92
+ * unit. day-of-month and day-of-week are OR'd when both are restricted, which
93
+ * is what standard cron does.
94
+ */
95
+ export function runsPerMonth(cron) {
96
+ const f = fields(cron);
97
+ if (f.length !== FIELD_COUNT)
98
+ return null;
99
+ const minutes = expand(f[0], MINUTE);
100
+ const hours = expand(f[1], HOUR);
101
+ const daysOfMonth = expand(f[2], DAY_OF_MONTH);
102
+ const months = expand(f[3], MONTH);
103
+ const daysOfWeek = expand(f[4], DAY_OF_WEEK);
104
+ if (!minutes || !hours || !daysOfMonth || !months || !daysOfWeek)
105
+ return null;
106
+ const everyDayOfMonth = daysOfMonth.size === DAYS_IN_MONTH_FIELD;
107
+ const everyDayOfWeek = daysOfWeek.size === DAYS_IN_WEEK;
108
+ let days;
109
+ if (everyDayOfMonth && everyDayOfWeek) {
110
+ days = DAYS_PER_MONTH;
111
+ }
112
+ else if (everyDayOfWeek) {
113
+ // Short months make a high day number fire less often than once a month;
114
+ // capping at the average month length is close enough for an advisory.
115
+ days = Math.min(daysOfMonth.size, DAYS_PER_MONTH);
116
+ }
117
+ else if (everyDayOfMonth) {
118
+ days = daysOfWeek.size * WEEKS_PER_MONTH;
119
+ }
120
+ else {
121
+ // Restricting both means a day matching EITHER fires. Adding them can
122
+ // double-count a day that matches both, which errs high — the safe
123
+ // direction for a warning about cost.
124
+ days = Math.min(daysOfMonth.size + daysOfWeek.size * WEEKS_PER_MONTH, DAYS_PER_MONTH);
125
+ }
126
+ return minutes.size * hours.size * days * (months.size / MONTHS_PER_YEAR);
127
+ }
128
+ /**
129
+ * Human phrasing for a cron, or the expression itself when it names no exact
130
+ * time — a wrong description is worse than the raw expression.
131
+ */
132
+ export function describeCron(cron) {
133
+ const f = fields(cron);
134
+ if (f.length !== FIELD_COUNT)
135
+ return cron.trim();
136
+ const [minute, hour, dayOfMonth, , dayOfWeek] = f;
137
+ if (!isPinned(minute) || !isPinned(hour))
138
+ return cron.trim();
139
+ const at = `${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`;
140
+ if (isWildcard(dayOfMonth) && isWildcard(dayOfWeek))
141
+ return `daily at ${at}`;
142
+ if (isWildcard(dayOfMonth) && isPinned(dayOfWeek)) {
143
+ return `weekly on ${dayName(Number(dayOfWeek))} at ${at}`;
144
+ }
145
+ if (isPinned(dayOfMonth) && isWildcard(dayOfWeek)) {
146
+ return `monthly on day ${Number(dayOfMonth)} at ${at}`;
147
+ }
148
+ return cron.trim();
149
+ }
150
+ /** Whole numbers read better here than decimals; under one, say it in words. */
151
+ function frequencyClause(runs) {
152
+ if (runs < 0.5)
153
+ return 'less than once a month';
154
+ return `~${Math.round(runs)} time(s)/month`;
155
+ }
156
+ /**
157
+ * Advisory shown before a schedule is created: how often it will run, and that
158
+ * each run is a full test run.
159
+ *
160
+ * States frequency only. Credit cost is deliberately not quoted — the API does
161
+ * not expose a per-action rate for the workspace wallet, and a figure derived
162
+ * from anything else would be wrong. Same reason `usage` does not print a
163
+ * "~N runs" estimate.
164
+ *
165
+ * An expression we cannot read still gets the advisory, without a frequency —
166
+ * the server is the authority on the cron, so refusing to say anything about a
167
+ * schedule we are about to create would be worse than saying less.
168
+ */
169
+ export function formatScheduleFrequencyAdvisory(cron) {
170
+ const tail = 'Each run is a full test run. Check your balance with `testsprite usage`.';
171
+ const runs = runsPerMonth(cron);
172
+ if (runs === null) {
173
+ return `This schedule will run on the cron \`${cron.trim()}\`. ${tail}`;
174
+ }
175
+ return `This schedule will run ${frequencyClause(runs)} (${describeCron(cron)}). ${tail}`;
176
+ }
177
+ const DAY_NAMES = [
178
+ 'Sunday',
179
+ 'Monday',
180
+ 'Tuesday',
181
+ 'Wednesday',
182
+ 'Thursday',
183
+ 'Friday',
184
+ 'Saturday',
185
+ ];
186
+ /** Cron allows both 0 and 7 for Sunday. */
187
+ function dayName(dow) {
188
+ return DAY_NAMES[dow % 7] ?? String(dow);
189
+ }
190
+ //# sourceMappingURL=cron.js.map