@testmutant/cli 0.0.2 → 1.0.0-alpha.4

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.
package/README.md CHANGED
@@ -30,6 +30,10 @@ The CLI reads configuration from environment variables or command-line flags.
30
30
  | --- | --- | --- |
31
31
  | `TESTMUTANT_API_KEY` | `--api-key <key>` | TestMutant API key used to authenticate requests. |
32
32
  | `TESTMUTANT_API_URL` | `--api-url <url>` | TestMutant API base URL. Defaults to `http://localhost:5086`. |
33
+ | `TESTMUTANT_REPOSITORY_PROVIDER` | | Optional repository provider override for `testmutant ci`. |
34
+ | `TESTMUTANT_REPOSITORY_FULL_NAME` | | Optional repository full name override for `testmutant ci`. |
35
+ | `TESTMUTANT_BASE_URL` | | Optional environment URL recorded by `testmutant ci`. |
36
+ | `TESTMUTANT_ENVIRONMENT` | | Optional environment name recorded by `testmutant ci`. |
33
37
  | | `--timeout <ms>` | API request timeout in milliseconds. Defaults to `30000`. |
34
38
  | | `--json` | Print command output as JSON. |
35
39
 
@@ -73,8 +77,8 @@ Store `TESTMUTANT_API_KEY` as a secret in your CI provider.
73
77
  Example GitHub Actions step:
74
78
 
75
79
  ```yaml
76
- - name: Verify TestMutant connection
77
- run: npx @testmutant/cli --json ping
80
+ - name: Record TestMutant CI run
81
+ run: npx @testmutant/cli --json ci
78
82
  env:
79
83
  TESTMUTANT_API_KEY: ${{ secrets.TESTMUTANT_API_KEY }}
80
84
  ```
@@ -86,6 +90,11 @@ Example GitHub Actions step:
86
90
  Verifies that the CLI can authenticate with the TestMutant API and prints the
87
91
  connected organization and CLI API version.
88
92
 
93
+ ### `testmutant ci`
94
+
95
+ Detects repository, branch, commit, and CI provider metadata, creates a
96
+ TestMutant run, immediately completes it, and prints the run id and status.
97
+
89
98
  ## License
90
99
 
91
100
  MIT. Copyright (c) 2026 Sleepycat Software LLC.
package/dist/action.js ADDED
@@ -0,0 +1,483 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // src/action.ts
5
+ var import_config4 = require("dotenv/config");
6
+ var import_node_fs2 = require("fs");
7
+ var import_node_path = require("path");
8
+
9
+ // src/config.ts
10
+ var DEFAULT_API_URL = "http://localhost:5086";
11
+ var API_KEY_ENV_VAR = "TESTMUTANT_API_KEY";
12
+ var API_URL_ENV_VAR = "TESTMUTANT_API_URL";
13
+ var CliError = class extends Error {
14
+ constructor(message, exitCode = 1) {
15
+ super(message);
16
+ this.exitCode = exitCode;
17
+ this.name = "CliError";
18
+ }
19
+ exitCode;
20
+ };
21
+ function resolveConfig(input = {}) {
22
+ const apiKey = input.apiKey ?? process.env[API_KEY_ENV_VAR];
23
+ const apiUrl = input.apiUrl ?? process.env[API_URL_ENV_VAR] ?? DEFAULT_API_URL;
24
+ const timeoutMs = parseTimeout(input.timeout);
25
+ if (!apiKey) {
26
+ throw new CliError(
27
+ `Missing API key. Set ${API_KEY_ENV_VAR} or pass --api-key.`,
28
+ 2
29
+ );
30
+ }
31
+ return {
32
+ apiKey,
33
+ apiUrl: normalizeApiUrl(apiUrl),
34
+ timeoutMs
35
+ };
36
+ }
37
+ function normalizeApiUrl(value) {
38
+ let url;
39
+ try {
40
+ url = new URL(value);
41
+ } catch {
42
+ throw new CliError(`Invalid API URL: ${value}`, 2);
43
+ }
44
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
45
+ throw new CliError("API URL must start with http:// or https://.", 2);
46
+ }
47
+ return url.toString().replace(/\/$/, "");
48
+ }
49
+ function parseTimeout(value) {
50
+ if (!value) {
51
+ return 3e4;
52
+ }
53
+ const timeoutMs = Number(value);
54
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) {
55
+ throw new CliError("Timeout must be a positive integer in milliseconds.", 2);
56
+ }
57
+ return timeoutMs;
58
+ }
59
+
60
+ // src/api-client.ts
61
+ var TestMutantApiClient = class {
62
+ constructor(options) {
63
+ this.options = options;
64
+ }
65
+ options;
66
+ async ping() {
67
+ return this.postJson("/api/cli/v1/ping", {
68
+ repositoryProvider: null,
69
+ repositoryFullName: null
70
+ });
71
+ }
72
+ async createRun(request) {
73
+ return this.postJson(
74
+ "/api/cli/v1/runs",
75
+ request,
76
+ 201
77
+ );
78
+ }
79
+ async completeRun(runId, request) {
80
+ return this.postJson(
81
+ `/api/cli/v1/runs/${encodeURIComponent(runId)}/complete`,
82
+ request
83
+ );
84
+ }
85
+ async postJson(path, body, expectedStatus = 200) {
86
+ const response = await this.request(path, body);
87
+ if (response.status === 401) {
88
+ throw new CliError("Unauthorized. Check your TestMutant API key.", 3);
89
+ }
90
+ if (response.status !== expectedStatus) {
91
+ const detail = await readErrorDetail(response);
92
+ throw new CliError(
93
+ `TestMutant API request failed with HTTP ${response.status}.${detail}`
94
+ );
95
+ }
96
+ try {
97
+ return await response.json();
98
+ } catch {
99
+ throw new CliError("TestMutant API returned invalid JSON.");
100
+ }
101
+ }
102
+ async request(path, body) {
103
+ const controller = new AbortController();
104
+ const timeout = setTimeout(() => controller.abort(), this.options.timeoutMs);
105
+ try {
106
+ return await fetch(new URL(path, this.options.apiUrl), {
107
+ method: "POST",
108
+ body: JSON.stringify(body),
109
+ signal: controller.signal,
110
+ headers: {
111
+ accept: "application/json",
112
+ "content-type": "application/json",
113
+ authorization: `Bearer ${this.options.apiKey}`,
114
+ "user-agent": this.options.userAgent
115
+ }
116
+ });
117
+ } catch (error) {
118
+ if (error instanceof Error && error.name === "AbortError") {
119
+ throw new CliError(
120
+ `TestMutant API request timed out after ${this.options.timeoutMs} ms.`
121
+ );
122
+ }
123
+ const message = error instanceof Error ? error.message : String(error);
124
+ throw new CliError(`Could not reach TestMutant API. ${message}`);
125
+ } finally {
126
+ clearTimeout(timeout);
127
+ }
128
+ }
129
+ };
130
+ async function readErrorDetail(response) {
131
+ const body = await response.text();
132
+ if (!body) {
133
+ return "";
134
+ }
135
+ const contentType = response.headers.get("content-type") ?? "";
136
+ if (contentType.includes("json")) {
137
+ try {
138
+ const problem = JSON.parse(body);
139
+ const parts = [
140
+ typeof problem.title === "string" ? problem.title : null,
141
+ typeof problem.detail === "string" ? problem.detail : null,
142
+ formatValidationErrors(problem.errors)
143
+ ].filter((part) => Boolean(part));
144
+ if (parts.length > 0) {
145
+ return ` ${truncate(parts.join(" "), 500)}`;
146
+ }
147
+ } catch {
148
+ return ` ${truncate(body, 500)}`;
149
+ }
150
+ }
151
+ return ` ${truncate(body, 500)}`;
152
+ }
153
+ function formatValidationErrors(errors) {
154
+ if (!errors || typeof errors !== "object") {
155
+ return null;
156
+ }
157
+ const messages = [];
158
+ for (const [field, value] of Object.entries(errors)) {
159
+ if (Array.isArray(value)) {
160
+ for (const item of value) {
161
+ if (typeof item === "string") {
162
+ messages.push(`${field}: ${item}`);
163
+ }
164
+ }
165
+ }
166
+ }
167
+ return messages.length > 0 ? messages.join(" ") : null;
168
+ }
169
+ function truncate(value, maxLength) {
170
+ if (value.length <= maxLength) {
171
+ return value;
172
+ }
173
+ return `${value.slice(0, maxLength)}...`;
174
+ }
175
+
176
+ // src/ci-metadata.ts
177
+ var import_node_child_process = require("child_process");
178
+ var import_node_fs = require("fs");
179
+ function buildCreateRunRequest(options = {}) {
180
+ const env = process.env;
181
+ const gitRepository = getGitRepositoryMetadata();
182
+ const repositoryProvider = normalize(options.repositoryProvider) ?? normalize(env.TESTMUTANT_REPOSITORY_PROVIDER) ?? detectRepositoryProvider(env) ?? gitRepository.provider;
183
+ const repositoryFullName = normalize(options.repositoryFullName) ?? normalize(env.TESTMUTANT_REPOSITORY_FULL_NAME) ?? detectRepositoryFullName(env) ?? gitRepository.fullName;
184
+ if (!repositoryFullName) {
185
+ throw new CliError(
186
+ "Could not determine repository full name from CI environment or git remote origin.",
187
+ 2
188
+ );
189
+ }
190
+ return {
191
+ mode: normalize(options.mode) ?? "Advisory",
192
+ runKind: normalize(options.runKind) ?? "Advisory",
193
+ repositoryProvider: repositoryProvider ?? "GitHub",
194
+ repositoryFullName,
195
+ baseUrl: normalizeUrl(options.baseUrl) ?? detectBaseUrl(env),
196
+ environmentName: normalize(options.environmentName) ?? detectEnvironmentName(env),
197
+ branch: detectBranch(env) ?? git(["rev-parse", "--abbrev-ref", "HEAD"]),
198
+ commitSha: detectCommitSha(env) ?? git(["rev-parse", "HEAD"]),
199
+ pullRequestNumber: detectPullRequestNumber(env),
200
+ ciProvider: detectCiProvider(env),
201
+ ciRunId: detectCiRunId(env)
202
+ };
203
+ }
204
+ function detectRepositoryProvider(env) {
205
+ if (env.GITHUB_ACTIONS || env.GITHUB_REPOSITORY) {
206
+ return "GitHub";
207
+ }
208
+ if (env.GITLAB_CI || env.CI_PROJECT_PATH) {
209
+ return "GitLab";
210
+ }
211
+ if (env.BITBUCKET_BUILD_NUMBER || env.BITBUCKET_REPO_FULL_NAME) {
212
+ return "Bitbucket";
213
+ }
214
+ if (env.TF_BUILD || env.BUILD_REPOSITORY_URI) {
215
+ return "AzureDevOps";
216
+ }
217
+ return null;
218
+ }
219
+ function detectRepositoryFullName(env) {
220
+ if (env.GITHUB_REPOSITORY) {
221
+ return normalize(env.GITHUB_REPOSITORY);
222
+ }
223
+ if (env.GITLAB_CI && env.CI_PROJECT_PATH) {
224
+ return normalize(env.CI_PROJECT_PATH);
225
+ }
226
+ if (env.BITBUCKET_REPO_FULL_NAME) {
227
+ return normalize(env.BITBUCKET_REPO_FULL_NAME);
228
+ }
229
+ if (env.CIRCLE_PROJECT_USERNAME && env.CIRCLE_PROJECT_REPONAME) {
230
+ return `${env.CIRCLE_PROJECT_USERNAME}/${env.CIRCLE_PROJECT_REPONAME}`;
231
+ }
232
+ if (env.BUILD_REPOSITORY_NAME) {
233
+ return normalize(env.BUILD_REPOSITORY_NAME);
234
+ }
235
+ return null;
236
+ }
237
+ function detectBranch(env) {
238
+ return normalize(env.GITHUB_HEAD_REF) ?? normalize(env.GITHUB_REF_NAME) ?? branchFromGitRef(env.GITHUB_REF) ?? normalize(env.CI_COMMIT_REF_NAME) ?? normalize(env.BITBUCKET_BRANCH) ?? normalize(env.CIRCLE_BRANCH) ?? normalize(env.BUILDKITE_BRANCH) ?? normalize(env.BUILD_SOURCEBRANCHNAME) ?? branchFromGitRef(env.BUILD_SOURCEBRANCH);
239
+ }
240
+ function detectCommitSha(env) {
241
+ return normalize(env.GITHUB_SHA) ?? normalize(env.CI_COMMIT_SHA) ?? normalize(env.BITBUCKET_COMMIT) ?? normalize(env.CIRCLE_SHA1) ?? normalize(env.BUILDKITE_COMMIT) ?? normalize(env.BUILD_SOURCEVERSION);
242
+ }
243
+ function detectPullRequestNumber(env) {
244
+ return numberFromValue(env.GITHUB_REF?.match(/^refs\/pull\/(\d+)\//)?.[1]) ?? githubEventPullRequestNumber(env) ?? numberFromValue(env.CI_MERGE_REQUEST_IID) ?? numberFromValue(env.BITBUCKET_PR_ID) ?? numberFromValue(env.CIRCLE_PULL_REQUEST?.split("/").pop()) ?? numberFromValue(env.BUILDKITE_PULL_REQUEST) ?? numberFromValue(env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER);
245
+ }
246
+ function detectCiProvider(env) {
247
+ if (env.GITHUB_ACTIONS) {
248
+ return "GitHubActions";
249
+ }
250
+ if (env.GITLAB_CI) {
251
+ return "GitLabCI";
252
+ }
253
+ if (env.BITBUCKET_BUILD_NUMBER) {
254
+ return "BitbucketPipelines";
255
+ }
256
+ if (env.CIRCLECI) {
257
+ return "CircleCI";
258
+ }
259
+ if (env.BUILDKITE) {
260
+ return "Buildkite";
261
+ }
262
+ if (env.TF_BUILD) {
263
+ return "AzurePipelines";
264
+ }
265
+ if (env.JENKINS_URL) {
266
+ return "Jenkins";
267
+ }
268
+ return env.CI ? "CI" : null;
269
+ }
270
+ function detectCiRunId(env) {
271
+ return normalize(env.GITHUB_RUN_ID) ?? normalize(env.CI_PIPELINE_ID) ?? normalize(env.BITBUCKET_BUILD_NUMBER) ?? normalize(env.CIRCLE_WORKFLOW_ID) ?? normalize(env.CIRCLE_BUILD_NUM) ?? normalize(env.BUILDKITE_BUILD_ID) ?? normalize(env.BUILD_BUILDID) ?? normalize(env.BUILD_TAG) ?? normalize(env.BUILD_NUMBER);
272
+ }
273
+ function detectBaseUrl(env) {
274
+ return normalizeUrl(env.TESTMUTANT_BASE_URL) ?? normalizeUrl(env.DEPLOY_URL) ?? normalizeUrl(env.URL) ?? normalizeUrl(env.VERCEL_BRANCH_URL) ?? normalizeUrl(env.VERCEL_URL) ?? normalizeUrl(env.CF_PAGES_URL) ?? normalizeUrl(env.RENDER_EXTERNAL_URL);
275
+ }
276
+ function detectEnvironmentName(env) {
277
+ return normalize(env.TESTMUTANT_ENVIRONMENT) ?? normalize(env.CI_ENVIRONMENT_NAME) ?? normalize(env.VERCEL_ENV) ?? normalize(env.NETLIFY_CONTEXT) ?? normalize(env.CF_PAGES_BRANCH);
278
+ }
279
+ function githubEventPullRequestNumber(env) {
280
+ const eventPath = normalize(env.GITHUB_EVENT_PATH);
281
+ if (!eventPath || !(0, import_node_fs.existsSync)(eventPath)) {
282
+ return null;
283
+ }
284
+ try {
285
+ const event = JSON.parse((0, import_node_fs.readFileSync)(eventPath, "utf8"));
286
+ return numberFromValue(event.pull_request?.number) ?? numberFromValue(event.number);
287
+ } catch {
288
+ return null;
289
+ }
290
+ }
291
+ function getGitRepositoryMetadata() {
292
+ const remote = git(["remote", "get-url", "origin"]);
293
+ return remote ? parseGitRemoteUrl(remote) : { provider: null, fullName: null };
294
+ }
295
+ function parseGitRemoteUrl(remoteUrl) {
296
+ const remote = remoteUrl.trim();
297
+ const url = parseRemoteAsUrl(remote);
298
+ const host = url?.host ?? parseScpRemoteHost(remote);
299
+ const path = url?.pathname ?? parseScpRemotePath(remote);
300
+ const fullName = path?.replace(/^\/+/, "").replace(/\.git$/i, "").replace(/^v\d+\//i, "");
301
+ return {
302
+ provider: host ? providerFromHost(host) : null,
303
+ fullName: normalize(fullName)
304
+ };
305
+ }
306
+ function parseRemoteAsUrl(remote) {
307
+ try {
308
+ return new URL(remote.replace(/^git\+/, ""));
309
+ } catch {
310
+ return null;
311
+ }
312
+ }
313
+ function parseScpRemoteHost(remote) {
314
+ return remote.match(/^(?:[^@]+@)?([^:]+):(.+)$/)?.[1] ?? null;
315
+ }
316
+ function parseScpRemotePath(remote) {
317
+ return remote.match(/^(?:[^@]+@)?([^:]+):(.+)$/)?.[2] ?? null;
318
+ }
319
+ function providerFromHost(host) {
320
+ const normalized = host.toLowerCase();
321
+ if (normalized.includes("github")) {
322
+ return "GitHub";
323
+ }
324
+ if (normalized.includes("gitlab")) {
325
+ return "GitLab";
326
+ }
327
+ if (normalized.includes("bitbucket")) {
328
+ return "Bitbucket";
329
+ }
330
+ if (normalized.includes("dev.azure") || normalized.includes("visualstudio")) {
331
+ return "AzureDevOps";
332
+ }
333
+ return null;
334
+ }
335
+ function branchFromGitRef(value) {
336
+ const ref = normalize(value);
337
+ if (!ref) {
338
+ return null;
339
+ }
340
+ return ref.match(/^refs\/heads\/(.+)$/)?.[1] ?? ref.match(/^refs\/tags\/(.+)$/)?.[1] ?? null;
341
+ }
342
+ function normalizeUrl(value) {
343
+ const normalized = normalize(value);
344
+ if (!normalized) {
345
+ return null;
346
+ }
347
+ if (/^https?:\/\//i.test(normalized)) {
348
+ return normalized;
349
+ }
350
+ return `https://${normalized}`;
351
+ }
352
+ function numberFromValue(value) {
353
+ if (typeof value === "number" && Number.isInteger(value) && value > 0) {
354
+ return value;
355
+ }
356
+ if (typeof value !== "string") {
357
+ return null;
358
+ }
359
+ if (value.toLowerCase() === "false") {
360
+ return null;
361
+ }
362
+ const parsed = Number(value);
363
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
364
+ }
365
+ function normalize(value) {
366
+ const trimmed = value?.trim();
367
+ return trimmed ? trimmed : null;
368
+ }
369
+ function git(args) {
370
+ try {
371
+ const safeDirectory = process.cwd().replace(/\\/g, "/");
372
+ return normalize(
373
+ (0, import_node_child_process.execFileSync)("git", ["-c", `safe.directory=${safeDirectory}`, ...args], {
374
+ encoding: "utf8",
375
+ stdio: ["ignore", "pipe", "ignore"]
376
+ })
377
+ );
378
+ } catch {
379
+ return null;
380
+ }
381
+ }
382
+
383
+ // src/run-ci.ts
384
+ async function runCi(options) {
385
+ applyOptionEnvironmentOverrides(options);
386
+ const config = resolveConfig({
387
+ apiKey: options.apiKey,
388
+ apiUrl: options.apiUrl,
389
+ timeout: options.timeout
390
+ });
391
+ const client = new TestMutantApiClient({
392
+ ...config,
393
+ userAgent: options.userAgent
394
+ });
395
+ const createRunRequest = buildCreateRunRequest({
396
+ mode: options.mode,
397
+ repositoryProvider: options.provider,
398
+ repositoryFullName: options.repository,
399
+ baseUrl: options.baseUrl,
400
+ environmentName: options.environmentName
401
+ });
402
+ const created = await client.createRun(createRunRequest);
403
+ const completed = await client.completeRun(created.runId, {
404
+ status: "Passed",
405
+ summary: "CI metadata captured.",
406
+ results: {
407
+ kind: "advisory",
408
+ message: "TestMutant CLI vertical slice completed successfully.",
409
+ repositoryFullName: createRunRequest.repositoryFullName,
410
+ branch: createRunRequest.branch,
411
+ commitSha: createRunRequest.commitSha,
412
+ ciProvider: createRunRequest.ciProvider,
413
+ ciRunId: createRunRequest.ciRunId,
414
+ generatedAtUtc: (/* @__PURE__ */ new Date()).toISOString()
415
+ },
416
+ resultJson: null,
417
+ errorMessage: null
418
+ });
419
+ return {
420
+ runId: completed.runId,
421
+ status: completed.status
422
+ };
423
+ }
424
+ function applyOptionEnvironmentOverrides(options) {
425
+ if (options.apiKey) {
426
+ process.env[API_KEY_ENV_VAR] = options.apiKey;
427
+ }
428
+ if (options.apiUrl) {
429
+ process.env[API_URL_ENV_VAR] = options.apiUrl;
430
+ }
431
+ if (!process.env[API_URL_ENV_VAR]) {
432
+ process.env[API_URL_ENV_VAR] = DEFAULT_API_URL;
433
+ }
434
+ }
435
+
436
+ // src/action.ts
437
+ var packageInfo = readPackageInfo();
438
+ main().catch((error) => {
439
+ if (error instanceof CliError) {
440
+ fail(error.message);
441
+ }
442
+ if (error instanceof Error) {
443
+ fail(
444
+ process.env.TESTMUTANT_DEBUG === "1" && error.stack ? error.stack : error.message
445
+ );
446
+ }
447
+ fail(String(error));
448
+ });
449
+ async function main() {
450
+ const result = await runCi({
451
+ apiKey: process.env.TESTMUTANT_API_KEY,
452
+ apiUrl: getInput("api_url"),
453
+ mode: getInput("mode") ?? "Advisory",
454
+ repository: getInput("repository"),
455
+ provider: getInput("provider") ?? "GitHub",
456
+ baseUrl: getInput("base_url"),
457
+ environmentName: getInput("environment_name"),
458
+ userAgent: `testmutant-action/${packageInfo.version}`
459
+ });
460
+ console.log("TestMutant run completed.");
461
+ console.log(`Run ID: ${result.runId}`);
462
+ console.log(`Status: ${result.status}`);
463
+ }
464
+ function getInput(name) {
465
+ const value = process.env[`INPUT_${name.toUpperCase()}`];
466
+ return value?.trim() ? value.trim() : void 0;
467
+ }
468
+ function fail(message) {
469
+ console.error(message);
470
+ console.error(`::error::${escapeGithubAnnotation(message)}`);
471
+ process.exit(1);
472
+ }
473
+ function escapeGithubAnnotation(value) {
474
+ return value.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
475
+ }
476
+ function readPackageInfo() {
477
+ const packageJsonPath = (0, import_node_path.join)(__dirname, "..", "package.json");
478
+ const packageJson = JSON.parse((0, import_node_fs2.readFileSync)(packageJsonPath, "utf8"));
479
+ return {
480
+ name: typeof packageJson.name === "string" ? packageJson.name : "@testmutant/cli",
481
+ version: typeof packageJson.version === "string" ? packageJson.version : "0.0.0"
482
+ };
483
+ }