@theholocron/holocron-plugin-codecov 5.0.0-alpha.452 → 5.0.0-alpha.453

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/dist/index.d.mts CHANGED
@@ -4,11 +4,24 @@
4
4
  * Implements the `coverage` capability against Codecov's REST API (`checkToken`), and exports the token declaration and
5
5
  * the `token` probe. See the README for auth, config and what a Codecov token can be checked for.
6
6
  */
7
- import { AuthError, Coverage, CoverageTokenCheck, PluginToken, ResolveTokenInput } from "@theholocron/cli";
7
+ import { AuthError, Coverage, CoverageConfigInput, CoverageExpectations, CoverageRepoReport, CoverageStatusContext, CoverageStatusInput, CoverageTokenCheck, CoverageUploadInput, CoverageUploadResult, PluginToken, ResolveTokenInput } from "@theholocron/cli";
8
+ import { spawnSync } from "node:child_process";
8
9
  import { CodecovClient, CodecovClientOptions, CodecovService, createCodecovClient } from "@theholocron/codecov-client";
9
- /** Resolves the Codecov token from `--token`, `HOLOCRON_CODECOV_TOKEN`, `CODECOV_TOKEN` or the keyring entry for `codecov`, and throws an `AuthError` when none is set. */
10
+ /**
11
+ * Resolves the Codecov repository **upload** token from `--token`, `HOLOCRON_CODECOV_UPLOAD_TOKEN`, `CODECOV_TOKEN` (what
12
+ * Codecov's own uploader reads) or the keyring entry for `codecov.upload`, and throws an `AuthError` when none is set.
13
+ */
10
14
  export declare const resolveToken: import("@theholocron/cli").TokenResolver;
11
- /** Every token this plugin takes, for `holocron doctor tokens`, with the layers that hold it. */
15
+ /**
16
+ * Resolves the Codecov API token (a personal access token, which Codecov's REST API takes as a bearer token) from
17
+ * `HOLOCRON_CODECOV_API_TOKEN` or the keyring entry `codecov.api`, and throws an `AuthError` naming the variable when none
18
+ * is set. It never falls back to the upload token, which the REST API answers with a 401.
19
+ */
20
+ export declare const resolveApiToken: import("@theholocron/cli").FeatureResolver;
21
+ /**
22
+ * Every token this plugin takes, for `holocron doctor tokens`, with the layers that hold it: the repository upload token
23
+ * (`ci`) and the optional personal API token the repository check reads (`dev` and `ci`, held in 1Password only).
24
+ */
12
25
  export declare const tokens: PluginToken[];
13
26
  /** The repository the plugin asks Codecov about. */
14
27
  interface CodecovTarget {
@@ -32,20 +45,90 @@ interface CodecovTargetOptions {
32
45
  }
33
46
  /** Works out the repository from the plugin options, or `undefined` when they do not name one. */
34
47
  export declare function resolveTarget(options: CodecovTargetOptions): CodecovTarget | undefined;
48
+ /** What one run of the Codecov CLI did. */
49
+ interface CodecovCliResult {
50
+ /** Whether it exited 0. */
51
+ ok: boolean;
52
+ /** Its standard output, trimmed, with the token removed. */
53
+ stdout: string;
54
+ /** Its standard error, trimmed, with the token removed (or the spawn error's message). */
55
+ stderr: string;
56
+ }
57
+ /** What {@link CodecovCli} takes. */
58
+ interface CodecovCliOptions {
59
+ /** Path of the Codecov CLI binary. */
60
+ binary: string;
61
+ /** Override the spawn function in tests. */
62
+ spawn?: SpawnFn;
63
+ /** The environment the CLI runs in (its CI detection reads it); the token is added to a copy. */
64
+ env: Record<string, string | undefined>;
65
+ }
66
+ /** Runs the Codecov CLI's `create-commit`, `create-report` and `do-upload`. */
67
+ declare class CodecovCli {
68
+ private readonly binary;
69
+ private readonly spawnImpl;
70
+ private readonly env;
71
+ constructor(opts: CodecovCliOptions);
72
+ /** Tells Codecov about the commit. */
73
+ createCommit(token: string): CodecovCliResult;
74
+ /** Opens the report the per-flag uploads attach to. */
75
+ createReport(token: string): CodecovCliResult;
76
+ /** Uploads `files` under `flag`, searching for nothing else. */
77
+ doUpload(token: string, flag: string, files: string[]): CodecovCliResult;
78
+ private run;
79
+ }
80
+ /** `spawnSync`, injected so a test never starts a process. */
81
+ type SpawnFn = typeof spawnSync;
82
+ /** Everything {@link uploadCoverage} touches outside itself, so every branch can be reached from a test. */
83
+ interface UploadDeps {
84
+ /** The environment the run reads: `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN`. */
85
+ env: (name: string) => string | undefined;
86
+ /** `fetch`, for the OIDC token. */
87
+ fetch: typeof fetch;
88
+ /** Downloads and checks the Codecov CLI, and returns the runner for it. */
89
+ prepareCli: () => Promise<CodecovCli>;
90
+ /** Expands a glob pattern, relative to `cwd`, into file paths (sorted). */
91
+ expandGlob: (pattern: string, cwd: string) => string[];
92
+ /** Reads a report as text. */
93
+ readFile: (path: string) => string;
94
+ /** Writes the rooted copy of a report. */
95
+ writeFile: (path: string, data: string) => void;
96
+ /** Makes a fresh scratch folder for the rooted copies and returns its path. */
97
+ makeTempDir: () => string;
98
+ /** Waits; injected so a retry never sleeps in a test. */
99
+ sleep: (ms: number) => Promise<void>;
100
+ /** Prints a line of progress (names and counts only). */
101
+ log: (line: string) => void;
102
+ /** Masks a value in the log (`::add-mask::`), called with each OIDC token before anything else sees it. */
103
+ mask: (value: string) => void;
104
+ }
35
105
  /** The `coverage` capability for Codecov. */
36
106
  export declare class CodecovCoverage implements Coverage {
37
107
  private readonly client;
38
108
  private readonly target;
109
+ private readonly apiClient?;
110
+ private readonly uploadDeps;
39
111
  /** The capability key, always `coverage`. */
40
112
  readonly key: "coverage";
41
113
  /** The provider name, `codecov`. */
42
114
  readonly providerName = "codecov";
43
115
  /**
44
116
  * `client` is a thunk, so the token is resolved on first use and a plugin load never needs one. `target` is `undefined`
45
- * when the options name no repository.
117
+ * when the options name no repository. `apiClient` builds the client from the API token for `checkRepo()` and throws an
118
+ * `AuthError` when there is none; left out, `checkRepo()` reports that it has no token.
46
119
  */
47
- constructor(client: () => CodecovClient, target: CodecovTarget | undefined);
120
+ constructor(client: () => CodecovClient, target: CodecovTarget | undefined, apiClient?: (() => CodecovClient) | undefined, uploadDeps?: () => UploadDeps);
121
+ checkRepo(expected: CoverageExpectations): Promise<CoverageRepoReport>;
48
122
  checkToken(): Promise<CoverageTokenCheck>;
123
+ /**
124
+ * Uploads the reports, one flag per group, authenticated with the job's OIDC token (no stored token, so the plugin
125
+ * needs none for this). The Codecov CLI does the upload; see `uploadCoverage()`.
126
+ */
127
+ upload(input: CoverageUploadInput): Promise<CoverageUploadResult>;
128
+ /** The commit statuses Codecov posts, by name: see `statusContexts()`. Offline, so it needs no token and no repository. */
129
+ statusContexts(input: CoverageStatusInput): CoverageStatusContext[];
130
+ /** The files Codecov reads its config from (`codecov.yml`): see `configFiles()`. Offline, so it needs no token and no repository. */
131
+ configFiles(input: CoverageConfigInput): Record<string, string>;
49
132
  }
50
133
  /** Options for the Codecov plugin: token resolution, the repository and test overrides. */
51
134
  export interface CodecovPluginOptions extends ResolveTokenInput, CodecovTargetOptions {
@@ -53,23 +136,37 @@ export interface CodecovPluginOptions extends ResolveTokenInput, CodecovTargetOp
53
136
  baseUrl?: string;
54
137
  /** Override `fetch` for tests. */
55
138
  fetch?: typeof fetch;
139
+ /** The workspace root, which the CLI passes to every plugin: where the repo check reads the flags and components from. */
140
+ repoRoot?: string;
141
+ /** `repoValidation.docsCoverage` of the config, which the CLI passes: `warn` or `required` adds the `documentation` flag. */
142
+ docsCoverage?: "off" | "warn" | "required";
143
+ /** Override the flags and components the repo check expects (tests); default: what `holocron sync` writes. */
144
+ expected?: () => CoverageExpectations;
56
145
  }
57
- /** What the plugin's capability and probes share: the options and a lazily built client. */
146
+ /** What the plugin's capability and probes share: the options and lazily built clients. */
58
147
  export interface PluginContext {
59
148
  /** The options the plugin was created with. */
60
149
  options: CodecovPluginOptions;
61
150
  /** Builds the client on first call and reuses it; the token is resolved then, not at plugin load. */
62
151
  client: () => CodecovClient;
152
+ /**
153
+ * Builds a client with the Codecov API token (`HOLOCRON_CODECOV_API_TOKEN`) that the repo check needs, and throws an
154
+ * `AuthError` when there is none. It never uses `--token` (that is the upload token) or the upload token.
155
+ */
156
+ apiClient: () => CodecovClient;
63
157
  }
64
- /** Creates the shared context for the given options; no token is resolved until `client()` is first called. */
158
+ /** Creates the shared context for the given options; no token is resolved until `client()` or `apiClient()` is first called. */
65
159
  export declare function createContext(options?: CodecovPluginOptions): PluginContext;
160
+ /** Builds the `coverage` capability from a plugin context; `apiToken` replaces the resolved API token for this one capability. */
161
+ export declare function coverageWithApiToken(ctx: PluginContext, apiToken: string): Coverage;
66
162
  /** Builds the `coverage` capability from a plugin context. */
67
163
  export declare function coverage(ctx: PluginContext): Coverage;
68
- /** Creates the Codecov plugin: its `connection` and `token` probes and the `coverage` capability. */
164
+ /** Creates the Codecov plugin: its `connection`, `repo` and `token` probes and the `coverage` capability. */
69
165
  export declare function createPlugin(options?: CodecovPluginOptions): {
70
166
  name: string;
71
167
  probes: {
72
168
  connection: import("@theholocron/cli").Probe;
169
+ repo: import("@theholocron/cli").Probe;
73
170
  token: import("@theholocron/cli").Probe;
74
171
  };
75
172
  capabilities: {
package/dist/index.mjs CHANGED
@@ -1,25 +1,56 @@
1
- import { AuthError, ProviderApiError, connectionProbe, createResolveToken, tokenExpectations } from "@theholocron/cli";
1
+ import { AuthError, AuthError as AuthError$1, ProviderApiError, connectionProbe, coverageExpectations, createFeatureResolver, createResolveToken, tokenExpectations } from "@theholocron/cli";
2
+ import { spawnSync } from "node:child_process";
3
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join, posix } from "node:path";
6
+ import { createEnvLookup } from "@theholocron/env-utils/lookup";
7
+ import { createHash } from "node:crypto";
2
8
  import { createCodecovClient } from "@theholocron/codecov-client";
3
9
  // src/probes/token/expectations.ts
4
10
  /**
5
- * Where the Codecov token is held: CI only (`measure:bundle` uploads bundle stats with it), so `ci` is the one layer
6
- * declared. Codecov has one token that does one thing, upload, and no permission model, so no permissions are declared and
11
+ * Where the Codecov upload token (`HOLOCRON_CODECOV_UPLOAD_TOKEN`) is held: CI only (`measure:bundle` uploads bundle stats
12
+ * with it), so `ci` is the one layer declared. Codecov has no permission model, so no permissions are declared and
7
13
  * the probe says so instead of guessing. This is the plugin's `tokens` declaration, read through `tokenExpectations()`;
8
14
  * change it and the Codecov row in `docs/src/content/docs/tokens.mdx` together.
9
15
  */
10
16
  const EXPECTED = { layers: ["ci"] };
17
+ /**
18
+ * Where the Codecov API token (`HOLOCRON_CODECOV_API_TOKEN`, a personal access token, read by `probe codecov repo`) is
19
+ * held: `dev` and `ci`, in 1Password only (nothing syncs it to GitHub). It has no permission model to declare either. Change it and the Codecov API row in `tokens.mdx` together.
20
+ */
21
+ const API_EXPECTED = { layers: ["dev", "ci"] };
11
22
  // src/auth.ts
12
- /** Resolves the Codecov token from `--token`, `HOLOCRON_CODECOV_TOKEN`, `CODECOV_TOKEN` or the keyring entry for `codecov`, and throws an `AuthError` when none is set. */
23
+ /**
24
+ * Resolves the Codecov repository **upload** token from `--token`, `HOLOCRON_CODECOV_UPLOAD_TOKEN`, `CODECOV_TOKEN` (what
25
+ * Codecov's own uploader reads) or the keyring entry for `codecov.upload`, and throws an `AuthError` when none is set.
26
+ */
13
27
  const resolveToken = createResolveToken({
14
- envName: "HOLOCRON_CODECOV_TOKEN",
28
+ envName: "HOLOCRON_CODECOV_UPLOAD_TOKEN",
15
29
  vendorEnvName: "CODECOV_TOKEN",
16
- keyringService: "codecov",
17
- errorMessage: "no Codecov token found. Pass --token <TOKEN>, set HOLOCRON_CODECOV_TOKEN / CODECOV_TOKEN, or run: holocron new token codecov <TOKEN>"
30
+ keyringService: "codecov.upload",
31
+ errorMessage: "no Codecov upload token found. Pass --token <TOKEN>, set HOLOCRON_CODECOV_UPLOAD_TOKEN / CODECOV_TOKEN, or run: holocron new token codecov.upload <TOKEN>"
32
+ });
33
+ /**
34
+ * Resolves the Codecov API token (a personal access token, which Codecov's REST API takes as a bearer token) from
35
+ * `HOLOCRON_CODECOV_API_TOKEN` or the keyring entry `codecov.api`, and throws an `AuthError` naming the variable when none
36
+ * is set. It never falls back to the upload token, which the REST API answers with a 401.
37
+ */
38
+ const resolveApiToken = createFeatureResolver({
39
+ envName: "HOLOCRON_CODECOV_API_TOKEN",
40
+ keyringKey: "codecov.api",
41
+ vendor: "Codecov API"
18
42
  });
19
- /** Every token this plugin takes, for `holocron doctor tokens`, with the layers that hold it. */
43
+ /**
44
+ * Every token this plugin takes, for `holocron doctor tokens`, with the layers that hold it: the repository upload token
45
+ * (`ci`) and the optional personal API token the repository check reads (`dev` and `ci`, held in 1Password only).
46
+ */
20
47
  const tokens = [{
21
48
  ...resolveToken.token,
22
49
  expect: EXPECTED
50
+ }, {
51
+ ...resolveApiToken.token,
52
+ optional: true,
53
+ expect: API_EXPECTED
23
54
  }];
24
55
  // src/target.ts
25
56
  /** Works out the repository from the plugin options, or `undefined` when they do not name one. */
@@ -38,22 +69,811 @@ function resolveTarget(options) {
38
69
  function describeTarget(target) {
39
70
  return `${target.owner}/${target.repo}`;
40
71
  }
72
+ // src/upload/parse-checksum.ts
73
+ /**
74
+ * The digest `sha256sum` printed for `name` in a checksum file (`<hex> <name>`, or `<hex> *<name>` for a binary
75
+ * file), or `undefined` when the file has no line for it.
76
+ */
77
+ function parseChecksum(text, name) {
78
+ for (const line of text.split("\n")) {
79
+ const match = /^([0-9a-fA-F]{64}) [ *](.+?)\r?$/.exec(line);
80
+ if (match && match[2] === name) return match[1].toLowerCase();
81
+ }
82
+ }
83
+ // src/upload/retry-with-wait.ts
84
+ /** Runs `attempt` until it resolves or `attempts` tries have failed, waiting between tries; rethrows the last failure. */
85
+ async function retryWithWait(input) {
86
+ for (let n = 1;; n++) try {
87
+ return await input.attempt(n);
88
+ } catch (error) {
89
+ if (n >= input.attempts) throw error;
90
+ const wait = input.waitMs(n);
91
+ input.onRetry?.(n, error, wait);
92
+ await input.sleep(wait);
93
+ }
94
+ }
95
+ // src/upload/sha256-matches.ts
96
+ /** Whether the SHA-256 digest of `bytes` equals `expected` (hex, any case). */
97
+ function sha256Matches(bytes, expected) {
98
+ return createHash("sha256").update(bytes).digest("hex") === expected.trim().toLowerCase();
99
+ }
100
+ // src/upload/verify-signature.ts
101
+ /** Imports the signing key into a private keyring and checks the detached signature; `true` only when `gpg` accepts it. */
102
+ function verifySignature(input) {
103
+ const home = [
104
+ "--homedir",
105
+ input.gnupgHome,
106
+ "--batch"
107
+ ];
108
+ const imported = input.spawn("gpg", [...home, "--import"], {
109
+ input: input.publicKey,
110
+ encoding: "utf-8"
111
+ });
112
+ if (imported.error || imported.status !== 0) return false;
113
+ const checked = input.spawn("gpg", [
114
+ ...home,
115
+ "--verify",
116
+ input.signaturePath,
117
+ input.checksumPath
118
+ ], { encoding: "utf-8" });
119
+ return !checked.error && checked.status === 0;
120
+ }
121
+ // src/upload/download-cli.ts
122
+ /** Where Codecov publishes its CLI (the Linux build), its checksum file and the signature of that file. */
123
+ const CODECOV_CLI_BASE = "https://cli.codecov.io/latest/linux";
124
+ /** Where the key that signs the checksum file is published. */
125
+ const CODECOV_SIGNING_KEY_URL = "https://keybase.io/codecovsecops/pgp_keys.asc";
126
+ async function getBytes(deps, sleep, url) {
127
+ return retryWithWait({
128
+ attempts: 3,
129
+ waitMs: (n) => n * 1e3,
130
+ sleep,
131
+ attempt: async () => {
132
+ const res = await deps.fetch(url);
133
+ if (!res.ok) throw new Error(`${url} answered ${res.status}`);
134
+ return new Uint8Array(await res.arrayBuffer());
135
+ }
136
+ });
137
+ }
138
+ /**
139
+ * Downloads the Codecov CLI, its checksum file, the signature and the signing key into `dir`, checks the signature of the
140
+ * checksum file with `gpg` and the binary's digest against it, and makes the binary executable. Returns its path.
141
+ * Throws, naming what failed, when anything does not check out: nothing unverified is ever made executable.
142
+ */
143
+ async function downloadCli(input) {
144
+ const { dir, deps, sleep } = input;
145
+ const decoder = new TextDecoder();
146
+ const binary = await getBytes(deps, sleep, `${CODECOV_CLI_BASE}/codecov`);
147
+ const sums = await getBytes(deps, sleep, `${CODECOV_CLI_BASE}/codecov.SHA256SUM`);
148
+ const signature = await getBytes(deps, sleep, `${CODECOV_CLI_BASE}/codecov.SHA256SUM.sig`);
149
+ const key = decoder.decode(await getBytes(deps, sleep, CODECOV_SIGNING_KEY_URL));
150
+ const binaryPath = join(dir, "codecov");
151
+ const sumsPath = join(dir, "codecov.SHA256SUM");
152
+ const signaturePath = join(dir, "codecov.SHA256SUM.sig");
153
+ const gnupgHome = join(dir, "gnupg");
154
+ deps.makeDir(dir);
155
+ deps.makeDir(gnupgHome, 448);
156
+ deps.writeFile(binaryPath, binary);
157
+ deps.writeFile(sumsPath, sums);
158
+ deps.writeFile(signaturePath, signature);
159
+ if (!verifySignature({
160
+ publicKey: key,
161
+ checksumPath: sumsPath,
162
+ signaturePath,
163
+ gnupgHome,
164
+ spawn: deps.spawn
165
+ })) throw new Error("the Codecov CLI's checksum file is not signed by Codecov's key (gpg did not accept it)");
166
+ const expected = parseChecksum(decoder.decode(sums), "codecov");
167
+ if (expected === void 0) throw new Error("the Codecov CLI's checksum file has no digest for `codecov`");
168
+ if (!sha256Matches(binary, expected)) throw new Error("the Codecov CLI's digest does not match its checksum file");
169
+ deps.makeExecutable(binaryPath);
170
+ return binaryPath;
171
+ }
172
+ // src/upload/expand-glob.ts
173
+ /** A path segment pattern as a regular expression: `*` is any run of characters and `?` one, neither crossing a `/`. */
174
+ function segmentPattern(segment) {
175
+ const source = [...segment].map((char) => char === "*" ? "[^/]*" : char === "?" ? "[^/]" : char.replace(/[.+^${}()|[\]\\]/g, "\\$&")).join("");
176
+ return new RegExp(`^${source}$`);
177
+ }
178
+ /** The names in a folder, sorted; a folder that cannot be read has none. */
179
+ function names(dir) {
180
+ try {
181
+ return readdirSync(dir).sort();
182
+ } catch {
183
+ return [];
184
+ }
185
+ }
186
+ /** Matches `segments` below `base` (a path relative to `cwd`, `""` for `cwd` itself), pushing each full match. */
187
+ function walk(cwd, base, segments, found) {
188
+ const [segment, ...rest] = segments;
189
+ if (segment === void 0) {
190
+ found.push(base);
191
+ return;
192
+ }
193
+ const at = (name) => base === "" ? name : `${base}/${name}`;
194
+ if (segment === "**") {
195
+ walk(cwd, base, rest, found);
196
+ for (const name of names(join(cwd, base))) if (!name.startsWith(".") && names(join(cwd, at(name))).length > 0) walk(cwd, at(name), segments, found);
197
+ return;
198
+ }
199
+ if (!/[*?]/.test(segment)) {
200
+ if (names(join(cwd, base)).includes(segment)) walk(cwd, at(segment), rest, found);
201
+ return;
202
+ }
203
+ const pattern = segmentPattern(segment);
204
+ for (const name of names(join(cwd, base))) if (pattern.test(name) && (!name.startsWith(".") || segment.startsWith("."))) walk(cwd, at(name), rest, found);
205
+ }
206
+ /**
207
+ * Expands a glob pattern relative to `cwd` into the matching paths (relative to `cwd`), sorted and without duplicates;
208
+ * no match is an empty list. `*` and `?` stay inside one path segment, a `**` segment crosses folders (a shell's
209
+ * `compgen -G` reads it as `*`, so this is the larger set), and a wildcard skips names that start with a dot. Braces and
210
+ * character classes are not patterns.
211
+ */
212
+ function expandGlob(pattern, cwd) {
213
+ const found = [];
214
+ walk(cwd, "", pattern.split("/").filter((segment) => segment !== "" && segment !== "."), found);
215
+ return [...new Set(found)].filter((path) => path !== "").sort();
216
+ }
217
+ // src/upload/shell.ts
218
+ /**
219
+ * Thin wrapper around `spawnSync` for the Codecov CLI.
220
+ *
221
+ * The CLI-transport path of the plugin, like the 1Password plugin's `op` wrapper: a uniform result so the callers do not
222
+ * repeat the exit-code and decoding code. The upload token goes to the CLI in `CODECOV_TOKEN`, never in argv (a child's
223
+ * argv shows in `ps`), and is removed from anything the CLI prints before the caller sees it.
224
+ */
225
+ /** The flags every Codecov CLI command is given: fail loudly, and take the commit from GitHub. */
226
+ const COMMON = [
227
+ "--fail-on-error",
228
+ "--git-service",
229
+ "github"
230
+ ];
231
+ /** Runs the Codecov CLI's `create-commit`, `create-report` and `do-upload`. */
232
+ var CodecovCli = class {
233
+ binary;
234
+ spawnImpl;
235
+ env;
236
+ constructor(opts) {
237
+ this.binary = opts.binary;
238
+ this.spawnImpl = opts.spawn ?? spawnSync;
239
+ this.env = opts.env;
240
+ }
241
+ /** Tells Codecov about the commit. */
242
+ createCommit(token) {
243
+ return this.run(token, ["create-commit", ...COMMON]);
244
+ }
245
+ /** Opens the report the per-flag uploads attach to. */
246
+ createReport(token) {
247
+ return this.run(token, ["create-report", ...COMMON]);
248
+ }
249
+ /** Uploads `files` under `flag`, searching for nothing else. */
250
+ doUpload(token, flag, files) {
251
+ return this.run(token, [
252
+ "do-upload",
253
+ "--flag",
254
+ flag,
255
+ "--disable-search",
256
+ ...COMMON,
257
+ ...files.flatMap((file) => ["--file", file])
258
+ ]);
259
+ }
260
+ run(token, args) {
261
+ const out = this.spawnImpl(this.binary, args, {
262
+ encoding: "utf-8",
263
+ stdio: [
264
+ "inherit",
265
+ "pipe",
266
+ "pipe"
267
+ ],
268
+ env: {
269
+ ...this.env,
270
+ CODECOV_TOKEN: token
271
+ }
272
+ });
273
+ const clean = (text) => text.split(token).join("***").trim();
274
+ if (out.error) return {
275
+ ok: false,
276
+ stdout: "",
277
+ stderr: clean(out.error.message)
278
+ };
279
+ return {
280
+ ok: out.status === 0,
281
+ stdout: clean(out.stdout ?? ""),
282
+ stderr: clean(out.stderr ?? "")
283
+ };
284
+ }
285
+ };
286
+ // src/upload/default-deps.ts
287
+ /**
288
+ * The real dependencies of {@link uploadCoverage}: the Actions environment, the global `fetch`, the file system, a
289
+ * `::add-mask::` command for the log, and a Codecov CLI downloaded, checked and made executable in a scratch folder on
290
+ * first use.
291
+ */
292
+ function defaultUploadDeps(options = {}) {
293
+ const environment = options.env ?? process.env;
294
+ const lookup = createEnvLookup(options.env);
295
+ const doFetch = options.fetch ?? fetch;
296
+ const spawn = options.spawn ?? spawnSync;
297
+ const tmp = options.tmp ?? tmpdir();
298
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
299
+ const log = options.write ?? ((line) => process.stdout.write(`${line}\n`));
300
+ return {
301
+ env: (name) => lookup.get(name),
302
+ fetch: doFetch,
303
+ prepareCli: async () => {
304
+ return new CodecovCli({
305
+ binary: await downloadCli({
306
+ dir: mkdtempSync(join(tmp, "codecov-cli-")),
307
+ sleep,
308
+ deps: {
309
+ fetch: doFetch,
310
+ spawn,
311
+ writeFile: (path, data) => writeFileSync(path, data),
312
+ makeExecutable: (path) => chmodSync(path, 493),
313
+ makeDir: (path, mode) => mkdirSync(path, {
314
+ recursive: true,
315
+ ...mode === void 0 ? {} : { mode }
316
+ })
317
+ }
318
+ }),
319
+ spawn,
320
+ env: environment
321
+ });
322
+ },
323
+ expandGlob,
324
+ readFile: (path) => readFileSync(path, "utf-8"),
325
+ writeFile: (path, data) => writeFileSync(path, data),
326
+ makeTempDir: () => mkdtempSync(join(tmp, "codecov-reports-")),
327
+ sleep,
328
+ log,
329
+ mask: (value) => log(`::add-mask::${value}`)
330
+ };
331
+ }
332
+ // src/upload/fetch-oidc-token.ts
333
+ /** The audience Codecov takes an OIDC token for. */
334
+ const CODECOV_OIDC_AUDIENCE = "https://codecov.io";
335
+ /**
336
+ * Asks the Actions runtime for a job OIDC token for Codecov. The token lives about five minutes, so a caller fetches a
337
+ * new one before every upload and masks it in the log before anything else sees it. Throws, without the token or the
338
+ * bearer, when the request fails or answers no value.
339
+ */
340
+ async function fetchOidcToken(input) {
341
+ const url = `${input.requestUrl}${input.requestUrl.includes("?") ? "&" : "?"}audience=${CODECOV_OIDC_AUDIENCE}`;
342
+ const res = await input.fetch(url, { headers: { authorization: `bearer ${input.requestToken}` } });
343
+ if (!res.ok) throw new Error(`could not get an OIDC token: the Actions runtime answered ${res.status}`);
344
+ const value = (await res.json().catch(() => void 0))?.value;
345
+ if (typeof value !== "string" || value === "") throw new Error("could not get an OIDC token: the answer had no value");
346
+ return value;
347
+ }
348
+ // src/upload/names-source-file.ts
349
+ /** Whether an lcov report names at least one source file (a line starting `SF:`); one that names none is rejected as empty. */
350
+ function namesSourceFile(content) {
351
+ return content.split("\n").some((line) => line.startsWith("SF:"));
352
+ }
353
+ // src/upload/root-report.ts
354
+ /**
355
+ * The folder a report's source paths start from, relative to the repo root: the report's folder less a trailing
356
+ * `coverage`, or `""` for a report at the repo root (in `.`, or in a `coverage` folder there).
357
+ */
358
+ function reportPackageDir(reportPath) {
359
+ let dir = posix.dirname(reportPath);
360
+ if (dir.endsWith("/coverage")) dir = dir.slice(0, -9);
361
+ return dir === "." || dir === "coverage" ? "" : dir;
362
+ }
363
+ /**
364
+ * A copy of an lcov report whose paths start at the repo root, so Codecov can place them. A package's report names its
365
+ * files from the package (`SF:src/index.ts`), and `src/index.ts` exists in dozens of packages; the copy names
366
+ * `SF:clients/doppler-client/src/index.ts`. Only relative `SF:` lines change (an absolute path is left alone), and a
367
+ * report at the repo root is returned as it is.
368
+ */
369
+ function rootReport(content, reportPath) {
370
+ const dir = reportPackageDir(reportPath);
371
+ if (dir === "") return content;
372
+ const lines = content.split("\n");
373
+ if (lines[lines.length - 1] === "") lines.pop();
374
+ return lines.map((line) => line.startsWith("SF:") && line[3] !== "/" ? `SF:${dir}/${line.slice(3)}` : line).join("\n") + (lines.length > 0 ? "\n" : "");
375
+ }
376
+ // src/upload/upload-coverage.ts
377
+ /** How many times a flag's upload is tried, and the wait after try `n` (15 s times `n`). */
378
+ const ATTEMPTS = 4;
379
+ const waitMs = (n) => n * 15e3;
380
+ /** A flag as part of a file name: anything outside letters, digits, `.`, `_` and `-` becomes `_`. */
381
+ const fileSafe = (flag) => flag.replace(/[^\w.-]/g, "_");
382
+ /**
383
+ * Uploads each group's reports to Codecov under the group's flag, authenticated with the job's OIDC token.
384
+ *
385
+ * The same steps the shell action took: a token before the commit is announced (`create-commit`) and the report opened
386
+ * (`create-report`), then, per group, the reports its globs match, each with a report that names no source file left out
387
+ * and the rest uploaded as copies whose `SF:` paths start at the repo root, in one `do-upload` that is retried (a fresh
388
+ * token before every try, 15 s times the attempt between them). A group with nothing to upload is skipped with a note; a
389
+ * group that fails every try ends the run. Throws (never printing a token) for what stops the run before a group: no
390
+ * OIDC token to ask for, malformed input, a Codecov CLI that cannot be trusted, a failed `create-commit` or
391
+ * `create-report`.
392
+ */
393
+ async function uploadCoverage(input, deps) {
394
+ const requestUrl = deps.env("ACTIONS_ID_TOKEN_REQUEST_URL");
395
+ const requestToken = deps.env("ACTIONS_ID_TOKEN_REQUEST_TOKEN");
396
+ if (!requestUrl || !requestToken) throw new Error("No OIDC token available: give the job `permissions: id-token: write`.");
397
+ for (const group of input.uploads) if (!group.flag || group.files.length === 0 || group.files.some((pattern) => !pattern)) throw new Error("Every upload needs a flag and at least one files pattern.");
398
+ const freshToken = async () => {
399
+ const token = await fetchOidcToken({
400
+ requestUrl,
401
+ requestToken,
402
+ fetch: deps.fetch
403
+ });
404
+ deps.mask(token);
405
+ return token;
406
+ };
407
+ const cli = await deps.prepareCli();
408
+ const token = await freshToken();
409
+ const commit = cli.createCommit(token);
410
+ if (!commit.ok) throw new Error(`create-commit failed: ${commit.stderr || "no output"}`);
411
+ const report = cli.createReport(token);
412
+ if (!report.ok) throw new Error(`create-report failed: ${report.stderr || "no output"}`);
413
+ const scratch = deps.makeTempDir();
414
+ const flags = [];
415
+ let uploaded = 0;
416
+ let problem;
417
+ for (const group of input.uploads) {
418
+ const notes = [];
419
+ const matched = [...new Set(group.files.flatMap((pattern) => deps.expandGlob(pattern, input.repoRoot)))];
420
+ const copies = [];
421
+ for (const file of matched) {
422
+ const content = deps.readFile(join(input.repoRoot, file));
423
+ if (!namesSourceFile(content)) {
424
+ notes.push(`${file} names no source file, left out`);
425
+ continue;
426
+ }
427
+ const copy = join(scratch, `${fileSafe(group.flag)}.${copies.length + 1}.info`);
428
+ deps.writeFile(copy, rootReport(content, file));
429
+ copies.push(copy);
430
+ }
431
+ if (copies.length === 0) {
432
+ notes.push("no coverage files");
433
+ deps.log(`· ${group.flag}: no coverage files`);
434
+ flags.push({
435
+ flag: group.flag,
436
+ outcome: "skipped",
437
+ files: 0,
438
+ notes
439
+ });
440
+ continue;
441
+ }
442
+ deps.log(`→ ${group.flag}: ${copies.length} file(s)`);
443
+ try {
444
+ await retryWithWait({
445
+ attempts: ATTEMPTS,
446
+ waitMs,
447
+ sleep: deps.sleep,
448
+ onRetry: (n, _error, wait) => deps.log(`${group.flag} upload failed (attempt ${n} of ${ATTEMPTS}); trying again in ${wait / 1e3}s.`),
449
+ attempt: async () => {
450
+ const result = cli.doUpload(await freshToken(), group.flag, copies);
451
+ if (!result.ok) throw new Error(result.stderr || "the Codecov CLI exited non-zero");
452
+ }
453
+ });
454
+ } catch (error) {
455
+ const reason = error instanceof Error ? error.message : String(error);
456
+ problem = `Codecov rejected the ${group.flag} upload ${ATTEMPTS} times: ${reason}`;
457
+ notes.push(problem);
458
+ flags.push({
459
+ flag: group.flag,
460
+ outcome: "failed",
461
+ files: 0,
462
+ notes
463
+ });
464
+ break;
465
+ }
466
+ uploaded += 1;
467
+ flags.push({
468
+ flag: group.flag,
469
+ outcome: "uploaded",
470
+ files: copies.length,
471
+ notes
472
+ });
473
+ }
474
+ if (problem === void 0 && uploaded === 0 && !input.allowEmpty) problem = "No group has a coverage file, so nothing was uploaded.";
475
+ return {
476
+ flags,
477
+ uploaded,
478
+ ...problem === void 0 ? {} : { problem }
479
+ };
480
+ }
481
+ // src/config-file/template.ts
482
+ /**
483
+ * The base `codecov.yml` a new file starts from, before the flags, the components and the status rules are added.
484
+ * Moved from astromech's `templates/codecov/codecov.yml` (#2238, step 3).
485
+ */
486
+ const CODECOV_TEMPLATE = [
487
+ "codecov:",
488
+ " require_ci_to_pass: true",
489
+ "",
490
+ "coverage:",
491
+ " precision: 2",
492
+ " round: down",
493
+ " status:",
494
+ " project:",
495
+ " default:",
496
+ " target: auto",
497
+ " threshold: 2%",
498
+ " # Infra-only PRs (dep bumps, config, lockfile) touch no coverable code,",
499
+ " # so codecov produces no report to compare. Pass instead of blocking",
500
+ " # forever on a required check that will never post.",
501
+ " if_not_found: success",
502
+ " patch:",
503
+ " default:",
504
+ " target: 80%",
505
+ " if_not_found: success",
506
+ "",
507
+ "comment:",
508
+ " layout: \"reach,diff,flags\"",
509
+ " behavior: default",
510
+ " require_changes: true",
511
+ "",
512
+ "component_management:",
513
+ " default_rules:",
514
+ " statuses:",
515
+ " - type: patch",
516
+ " target: 80%",
517
+ " if_not_found: success",
518
+ " informational: true",
519
+ " individual_components:"
520
+ ].join("\n");
521
+ // src/capabilities/status-contexts.ts
522
+ /** The flag whose statuses are the doc-comment gate (`repoValidation.docsCoverage`); the name `codecov.yml` gives it. */
523
+ const DOCUMENTATION_FLAG = "documentation";
524
+ /**
525
+ * The commit statuses Codecov posts for a repository, by name, sorted. `codecov/project` and `codecov/patch` count the
526
+ * tests and are required. Each component posts an informational `codecov/patch/<component>`. With the documentation
527
+ * flag on (`warn` or `required`), `codecov/patch/documentation` and `codecov/project/documentation` exist, and only the
528
+ * patch one gates, and only when the mode is `required`. Pure: no read of the config or of Codecov.
529
+ */
530
+ function statusContexts(input) {
531
+ const contexts = [
532
+ {
533
+ name: "codecov/patch",
534
+ required: true
535
+ },
536
+ {
537
+ name: "codecov/project",
538
+ required: true
539
+ },
540
+ ...[...new Set(input.components)].map((component) => ({
541
+ name: `codecov/patch/${component}`,
542
+ required: false
543
+ }))
544
+ ];
545
+ if (input.documentation !== "off") contexts.push({
546
+ name: `codecov/patch/${DOCUMENTATION_FLAG}`,
547
+ required: input.documentation === "required"
548
+ }, {
549
+ name: `codecov/project/${DOCUMENTATION_FLAG}`,
550
+ required: false
551
+ });
552
+ return [...new Map(contexts.map((context) => [context.name, context])).values()].sort((a, b) => a.name < b.name ? -1 : 1);
553
+ }
554
+ // src/config-file/yaml-rules.ts
555
+ const INDIVIDUAL_COMPONENTS_MARKER = " individual_components:";
556
+ /**
557
+ * Ensure every codecov status default carries `if_not_found: success`, so an
558
+ * infra-only PR (dep bump, config, lockfile — no coverable change) passes
559
+ * instead of hanging forever on a required check codecov never posts.
560
+ *
561
+ * Injects the key on the line after each `target:` that sits inside a status
562
+ * block (`coverage.status.*.default` or a `statuses:` list item — indent ≥ 8,
563
+ * or ≥ 8 for a `- type:` list entry), when the immediate sibling lines do not
564
+ * already declare it.
565
+ */
566
+ function ensureIfNotFound(yaml) {
567
+ const lines = yaml.split("\n");
568
+ const out = [];
569
+ for (let i = 0; i < lines.length; i++) {
570
+ const line = lines[i];
571
+ out.push(line);
572
+ const m = /^(\s{8,})target:\s+\S+\s*$/.exec(line);
573
+ if (!m) continue;
574
+ const indent = m[1];
575
+ let alreadySet = false;
576
+ for (let j = i + 1; j < lines.length; j++) {
577
+ const sib = lines[j];
578
+ if (sib.trim() === "") continue;
579
+ const sibIndent = sib.match(/^\s*/)[0].length;
580
+ if (sibIndent < indent.length) break;
581
+ if (sibIndent === indent.length && /^\s*if_not_found\s*:/.test(sib)) {
582
+ alreadySet = true;
583
+ break;
584
+ }
585
+ if (sibIndent === indent.length && /^\s*(- |\w)/.test(sib) && !/^\s*(threshold|flags|paths|branches)\s*:/.test(sib)) break;
586
+ }
587
+ if (!alreadySet) out.push(`${indent}if_not_found: success`);
588
+ }
589
+ return out.join("\n");
590
+ }
591
+ /** `[start, end)` of a top-level key's section; trailing blank lines are not part of it. `null` when absent. */
592
+ function section(lines, key) {
593
+ const start = lines.indexOf(`${key}:`);
594
+ if (start === -1) return null;
595
+ let end = lines.findIndex((line, i) => i > start && /^[A-Za-z_]/.test(line));
596
+ if (end === -1) end = lines.length;
597
+ while (lines[end - 1].trim() === "") end--;
598
+ return [start, end];
599
+ }
600
+ /** Insert the entries of `wanted` that no existing list item names, after the list's last line (`listEnd`). */
601
+ function appendMissingItems(lines, listStart, listEnd, wanted, itemName, render) {
602
+ const have = new Set(lines.slice(listStart + 1, listEnd).map((line) => itemName.exec(line)?.[1]));
603
+ lines.splice(listEnd, 0, ...wanted.filter((name) => !have.has(name)).map(render));
604
+ }
605
+ const FLAG_ENTRY = /^ {4}- name:\s*(\S+)/;
606
+ const flagEntry = (name) => ` - name: ${name}`;
607
+ /**
608
+ * Ensure a top-level `flag_management:` section carries `default_rules.carryforward`
609
+ * and one `individual_flags` entry per flag. A missing section is inserted before
610
+ * `component_management:`; an existing one only gains the entries it lacks, so hand
611
+ * edits (extra flags, per-flag `paths`/`statuses`, a different `carryforward`) survive.
612
+ */
613
+ function ensureFlagManagement(yaml, flags) {
614
+ const lines = yaml.split("\n");
615
+ const listHead = flags.length === 0 ? " individual_flags: []" : " individual_flags:";
616
+ const range = section(lines, "flag_management");
617
+ if (!range) {
618
+ const block = [
619
+ "flag_management:",
620
+ " default_rules:",
621
+ " carryforward: true",
622
+ listHead,
623
+ ...flags.map(flagEntry)
624
+ ];
625
+ const at = lines.indexOf("component_management:");
626
+ if (at === -1) lines.push("", ...block);
627
+ else lines.splice(at, 0, ...block, "");
628
+ return lines.join("\n");
629
+ }
630
+ const [start, end] = range;
631
+ const list = lines.findIndex((line, i) => i > start && i < end && /^ {2}individual_flags:/.test(line));
632
+ if (list === -1) lines.splice(end, 0, listHead, ...flags.map(flagEntry));
633
+ else if (/\[\s*\]\s*$/.test(lines[list])) {
634
+ if (flags.length > 0) lines.splice(list, 1, listHead, ...flags.map(flagEntry));
635
+ } else appendMissingItems(lines, list, end, flags, FLAG_ENTRY, flagEntry);
636
+ return lines.join("\n");
637
+ }
638
+ /**
639
+ * Scope `coverage.status.project.default` and `coverage.status.patch.default` to
640
+ * the flags, so the required `codecov/project` and `codecov/patch` contexts keep
641
+ * their names while only counting the grouped (non-`docs`) coverage. A block that
642
+ * already lists flags only gains the missing ones; an inline `flags: [...]` is left alone.
643
+ */
644
+ function scopeAggregateStatuses(yaml, flags) {
645
+ if (flags.length === 0) return yaml;
646
+ const lines = yaml.split("\n");
647
+ for (const kind of ["project", "patch"]) {
648
+ const at = lines.indexOf(` ${kind}:`);
649
+ if (at === -1 || lines[at + 1] !== " default:") continue;
650
+ let end = at + 2;
651
+ while (end < lines.length && /^ {8}/.test(lines[end])) end++;
652
+ const flagsAt = lines.findIndex((line, i) => i >= at + 2 && i < end && /^ {8}flags:/.test(line));
653
+ if (flagsAt === -1) lines.splice(at + 2, 0, " flags:", ...flags.map((name) => ` - ${name}`));
654
+ else if (!/^ {8}flags:\s*\S/.test(lines[flagsAt])) {
655
+ let listEnd = flagsAt + 1;
656
+ while (listEnd < end && /^ {10}- /.test(lines[listEnd])) listEnd++;
657
+ appendMissingItems(lines, flagsAt, listEnd, flags, /^ {10}- (\S+)/, (name) => ` - ${name}`);
658
+ }
659
+ }
660
+ return lines.join("\n");
661
+ }
662
+ /**
663
+ * Make the per-component statuses (`component_management.default_rules.statuses`)
664
+ * informational, so the ~70 `codecov/patch/<component>` contexts post but never block.
665
+ */
666
+ function ensureInformationalComponentStatuses(yaml) {
667
+ const lines = yaml.split("\n");
668
+ const range = section(lines, "component_management");
669
+ if (!range) return yaml;
670
+ const stop = lines.indexOf(INDIVIDUAL_COMPONENTS_MARKER);
671
+ const limit = stop === -1 ? range[1] : stop;
672
+ const starts = lines.flatMap((line, i) => i > range[0] && i < limit && /^ {6}- type:/.test(line) ? [i] : []);
673
+ for (const first of starts.reverse()) {
674
+ let last = first + 1;
675
+ while (last < limit && /^ {8}\S/.test(lines[last])) last++;
676
+ if (!lines.slice(first, last).some((line) => /^ {8}informational:/.test(line))) lines.splice(last, 0, " informational: true");
677
+ }
678
+ return lines.join("\n");
679
+ }
680
+ /** Documentation Codecov would otherwise count as testable code, though nothing reports coverage for it. */
681
+ const IGNORED_DOCS = ["**/*.mdx"];
682
+ const ignoreEntry = (glob) => ` - "${glob}"`;
683
+ /**
684
+ * Ensure a top-level `ignore:` list names the documentation files in {@link IGNORED_DOCS}. Without it a docs-only
685
+ * PR that adds `.mdx` pages is judged to change testable files, posts no coverage and fails `codecov/patch` and
686
+ * `codecov/project` ("Empty Upload", #1442). A missing list is inserted before `coverage:`; an existing one only
687
+ * gains the entries it lacks, so hand-added globs survive.
688
+ */
689
+ function ensureIgnore(yaml) {
690
+ const lines = yaml.split("\n");
691
+ const range = section(lines, "ignore");
692
+ if (!range) {
693
+ const block = [
694
+ "ignore:",
695
+ ...IGNORED_DOCS.map(ignoreEntry),
696
+ ""
697
+ ];
698
+ const at = lines.indexOf("coverage:");
699
+ if (at === -1) {
700
+ while (lines.at(-1) === "") lines.pop();
701
+ lines.push("", ...block.slice(0, -1));
702
+ } else lines.splice(at, 0, ...block);
703
+ return lines.join("\n");
704
+ }
705
+ appendMissingItems(lines, range[0], range[1], IGNORED_DOCS, /^ {2}- ["']?([^"'\s]+)/, ignoreEntry);
706
+ return lines.join("\n");
707
+ }
708
+ /** What each aggregate asks of the `documentation` flag: the patch must be fully documented, the project must not drop. */
709
+ const DOCUMENTATION_TARGETS = {
710
+ project: "auto",
711
+ patch: "100%"
712
+ };
713
+ function documentationStatus(kind, mode) {
714
+ return [
715
+ ` ${DOCUMENTATION_FLAG}:`,
716
+ " flags:",
717
+ ` - ${DOCUMENTATION_FLAG}`,
718
+ ` target: ${DOCUMENTATION_TARGETS[kind]}`,
719
+ " if_not_found: success",
720
+ ...mode === "warn" ? [" informational: true"] : []
721
+ ];
722
+ }
723
+ /**
724
+ * Ensure `codecov.yml` carries the `documentation` flag and a named `documentation` status under
725
+ * `coverage.status.project` and `coverage.status.patch` (spec `tech-api-docs`). They are named statuses scoped to that
726
+ * flag, so the required `codecov/project` and `codecov/patch` keep counting only the tests. `warn` makes them
727
+ * informational and `required` does not; an existing status only has that line brought in line, so hand edits survive.
728
+ * `off` adds nothing and leaves what is there alone: setup never deletes.
729
+ */
730
+ function ensureDocumentationCoverage(yaml, mode) {
731
+ if (mode === "off") return yaml;
732
+ const lines = ensureFlagManagement(yaml, [DOCUMENTATION_FLAG]).split("\n");
733
+ for (const kind of ["project", "patch"]) {
734
+ const at = lines.indexOf(` ${kind}:`);
735
+ if (at === -1) continue;
736
+ let end = at + 1;
737
+ while (end < lines.length && (lines[end].trim() === "" || /^ {5}/.test(lines[end]))) end++;
738
+ while (lines[end - 1].trim() === "") end--;
739
+ const own = lines.findIndex((line, i) => i > at && i < end && line === ` documentation:`);
740
+ if (own === -1) {
741
+ lines.splice(end, 0, ...documentationStatus(kind, mode));
742
+ continue;
743
+ }
744
+ let ownEnd = own + 1;
745
+ while (ownEnd < end && /^ {8}/.test(lines[ownEnd])) ownEnd++;
746
+ const keep = lines.slice(own, ownEnd).filter((line) => !/^ {8}informational:/.test(line));
747
+ lines.splice(own, ownEnd - own, ...keep, ...mode === "warn" ? [" informational: true"] : []);
748
+ }
749
+ return lines.join("\n");
750
+ }
751
+ /** Everything `codecov.yml` needs on top of the components list: if_not_found, ignored docs, flags, scoped aggregates, informational components, and the documentation flag when the repo asks for it. */
752
+ function applyStatusRules(yaml, flags, docsCoverage) {
753
+ return ensureDocumentationCoverage(ensureInformationalComponentStatuses(scopeAggregateStatuses(ensureFlagManagement(ensureIgnore(ensureIfNotFound(yaml)), flags), flags)), docsCoverage);
754
+ }
755
+ // src/config-file/codecov-config.ts
756
+ function scaffoldHeader() {
757
+ return [
758
+ `# Scaffolded by holocron setup — edit this file freely.`,
759
+ `# Source: theholocron/holocron · plugins/holocron-plugin-codecov/src/config-file/codecov-config.ts`,
760
+ ``
761
+ ].join("\n");
762
+ }
763
+ /** The YAML list of components, one per package and grouped by workspace root, that `codecov.yml` carries. */
764
+ function codecovComponentBlock(components) {
765
+ if (components.length === 0) return "\n []\n";
766
+ let group;
767
+ return "\n" + components.flatMap(({ id, path }) => {
768
+ const root = path.split("/")[0];
769
+ const heading = root === group ? [] : [` # ${root}`];
770
+ group = root;
771
+ return [
772
+ ...heading,
773
+ ` - component_id: ${id}`,
774
+ ` name: "${id}"`,
775
+ ` paths:`,
776
+ ` - ${path}/**`,
777
+ ``
778
+ ];
779
+ }).join("\n");
780
+ }
781
+ /**
782
+ * Brings an existing `codecov.yml` up to date with the components, the flags and the repo's options, keeping every hand
783
+ * edit. A file with no `individual_components` list keeps its components as they are.
784
+ */
785
+ function mergeCodecovComponents(existing, components, options) {
786
+ const idx = existing.indexOf(INDIVIDUAL_COMPONENTS_MARKER);
787
+ if (idx === -1) return applyStatusRules(existing, options.flags, options.documentation);
788
+ return applyStatusRules(existing.slice(0, idx + 24), options.flags, options.documentation) + codecovComponentBlock(components);
789
+ }
790
+ /** A brand-new `codecov.yml`: the scaffold header, the base template and this repo's component list. */
791
+ function createCodecovConfig(components, options) {
792
+ const base = applyStatusRules(CODECOV_TEMPLATE, options.flags, options.documentation);
793
+ return `${scaffoldHeader()}${base}${codecovComponentBlock(components)}`;
794
+ }
795
+ // src/capabilities/config-files.ts
796
+ /** The one file Codecov reads its flags, components and statuses from, relative to the repository root. */
797
+ const CODECOV_CONFIG_FILE = "codecov.yml";
798
+ /**
799
+ * The config files Codecov needs, as text by path. `codecov.yml` is merged into the copy already in the repo (every
800
+ * hand edit kept) or, with none, scaffolded. Pure: the existing text comes in through `input.existing`, nothing is read
801
+ * or written here.
802
+ */
803
+ function configFiles(input) {
804
+ const options = {
805
+ flags: input.flags,
806
+ documentation: input.documentation
807
+ };
808
+ const existing = input.existing(CODECOV_CONFIG_FILE);
809
+ return { [CODECOV_CONFIG_FILE]: existing === null ? createCodecovConfig(input.components, options) : mergeCodecovComponents(existing, input.components, options) };
810
+ }
811
+ // src/capabilities/diff-names.ts
812
+ /** Compares the names a config declares with the names a service has: which are missing there and which are extra. Both sorted. */
813
+ function diffNames(expected, actual) {
814
+ const want = [...new Set(expected)].sort();
815
+ const have = new Set(actual);
816
+ const wanted = new Set(want);
817
+ return {
818
+ expected: want,
819
+ missing: want.filter((name) => !have.has(name)),
820
+ extra: [...have].filter((name) => !wanted.has(name)).sort()
821
+ };
822
+ }
41
823
  // src/capabilities/coverage.ts
824
+ const NO_API_TOKEN = "set HOLOCRON_CODECOV_API_TOKEN to a Codecov personal API token to compare flags and components (the upload token HOLOCRON_CODECOV_UPLOAD_TOKEN is not accepted by Codecov's REST API)";
42
825
  /** The `coverage` capability for Codecov. */
43
826
  var CodecovCoverage = class {
44
827
  client;
45
828
  target;
829
+ apiClient;
830
+ uploadDeps;
46
831
  /** The capability key, always `coverage`. */
47
832
  key = "coverage";
48
833
  /** The provider name, `codecov`. */
49
834
  providerName = "codecov";
50
835
  /**
51
836
  * `client` is a thunk, so the token is resolved on first use and a plugin load never needs one. `target` is `undefined`
52
- * when the options name no repository.
837
+ * when the options name no repository. `apiClient` builds the client from the API token for `checkRepo()` and throws an
838
+ * `AuthError` when there is none; left out, `checkRepo()` reports that it has no token.
53
839
  */
54
- constructor(client, target) {
840
+ constructor(client, target, apiClient, uploadDeps = defaultUploadDeps) {
55
841
  this.client = client;
56
842
  this.target = target;
843
+ this.apiClient = apiClient;
844
+ this.uploadDeps = uploadDeps;
845
+ }
846
+ async checkRepo(expected) {
847
+ if (!this.target) throw new Error("@theholocron/holocron-plugin-codecov needs a repository (the plugin options owner and repo, or the active repo) for checkRepo");
848
+ const unchecked = (reason) => ({
849
+ checked: false,
850
+ reason,
851
+ flags: diffNames(expected.flags, expected.flags),
852
+ components: diffNames(expected.components, expected.components)
853
+ });
854
+ let api;
855
+ try {
856
+ if (!this.apiClient) return unchecked(NO_API_TOKEN);
857
+ api = this.apiClient();
858
+ } catch (err) {
859
+ if (err instanceof AuthError$1) return unchecked(NO_API_TOKEN);
860
+ throw err;
861
+ }
862
+ const { service, owner, repo } = this.target;
863
+ try {
864
+ const [flags, components] = await Promise.all([api.flags.list(service, owner, repo), api.components.list(service, owner, repo)]);
865
+ return {
866
+ checked: true,
867
+ flags: diffNames(expected.flags, flags.map((flag) => flag.flag_name)),
868
+ components: diffNames(expected.components, components.map((component) => component.component_id))
869
+ };
870
+ } catch (err) {
871
+ if (err instanceof ProviderApiError) {
872
+ if (err.status === 401 || err.status === 403) return unchecked(`Codecov answered ${err.status} for ${describeTarget(this.target)}: HOLOCRON_CODECOV_API_TOKEN must be a personal API token that can see the repository`);
873
+ if (err.status === 404) return unchecked(`Codecov has no ${describeTarget(this.target)}, or the API token cannot see it (404)`);
874
+ }
875
+ throw new Error(`Codecov could not be asked about ${describeTarget(this.target)}: ${String(err)}`, { cause: err });
876
+ }
57
877
  }
58
878
  async checkToken() {
59
879
  if (!this.target) throw new Error("@theholocron/holocron-plugin-codecov needs a repository (the plugin options owner and repo, or the active repo) for checkToken");
@@ -78,6 +898,21 @@ var CodecovCoverage = class {
78
898
  throw new Error(`Codecov could not be asked about ${describeTarget(this.target)}: ${String(err)}`, { cause: err });
79
899
  }
80
900
  }
901
+ /**
902
+ * Uploads the reports, one flag per group, authenticated with the job's OIDC token (no stored token, so the plugin
903
+ * needs none for this). The Codecov CLI does the upload; see `uploadCoverage()`.
904
+ */
905
+ upload(input) {
906
+ return uploadCoverage(input, this.uploadDeps());
907
+ }
908
+ /** The commit statuses Codecov posts, by name: see `statusContexts()`. Offline, so it needs no token and no repository. */
909
+ statusContexts(input) {
910
+ return statusContexts(input);
911
+ }
912
+ /** The files Codecov reads its config from (`codecov.yml`): see `configFiles()`. Offline, so it needs no token and no repository. */
913
+ configFiles(input) {
914
+ return configFiles(input);
915
+ }
81
916
  };
82
917
  // src/probes/token/parse-token-args.ts
83
918
  /** Reads `--layer <word>` and `--token-name <VAR>` (either spelling) from the words after the probe name. */
@@ -96,6 +931,113 @@ function parseTokenArgs(args) {
96
931
  ...tokenName ? { tokenName } : {}
97
932
  };
98
933
  }
934
+ // src/probes/repo/repo.ts
935
+ /**
936
+ * The `repo` probe for Codecov: compares the flags and components `holocron sync` writes to `codecov.yml` with the ones
937
+ * Codecov has for the repository, through `coverage.checkRepo()`. One row per difference, `ok` per list that matches.
938
+ *
939
+ * - a **component** declared but missing on Codecov is a `fail`: `codecov.yml` has not reached the default branch, or
940
+ * Codecov has not read it;
941
+ * - a **flag** declared but missing is `info`: Codecov only knows a flag once an upload carried it, so a package with no
942
+ * tests yet has none;
943
+ * - anything on Codecov the config does not declare is `info`: a hand-made or retired name.
944
+ *
945
+ * Codecov's REST API takes a personal API token, not the upload token, so without `HOLOCRON_CODECOV_API_TOKEN` the probe
946
+ * reports `info` naming the variable and never fails. It only reads.
947
+ *
948
+ * It accepts `--environment <layer or name>` like the `token` probes: the CLI runs it once per Codecov token the
949
+ * Environment holds and passes `--token-name <VARIABLE>`. For `HOLOCRON_CODECOV_API_TOKEN` the probe checks with that
950
+ * token; for any other (the upload token) it says it does not check it. A bare `--token`, which is the upload token for
951
+ * this plugin, is never used here and the probe says so.
952
+ */
953
+ function repoProbe(ctx) {
954
+ return {
955
+ summary: "Compare the flags and components `holocron sync` writes to codecov.yml with the ones Codecov has for the repository. Needs HOLOCRON_CODECOV_API_TOKEN (a personal API token). Read-only.",
956
+ writes: false,
957
+ acceptsToken: true,
958
+ async run(probe) {
959
+ const { tokenName } = parseTokenArgs(probe.args ?? []);
960
+ if (tokenName !== void 0 && tokenName !== ctx.apiTokenName) {
961
+ probe.say({
962
+ status: "info",
963
+ label: tokenName,
964
+ detail: `not the API token (${ctx.apiTokenName}), so this probe does not check it`
965
+ });
966
+ return;
967
+ }
968
+ let apiToken;
969
+ if (tokenName !== void 0) {
970
+ apiToken = ctx.cliToken;
971
+ if (apiToken !== void 0) probe.secret(apiToken);
972
+ } else if (ctx.cliToken !== void 0) probe.say({
973
+ status: "info",
974
+ label: "--token",
975
+ detail: `a token given with --token is the upload token, which the REST API does not take, so it is not used; use --environment for ${ctx.apiTokenName}`
976
+ });
977
+ if (!ctx.repo) {
978
+ probe.say({
979
+ status: "info",
980
+ label: "repository",
981
+ detail: "none to ask Codecov about: set the plugin options owner and repo"
982
+ });
983
+ return;
984
+ }
985
+ let report;
986
+ try {
987
+ report = await ctx.coverage(apiToken).checkRepo?.(ctx.expected());
988
+ } catch (err) {
989
+ probe.say({
990
+ status: "fail",
991
+ label: "Codecov API",
992
+ detail: err instanceof Error ? err.message : String(err)
993
+ });
994
+ return;
995
+ }
996
+ if (!report) {
997
+ probe.say({
998
+ status: "info",
999
+ label: "Codecov API",
1000
+ detail: "the coverage provider has no repository check"
1001
+ });
1002
+ return;
1003
+ }
1004
+ if (!report.checked) {
1005
+ probe.say({
1006
+ status: "info",
1007
+ label: "Codecov API",
1008
+ detail: report.reason ?? "not checked"
1009
+ });
1010
+ return;
1011
+ }
1012
+ const lists = [{
1013
+ kind: "component",
1014
+ diff: report.components,
1015
+ missing: "fail"
1016
+ }, {
1017
+ kind: "flag",
1018
+ diff: report.flags,
1019
+ missing: "info"
1020
+ }];
1021
+ for (const { kind, diff, missing } of lists) {
1022
+ for (const name of diff.missing) probe.say({
1023
+ status: missing,
1024
+ label: `${kind} ${name}`,
1025
+ detail: kind === "flag" ? "declared in the config, not on Codecov (no upload has carried it yet)" : "declared in the config, not on Codecov (codecov.yml not on the default branch yet?)"
1026
+ });
1027
+ for (const name of diff.extra) probe.say({
1028
+ status: "info",
1029
+ label: `${kind} ${name}`,
1030
+ detail: "on Codecov, not declared in the config"
1031
+ });
1032
+ if (diff.missing.length === 0 && diff.extra.length === 0) probe.say({
1033
+ status: "ok",
1034
+ label: `${kind}s`,
1035
+ detail: `${diff.expected.length} declared, all on Codecov for ${ctx.repo}`
1036
+ });
1037
+ }
1038
+ }
1039
+ };
1040
+ }
99
1041
  // src/probes/token/token.ts
100
1042
  /**
101
1043
  * The `token` probe for Codecov. Codecov has no permission model, so the probe cannot judge permissions; it checks what
@@ -183,10 +1125,19 @@ function tokenProbe(ctx) {
183
1125
  };
184
1126
  }
185
1127
  // src/index.ts
186
- /** Creates the shared context for the given options; no token is resolved until `client()` is first called. */
1128
+ /** Creates the shared context for the given options; no token is resolved until `client()` or `apiClient()` is first called. */
187
1129
  function createContext(options = {}) {
188
1130
  let client;
1131
+ let apiClient;
189
1132
  return {
1133
+ apiClient: () => apiClient ??= createCodecovClient({
1134
+ token: resolveApiToken({
1135
+ ...options.env ? { env: options.env } : {},
1136
+ ...options.keyring ? { keyring: options.keyring } : {}
1137
+ }),
1138
+ baseUrl: options.baseUrl,
1139
+ fetch: options.fetch
1140
+ }),
190
1141
  options,
191
1142
  client: () => client ??= createCodecovClient({
192
1143
  token: resolveToken(options),
@@ -195,11 +1146,19 @@ function createContext(options = {}) {
195
1146
  })
196
1147
  };
197
1148
  }
1149
+ /** Builds the `coverage` capability from a plugin context; `apiToken` replaces the resolved API token for this one capability. */
1150
+ function coverageWithApiToken(ctx, apiToken) {
1151
+ return new CodecovCoverage(ctx.client, resolveTarget(ctx.options), () => createCodecovClient({
1152
+ token: apiToken,
1153
+ baseUrl: ctx.options.baseUrl,
1154
+ fetch: ctx.options.fetch
1155
+ }));
1156
+ }
198
1157
  /** Builds the `coverage` capability from a plugin context. */
199
1158
  function coverage(ctx) {
200
- return new CodecovCoverage(ctx.client, resolveTarget(ctx.options));
1159
+ return new CodecovCoverage(ctx.client, resolveTarget(ctx.options), ctx.apiClient);
201
1160
  }
202
- /** Creates the Codecov plugin: its `connection` and `token` probes and the `coverage` capability. */
1161
+ /** Creates the Codecov plugin: its `connection`, `repo` and `token` probes and the `coverage` capability. */
203
1162
  function createPlugin(options = {}) {
204
1163
  const ctx = createContext(options);
205
1164
  const target = resolveTarget(options);
@@ -214,6 +1173,13 @@ function createPlugin(options = {}) {
214
1173
  subject: "a token is set (see `probe codecov token` for what can be checked)"
215
1174
  })
216
1175
  }),
1176
+ repo: repoProbe({
1177
+ coverage: (apiToken) => apiToken ? coverageWithApiToken(ctx, apiToken) : coverage(ctx),
1178
+ apiTokenName: resolveApiToken.token.envName,
1179
+ cliToken: options.cliToken,
1180
+ expected: () => options.expected ? options.expected() : coverageExpectations(options.repoRoot ?? process.cwd(), options.docsCoverage ?? "off"),
1181
+ repo: target ? describeTarget(target) : void 0
1182
+ }),
217
1183
  token: tokenProbe({
218
1184
  token: () => resolveToken(options),
219
1185
  coverage: () => coverage(ctx),
@@ -223,4 +1189,4 @@ function createPlugin(options = {}) {
223
1189
  capabilities: { coverage: () => coverage(ctx) }
224
1190
  };
225
1191
  }
226
- export { AuthError, CodecovCoverage, coverage, createCodecovClient, createContext, createPlugin, resolveTarget, resolveToken, tokens };
1192
+ export { AuthError, CodecovCoverage, coverage, coverageWithApiToken, createCodecovClient, createContext, createPlugin, resolveApiToken, resolveTarget, resolveToken, tokens };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-codecov",
3
- "version": "5.0.0-alpha.452",
3
+ "version": "5.0.0-alpha.453",
4
4
  "description": "Holocron plugin for Codecov. Implements the coverage capability against Codecov's REST API: checks that the service accepts a token for the repository.",
5
5
  "keywords": [
6
6
  "codecov",
@@ -29,6 +29,9 @@
29
29
  "files": [
30
30
  "dist"
31
31
  ],
32
+ "dependencies": {
33
+ "@theholocron/env-utils": "^1.17.0-alpha.4"
34
+ },
32
35
  "devDependencies": {
33
36
  "@types/node": "^26",
34
37
  "@vitest/coverage-v8": "^5.1.0",
@@ -39,17 +42,17 @@
39
42
  "tsdown": "^0.23.7",
40
43
  "typescript": "^5.9.3",
41
44
  "vitest": "^5.1.0",
42
- "@theholocron/cli": "5.0.0-alpha.452",
43
- "@theholocron/http-client": "^1.58.0-alpha.35",
44
- "@theholocron/eslint-config": "^8.9.0-alpha.17",
45
- "@theholocron/tsdown-config": "^8.9.0-alpha.17",
46
- "@theholocron/vitest-config": "^8.9.0-alpha.17",
47
- "@theholocron/tsconfig": "^8.9.0-alpha.17",
48
- "@theholocron/codecov-client": "^1.58.0-alpha.35"
45
+ "@theholocron/codecov-client": "^1.58.0-alpha.37",
46
+ "@theholocron/eslint-config": "^8.9.0-alpha.18",
47
+ "@theholocron/cli": "5.0.0-alpha.453",
48
+ "@theholocron/tsdown-config": "^8.9.0-alpha.18",
49
+ "@theholocron/vitest-config": "^8.9.0-alpha.18",
50
+ "@theholocron/tsconfig": "^8.9.0-alpha.18",
51
+ "@theholocron/http-client": "^1.58.0-alpha.37"
49
52
  },
50
53
  "peerDependencies": {
51
54
  "@theholocron/codecov-client": "^1.58.0",
52
- "@theholocron/cli": "5.0.0-alpha.452"
55
+ "@theholocron/cli": "5.0.0-alpha.453"
53
56
  },
54
57
  "engines": {
55
58
  "node": ">=22"