@theholocron/holocron-plugin-github 5.0.0-alpha.98 → 5.0.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.
package/dist/index.mjs CHANGED
@@ -1,48 +1,82 @@
1
1
  import { createRequire } from "node:module";
2
- import { createGitHubClient, createGitHubClient as createGitHubClient$1 } from "@theholocron/github-client";
3
- import { AuthError, createFeatureResolver } from "@theholocron/cli";
2
+ import { AGGREGATE_CHECK_NAME, AuthError, MissingTokenError, ProviderApiError, areaLabelsForFiles, areaLabelsForTitle, connectionProbe, createFeatureResolver, pickByCreation, readKeysLimited, reportProgress, requiredChecksVerdict, tokenExpectations, tokenRotationRows, whoamiAction } from "@theholocron/cli";
3
+ import { createGitHubClient, createGitHubClient as createGitHubClient$1, parseTokenExpiration } from "@theholocron/github-client";
4
4
  import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
5
5
  import { dirname, join } from "node:path";
6
- //#region src/auth.ts
6
+ import { findRootSync } from "@theholocron/fs-utils";
7
+ import { ProviderApiError as ProviderApiError$1 } from "@theholocron/http-client";
8
+ import { errorMessage } from "@theholocron/misc-utils";
9
+ // src/auth.ts
10
+ /** Resolves the token for read-only GitHub access (`HOLOCRON_READ_TOKEN`, keyring key `github.read`). */
7
11
  const resolveReadToken = createFeatureResolver({
8
12
  envName: "HOLOCRON_READ_TOKEN",
9
13
  keyringKey: "github.read"
10
14
  });
15
+ /** Resolves the token for issue operations (`HOLOCRON_ISSUES_TOKEN`, keyring key `github.issues`). */
11
16
  const resolveIssuesToken = createFeatureResolver({
12
17
  envName: "HOLOCRON_ISSUES_TOKEN",
13
18
  keyringKey: "github.issues"
14
19
  });
20
+ /**
21
+ * Resolves the token for pull request operations (`HOLOCRON_PULLS_TOKEN`, keyring key `github.pulls`): open, change and
22
+ * read pull requests, with no administration. Optional: without it the `source` capability uses the admin token.
23
+ */
24
+ const resolvePullsToken = createFeatureResolver({
25
+ envName: "HOLOCRON_PULLS_TOKEN",
26
+ keyringKey: "github.pulls"
27
+ });
28
+ /** Resolves the token for syncing repo files and settings (`HOLOCRON_SYNC_TOKEN`, keyring key `github.sync`). */
15
29
  const resolveSyncToken = createFeatureResolver({
16
30
  envName: "HOLOCRON_SYNC_TOKEN",
17
31
  keyringKey: "github.sync"
18
32
  });
33
+ /** Resolves the token for release operations (`HOLOCRON_RELEASE_TOKEN`, keyring key `github.release`). */
19
34
  const resolveReleaseToken = createFeatureResolver({
20
35
  envName: "HOLOCRON_RELEASE_TOKEN",
21
36
  keyringKey: "github.release"
22
37
  });
38
+ /** Resolves the repo-scoped admin token (`HOLOCRON_ADMIN_TOKEN`, keyring key `github.admin`). */
23
39
  const resolveAdminToken = createFeatureResolver({
24
40
  envName: "HOLOCRON_ADMIN_TOKEN",
25
41
  keyringKey: "github.admin"
26
42
  });
43
+ /** Resolves the org-level secrets token (`HOLOCRON_SECRETS_TOKEN`, keyring key `github.secrets`). */
44
+ const resolveSecretsToken = createFeatureResolver({
45
+ envName: "HOLOCRON_SECRETS_TOKEN",
46
+ keyringKey: "github.secrets"
47
+ });
48
+ /** Resolves the token for deployment operations (`HOLOCRON_DEPLOY_TOKEN`, keyring key `github.deploy`). */
27
49
  const resolveDeployToken = createFeatureResolver({
28
50
  envName: "HOLOCRON_DEPLOY_TOKEN",
29
51
  keyringKey: "github.deploy"
30
52
  });
53
+ /**
54
+ * Resolves the token for the user-sync files in the org's private config repo (`HOLOCRON_USER_SYNC_TOKEN`, keyring
55
+ * key `github.user-sync`).
56
+ */
57
+ const resolveUserSyncToken = createFeatureResolver({
58
+ envName: "HOLOCRON_USER_SYNC_TOKEN",
59
+ keyringKey: "github.user-sync"
60
+ });
61
+ /** Resolves the org-level token (`HOLOCRON_ORG_TOKEN`, keyring key `github.org`). */
31
62
  const resolveOrgToken = createFeatureResolver({
32
63
  envName: "HOLOCRON_ORG_TOKEN",
33
64
  keyringKey: "github.org"
34
65
  });
35
- //#endregion
36
- //#region src/capabilities/ci.ts
66
+ // src/capabilities/ci.ts
67
+ /** The GitHub implementation of the `ci` capability, backed by GitHub Actions workflow runs. */
37
68
  var GitHubCi = class {
38
69
  client;
39
70
  opts;
71
+ /** Capability key, always `"ci"`. */
40
72
  key = "ci";
73
+ /** Provider name, always `"github"`. */
41
74
  providerName = "github";
42
75
  constructor(client, opts) {
43
76
  this.client = client;
44
77
  this.opts = opts;
45
78
  }
79
+ /** Lists workflow runs for the repo, optionally filtered by branch, status and limit. */
46
80
  async listRuns(filter) {
47
81
  return (await this.client.workflows.listRuns(this.opts.repo, {
48
82
  branch: filter?.branch,
@@ -50,6 +84,7 @@ var GitHubCi = class {
50
84
  status: filter?.status
51
85
  })).map((r) => this.mapRun(r));
52
86
  }
87
+ /** Fetches one workflow run by id. */
53
88
  async getRun(id) {
54
89
  const raw = await this.client.workflows.getRun(this.opts.repo, id);
55
90
  return this.mapRun(raw);
@@ -77,17 +112,79 @@ var GitHubCi = class {
77
112
  }
78
113
  }
79
114
  };
80
- //#endregion
81
- //#region src/capabilities/environments.ts
115
+ // src/capabilities/check-runs.ts
116
+ /** Every check run on a commit in the plain shape the CLI reads (the aggregate's own included). */
117
+ async function readCheckRuns(client, repo, ref) {
118
+ return (await client.checks.listCheckRunsForRef(repo, ref)).map((run) => ({
119
+ id: run.id,
120
+ name: run.name,
121
+ status: run.status,
122
+ conclusion: run.conclusion,
123
+ startedAt: run.started_at ?? null,
124
+ url: run.details_url ?? run.html_url,
125
+ appSlug: run.app?.slug ?? null
126
+ }));
127
+ }
128
+ /** The commit statuses on a commit, newest first, in the plain shape the CLI reads. */
129
+ async function readCommitStatuses(client, repo, ref) {
130
+ return (await client.statuses.listCommitStatuses(repo, ref)).map((status) => ({
131
+ context: status.context,
132
+ state: status.state,
133
+ url: status.target_url
134
+ }));
135
+ }
136
+ /** GitHub's `output` for a write: the title and summary, and the details only when there are some. */
137
+ function outputFor(write) {
138
+ return {
139
+ title: write.title,
140
+ summary: write.summary,
141
+ ...write.text === "" ? {} : { text: write.text }
142
+ };
143
+ }
144
+ /** Posts a check run on a commit and returns its id. */
145
+ async function postCheckRun(client, repo, sha, name, write) {
146
+ return (await client.checks.createCheckRun(repo, {
147
+ name,
148
+ head_sha: sha,
149
+ status: write.status,
150
+ ...write.conclusion === void 0 ? {} : { conclusion: write.conclusion },
151
+ output: outputFor(write),
152
+ ...write.startedAt === void 0 ? {} : { started_at: write.startedAt }
153
+ })).id;
154
+ }
155
+ /** Changes a check run: its state, verdict and output. */
156
+ async function patchCheckRun(client, repo, id, write) {
157
+ await client.checks.updateCheckRun(repo, id, {
158
+ status: write.status,
159
+ ...write.conclusion === void 0 ? {} : { conclusion: write.conclusion },
160
+ output: outputFor(write)
161
+ });
162
+ }
163
+ // src/capabilities/commit-checks.ts
164
+ /**
165
+ * The real {@link CommitChecksReader}: one list of the commit's check runs and, only when asked, one of its statuses.
166
+ * Read now, never cached.
167
+ */
168
+ function commitChecksReader(client) {
169
+ return async (repo, sha, withStatuses) => ({
170
+ checkRuns: await readCheckRuns(client, repo, sha),
171
+ commitStatuses: withStatuses ? await readCommitStatuses(client, repo, sha) : []
172
+ });
173
+ }
174
+ // src/capabilities/environments.ts
175
+ /** The GitHub implementation of the `environments` capability, managing a repo's deployment environments. */
82
176
  var GitHubEnvironments = class {
83
177
  client;
84
178
  opts;
179
+ /** Capability key, always `"environments"`. */
85
180
  key = "environments";
181
+ /** Provider name, always `"github"`. */
86
182
  providerName = "github";
87
183
  constructor(client, opts) {
88
184
  this.client = client;
89
185
  this.opts = opts;
90
186
  }
187
+ /** Lists the repo's environments with their wait timer, self-review rule and required reviewers. */
91
188
  async listEnvironments() {
92
189
  return (await this.client.environments.listEnvironments(this.opts.repo)).map((e) => ({
93
190
  name: e.name,
@@ -96,6 +193,7 @@ var GitHubEnvironments = class {
96
193
  reviewers: this.flattenReviewers(e.protection_rules)
97
194
  }));
98
195
  }
196
+ /** Creates or updates an environment, sending only the settings the given environment defines. */
99
197
  async upsertEnvironment(env) {
100
198
  const body = {};
101
199
  if (env.waitTimer !== void 0) body.wait_timer = env.waitTimer;
@@ -106,6 +204,7 @@ var GitHubEnvironments = class {
106
204
  }));
107
205
  await this.client.environments.upsertEnvironment(this.opts.repo, env.name, body);
108
206
  }
207
+ /** Deletes the named environment. */
109
208
  async deleteEnvironment(name) {
110
209
  await this.client.environments.deleteEnvironment(this.opts.repo, name);
111
210
  }
@@ -119,16 +218,847 @@ var GitHubEnvironments = class {
119
218
  }));
120
219
  }
121
220
  };
122
- //#endregion
123
- //#region src/capabilities/issues.ts
221
+ // src/capabilities/issue-field-setter.ts
222
+ /**
223
+ * Sets and clears one organization issue field (Priority, Effort, Start date, Target date) on an issue, for the
224
+ * `issues` capability's `create` and `update` and for `createPrioritySetter()`.
225
+ *
226
+ * The field list is read once per setter. A value is added with `POST`, which leaves the issue's other field values
227
+ * alone (`PUT` replaces all of them, and a multi-select value cannot be sent back with certainty); a value that differs
228
+ * is removed first. A missing field, a missing option or a refusal from GitHub (401, 403, 404, 422) comes back as a
229
+ * `note` for the caller's `dropped` list; a rate limit and every other failure are thrown. Spec
230
+ * `tech-github-issue-priority-field`, #2253, and `tool-work-commands`, #2429.
231
+ *
232
+ * Not verified against the live API: that Effort, Start date and Target date are written the way Priority is.
233
+ */
234
+ /** Whether GitHub refused for a reason about access or setup, which a run reports and goes on from. */
235
+ function fieldRefusal(err) {
236
+ if (!(err instanceof ProviderApiError)) return void 0;
237
+ if (err.status === void 0 || ![
238
+ 401,
239
+ 403,
240
+ 404,
241
+ 422
242
+ ].includes(err.status)) return void 0;
243
+ if (/rate limit/i.test(`${err.message} ${String(err.details)}`)) return void 0;
244
+ return `GitHub refused: ${err.status}`;
245
+ }
246
+ const DATA_TYPE = {
247
+ select: "single_select",
248
+ date: "date"
249
+ };
250
+ /** Makes the setter for the issues of `repo` (`owner/name`); the organization's field list is read on first use and kept. */
251
+ function createFieldSetter(client, repo) {
252
+ const org = repo.split("/")[0];
253
+ let fields;
254
+ const listFields = () => fields ??= client.issueFields.list(org).then((list) => list, (err) => {
255
+ const why = fieldRefusal(err);
256
+ if (why === void 0) throw err;
257
+ return why;
258
+ });
259
+ const label = (target) => `${target.name.toLowerCase()} field`;
260
+ const find = async (target) => {
261
+ const list = await listFields();
262
+ if (typeof list === "string") return { note: `${label(target)} (${list})` };
263
+ const field = list.find((f) => f.name.toLowerCase() === target.name.toLowerCase() && f.data_type === DATA_TYPE[target.type]);
264
+ return field ? { field } : { note: `${label(target)} (${org} has no ${target.name} issue field)` };
265
+ };
266
+ const currentOf = async (number, field, target, flags) => {
267
+ if (flags.isNew) return void 0;
268
+ const found = (await client.issueFields.values(repo, number)).find((v) => v.issue_field_id === field.id);
269
+ if (!found) return void 0;
270
+ return target.type === "date" ? String(found.value).slice(0, 10) : found.single_select_option?.name ?? String(found.value);
271
+ };
272
+ return {
273
+ async set(number, target, flags = {}) {
274
+ if (!target.value) return { changed: false };
275
+ const found = await find(target);
276
+ if ("note" in found) return {
277
+ changed: false,
278
+ note: found.note
279
+ };
280
+ const { field } = found;
281
+ let value = target.value;
282
+ if (target.type === "select") {
283
+ const option = field.options?.find((o) => o.name.toLowerCase() === value.toLowerCase());
284
+ if (!option) return {
285
+ changed: false,
286
+ note: `${label(target)} (no "${value}" option)`
287
+ };
288
+ value = option.name;
289
+ }
290
+ try {
291
+ const current = await currentOf(number, field, target, flags);
292
+ if (current?.toLowerCase() === value.toLowerCase()) return { changed: false };
293
+ if (flags.dryRun) return { changed: true };
294
+ if (current !== void 0) await client.issueFields.deleteValue(repo, number, field.id);
295
+ await client.issueFields.addValues(repo, number, [{
296
+ field_id: field.id,
297
+ value
298
+ }]);
299
+ return { changed: true };
300
+ } catch (err) {
301
+ const why = fieldRefusal(err);
302
+ if (why === void 0) throw err;
303
+ return {
304
+ changed: false,
305
+ note: `${label(target)} (${why})`
306
+ };
307
+ }
308
+ },
309
+ async clear(number, target, flags = {}) {
310
+ if (flags.isNew) return { changed: false };
311
+ const found = await find(target);
312
+ if ("note" in found) return {
313
+ changed: false,
314
+ note: found.note
315
+ };
316
+ try {
317
+ if (await currentOf(number, found.field, target, flags) === void 0) return { changed: false };
318
+ if (flags.dryRun) return { changed: true };
319
+ await client.issueFields.deleteValue(repo, number, found.field.id);
320
+ return { changed: true };
321
+ } catch (err) {
322
+ const why = fieldRefusal(err);
323
+ if (why === void 0) throw err;
324
+ return {
325
+ changed: false,
326
+ note: `${label(target)} (${why})`
327
+ };
328
+ }
329
+ }
330
+ };
331
+ }
332
+ // src/capabilities/issue-kind.ts
333
+ /** The Type name of each core kind; always known, whatever is declared. */
334
+ const CORE_TYPE_NAMES = {
335
+ bug: "Bug",
336
+ feature: "Feature",
337
+ task: "Task"
338
+ };
339
+ /** The kind each label names where there is no Type. */
340
+ const LABEL_KINDS = {
341
+ bug: "bug",
342
+ enhancement: "feature",
343
+ chore: "task"
344
+ };
345
+ /** The core three Types plus the declared ones (in the declaration's spelling); a core name wins over a declared one. */
346
+ function kindNames(declared) {
347
+ const names = new Map(Object.entries(CORE_TYPE_NAMES));
348
+ for (const { name } of declared ?? []) if (!names.has(name.toLowerCase())) names.set(name.toLowerCase(), name);
349
+ return {
350
+ nameOf: (kind) => names.get(kind) ?? kind.charAt(0).toUpperCase() + kind.slice(1),
351
+ kindOf: (typeName) => typeName ? typeName.toLowerCase() : void 0
352
+ };
353
+ }
354
+ /** The names with nothing declared. */
355
+ const CORE_KIND_NAMES = kindNames(void 0);
356
+ /**
357
+ * The kind of an issue: its Type (a Type outside the core three is its lower-case name, so a migration does not lose an
358
+ * Epic), else the one kind its labels name (two different ones name none).
359
+ */
360
+ function kindOfIssue(issue, names = CORE_KIND_NAMES) {
361
+ const typed = names.kindOf(issue.type?.name);
362
+ if (typed) return typed;
363
+ const named = new Set(issue.labels.flatMap((l) => LABEL_KINDS[l.name.toLowerCase()] ?? []));
364
+ return named.size === 1 ? [...named][0] : void 0;
365
+ }
366
+ /** Whether the issue's Type is already the kind's. */
367
+ function hasKindType(issue, kind, names = CORE_KIND_NAMES) {
368
+ return issue.type?.name?.toLowerCase() === names.nameOf(kind).toLowerCase();
369
+ }
370
+ /** Sets the Type of issue `number`; a refusal is returned as a `dropped` line, anything else (a rate limit) is thrown. */
371
+ async function writeKind(client, repo, number, kind, names = CORE_KIND_NAMES) {
372
+ const name = names.nameOf(kind);
373
+ try {
374
+ await client.issues.updateIssue(repo, number, { type: name });
375
+ return;
376
+ } catch (err) {
377
+ const why = fieldRefusal(err);
378
+ if (why === void 0) throw err;
379
+ return `kind ${name} (${why})`;
380
+ }
381
+ }
382
+ // src/capabilities/issue-priority.ts
383
+ /** The Priority field's option for each level. */
384
+ const PRIORITY_OPTION_NAMES = {
385
+ urgent: "Urgent",
386
+ high: "High",
387
+ medium: "Medium",
388
+ low: "Low"
389
+ };
390
+ /** Makes the Priority setter for the issues of `repo` (`owner/name`). */
391
+ function createPrioritySetter(client, repo) {
392
+ const fields = createFieldSetter(client, repo);
393
+ return { set: (number, level, flags = {}) => !level || level === "none" ? Promise.resolve({ changed: false }) : fields.set(number, {
394
+ name: "Priority",
395
+ type: "select",
396
+ value: PRIORITY_OPTION_NAMES[level]
397
+ }, flags) };
398
+ }
399
+ // src/capabilities/issue-work-fields.ts
400
+ /** The Effort field's option for each effort. */
401
+ const EFFORT_NAMES = {
402
+ high: "High",
403
+ medium: "Medium",
404
+ low: "Low"
405
+ };
406
+ /** Makes the reader for the issues of `repo` (`owner/name`); the organization's field list is read once, on first use. */
407
+ function createWorkFieldReader(client, repo) {
408
+ const org = repo.split("/")[0];
409
+ let fields;
410
+ const listFields = () => fields ??= client.issueFields.list(org).catch((err) => {
411
+ if (fieldRefusal(err) === void 0) throw err;
412
+ return [];
413
+ });
414
+ const idOf = (list, name) => list.find((f) => f.name.toLowerCase() === name)?.id;
415
+ return { async read(number) {
416
+ const list = await listFields();
417
+ const effortId = idOf(list, "effort");
418
+ const startId = idOf(list, "start date");
419
+ const targetId = idOf(list, "target date");
420
+ if (effortId === void 0 && startId === void 0 && targetId === void 0) return {};
421
+ const values = await client.issueFields.values(repo, number).catch((err) => {
422
+ if (fieldRefusal(err) === void 0) throw err;
423
+ return [];
424
+ });
425
+ const valueOf = (id) => values.find((v) => v.issue_field_id === id);
426
+ const effort = (valueOf(effortId)?.single_select_option?.name ?? "").toLowerCase();
427
+ const start = valueOf(startId);
428
+ const target = valueOf(targetId);
429
+ return {
430
+ ...effort in EFFORT_NAMES ? { effort } : {},
431
+ ...start ? { startDate: String(start.value).slice(0, 10) } : {},
432
+ ...target ? { targetDate: String(target.value).slice(0, 10) } : {}
433
+ };
434
+ } };
435
+ }
436
+ /** Sets the work fields the record carries; one it does not carry is not touched. */
437
+ async function writeWorkFields(fields, number, record, flags) {
438
+ const wanted = [
439
+ ["effort", {
440
+ name: "Effort",
441
+ type: "select",
442
+ value: record.effort && EFFORT_NAMES[record.effort]
443
+ }],
444
+ ["startDate", {
445
+ name: "Start date",
446
+ type: "date",
447
+ value: record.startDate
448
+ }],
449
+ ["targetDate", {
450
+ name: "Target date",
451
+ type: "date",
452
+ value: record.targetDate
453
+ }]
454
+ ];
455
+ const out = {
456
+ changed: [],
457
+ notes: []
458
+ };
459
+ for (const [label, target] of wanted) {
460
+ const result = await fields.set(number, target, flags);
461
+ if (result.note) out.notes.push(result.note);
462
+ else if (result.changed) out.changed.push(label);
463
+ }
464
+ return out;
465
+ }
466
+ // src/capabilities/issues-migration.ts
467
+ /**
468
+ * Export and import of GitHub issues for `holocron migrate`.
469
+ *
470
+ * GitHub holds less than a planning tool, so what does not fit is named in each result's `dropped` list rather than
471
+ * lost quietly:
472
+ * - priority is a label (`priority: high`), because on GitHub it lives in a project field, not on the issue;
473
+ * - an import cannot backdate an issue or a comment, and cannot post as someone else, so the original date and
474
+ * author go in the text;
475
+ * - an import does not set parent or blocked-by links (they need GraphQL node ids of issues made in the same run);
476
+ * - an assignee is not mapped (a Linear user is not a GitHub login).
477
+ * - the organization's `Priority` issue field is set from the priority (`issue-priority.ts`), beside the label.
478
+ * A migrated issue ends with `<!-- holocron:migrated-from <url> -->`, which is how a second run finds it.
479
+ */
480
+ const MARKER = /<!-- holocron:migrated-from (\S+) -->/;
481
+ const PRIORITY_LABEL = /^priority\s*[:/-]\s*(urgent|high|medium|low)$/i;
482
+ const LINK_QUERY = `query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) {
483
+ issue(number: $number) { parent { number } blockedBy(first: 50) { nodes { number } } } } }`;
484
+ /** Splits `priority: high` labels from the rest. */
485
+ function splitLabels(names) {
486
+ let priority;
487
+ const labels = [];
488
+ for (const name of names) {
489
+ const match = PRIORITY_LABEL.exec(name);
490
+ if (match) priority = match[1].toLowerCase();
491
+ else labels.push(name);
492
+ }
493
+ return {
494
+ labels,
495
+ ...priority ? { priority } : {}
496
+ };
497
+ }
498
+ function categoryOf(issue) {
499
+ if (issue.state === "closed") return "done";
500
+ const names = issue.labels.map((l) => l.name.toLowerCase());
501
+ if (names.some((n) => n === "status:in-review" || n === "status: in review")) return "in-review";
502
+ if (names.some((n) => n === "status:in-progress" || n === "status: in progress")) return "in-progress";
503
+ return "open";
504
+ }
505
+ /** How many issues an export fetches at once. GitHub's secondary rate limit punishes bursts of requests, not volume. */
506
+ const EXPORT_CONCURRENCY = 4;
507
+ /** Runs `fn` over `items`, at most `limit` at a time, and returns the results in the order of `items`. */
508
+ async function mapLimit(items, limit, fn) {
509
+ const results = new Array(items.length);
510
+ let next = 0;
511
+ const worker = async () => {
512
+ while (next < items.length) {
513
+ const at = next++;
514
+ results[at] = await fn(items[at]);
515
+ }
516
+ };
517
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
518
+ return results;
519
+ }
520
+ /** GitHub's own answer to a burst of requests (403 or 429 naming the secondary limit) becomes a message that says what to do. */
521
+ function explainSecondaryLimit(err) {
522
+ if (err instanceof ProviderApiError && (err.status === 403 || err.status === 429) && String(err.details).includes("secondary rate limit")) return /* @__PURE__ */ new Error("GitHub's secondary rate limit stopped the export. It limits bursts of requests, not the hourly quota, and nothing has been written. Wait a couple of minutes and run the command again.");
523
+ return err;
524
+ }
525
+ /**
526
+ * Reads the issues `selector` names, with their comments, priority label, parent and blockers.
527
+ *
528
+ * With `limit`, only that many survivors of the other filters are read, from the `order` end of the creation order. A
529
+ * list of keys is sorted by issue number (which rises with creation in one repository) before anything is fetched, then
530
+ * fetched a few at a time until enough are kept; a listing already carries `created_at`, so it is cut before the
531
+ * per-issue comment and link requests. `info.matched` receives how many the selection matched before the cut.
532
+ */
533
+ async function exportIssues(client, repo, selector, info = {}, kinds = CORE_KIND_NAMES) {
534
+ return readIssues(client, repo, selector, info, kinds).catch((err) => {
535
+ throw explainSecondaryLimit(err);
536
+ });
537
+ }
538
+ async function readIssues(client, repo, selector, info, kinds) {
539
+ const [owner = "", name = ""] = repo.split("/", 2);
540
+ const since = selector.since ? Date.parse(selector.since) : void 0;
541
+ const survives = (i) => !i.pull_request && !(selector.openOnly && i.state === "closed") && (since === void 0 || Date.parse(i.updated_at) >= since);
542
+ const { limit, order = "oldest" } = selector;
543
+ let issues;
544
+ if (selector.keys) {
545
+ const fetch = (k) => client.issues.getIssue(repo, parseNumber(k));
546
+ info.matched = selector.keys.length;
547
+ issues = limit === void 0 ? (await mapLimit(selector.keys, EXPORT_CONCURRENCY, fetch)).filter(survives) : await readKeysLimited({
548
+ keys: selector.keys,
549
+ order,
550
+ limit,
551
+ concurrency: EXPORT_CONCURRENCY,
552
+ fetch,
553
+ keep: survives
554
+ });
555
+ } else {
556
+ let raw;
557
+ if (selector.milestone) {
558
+ const milestone = await findMilestone(client, repo, selector.milestone);
559
+ if (!milestone) throw new Error(`Milestone "${selector.milestone}" not found in ${repo}.`);
560
+ raw = await listAll(client, repo, { milestone: String(milestone.number) });
561
+ } else if (selector.all) raw = await listAll(client, repo, {});
562
+ else throw new Error("export needs keys, a milestone or all");
563
+ issues = raw.filter(survives);
564
+ info.matched = issues.length;
565
+ if (limit !== void 0) issues = pickByCreation(issues, (i) => i.created_at ?? i.updated_at, order, limit);
566
+ }
567
+ const work = createWorkFieldReader(client, repo);
568
+ const records = [];
569
+ for (const issue of issues) {
570
+ reportProgress(info.onProgress, records.length, issues.length);
571
+ const comments = await client.issues.listComments(repo, issue.number);
572
+ const links = (await client.graphql.query(LINK_QUERY, {
573
+ owner,
574
+ name,
575
+ number: issue.number
576
+ }).catch(() => void 0))?.repository.issue;
577
+ const { labels, priority } = splitLabels(issue.labels.map((l) => l.name));
578
+ const body = issue.body?.replace(MARKER, "").trimEnd();
579
+ const migratedFrom = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
580
+ const kind = kindOfIssue(issue, kinds);
581
+ const workFields = await work.read(issue.number);
582
+ records.push({
583
+ key: `#${issue.number}`,
584
+ url: issue.html_url,
585
+ title: issue.title,
586
+ ...body ? { body } : {},
587
+ statusCategory: categoryOf(issue),
588
+ closed: issue.state === "closed",
589
+ ...priority ? { priority } : {},
590
+ labels: labels.filter((l) => !l.toLowerCase().startsWith("status:")),
591
+ ...kind ? { kind } : {},
592
+ ...workFields,
593
+ ...issue.assignee ? { assignee: {
594
+ id: issue.assignee.login,
595
+ displayName: issue.assignee.name ?? issue.assignee.login,
596
+ ...issue.assignee.email ? { emailAddress: issue.assignee.email } : {}
597
+ } } : {},
598
+ ...issue.milestone ? { milestone: issue.milestone.title } : {},
599
+ ...links?.parent ? { parent: `#${links.parent.number}` } : {},
600
+ blockedBy: (links?.blockedBy.nodes ?? []).map((n) => `#${n.number}`),
601
+ comments: comments.map((c) => ({
602
+ ...c.user ? { author: c.user.login } : {},
603
+ body: c.body,
604
+ createdAt: c.created_at
605
+ })),
606
+ createdAt: issue.created_at ?? issue.updated_at,
607
+ updatedAt: issue.updated_at,
608
+ ...migratedFrom ? { migratedFrom } : {}
609
+ });
610
+ }
611
+ reportProgress(info.onProgress, records.length, issues.length);
612
+ return records;
613
+ }
614
+ /** Makes the records as issues, skipping any whose source address an earlier run already recorded. */
615
+ async function importIssues(client, repo, records, options = {}, kinds = CORE_KIND_NAMES) {
616
+ const existing = /* @__PURE__ */ new Map();
617
+ for (const issue of await listAll(client, repo, {})) {
618
+ const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
619
+ if (url) existing.set(url, issue.number);
620
+ }
621
+ const priority = createPrioritySetter(client, repo);
622
+ const fields = createFieldSetter(client, repo);
623
+ const results = [];
624
+ const tick = () => reportProgress(options.onProgress, results.length, records.length);
625
+ for (const record of records) {
626
+ const found = existing.get(record.url);
627
+ if (found !== void 0) {
628
+ results.push({
629
+ source: record.key,
630
+ key: `#${found}`,
631
+ created: false,
632
+ dropped: []
633
+ });
634
+ tick();
635
+ continue;
636
+ }
637
+ const dropped = droppedFor(record);
638
+ if (options.dryRun) {
639
+ results.push({
640
+ source: record.key,
641
+ created: true,
642
+ dropped
643
+ });
644
+ tick();
645
+ continue;
646
+ }
647
+ const number = await createFromRecord(client, repo, record, options);
648
+ const field = await priority.set(number, record.priority, { isNew: true });
649
+ if (field.note) dropped.push(field.note);
650
+ dropped.push(...(await writeWorkFields(fields, number, record, { isNew: true })).notes);
651
+ const kindNote = record.kind ? await writeKind(client, repo, number, record.kind, kinds) : void 0;
652
+ if (kindNote) dropped.push(kindNote);
653
+ results.push({
654
+ source: record.key,
655
+ key: `#${number}`,
656
+ created: true,
657
+ dropped
658
+ });
659
+ tick();
660
+ }
661
+ return results;
662
+ }
663
+ /** What GitHub cannot hold of this record, for the report. */
664
+ function droppedFor(record) {
665
+ const dropped = ["createdAt (GitHub sets it; the original date is in the text)"];
666
+ if (record.assignee && !record.assignee.login) dropped.push("assignee (not mapped)");
667
+ if (record.parent) dropped.push("parent (not set on GitHub)");
668
+ if (record.blockedBy.length > 0) dropped.push("blockedBy (not set on GitHub)");
669
+ return dropped;
670
+ }
671
+ /** The labels a record becomes on GitHub: its own, plus `priority: <level>` (GitHub's priority is a label). */
672
+ function labelsFor(record) {
673
+ return [...record.labels, ...record.priority && record.priority !== "none" ? [`priority: ${record.priority}`] : []];
674
+ }
675
+ /** The text a comment gets when it is copied: GitHub cannot post as another author or backdate. */
676
+ function renderComment(comment) {
677
+ return `${comment.author ? `**${comment.author}**` : "Someone"} commented on ${comment.createdAt}:\n\n${comment.body}`;
678
+ }
679
+ /** Makes one issue from a record, with its comments, and closes it when the record is closed; returns its number. */
680
+ async function createFromRecord(client, repo, record, options) {
681
+ const milestoneName = options.milestone ?? record.milestone;
682
+ const milestone = milestoneName ? await ensureMilestone(client, repo, milestoneName) : void 0;
683
+ const labels = labelsFor(record);
684
+ const created = await client.issues.createIssue(repo, {
685
+ title: record.title,
686
+ body: withProvenance(record),
687
+ ...labels.length > 0 ? { labels } : {},
688
+ ...milestone !== void 0 ? { milestone } : {},
689
+ ...record.assignee?.login ? { assignees: [record.assignee.login] } : {}
690
+ });
691
+ for (const comment of record.comments) await client.issues.createComment(repo, created.number, renderComment(comment));
692
+ if (record.closed) await client.issues.updateIssue(repo, created.number, {
693
+ state: "closed",
694
+ state_reason: "completed"
695
+ });
696
+ return created.number;
697
+ }
698
+ /** The text of a migrated issue: the record's body, then where it came from and the marker a second run looks for. */
699
+ function withProvenance(record) {
700
+ return `${record.body ? `${record.body}\n\n` : ""}---\n_Migrated from [${record.key}](${record.url}); created ${record.createdAt}._\n<!-- holocron:migrated-from ${record.url} -->`;
701
+ }
702
+ function parseNumber(key) {
703
+ const n = key.trim().replace(/^.*#/, "");
704
+ if (!/^\d+$/.test(n)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
705
+ return parseInt(n, 10);
706
+ }
707
+ async function listAll(client, repo, extra) {
708
+ const all = [];
709
+ for (let page = 1;; page++) {
710
+ const batch = await client.issues.listIssues(repo, {
711
+ state: "all",
712
+ per_page: 100,
713
+ page,
714
+ ...extra
715
+ });
716
+ all.push(...batch);
717
+ if (batch.length < 100) return all;
718
+ }
719
+ }
720
+ async function findMilestone(client, repo, ref) {
721
+ return (await client.issues.listMilestones(repo, { state: "all" })).find((m) => String(m.number) === ref || m.title.toLowerCase() === ref.toLowerCase());
722
+ }
723
+ async function ensureMilestone(client, repo, title) {
724
+ return (await findMilestone(client, repo, title))?.number ?? (await client.issues.createMilestone(repo, title)).number;
725
+ }
726
+ // src/capabilities/issues-sync.ts
727
+ const COMMENT_HEADER = /^(?:\*\*.*?\*\*|Someone) commented on (\S+?):\n/;
728
+ /** Whether GitHub is asking to be left alone: a 429, or a 403 that says it is a rate limit. */
729
+ function isRateLimited(err) {
730
+ return err instanceof ProviderApiError && (err.status === 429 || err.status === 403 && /rate limit/i.test(`${err.message} ${String(err.details)}`));
731
+ }
732
+ const normalize = (text) => text.replace(/\r\n/g, "\n").trim();
733
+ const sorted = (names) => names.map((n) => n.toLowerCase()).sort().join("\n");
734
+ /** Makes the records missing from the repo and updates the ones an earlier run made. See the file comment. */
735
+ async function syncIssues(client, repo, records, options = {}, kinds = CORE_KIND_NAMES) {
736
+ const existing = /* @__PURE__ */ new Map();
737
+ for (const issue of await listAll(client, repo, {})) {
738
+ const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
739
+ if (url) existing.set(url, issue);
740
+ }
741
+ const priority = createPrioritySetter(client, repo);
742
+ const fields = createFieldSetter(client, repo);
743
+ const results = [];
744
+ for (const record of records) try {
745
+ const found = existing.get(record.url);
746
+ results.push(found ? await update(client, repo, found, record, options, priority, fields, kinds) : await create(client, repo, record, options, priority, fields, kinds));
747
+ reportProgress(options.onProgress, results.length, records.length);
748
+ } catch (err) {
749
+ if (isRateLimited(err)) return results;
750
+ throw err;
751
+ }
752
+ return results;
753
+ }
754
+ async function create(client, repo, record, options, priority, fields, kinds) {
755
+ const dropped = droppedFor(record);
756
+ if (options.dryRun) return {
757
+ source: record.key,
758
+ created: true,
759
+ updated: false,
760
+ changes: [],
761
+ dropped
762
+ };
763
+ const number = await createFromRecord(client, repo, record, options);
764
+ const field = await priority.set(number, record.priority, { isNew: true });
765
+ if (field.note) dropped.push(field.note);
766
+ dropped.push(...(await writeWorkFields(fields, number, record, { isNew: true })).notes);
767
+ const kindNote = record.kind ? await writeKind(client, repo, number, record.kind, kinds) : void 0;
768
+ if (kindNote) dropped.push(kindNote);
769
+ return {
770
+ source: record.key,
771
+ key: `#${number}`,
772
+ created: true,
773
+ updated: false,
774
+ changes: [],
775
+ dropped
776
+ };
777
+ }
778
+ async function update(client, repo, issue, record, options, priority, fields, kinds) {
779
+ const patch = {};
780
+ const changes = [];
781
+ if (issue.title !== record.title) {
782
+ patch.title = record.title;
783
+ changes.push("title");
784
+ }
785
+ const body = withProvenance(record);
786
+ if (normalize(issue.body) !== normalize(body)) {
787
+ patch.body = body;
788
+ changes.push("description");
789
+ }
790
+ if (issue.state === "closed" !== record.closed) {
791
+ patch.state = record.closed ? "closed" : "open";
792
+ if (record.closed) patch.state_reason = "completed";
793
+ changes.push("state");
794
+ }
795
+ const current = issue.labels.map((l) => l.name);
796
+ const finalLabels = [...labelsFor(record), ...current.filter((n) => n.toLowerCase().startsWith("status:"))];
797
+ if (sorted(finalLabels) !== sorted(current)) {
798
+ patch.labels = finalLabels;
799
+ changes.push("labels");
800
+ }
801
+ const login = record.assignee?.login;
802
+ if (login && issue.assignee?.login.toLowerCase() !== login.toLowerCase()) {
803
+ patch.assignees = [login];
804
+ changes.push("assignee");
805
+ }
806
+ const field = await priority.set(issue.number, record.priority, { dryRun: options.dryRun });
807
+ if (field.changed) changes.push("priority field");
808
+ const work = await writeWorkFields(fields, issue.number, record, { dryRun: options.dryRun });
809
+ changes.push(...work.changed);
810
+ const kindWrong = record.kind !== void 0 && !hasKindType(issue, record.kind, kinds);
811
+ if (kindWrong) changes.push("kind");
812
+ const kindNote = kindWrong && !options.dryRun ? await writeKind(client, repo, issue.number, record.kind, kinds) : void 0;
813
+ const comments = await client.issues.listComments(repo, issue.number);
814
+ const seen = new Set(comments.map((c) => COMMENT_HEADER.exec(c.body)?.[1]));
815
+ const missing = record.comments.filter((c) => !seen.has(c.createdAt));
816
+ if (missing.length > 0) changes.push("comments");
817
+ if (!options.dryRun) {
818
+ if (Object.keys(patch).length > 0) await client.issues.updateIssue(repo, issue.number, patch);
819
+ for (const comment of missing) await client.issues.createComment(repo, issue.number, renderComment(comment));
820
+ }
821
+ return {
822
+ source: record.key,
823
+ key: `#${issue.number}`,
824
+ created: false,
825
+ updated: changes.length > 0,
826
+ changes,
827
+ dropped: [
828
+ ...droppedFor(record),
829
+ ...field.note ? [field.note] : [],
830
+ ...work.notes,
831
+ ...kindNote ? [kindNote] : []
832
+ ]
833
+ };
834
+ }
835
+ // src/capabilities/issues-update.ts
836
+ /** Runs one step; a refusal or a bad key is a `dropped` line, anything else (a rate limit) is thrown. */
837
+ async function guarded(what, out, step) {
838
+ try {
839
+ await step();
840
+ } catch (err) {
841
+ const why = fieldRefusal(err);
842
+ if (why !== void 0) out.dropped.push(`${what} (${why})`);
843
+ else if (!(err instanceof ProviderApiError)) out.dropped.push(`${what} (${err.message})`);
844
+ else throw err;
845
+ }
846
+ }
847
+ const CLEAR_FIELD = {
848
+ priority: {
849
+ name: "Priority",
850
+ type: "select"
851
+ },
852
+ effort: {
853
+ name: "Effort",
854
+ type: "select"
855
+ },
856
+ startDate: {
857
+ name: "Start date",
858
+ type: "date"
859
+ },
860
+ targetDate: {
861
+ name: "Target date",
862
+ type: "date"
863
+ }
864
+ };
865
+ /**
866
+ * Writes the {@link IssueFields} of an issue, and clears and unblocks as `clear` and `unblock` ask. `issue` is the issue
867
+ * as it is now (its numeric id and Type); `isNew` says it was just made, so nothing is read to compare.
868
+ */
869
+ async function applyIssueFields(ctx, issue, input, isNew) {
870
+ const { client, repo } = ctx;
871
+ const fields = ctx.fields ??= createFieldSetter(client, repo);
872
+ const out = {
873
+ changed: [],
874
+ dropped: []
875
+ };
876
+ const flags = { isNew };
877
+ const clear = new Set(input.clear ?? []);
878
+ if (input.kind) {
879
+ const name = ctx.kinds.nameOf(input.kind);
880
+ if (issue.type?.name?.toLowerCase() !== name.toLowerCase()) await guarded(`kind ${name}`, out, async () => {
881
+ await client.issues.updateIssue(repo, issue.number, { type: name });
882
+ out.changed.push(`kind: ${name}`);
883
+ });
884
+ } else if (clear.has("kind") && issue.type) await guarded("kind", out, async () => {
885
+ await client.issues.updateIssue(repo, issue.number, { type: null });
886
+ out.changed.push("kind cleared");
887
+ });
888
+ const values = [
889
+ [
890
+ "priority",
891
+ "Priority",
892
+ "select",
893
+ input.priority && input.priority !== "none" ? PRIORITY_OPTION_NAMES[input.priority] : void 0
894
+ ],
895
+ [
896
+ "effort",
897
+ "Effort",
898
+ "select",
899
+ input.effort ? EFFORT_NAMES[input.effort] : void 0
900
+ ],
901
+ [
902
+ "startDate",
903
+ "Start date",
904
+ "date",
905
+ input.startDate
906
+ ],
907
+ [
908
+ "targetDate",
909
+ "Target date",
910
+ "date",
911
+ input.targetDate
912
+ ]
913
+ ];
914
+ for (const [label, name, type, value] of values) {
915
+ if (!value) continue;
916
+ const result = await fields.set(issue.number, {
917
+ name,
918
+ type,
919
+ value
920
+ }, flags);
921
+ if (result.note) out.dropped.push(result.note);
922
+ else if (result.changed) out.changed.push(`${label}: ${value}`);
923
+ }
924
+ for (const key of clear) {
925
+ const target = CLEAR_FIELD[key];
926
+ if (!target) continue;
927
+ const result = await fields.clear(issue.number, target, flags);
928
+ if (result.note) out.dropped.push(result.note);
929
+ else if (result.changed) out.changed.push(`${key} cleared`);
930
+ }
931
+ if (input.parent) {
932
+ const parentKey = input.parent;
933
+ await guarded(`parent ${parentKey}`, out, async () => {
934
+ const parentNumber = ctx.parseKey(parentKey);
935
+ const current = isNew ? null : await client.issues.getParent(repo, issue.number);
936
+ if (current?.number === parentNumber) return;
937
+ await client.issues.addSubIssue(repo, parentNumber, issue.id, current !== null);
938
+ out.changed.push(`parent: ${parentKey}`);
939
+ });
940
+ } else if (clear.has("parent") && !isNew) await guarded("parent", out, async () => {
941
+ const current = await client.issues.getParent(repo, issue.number);
942
+ if (!current) return;
943
+ await client.issues.removeSubIssue(repo, current.number, issue.id);
944
+ out.changed.push("parent cleared");
945
+ });
946
+ const adds = input.blockedBy ?? [];
947
+ const removes = input.unblock ?? [];
948
+ if (adds.length > 0 || removes.length > 0) {
949
+ let blockers;
950
+ const current = async () => blockers ??= isNew ? [] : await client.issues.listBlockedBy(repo, issue.number);
951
+ for (const key of adds) await guarded(`blocked by ${key}`, out, async () => {
952
+ const number = ctx.parseKey(key);
953
+ if ((await current()).some((b) => b.number === number)) return;
954
+ const blocker = await client.issues.getIssue(repo, number);
955
+ await client.issues.addBlockedBy(repo, issue.number, blocker.id);
956
+ out.changed.push(`blocked by: ${key}`);
957
+ });
958
+ for (const key of removes) await guarded(`unblock ${key}`, out, async () => {
959
+ const number = ctx.parseKey(key);
960
+ const blocker = (await current()).find((b) => b.number === number);
961
+ if (!blocker) return;
962
+ await client.issues.removeBlockedBy(repo, issue.number, blocker.id);
963
+ out.changed.push(`unblocked: ${key}`);
964
+ });
965
+ }
966
+ return out;
967
+ }
968
+ const sameSet = (a, b) => a.length === b.length && a.every((x) => b.includes(x));
969
+ /** Changes an issue to match the patch; whatever is already as asked is not written. */
970
+ async function updateGitHubIssue(ctx, key, patch) {
971
+ const { client, repo } = ctx;
972
+ const number = ctx.parseKey(key);
973
+ const issue = await client.issues.getIssue(repo, number);
974
+ const changed = [];
975
+ const clear = new Set(patch.clear ?? []);
976
+ const body = {};
977
+ if (patch.title !== void 0 && patch.title !== issue.title) {
978
+ body.title = patch.title;
979
+ changed.push("title");
980
+ }
981
+ if (patch.body !== void 0 && patch.body !== (issue.body ?? "")) {
982
+ body.body = patch.body;
983
+ changed.push("body");
984
+ }
985
+ if (patch.state && patch.state !== issue.state) {
986
+ body.state = patch.state;
987
+ if (patch.state === "closed") body.state_reason = patch.stateReason ?? "completed";
988
+ changed.push(`state: ${patch.state}`);
989
+ }
990
+ const have = (issue.assignees ?? (issue.assignee ? [issue.assignee] : [])).map((a) => a.login);
991
+ if (patch.assignees?.length) {
992
+ const isMe = (a) => /^@?me$/i.test(a);
993
+ const me = patch.assignees.some(isMe) ? await ctx.myLogin() : void 0;
994
+ const want = [...new Set(patch.assignees.map((a) => isMe(a) && me ? me : a.replace(/^@/, "")))];
995
+ if (!sameSet(want.map((a) => a.toLowerCase()), have.map((a) => a.toLowerCase()))) {
996
+ body.assignees = want;
997
+ changed.push(`assignees: ${want.join(", ")}`);
998
+ }
999
+ } else if (clear.has("assignees") && have.length > 0) {
1000
+ body.assignees = [];
1001
+ changed.push("assignees cleared");
1002
+ }
1003
+ if (patch.milestone) {
1004
+ const milestone = await ctx.resolveMilestone(patch.milestone);
1005
+ if (issue.milestone?.number !== milestone) {
1006
+ body.milestone = milestone;
1007
+ changed.push(`milestone: ${patch.milestone}`);
1008
+ }
1009
+ } else if (clear.has("milestone") && issue.milestone) {
1010
+ body.milestone = null;
1011
+ changed.push("milestone cleared");
1012
+ }
1013
+ if (Object.keys(body).length > 0) await client.issues.updateIssue(repo, number, body);
1014
+ const labels = new Set(issue.labels.map((l) => l.name.toLowerCase()));
1015
+ const add = [...new Set(patch.addLabels ?? [])].filter((l) => !labels.has(l.toLowerCase()));
1016
+ if (add.length > 0) {
1017
+ await client.issues.addLabels(repo, number, add);
1018
+ changed.push(`labels added: ${add.join(", ")}`);
1019
+ }
1020
+ for (const label of new Set(patch.removeLabels ?? [])) {
1021
+ if (!labels.has(label.toLowerCase())) continue;
1022
+ const exact = issue.labels.find((l) => l.name.toLowerCase() === label.toLowerCase()).name;
1023
+ await client.issues.removeLabel(repo, number, exact);
1024
+ changed.push(`label removed: ${exact}`);
1025
+ }
1026
+ const fields = await applyIssueFields(ctx, issue, patch, false);
1027
+ const all = [...changed, ...fields.changed];
1028
+ return {
1029
+ key: `#${number}`,
1030
+ changed: all,
1031
+ ...fields.dropped.length > 0 ? { dropped: fields.dropped } : {}
1032
+ };
1033
+ }
1034
+ // src/capabilities/issues.ts
1035
+ /** Issues read per request when `search` has a `text`; GitHub's largest page. */
1036
+ const TEXT_PAGE_SIZE = 100;
1037
+ /** Pages `search` reads for a `text` before it stops (the 2000 most recently updated issues). */
1038
+ const TEXT_MAX_PAGES = 20;
1039
+ /** A Type as the capability reports it: GitHub's `null`s are left out. */
1040
+ function toTypeInfo(t) {
1041
+ return {
1042
+ id: t.id,
1043
+ name: t.name,
1044
+ ...t.description ? { description: t.description } : {},
1045
+ ...t.color ? { color: t.color } : {},
1046
+ enabled: t.is_enabled
1047
+ };
1048
+ }
1049
+ /** The GitHub implementation of the `issues` capability, backed by GitHub Issues and status labels. */
124
1050
  var GitHubIssues = class {
125
1051
  client;
1052
+ /** Capability key, always `"issues"`. */
126
1053
  key = "issues";
1054
+ /** Provider name, always `"github"`. */
127
1055
  providerName = "github";
128
1056
  owner;
129
1057
  repoName;
130
1058
  repo;
131
1059
  labels;
1060
+ kinds;
1061
+ orgClient;
132
1062
  constructor(client, opts) {
133
1063
  this.client = client;
134
1064
  const [owner = "", repoName = ""] = opts.repo.split("/", 2);
@@ -136,6 +1066,8 @@ var GitHubIssues = class {
136
1066
  this.repoName = repoName;
137
1067
  this.repo = opts.repo;
138
1068
  this.labels = opts.labels;
1069
+ this.kinds = kindNames(opts.issueTypes);
1070
+ this.orgClient = opts.orgClient;
139
1071
  }
140
1072
  async getMyself() {
141
1073
  const raw = await this.client.user.getCurrentUser();
@@ -145,7 +1077,18 @@ var GitHubIssues = class {
145
1077
  ...raw.email ? { emailAddress: raw.email } : {}
146
1078
  };
147
1079
  }
1080
+ /**
1081
+ * Searches the repo's issues, newest update first, leaving out pull requests.
1082
+ *
1083
+ * With `filter.text`, the issues are paged (newest update first, 100 a page, at most 20 pages) and compared
1084
+ * client-side, without regard to case, until `limit` matches are found or the issues run out. GitHub's issue
1085
+ * search (`GET /search/issues`) is deliberately not used: it indexes the words of a body, so punctuation and an
1086
+ * HTML comment such as `<!-- holocron:idea notes/a.md -->` cannot be relied on to match, it is limited to 30
1087
+ * requests a minute and it is eventually consistent (an issue made a moment ago may be missing). Paging has none
1088
+ * of those limits, at the cost of reading up to 20 pages of a very large repository.
1089
+ */
148
1090
  async search(filter) {
1091
+ if (filter.text) return this.searchText(filter, filter.text);
149
1092
  const params = {
150
1093
  state: filter.openOnly ? "open" : "all",
151
1094
  sort: "updated",
@@ -164,17 +1107,71 @@ var GitHubIssues = class {
164
1107
  assignee: params.assignee
165
1108
  })).filter((i) => !i.pull_request).map((i) => this.mapIssue(i));
166
1109
  }
1110
+ async searchText(filter, text) {
1111
+ const needle = text.toLowerCase();
1112
+ const limit = filter.limit ?? 50;
1113
+ const assignee = filter.assignee === "currentUser" ? (await this.getMyself()).id : filter.assignee || void 0;
1114
+ const found = [];
1115
+ for (let page = 1; page <= TEXT_MAX_PAGES; page++) {
1116
+ const raw = await this.client.issues.listIssues(this.repo, {
1117
+ state: filter.openOnly ? "open" : "all",
1118
+ sort: "updated",
1119
+ direction: "desc",
1120
+ per_page: TEXT_PAGE_SIZE,
1121
+ page,
1122
+ filter: "all",
1123
+ ...assignee ? { assignee } : {}
1124
+ });
1125
+ for (const issue of raw) {
1126
+ if (issue.pull_request) continue;
1127
+ if (`${issue.title}\n${issue.body ?? ""}`.toLowerCase().includes(needle)) {
1128
+ found.push(this.mapIssue(issue));
1129
+ if (found.length >= limit) return found;
1130
+ }
1131
+ }
1132
+ if (raw.length < TEXT_PAGE_SIZE) break;
1133
+ }
1134
+ return found;
1135
+ }
1136
+ /** Fetches one issue by its key. */
167
1137
  async get(key) {
168
1138
  const number = parseIssueNumber(key, this.owner, this.repoName);
169
1139
  const raw = await this.client.issues.getIssue(this.repo, number);
170
1140
  return this.mapIssue(raw);
171
1141
  }
1142
+ /**
1143
+ * Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. Type, Priority,
1144
+ * Effort, the dates, the parent and the blockers are set after the issue exists; what GitHub refuses of them comes
1145
+ * back in `dropped`, never as a failure, because the issue is made by then and its key must not be lost.
1146
+ */
172
1147
  async create(input) {
173
1148
  const body = { title: input.summary };
1149
+ if (input.assignees?.length) {
1150
+ const isMe = (a) => /^@?me$/i.test(a);
1151
+ const me = input.assignees.some(isMe) ? (await this.getMyself()).id : void 0;
1152
+ body.assignees = [...new Set(input.assignees.map((a) => isMe(a) && me ? me : a.replace(/^@/, "")))];
1153
+ }
174
1154
  if (input.body) body.body = input.body;
175
1155
  if (input.labels?.length) body.labels = input.labels;
176
1156
  if (input.milestone) body.milestone = await this.resolveMilestone(input.milestone);
177
- return { key: `#${(await this.client.issues.createIssue(this.repo, body)).number}` };
1157
+ const raw = await this.client.issues.createIssue(this.repo, body);
1158
+ const key = `#${raw.number}`;
1159
+ const fields = await applyIssueFields(this.fieldContext(), raw, input, true).catch((err) => ({
1160
+ changed: [],
1161
+ dropped: [`fields (not set: ${err.message})`]
1162
+ }));
1163
+ return {
1164
+ key,
1165
+ ...fields.dropped.length > 0 ? { dropped: fields.dropped } : {}
1166
+ };
1167
+ }
1168
+ /** Changes an issue; see {@link updateGitHubIssue}. */
1169
+ update(key, patch) {
1170
+ return updateGitHubIssue({
1171
+ ...this.fieldContext(),
1172
+ myLogin: async () => (await this.getMyself()).id,
1173
+ resolveMilestone: (ref) => this.resolveMilestone(ref)
1174
+ }, key, patch);
178
1175
  }
179
1176
  async transition(key, slot) {
180
1177
  const number = parseIssueNumber(key, this.owner, this.repoName);
@@ -216,10 +1213,12 @@ var GitHubIssues = class {
216
1213
  via: `label set to ${targetLabel}`
217
1214
  };
218
1215
  }
1216
+ /** Adds a comment to the issue with the given key. */
219
1217
  async comment(key, body) {
220
1218
  const number = parseIssueNumber(key, this.owner, this.repoName);
221
1219
  await this.client.issues.createComment(this.repo, number, body);
222
1220
  }
1221
+ /** Checks the authenticated user, the repo and the label-backed lifecycle slots, and reports what resolves. */
223
1222
  async doctor() {
224
1223
  const me = await this.getMyself();
225
1224
  const repo = await this.client.repos.getRepo(this.repo);
@@ -288,6 +1287,58 @@ var GitHubIssues = class {
288
1287
  lifecycle
289
1288
  };
290
1289
  }
1290
+ /** Reads issues with their comments, priority label, parent and blockers, for `holocron migrate`. */
1291
+ export(selector, info) {
1292
+ return exportIssues(this.client, this.repo, selector, info, this.kinds);
1293
+ }
1294
+ /** Makes the records as issues; one already made by an earlier run is skipped. */
1295
+ import(records, options) {
1296
+ return importIssues(this.client, this.repo, records, options, this.kinds);
1297
+ }
1298
+ /** Like `import`, and it also updates what an earlier import or sync made, for `holocron sync issues`. */
1299
+ sync(records, options) {
1300
+ return syncIssues(this.client, this.repo, records, options, this.kinds);
1301
+ }
1302
+ async listTypes() {
1303
+ const client = this.orgClient?.();
1304
+ return client ? (await client.issueTypes.list(this.owner)).map(toTypeInfo) : void 0;
1305
+ }
1306
+ async createType(type) {
1307
+ const client = this.orgClient?.();
1308
+ if (!client) throw new Error("no organization token (HOLOCRON_ORG_TOKEN) to make an issue Type with");
1309
+ return toTypeInfo(await client.issueTypes.create(this.owner, {
1310
+ name: type.name,
1311
+ is_enabled: type.enabled ?? true,
1312
+ ...type.description !== void 0 ? { description: type.description } : {},
1313
+ ...type.color !== void 0 ? { color: type.color } : {}
1314
+ }));
1315
+ }
1316
+ async updateType(id, patch) {
1317
+ const client = this.orgClient?.();
1318
+ if (!client) throw new Error("no organization token (HOLOCRON_ORG_TOKEN) to change an issue Type with");
1319
+ const current = (await client.issueTypes.list(this.owner)).find((t) => String(t.id) === String(id));
1320
+ if (!current) throw new Error(`the organization has no issue Type with id ${id}`);
1321
+ const description = patch.description ?? current.description;
1322
+ const color = patch.color ?? current.color;
1323
+ await client.issueTypes.update(this.owner, current.id, {
1324
+ name: current.name,
1325
+ is_enabled: current.is_enabled,
1326
+ ...description != null ? { description } : {},
1327
+ ...color != null ? { color } : {}
1328
+ });
1329
+ }
1330
+ fieldSetter;
1331
+ /** What the field writers need; the setter is shared so the organization's field list is read once. */
1332
+ fieldContext() {
1333
+ this.fieldSetter ??= createFieldSetter(this.client, this.repo);
1334
+ return {
1335
+ client: this.client,
1336
+ repo: this.repo,
1337
+ parseKey: (k) => parseIssueNumber(k, this.owner, this.repoName),
1338
+ fields: this.fieldSetter,
1339
+ kinds: this.kinds
1340
+ };
1341
+ }
291
1342
  async resolveMilestone(ref) {
292
1343
  if (/^\d+$/.test(ref)) return parseInt(ref, 10);
293
1344
  const match = (await this.client.issues.listMilestones(this.repo, { state: "all" })).find((m) => m.title.toLowerCase() === ref.toLowerCase());
@@ -337,79 +1388,887 @@ function parseIssueNumber(key, owner, repoName) {
337
1388
  if (!/^\d+$/.test(num)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
338
1389
  return parseInt(num, 10);
339
1390
  }
340
- //#endregion
341
- //#region src/sodium.ts
1391
+ // src/capabilities/required-board-checks.ts
342
1392
  /**
343
- * libsodium sealed-box encryption for GitHub Actions secrets.
344
- *
345
- * GitHub stores Actions / Codespaces / Dependabot secrets encrypted
346
- * with a curve25519 public key (returned by the `/actions/secrets/public-key`
347
- * endpoint). Callers fetch that key, encrypt the plaintext value with
348
- * `crypto_box_seal`, then PUT the base64-encoded ciphertext + `key_id`.
349
- *
350
- * Reference: https://docs.github.com/en/rest/actions/secrets#create-or-update-a-repository-secret
351
- *
352
- * **Why createRequire?** `libsodium-wrappers@0.7.x` ships a broken
353
- * ESM bundle — the `dist/modules-esm/libsodium-wrappers.mjs` entry
354
- * imports a sibling `libsodium.mjs` that isn't included in the npm
355
- * tarball. Native `import` against the package therefore fails.
356
- * `createRequire` routes through Node's CJS resolver, which honors
357
- * the `"require"` condition in the package's exports map and loads
358
- * the self-contained CJS bundle instead. Same API, working module.
1393
+ * The state of a pull request's required checks on its head commit, for a repo with no `ci / Required checks`
1394
+ * aggregate. The rule is the CLI's `requiredChecksVerdict()`, the one `close work` uses: a required check that has not
1395
+ * posted or whose newest run is unfinished or cancelled is `pending`, a failed one is `failure`, and an empty list is
1396
+ * `none` (unknown, never green) with no read at all.
359
1397
  */
360
- const sodium = createRequire(import.meta.url)("libsodium-wrappers");
1398
+ async function requiredBoardChecks(read, repo, sha, required) {
1399
+ if (required.expected.length === 0) return "none";
1400
+ const { checkRuns, commitStatuses } = await read(repo, sha, required.statuses.length > 0);
1401
+ return requiredChecksVerdict({
1402
+ expected: required.expected,
1403
+ statuses: required.statuses,
1404
+ checkRuns,
1405
+ commitStatuses
1406
+ }).state;
1407
+ }
1408
+ // src/capabilities/project-pull-requests.ts
361
1409
  /**
362
- * Encrypt `value` for the given GitHub-provided base64 public key.
363
- * Returns the base64 ciphertext to send as `encrypted_value`.
1410
+ * One issue's closing pull requests and the aggregate check on each one's newest commit. It is its own small query,
1411
+ * never part of the board's items query: nested under `items(first: 100)` it multiplies past GitHub's resource limit.
364
1412
  */
365
- async function encryptSecret(publicKeyBase64, value) {
366
- await sodium.ready;
367
- const publicKey = sodium.from_base64(publicKeyBase64, sodium.base64_variants.ORIGINAL);
368
- const plaintext = sodium.from_string(value);
369
- const ciphertext = sodium.crypto_box_seal(plaintext, publicKey);
370
- return sodium.to_base64(ciphertext, sodium.base64_variants.ORIGINAL);
1413
+ const CLOSING_QUERY = `query($id: ID!) { node(id: $id) { ... on Issue {
1414
+ closedByPullRequestsReferences(first: 5, includeClosedPrs: true) { nodes {
1415
+ number state isDraft repository { nameWithOwner }
1416
+ commits(last: 1) { nodes { commit { checkSuites(first: 30) { nodes {
1417
+ checkRuns(first: 5, filterBy: { checkName: "${AGGREGATE_CHECK_NAME}" }) { nodes { databaseId status conclusion startedAt } }
1418
+ } } } } }
1419
+ } }
1420
+ } } }`;
1421
+ /**
1422
+ * The same read for a repo with no aggregate: the pull requests and their head commit, whose check runs and statuses
1423
+ * are then read through REST (a commit's check suites are too many to nest here).
1424
+ */
1425
+ const CLOSING_REQUIRED_QUERY = `query($id: ID!) { node(id: $id) { ... on Issue {
1426
+ closedByPullRequestsReferences(first: 5, includeClosedPrs: true) { nodes {
1427
+ number state isDraft headRefOid repository { nameWithOwner }
1428
+ } }
1429
+ } } }`;
1430
+ const FAILED$1 = /* @__PURE__ */ new Set([
1431
+ "FAILURE",
1432
+ "TIMED_OUT",
1433
+ "STARTUP_FAILURE",
1434
+ "ACTION_REQUIRED",
1435
+ "STALE"
1436
+ ]);
1437
+ /**
1438
+ * The state of the aggregate check from the runs of that name on one commit. Only the newest run counts (latest
1439
+ * `startedAt`, then id), so a cancelled first batch or a re-run that went green does not hold the verdict red. A run
1440
+ * that is not finished, or that was cancelled, is `pending`; one with no verdict (neutral, skipped) or none posted is `none`.
1441
+ */
1442
+ function aggregateChecks(runs) {
1443
+ const newest = [...runs].sort((a, b) => (b.startedAt ?? "").localeCompare(a.startedAt ?? "") || b.databaseId - a.databaseId)[0];
1444
+ if (!newest) return "none";
1445
+ if (newest.status !== "COMPLETED") return "pending";
1446
+ if (newest.conclusion === "SUCCESS") return "success";
1447
+ if (newest.conclusion && FAILED$1.has(newest.conclusion)) return "failure";
1448
+ if (newest.conclusion === "CANCELLED") return "pending";
1449
+ return "none";
371
1450
  }
372
- //#endregion
373
- //#region src/capabilities/secrets.ts
374
- var GitHubSecrets = class {
375
- client;
376
- opts;
377
- key = "secrets";
378
- providerName = "github";
379
- constructor(client, opts) {
380
- this.client = client;
381
- this.opts = opts;
382
- }
383
- async listSecrets(scope) {
384
- return this.client.secrets.listSecrets(this.opts.repo, toGHScope(scope));
385
- }
386
- async setSecret(scope, name, value) {
387
- const ghScope = toGHScope(scope);
388
- const pk = await this.client.secrets.getPublicKey(this.opts.repo, ghScope);
389
- const body = {
390
- encrypted_value: await encryptSecret(pk.key, value),
391
- key_id: pk.key_id
1451
+ /** The neutral pull requests an issue is closed by; only an open one has its checks read, the others are `none`. */
1452
+ function toBoardPullRequests(nodes, keyOf) {
1453
+ return nodes.map((pr) => {
1454
+ const state = pr.state === "OPEN" ? "open" : pr.state === "MERGED" ? "merged" : "closed";
1455
+ const runs = (pr.commits?.nodes ?? []).flatMap((c) => c.commit.checkSuites.nodes.flatMap((suite) => suite.checkRuns.nodes));
1456
+ return {
1457
+ key: keyOf(pr.repository.nameWithOwner, pr.number),
1458
+ state,
1459
+ draft: pr.isDraft,
1460
+ checks: state === "open" ? aggregateChecks(runs) : "none"
392
1461
  };
393
- if (scope.kind === "organization") body.visibility = "all";
394
- await this.client.secrets.putSecret(this.opts.repo, ghScope, name, body);
395
- }
396
- async deleteSecret(scope, name) {
397
- await this.client.secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
1462
+ });
1463
+ }
1464
+ /**
1465
+ * Like {@link toBoardPullRequests} for a repo with no aggregate: an open pull request's `checks` is the verdict of the
1466
+ * required checks on its head commit (one read each); a merged or closed one is `none` and is not read.
1467
+ */
1468
+ function toRequiredBoardPullRequests(nodes, keyOf, input) {
1469
+ return Promise.all(nodes.map(async (pr) => {
1470
+ const state = pr.state === "OPEN" ? "open" : pr.state === "MERGED" ? "merged" : "closed";
1471
+ return {
1472
+ key: keyOf(pr.repository.nameWithOwner, pr.number),
1473
+ state,
1474
+ draft: pr.isDraft,
1475
+ checks: state === "open" ? await requiredBoardChecks(input.read, pr.repository.nameWithOwner, pr.headRefOid, input.required) : "none"
1476
+ };
1477
+ }));
1478
+ }
1479
+ /**
1480
+ * Reads the closing pull requests of each issue (by node id) with one small query per issue, a few at a time. A query
1481
+ * that fails is that issue's `problem` and nothing else: the others are read, and the caller leaves the failed one's
1482
+ * pull-request rules unapplied. With `requiredInput` (a repo with no aggregate) each open pull request's `checks` is
1483
+ * the verdict of the required checks on its head commit instead of the aggregate's state.
1484
+ */
1485
+ async function readClosingPullRequests(graphql, contentIds, keyOf, requiredInput) {
1486
+ const results = /* @__PURE__ */ new Map();
1487
+ let next = 0;
1488
+ const worker = async () => {
1489
+ for (let i = next++; i < contentIds.length; i = next++) {
1490
+ const id = contentIds[i];
1491
+ try {
1492
+ const nodes = (await graphql.query(requiredInput ? CLOSING_REQUIRED_QUERY : CLOSING_QUERY, { id })).node?.closedByPullRequestsReferences?.nodes;
1493
+ results.set(id, nodes ? { pullRequests: requiredInput ? await toRequiredBoardPullRequests(nodes, keyOf, requiredInput) : toBoardPullRequests(nodes, keyOf) } : { problem: "GitHub returned no pull request list" });
1494
+ } catch (err) {
1495
+ results.set(id, { problem: err instanceof Error ? err.message : String(err) });
1496
+ }
1497
+ }
1498
+ };
1499
+ await Promise.all(Array.from({ length: Math.min(4, contentIds.length) }, worker));
1500
+ return results;
1501
+ }
1502
+ // src/capabilities/projects.ts
1503
+ /** The name of the single select field that holds an item's status. */
1504
+ const STATUS_FIELD = "Status";
1505
+ /** The name of the field `move` carries over besides the status. */
1506
+ const PRIORITY_FIELD = "Priority";
1507
+ const P_LEVELS = {
1508
+ p0: "urgent",
1509
+ p1: "high",
1510
+ p2: "medium",
1511
+ p3: "low"
1512
+ };
1513
+ /** The neutral priority a `Priority` option stands for, by its name; undefined for a name that is not one of them. */
1514
+ function priorityOf(value) {
1515
+ const name = value?.trim().toLowerCase();
1516
+ if (name === "urgent" || name === "high" || name === "medium" || name === "low") return name;
1517
+ return name ? P_LEVELS[name] : void 0;
1518
+ }
1519
+ const PROJECT_FIELDS = "id number title closed url";
1520
+ const BOARD_QUERY = `query($id: ID!) { node(id: $id) { ... on ProjectV2 {
1521
+ ${PROJECT_FIELDS}
1522
+ fields(first: 100) { nodes {
1523
+ ... on ProjectV2FieldCommon { id name dataType }
1524
+ ... on ProjectV2SingleSelectField { options { id name color description } }
1525
+ } }
1526
+ views(first: 50) { nodes { id name layout filter groupByFields(first: 5) { nodes { ... on ProjectV2FieldCommon { name } } } } }
1527
+ workflows(first: 50) { nodes { id name enabled } }
1528
+ } } }`;
1529
+ const ITEMS_QUERY = `query($id: ID!, $after: String) { node(id: $id) { ... on ProjectV2 {
1530
+ items(first: 100, after: $after) {
1531
+ pageInfo { hasNextPage endCursor }
1532
+ nodes {
1533
+ id
1534
+ fieldValues(first: 30) { nodes { ... on ProjectV2ItemFieldSingleSelectValue { name field { ... on ProjectV2FieldCommon { name } } } } }
1535
+ content {
1536
+ __typename
1537
+ ... on Issue { id number title state repository { nameWithOwner } blockedBy(first: 50) { nodes { number state repository { nameWithOwner } } } }
1538
+ ... on PullRequest { id number title state repository { nameWithOwner } }
1539
+ }
1540
+ }
398
1541
  }
1542
+ } } }`;
1543
+ const LIST_QUERY = `query($owner: String!, $after: String) { organization(login: $owner) { id projectsV2(first: 100, after: $after) {
1544
+ pageInfo { hasNextPage endCursor }
1545
+ nodes { ${PROJECT_FIELDS} }
1546
+ } } }`;
1547
+ const OWNER_QUERY = "query($owner: String!) { organization(login: $owner) { id } }";
1548
+ const SET_VALUE = `mutation($project: ID!, $item: ID!, $field: ID!, $option: String!) {
1549
+ updateProjectV2ItemFieldValue(input: { projectId: $project, itemId: $item, fieldId: $field, value: { singleSelectOptionId: $option } }) { projectV2Item { id } }
1550
+ }`;
1551
+ const UPDATE_OPTIONS = `mutation($field: ID!, $options: [ProjectV2SingleSelectFieldOptionInput!]!) {
1552
+ updateProjectV2Field(input: { fieldId: $field, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
1553
+ }`;
1554
+ const DATA_TYPES = {
1555
+ single_select: "SINGLE_SELECT",
1556
+ text: "TEXT",
1557
+ number: "NUMBER",
1558
+ date: "DATE",
1559
+ iteration: "ITERATION"
399
1560
  };
400
- function toGHScope(scope) {
401
- if (scope.kind === "organization") return {
402
- kind: "organization",
403
- org: scope.name
1561
+ function fieldTypeOf(dataType) {
1562
+ return Object.keys(DATA_TYPES).find((t) => DATA_TYPES[t] === dataType);
1563
+ }
1564
+ function toSummary(n) {
1565
+ return {
1566
+ id: n.id,
1567
+ number: n.number,
1568
+ name: n.title,
1569
+ url: n.url,
1570
+ closed: n.closed
404
1571
  };
405
- return scope;
406
1572
  }
407
- //#endregion
408
- //#region src/capabilities/labels.ts
409
- /**
410
- * Idempotently synchronise a repo's labels to the canonical set.
411
- *
412
- * - Creates labels that are missing.
1573
+ function toOptionInput(o) {
1574
+ return {
1575
+ ...o.id ? { id: o.id } : {},
1576
+ name: o.name,
1577
+ color: (o.color ?? "GRAY").toUpperCase(),
1578
+ description: o.description ?? ""
1579
+ };
1580
+ }
1581
+ /** The GitHub implementation of the `projects` capability, backed by Projects v2. */
1582
+ var GitHubProjects = class {
1583
+ graphql;
1584
+ readCommitChecks;
1585
+ /** Capability key, always `"projects"`. */
1586
+ key = "projects";
1587
+ /** Provider name, always `"github"`. */
1588
+ providerName = "github";
1589
+ repo;
1590
+ constructor(graphql, opts, readCommitChecks) {
1591
+ this.graphql = graphql;
1592
+ this.readCommitChecks = readCommitChecks;
1593
+ this.repo = opts.repo;
1594
+ }
1595
+ /** Every board of the organization, open and closed. */
1596
+ async list(owner) {
1597
+ const boards = [];
1598
+ let after = null;
1599
+ for (;;) {
1600
+ const page = (await this.graphql.query(LIST_QUERY, {
1601
+ owner,
1602
+ after
1603
+ })).organization.projectsV2;
1604
+ boards.push(...page.nodes.map(toSummary));
1605
+ if (!page.pageInfo.hasNextPage) return boards;
1606
+ after = page.pageInfo.endCursor;
1607
+ }
1608
+ }
1609
+ /** The open board with exactly this name. */
1610
+ async find(owner, name) {
1611
+ return (await this.list(owner)).find((b) => !b.closed && b.name === name);
1612
+ }
1613
+ /**
1614
+ * Makes a board. With `template.source` naming an open board it is copied (fields, options, views and automation
1615
+ * rules, no items); otherwise the board is created and brought in line with the template.
1616
+ */
1617
+ async create(owner, name, template) {
1618
+ const ownerId = await this.ownerId(owner);
1619
+ const source = template.source ? await this.find(owner, template.source) : void 0;
1620
+ if (source) return toSummary((await this.graphql.query(`mutation($project: ID!, $owner: ID!, $title: String!) {
1621
+ copyProjectV2(input: { projectId: $project, ownerId: $owner, title: $title, includeDraftIssues: false }) { projectV2 { ${PROJECT_FIELDS} } }
1622
+ }`, {
1623
+ project: source.id,
1624
+ owner: ownerId,
1625
+ title: name
1626
+ })).copyProjectV2.projectV2);
1627
+ const board = toSummary((await this.graphql.query(`mutation($owner: ID!, $title: String!) {
1628
+ createProjectV2(input: { ownerId: $owner, title: $title }) { projectV2 { ${PROJECT_FIELDS} } }
1629
+ }`, {
1630
+ owner: ownerId,
1631
+ title: name
1632
+ })).createProjectV2.projectV2);
1633
+ await this.ensure(owner, board, template);
1634
+ return board;
1635
+ }
1636
+ /** Closes the board; `updateProjectV2` with `closed: true` is the only way, and reversible. */
1637
+ async close(_owner, board) {
1638
+ await this.graphql.query(`mutation($project: ID!) { updateProjectV2(input: { projectId: $project, closed: true }) { projectV2 { id } } }`, { project: board.id });
1639
+ }
1640
+ /** The live board: statuses, other fields, views and automation rules. */
1641
+ async read(_owner, board) {
1642
+ const raw = await this.readRaw(board.id);
1643
+ const status = raw.fields.find((f) => f.name === STATUS_FIELD);
1644
+ const fields = [];
1645
+ for (const f of raw.fields) {
1646
+ const type = fieldTypeOf(f.dataType);
1647
+ if (!type || f.name === STATUS_FIELD) continue;
1648
+ fields.push({
1649
+ name: f.name,
1650
+ type,
1651
+ ...f.options ? { options: f.options.map((o) => o.name) } : {}
1652
+ });
1653
+ }
1654
+ const views = [];
1655
+ for (const v of raw.views) {
1656
+ const layout = v.layout === "BOARD_LAYOUT" ? "board" : v.layout === "TABLE_LAYOUT" ? "table" : void 0;
1657
+ if (!layout) continue;
1658
+ views.push({
1659
+ name: v.name,
1660
+ layout,
1661
+ ...v.filter ? { filter: v.filter } : {},
1662
+ ...v.groupBy[0] ? { groupBy: v.groupBy[0] } : {}
1663
+ });
1664
+ }
1665
+ return {
1666
+ board: raw.summary,
1667
+ statuses: (status?.options ?? []).map((o) => o.name),
1668
+ fields,
1669
+ views,
1670
+ rules: raw.rules.map(({ name, enabled }) => ({
1671
+ name,
1672
+ enabled
1673
+ }))
1674
+ };
1675
+ }
1676
+ /**
1677
+ * Brings the board in line with the template. Never deletes a field, option or view, and never sends an option
1678
+ * list without ids. Stops (throws) when the status field cannot be read.
1679
+ */
1680
+ async ensure(_owner, board, template) {
1681
+ const raw = await this.readRaw(board.id);
1682
+ const status = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
1683
+ if (!status) throw new Error(`cannot read the "${STATUS_FIELD}" field of board "${board.name}"; stopped before any write so no item loses its status`);
1684
+ const changes = [];
1685
+ const todos = [];
1686
+ const statusChanges = await this.ensureOptions(board, status, template.statuses.map((s) => ({
1687
+ name: s.name,
1688
+ color: s.color,
1689
+ description: s.description
1690
+ })));
1691
+ changes.push(...statusChanges.map((c) => `status ${c}`));
1692
+ for (const want of template.fields) {
1693
+ const have = raw.fields.find((f) => f.name === want.name);
1694
+ if (!have) {
1695
+ await this.createField(board.id, want);
1696
+ changes.push(`field ${want.name} created`);
1697
+ continue;
1698
+ }
1699
+ if (fieldTypeOf(have.dataType) !== want.type) {
1700
+ todos.push(`field "${want.name}" is ${have.dataType} but the template says ${want.type}; change it by hand`);
1701
+ continue;
1702
+ }
1703
+ if (want.type === "single_select" && have.options && want.options) {
1704
+ const diff = await this.ensureOptions(board, have, want.options.map((name) => ({ name })));
1705
+ changes.push(...diff.map((c) => `field ${want.name} option ${c}`));
1706
+ }
1707
+ }
1708
+ for (const want of template.views) {
1709
+ const have = raw.views.find((v) => v.name === want.name);
1710
+ const layout = want.layout === "board" ? "BOARD_LAYOUT" : "TABLE_LAYOUT";
1711
+ let viewId = have?.id;
1712
+ if (!viewId) {
1713
+ viewId = await this.createView(board.id, want.name, layout);
1714
+ changes.push(`view ${want.name} created`);
1715
+ } else if (have && have.layout !== layout) {
1716
+ await this.updateView(viewId, { layout });
1717
+ changes.push(`view ${want.name} layout set to ${want.layout}`);
1718
+ }
1719
+ if (want.filter !== void 0 && want.filter !== (have?.filter ?? "")) {
1720
+ await this.updateView(viewId, { filter: want.filter });
1721
+ changes.push(`view ${want.name} filter set`);
1722
+ }
1723
+ if (want.groupBy && have?.groupBy[0] !== want.groupBy) todos.push(`group view "${want.name}" by ${want.groupBy}; the API cannot set a view's grouping`);
1724
+ }
1725
+ for (const rule of template.rules ?? []) {
1726
+ const have = raw.rules.find((r) => r.name === rule);
1727
+ if (!have) todos.push(`create the automation rule "${rule}"; the API cannot create one`);
1728
+ else if (!have.enabled) todos.push(`turn on the automation rule "${rule}"; the API cannot switch one`);
1729
+ }
1730
+ return {
1731
+ created: false,
1732
+ changes,
1733
+ todos
1734
+ };
1735
+ }
1736
+ /**
1737
+ * Makes a single select field hold the wanted options in order, every existing one sent with its id. Options the
1738
+ * template does not mention stay, after the wanted ones. Returns what changed (`Blocked added`, `order set`).
1739
+ */
1740
+ async ensureOptions(board, field, wanted) {
1741
+ /* v8 ignore next -- every caller passes a field it found with options; the fallback only satisfies the type */
1742
+ const existing = field.options ?? [];
1743
+ const next = [];
1744
+ const changes = [];
1745
+ for (const w of wanted) {
1746
+ const have = existing.find((o) => o.name === w.name);
1747
+ if (have) {
1748
+ next.push({
1749
+ id: have.id,
1750
+ name: have.name,
1751
+ color: (w.color ?? have.color).toUpperCase(),
1752
+ description: w.description ?? have.description
1753
+ });
1754
+ if (next[next.length - 1].color !== have.color || next[next.length - 1].description !== have.description) changes.push(`${have.name} updated`);
1755
+ } else {
1756
+ next.push({
1757
+ name: w.name,
1758
+ color: (w.color ?? "GRAY").toUpperCase(),
1759
+ description: w.description ?? ""
1760
+ });
1761
+ changes.push(`${w.name} added`);
1762
+ }
1763
+ }
1764
+ for (const have of existing) if (!next.some((n) => n.id === have.id)) next.push({ ...have });
1765
+ const sameOrder = next.length === existing.length && next.every((n, i) => n.id === existing[i]?.id);
1766
+ if (changes.length === 0 && sameOrder) return [];
1767
+ if (sameOrder === false && !changes.some((c) => c.endsWith("added"))) changes.push("order set");
1768
+ const before = await this.fetchItems(board.id);
1769
+ const snapshot = /* @__PURE__ */ new Map();
1770
+ for (const item of before) {
1771
+ const value = item.values[field.name];
1772
+ if (value) snapshot.set(item.id, value);
1773
+ }
1774
+ await this.graphql.query(UPDATE_OPTIONS, {
1775
+ field: field.id,
1776
+ options: next.map(toOptionInput)
1777
+ });
1778
+ const afterField = (await this.readRaw(board.id)).fields.find((f) => f.id === field.id);
1779
+ const afterItems = await this.fetchItems(board.id);
1780
+ const afterValues = new Map(afterItems.map((i) => [i.id, i.values[field.name]]));
1781
+ const lost = [...snapshot].filter(([itemId]) => !afterValues.get(itemId));
1782
+ if (lost.length > 0) {
1783
+ let restored = 0;
1784
+ for (const [itemId, name] of lost) {
1785
+ const option = afterField?.options?.find((o) => o.name === name);
1786
+ if (!option) continue;
1787
+ await this.graphql.query(SET_VALUE, {
1788
+ project: board.id,
1789
+ item: itemId,
1790
+ field: field.id,
1791
+ option: option.id
1792
+ });
1793
+ restored++;
1794
+ }
1795
+ throw new Error(`updating "${field.name}" on board "${board.name}" blanked ${lost.length} item value(s); wrote ${restored} back by option name`);
1796
+ }
1797
+ return changes;
1798
+ }
1799
+ async createField(projectId, want) {
1800
+ await this.graphql.query(`mutation($project: ID!, $name: String!, $type: ProjectV2CustomFieldType!, $options: [ProjectV2SingleSelectFieldOptionInput!]) {
1801
+ createProjectV2Field(input: { projectId: $project, name: $name, dataType: $type, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
1802
+ }`, {
1803
+ project: projectId,
1804
+ name: want.name,
1805
+ type: DATA_TYPES[want.type],
1806
+ options: want.type === "single_select" ? (want.options ?? []).map((name) => toOptionInput({ name })) : void 0
1807
+ });
1808
+ }
1809
+ async createView(projectId, name, layout) {
1810
+ return (await this.graphql.query(`mutation($project: ID!, $name: String!, $layout: ProjectV2ViewLayout!) {
1811
+ createProjectV2View(input: { projectId: $project, name: $name, layout: $layout }) { projectV2View { id } }
1812
+ }`, {
1813
+ project: projectId,
1814
+ name,
1815
+ layout
1816
+ })).createProjectV2View.projectV2View.id;
1817
+ }
1818
+ async updateView(viewId, change) {
1819
+ await this.graphql.query(`mutation($view: ID!, $layout: ProjectV2ViewLayout, $filter: String) {
1820
+ updateProjectV2View(input: { viewId: $view, layout: $layout, filter: $filter }) { projectV2View { id } }
1821
+ }`, {
1822
+ view: viewId,
1823
+ layout: change.layout,
1824
+ filter: change.filter
1825
+ });
1826
+ }
1827
+ /**
1828
+ * The board's issues and pull requests with their status, whether they are open and their open blockers. A second step
1829
+ * then reads, one small query per issue, the pull requests that close each open issue a rule could still move (it has a
1830
+ * status that is not `done` or `blocked` and no open blocker), each with the aggregate `ci / Required checks` state of
1831
+ * its head commit. An issue whose read fails keeps no `pullRequests` and carries `pullRequestsProblem` instead.
1832
+ *
1833
+ * With `required` (a repo with no aggregate) each open pull request's `checks` is the verdict of those required
1834
+ * checks on its head commit, read with one check-runs list per pull request (and its statuses only when a required
1835
+ * context may be one); without it the read is the aggregate's, exactly as before.
1836
+ */
1837
+ async items(_owner, board, template, required) {
1838
+ if (required && !this.readCommitChecks) throw new Error("this GitHub projects provider was built without a way to read a commit's checks");
1839
+ const categories = new Map(template.statuses.map((s) => [s.name, s.category]));
1840
+ const raw = await this.fetchItems(board.id);
1841
+ const wanted = raw.filter((i) => {
1842
+ const status = i.values[STATUS_FIELD];
1843
+ const category = status ? categories.get(status) : void 0;
1844
+ return i.issue && i.open && status !== void 0 && i.blockers.length === 0 && category !== "done" && category !== "blocked";
1845
+ });
1846
+ const closing = await readClosingPullRequests(this.graphql, wanted.map((i) => i.contentId), (r, n) => this.keyOf(r, n), required && this.readCommitChecks ? {
1847
+ required,
1848
+ read: this.readCommitChecks
1849
+ } : void 0);
1850
+ return raw.map((i) => {
1851
+ const read = closing.get(i.contentId);
1852
+ const status = i.values[STATUS_FIELD];
1853
+ const category = status ? categories.get(status) : void 0;
1854
+ const priority = priorityOf(i.values[PRIORITY_FIELD]);
1855
+ return {
1856
+ key: this.keyOf(i.repo, i.number),
1857
+ title: i.title,
1858
+ open: i.open,
1859
+ ...status ? { status } : {},
1860
+ ...category ? { category } : {},
1861
+ blockedBy: i.blockers.map((b) => this.keyOf(b.repo, b.number)),
1862
+ ...priority ? { priority } : {},
1863
+ ...read && "pullRequests" in read ? { pullRequests: read.pullRequests } : {},
1864
+ ...read && "problem" in read ? { pullRequestsProblem: read.problem } : {}
1865
+ };
1866
+ });
1867
+ }
1868
+ /** Puts an item in a status; `transitioned` is false when it already is there. */
1869
+ async setStatus(_owner, board, key, status) {
1870
+ const ref = this.parseKey(key);
1871
+ const field = (await this.readRaw(board.id)).fields.find((f) => f.name === STATUS_FIELD && f.options);
1872
+ const option = field?.options?.find((o) => o.name === status);
1873
+ if (!field || !option) throw new Error(`board "${board.name}" has no status "${status}"`);
1874
+ const item = (await this.fetchItems(board.id)).find((i) => i.repo === ref.repo && i.number === ref.number);
1875
+ if (!item) throw new Error(`${key} is not on board "${board.name}"`);
1876
+ if (item.values[STATUS_FIELD] === status) return {
1877
+ transitioned: false,
1878
+ status
1879
+ };
1880
+ await this.graphql.query(SET_VALUE, {
1881
+ project: board.id,
1882
+ item: item.id,
1883
+ field: field.id,
1884
+ option: option.id
1885
+ });
1886
+ return {
1887
+ transitioned: true,
1888
+ status,
1889
+ via: "project field set"
1890
+ };
1891
+ }
1892
+ /**
1893
+ * Puts the open items of `from` on `to` with their status and priority, only where the target has no value;
1894
+ * closed and merged ones stay, and are set to the template's done status when theirs is not a done one.
1895
+ */
1896
+ async move(_owner, from, to, template) {
1897
+ const report = {
1898
+ moved: [],
1899
+ kept: [],
1900
+ left: []
1901
+ };
1902
+ const [source, target, fromRaw, toRaw] = await Promise.all([
1903
+ this.fetchItems(from.id),
1904
+ this.fetchItems(to.id),
1905
+ this.readRaw(from.id),
1906
+ this.readRaw(to.id)
1907
+ ]);
1908
+ const done = template.statuses.find((s) => s.category === "done")?.name;
1909
+ const doneNames = new Set(template.statuses.filter((s) => s.category === "done").map((s) => s.name));
1910
+ const carried = [STATUS_FIELD, PRIORITY_FIELD];
1911
+ for (const item of source) {
1912
+ const key = this.keyOf(item.repo, item.number);
1913
+ if (!item.open) {
1914
+ const current = item.values[STATUS_FIELD];
1915
+ if (done && (!current || !doneNames.has(current))) await this.setOption(from.id, fromRaw, item.id, STATUS_FIELD, done);
1916
+ report.left.push(key);
1917
+ continue;
1918
+ }
1919
+ let targetItem = target.find((t) => t.contentId === item.contentId);
1920
+ if (targetItem) report.kept.push(key);
1921
+ else {
1922
+ const data = await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
1923
+ project: to.id,
1924
+ content: item.contentId
1925
+ });
1926
+ targetItem = {
1927
+ ...item,
1928
+ id: data.addProjectV2ItemById.item.id,
1929
+ values: {}
1930
+ };
1931
+ report.moved.push(key);
1932
+ }
1933
+ for (const name of carried) {
1934
+ const value = item.values[name];
1935
+ if (value && !targetItem.values[name]) await this.setOption(to.id, toRaw, targetItem.id, name, value);
1936
+ }
1937
+ }
1938
+ return report;
1939
+ }
1940
+ /**
1941
+ * Puts issues on the board (`addProjectV2ItemById`, the content id the issue's node id) and sets Status and Priority
1942
+ * through the single select update, only where the item has no value yet. A status or priority with no option on
1943
+ * the board is reported in `dropped`; no option is ever created, so no value is cleared.
1944
+ */
1945
+ async addItems(_owner, board, items, template) {
1946
+ const raw = await this.readRaw(board.id);
1947
+ const onBoard = await this.fetchItems(board.id);
1948
+ const statusField = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
1949
+ const priorityField = raw.fields.find((f) => f.name === PRIORITY_FIELD && f.options);
1950
+ const results = [];
1951
+ for (const input of items) {
1952
+ const ref = this.parseKey(input.key);
1953
+ let current = onBoard.find((i) => i.repo === ref.repo && i.number === ref.number);
1954
+ const added = !current;
1955
+ if (!current) current = {
1956
+ id: (await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
1957
+ project: board.id,
1958
+ content: await this.nodeId(ref)
1959
+ })).addProjectV2ItemById.item.id,
1960
+ contentId: "",
1961
+ repo: ref.repo,
1962
+ number: ref.number,
1963
+ title: "",
1964
+ open: true,
1965
+ issue: false,
1966
+ values: {},
1967
+ blockers: []
1968
+ };
1969
+ const dropped = [];
1970
+ if (input.status !== void 0 || input.category !== void 0) {
1971
+ const name = this.statusFor(input, template, statusField?.options);
1972
+ if (!name) dropped.push(`status ${input.status ?? input.category} (no matching option on the board)`);
1973
+ else if (!current.values[STATUS_FIELD]) await this.setOption(board.id, raw, current.id, STATUS_FIELD, name);
1974
+ }
1975
+ if (input.priority !== void 0 && input.priority !== "none") {
1976
+ const option = priorityField?.options?.find((o) => priorityOf(o.name) === input.priority);
1977
+ if (!option) dropped.push(`priority ${input.priority} (no matching option on the board)`);
1978
+ else if (!current.values[PRIORITY_FIELD]) await this.setOption(board.id, raw, current.id, PRIORITY_FIELD, option.name);
1979
+ }
1980
+ results.push({
1981
+ key: input.key,
1982
+ added,
1983
+ dropped
1984
+ });
1985
+ }
1986
+ return results;
1987
+ }
1988
+ /** The board's own status for an input: the option named like its status, else the template's status of its category. */
1989
+ statusFor(input, template, options) {
1990
+ const has = (name) => options?.find((o) => o.name.toLowerCase() === name.toLowerCase())?.name;
1991
+ const named = input.status === void 0 ? void 0 : has(input.status);
1992
+ if (named) return named;
1993
+ const byCategory = template.statuses.find((s) => s.category === input.category);
1994
+ return byCategory ? has(byCategory.name) : void 0;
1995
+ }
1996
+ /** The node id of an issue, which `addProjectV2ItemById` takes as the content id. */
1997
+ async nodeId(ref) {
1998
+ const [owner, name] = ref.repo.split("/");
1999
+ const id = (await this.graphql.query(`query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { id } } }`, {
2000
+ owner,
2001
+ name,
2002
+ number: ref.number
2003
+ })).repository?.issue?.id;
2004
+ if (!id) throw new Error(`issue ${ref.repo}#${ref.number} not found`);
2005
+ return id;
2006
+ }
2007
+ /** A `holocron doctor` smoke check: how many boards the token sees in the configured repository's organization. */
2008
+ async whoami() {
2009
+ try {
2010
+ return {
2011
+ ok: true,
2012
+ boards: (await this.list(this.repo.split("/")[0] ?? "")).length
2013
+ };
2014
+ } catch {
2015
+ return {
2016
+ ok: false,
2017
+ boards: 0
2018
+ };
2019
+ }
2020
+ }
2021
+ /** Sets a single select value by option name; a field or option the board lacks is skipped. */
2022
+ async setOption(projectId, raw, itemId, fieldName, optionName) {
2023
+ const field = raw.fields.find((f) => f.name === fieldName && f.options);
2024
+ const option = field?.options?.find((o) => o.name === optionName);
2025
+ if (!field || !option) return;
2026
+ await this.graphql.query(SET_VALUE, {
2027
+ project: projectId,
2028
+ item: itemId,
2029
+ field: field.id,
2030
+ option: option.id
2031
+ });
2032
+ }
2033
+ async ownerId(owner) {
2034
+ return (await this.graphql.query(OWNER_QUERY, { owner })).organization.id;
2035
+ }
2036
+ async readRaw(id) {
2037
+ const n = (await this.graphql.query(BOARD_QUERY, { id })).node;
2038
+ if (!n) throw new Error(`board ${id} not found`);
2039
+ return {
2040
+ summary: toSummary(n),
2041
+ fields: n.fields.nodes.filter((f) => f.id).map((f) => ({
2042
+ id: f.id,
2043
+ name: f.name,
2044
+ dataType: f.dataType,
2045
+ ...f.options ? { options: f.options } : {}
2046
+ })),
2047
+ views: n.views.nodes.map((v) => ({
2048
+ id: v.id,
2049
+ name: v.name,
2050
+ layout: v.layout,
2051
+ filter: v.filter,
2052
+ groupBy: (v.groupByFields?.nodes ?? []).map((g) => g.name)
2053
+ })),
2054
+ rules: n.workflows.nodes.map((w) => ({
2055
+ id: w.id,
2056
+ name: w.name,
2057
+ enabled: w.enabled
2058
+ }))
2059
+ };
2060
+ }
2061
+ async fetchItems(id) {
2062
+ const items = [];
2063
+ let after = null;
2064
+ for (;;) {
2065
+ const page = (await this.graphql.query(ITEMS_QUERY, {
2066
+ id,
2067
+ after
2068
+ })).node.items;
2069
+ for (const n of page.nodes) {
2070
+ const c = n.content;
2071
+ if (!c || !c.repository) continue;
2072
+ const values = {};
2073
+ for (const v of n.fieldValues.nodes) if (v.name && v.field?.name) values[v.field.name] = v.name;
2074
+ items.push({
2075
+ id: n.id,
2076
+ contentId: c.id,
2077
+ repo: c.repository.nameWithOwner,
2078
+ number: c.number,
2079
+ title: c.title,
2080
+ open: c.state === "OPEN",
2081
+ issue: c.__typename === "Issue",
2082
+ values,
2083
+ blockers: (c.blockedBy?.nodes ?? []).filter((b) => b.state === "OPEN").map((b) => ({
2084
+ repo: b.repository.nameWithOwner,
2085
+ number: b.number
2086
+ }))
2087
+ });
2088
+ }
2089
+ if (!page.pageInfo.hasNextPage) return items;
2090
+ after = page.pageInfo.endCursor;
2091
+ }
2092
+ }
2093
+ keyOf(repo, number) {
2094
+ return repo === this.repo ? `#${number}` : `${repo}#${number}`;
2095
+ }
2096
+ parseKey(key) {
2097
+ const trimmed = key.trim();
2098
+ const hash = trimmed.lastIndexOf("#");
2099
+ const repo = hash > 0 ? trimmed.slice(0, hash) : void 0;
2100
+ const digits = trimmed.slice(hash + 1);
2101
+ if (!/^\d+$/.test(digits) || repo !== void 0 && !/^[^#\s]+$/.test(repo)) throw new Error(`not an issue key: ${key}`);
2102
+ return {
2103
+ repo: repo ?? this.repo,
2104
+ number: Number(digits)
2105
+ };
2106
+ }
2107
+ };
2108
+ // src/sodium.ts
2109
+ /**
2110
+ * libsodium sealed-box encryption for GitHub Actions secrets.
2111
+ *
2112
+ * GitHub stores Actions / Codespaces / Dependabot secrets encrypted
2113
+ * with a curve25519 public key (returned by the `/actions/secrets/public-key`
2114
+ * endpoint). Callers fetch that key, encrypt the plaintext value with
2115
+ * `crypto_box_seal`, then PUT the base64-encoded ciphertext + `key_id`.
2116
+ *
2117
+ * Reference: https://docs.github.com/en/rest/actions/secrets#create-or-update-a-repository-secret
2118
+ *
2119
+ * **Why createRequire?** `libsodium-wrappers@0.7.x` ships a broken
2120
+ * ESM bundle — the `dist/modules-esm/libsodium-wrappers.mjs` entry
2121
+ * imports a sibling `libsodium.mjs` that isn't included in the npm
2122
+ * tarball. Native `import` against the package therefore fails.
2123
+ * `createRequire` routes through Node's CJS resolver, which honors
2124
+ * the `"require"` condition in the package's exports map and loads
2125
+ * the self-contained CJS bundle instead. Same API, working module.
2126
+ */
2127
+ const sodium = createRequire(import.meta.url)("libsodium-wrappers");
2128
+ /**
2129
+ * Encrypt `value` for the given GitHub-provided base64 public key.
2130
+ * Returns the base64 ciphertext to send as `encrypted_value`.
2131
+ */
2132
+ async function encryptSecret(publicKeyBase64, value) {
2133
+ await sodium.ready;
2134
+ const publicKey = sodium.from_base64(publicKeyBase64, sodium.base64_variants.ORIGINAL);
2135
+ const plaintext = sodium.from_string(value);
2136
+ const ciphertext = sodium.crypto_box_seal(plaintext, publicKey);
2137
+ return sodium.to_base64(ciphertext, sodium.base64_variants.ORIGINAL);
2138
+ }
2139
+ // src/capabilities/secrets.ts
2140
+ /** The GitHub implementation of the `secrets` capability, covering repository, environment and organization secrets. */
2141
+ var GitHubSecrets = class {
2142
+ client;
2143
+ opts;
2144
+ orgClient;
2145
+ /** Capability key, always `"secrets"`. */
2146
+ key = "secrets";
2147
+ /** Provider name, always `"github"`. */
2148
+ providerName = "github";
2149
+ /**
2150
+ * `client` handles repo and environment scopes; `orgClient`, when given, handles
2151
+ * the organization scope. They differ when a dedicated org-only token exists:
2152
+ * it can write org secrets but not repo ones, and `github.admin` is the reverse.
2153
+ */
2154
+ constructor(client, opts, orgClient) {
2155
+ this.client = client;
2156
+ this.opts = opts;
2157
+ this.orgClient = orgClient;
2158
+ }
2159
+ /** Repository name to numeric id, so one run asks GitHub once per repository however many secrets name it. */
2160
+ repoIds = /* @__PURE__ */ new Map();
2161
+ clientFor(scope) {
2162
+ return scope.kind === "organization" ? this.orgClient ?? this.client : this.client;
2163
+ }
2164
+ async listSecrets(scope) {
2165
+ return this.clientFor(scope).secrets.listSecrets(this.opts.repo, toGHScope(scope));
2166
+ }
2167
+ async setSecret(scope, name, value) {
2168
+ const ghScope = toGHScope(scope);
2169
+ const client = this.clientFor(scope);
2170
+ const readers = scope.kind === "organization" ? await this.readers(scope) : {};
2171
+ const pk = await client.secrets.getPublicKey(this.opts.repo, ghScope);
2172
+ const body = {
2173
+ encrypted_value: await encryptSecret(pk.key, value),
2174
+ key_id: pk.key_id
2175
+ };
2176
+ Object.assign(body, readers);
2177
+ await client.secrets.putSecret(this.opts.repo, ghScope, name, body);
2178
+ }
2179
+ /**
2180
+ * Who can read each organization secret, by name (never a value): `selected` ones come with the names of their
2181
+ * repositories. Any other scope has no visibility and gives `{}`.
2182
+ */
2183
+ async listSecretAccess(scope) {
2184
+ if (scope.kind !== "organization") return {};
2185
+ const client = this.clientFor(scope);
2186
+ const found = {};
2187
+ for (const info of await client.secrets.listOrgSecretInfo(scope.name)) found[info.name] = info.visibility === "selected" ? {
2188
+ visibility: "selected",
2189
+ repos: await client.secrets.listSelectedRepositories(scope.name, info.name)
2190
+ } : { visibility: info.visibility };
2191
+ return found;
2192
+ }
2193
+ /** The `visibility` (and repository ids) of an organization write. No `visibility` keeps the older default, `all`. */
2194
+ async readers(scope) {
2195
+ const visibility = scope.visibility ?? "all";
2196
+ if (visibility !== "selected") return { visibility };
2197
+ if (!scope.repos?.length) throw new Error(`organization secret with visibility "selected" needs a non-empty repos list`);
2198
+ const ids = [];
2199
+ for (const name of scope.repos) ids.push(await this.repoId(scope.name, name));
2200
+ return {
2201
+ visibility,
2202
+ selected_repository_ids: ids
2203
+ };
2204
+ }
2205
+ repoId(org, name) {
2206
+ const full = `${org}/${name}`;
2207
+ let id = this.repoIds.get(full);
2208
+ if (!id) {
2209
+ id = this.client.repos.getRepo(full).then((repo) => repo.id, (err) => {
2210
+ throw new Error(`could not resolve repository ${full}: ${err instanceof Error ? err.message : String(err)}`);
2211
+ });
2212
+ this.repoIds.set(full, id);
2213
+ }
2214
+ return id;
2215
+ }
2216
+ /** Deletes the named secret in the given scope. */
2217
+ async deleteSecret(scope, name) {
2218
+ await this.clientFor(scope).secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
2219
+ }
2220
+ };
2221
+ function toGHScope(scope) {
2222
+ if (scope.kind === "organization") return {
2223
+ kind: "organization",
2224
+ org: scope.name
2225
+ };
2226
+ return scope;
2227
+ }
2228
+ // src/capabilities/files.ts
2229
+ /** Reads one file; `null` when it does not exist. `version` is the blob sha `writeFile` needs to replace exactly this one. */
2230
+ /** A fine-grained token only reaches the repositories and permissions it was given; say which one is missing. */
2231
+ function noAccess(repo, action, cause) {
2232
+ return new Error(`the token cannot ${action} files in ${repo} (403): give the user-sync token (HOLOCRON_USER_SYNC_TOKEN, or holocron new token github.user-sync) access to that repository with Contents: ${action === "read" ? "read" : "read and write"}`, { cause });
2233
+ }
2234
+ async function readRepoFile(client, repo, path) {
2235
+ try {
2236
+ const file = await client.git.getContents(repo, path);
2237
+ if (file.encoding !== "base64") throw new Error(`${repo}/${path}: unexpected encoding \`${file.encoding}\``);
2238
+ return {
2239
+ content: Buffer.from(file.content, "base64").toString("utf-8"),
2240
+ version: file.sha
2241
+ };
2242
+ } catch (err) {
2243
+ if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "read", err);
2244
+ if (!(err instanceof ProviderApiError && err.status === 404)) throw err;
2245
+ }
2246
+ try {
2247
+ await client.repos.getRepo(repo);
2248
+ } catch (err) {
2249
+ if (err instanceof ProviderApiError && err.status === 404) throw new Error(`${repo} was not found: it does not exist, or the token cannot see it`, { cause: err });
2250
+ throw err;
2251
+ }
2252
+ return null;
2253
+ }
2254
+ /** Creates or replaces one file in a commit; GitHub refuses (409) a `version` that has since changed. */
2255
+ async function writeRepoFile(client, repo, path, content, opts) {
2256
+ try {
2257
+ await client.git.putContents(repo, path, {
2258
+ message: opts.message,
2259
+ content,
2260
+ ...opts.version ? { sha: opts.version } : {}
2261
+ });
2262
+ } catch (err) {
2263
+ if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "write", err);
2264
+ throw err;
2265
+ }
2266
+ }
2267
+ // src/capabilities/labels.ts
2268
+ /**
2269
+ * Idempotently synchronise a repo's labels to the canonical set.
2270
+ *
2271
+ * - Creates labels that are missing.
413
2272
  * - PATCHes labels whose color or description has drifted.
414
2273
  * - DELETEs labels listed in `stale`.
415
2274
  * - Leaves unrecognised labels that aren't in `stale` untouched.
@@ -443,14 +2302,615 @@ async function syncLabels(client, repo, canonical, stale) {
443
2302
  }
444
2303
  return `${created} created, ${updated} updated, ${deleted} deleted`;
445
2304
  }
446
- //#endregion
447
- //#region src/capabilities/properties.ts
448
- async function syncProperties(client, repo, values) {
449
- await client.properties.setProperties(repo, values);
2305
+ /**
2306
+ * Make the labels a repo lacks and change nothing else: an existing label (found without regard to case) keeps its
2307
+ * colour and description, and nothing is deleted. Used for the `area:<name>` family, which is not in the canonical set.
2308
+ */
2309
+ async function ensureLabels(client, repo, labels) {
2310
+ const existing = await client.labels.listLabels(repo);
2311
+ const have = new Set(existing.map((l) => l.name.toLowerCase()));
2312
+ let created = 0;
2313
+ for (const label of labels) {
2314
+ if (have.has(label.name.toLowerCase())) continue;
2315
+ await client.labels.createLabel(repo, {
2316
+ name: label.name,
2317
+ color: label.color,
2318
+ description: label.description
2319
+ });
2320
+ created++;
2321
+ }
2322
+ return `${created} created, ${labels.length - created} already there`;
2323
+ }
2324
+ // src/capabilities/property-fix-hints.ts
2325
+ /** GitHub's wording when a custom property value is not one the organization's definition allows. */
2326
+ const NOT_ALLOWED = /Value '([^']+)' is not allowed for property '([^']+)'/g;
2327
+ /**
2328
+ * What to do about each value GitHub says an organization custom property does not allow, one sentence per property,
2329
+ * read from GitHub's own message so it works even when the organization's definitions cannot be read. The values
2330
+ * belong to the organization's definition, not to the repository, so the fix is to add them there: a repository cannot
2331
+ * make its own value allowed. Empty when GitHub's message names no such value.
2332
+ */
2333
+ function propertyFixHints(githubMessage) {
2334
+ const byProperty = /* @__PURE__ */ new Map();
2335
+ for (const [, value, property] of githubMessage.matchAll(NOT_ALLOWED)) {
2336
+ const values = byProperty.get(property) ?? [];
2337
+ if (!values.includes(value)) values.push(value);
2338
+ byProperty.set(property, values);
2339
+ }
2340
+ return [...byProperty].map(([property, values]) => `add ${values.map((v) => `"${v}"`).join(", ")} to the allowed values of the organization custom property ${property} (the organization's Settings, Custom properties), then run setup again`);
2341
+ }
2342
+ // src/capabilities/rejected-properties.ts
2343
+ /** The values `setup` sends for `true_false` properties; anything else is rejected. */
2344
+ const BOOLEANS = /* @__PURE__ */ new Set(["true", "false"]);
2345
+ /**
2346
+ * What is wrong with `values` when compared with the organization's property definitions, one sentence per
2347
+ * problem, in the order the properties are given: a property the organization does not define, a value a
2348
+ * `single_select` or `multi_select` property does not allow, or a `true_false` property that is not `true` or
2349
+ * `false`. A `string` or `url` property has nothing to check here. Empty when every value fits its definition.
2350
+ */
2351
+ function rejectedProperties(values, schema) {
2352
+ const byName = new Map(schema.map((property) => [property.property_name, property]));
2353
+ const problems = [];
2354
+ for (const [name, value] of Object.entries(values)) {
2355
+ const definition = byName.get(name);
2356
+ if (!definition) {
2357
+ problems.push(`${name} is not a custom property of the organization`);
2358
+ continue;
2359
+ }
2360
+ const sent = Array.isArray(value) ? value : [value];
2361
+ if (definition.value_type === "true_false") {
2362
+ for (const item of sent.filter((item) => !BOOLEANS.has(item))) problems.push(`${name} is "${item}", but it takes only true or false`);
2363
+ continue;
2364
+ }
2365
+ const allowed = definition.allowed_values ?? [];
2366
+ if (definition.value_type !== "single_select" && definition.value_type !== "multi_select") continue;
2367
+ for (const item of sent.filter((item) => !allowed.includes(item))) problems.push(`${name} has "${item}", which is not one of its allowed values (${allowed.join(", ")})`);
2368
+ }
2369
+ return problems;
2370
+ }
2371
+ // src/capabilities/properties.ts
2372
+ /** GitHub's own message from a 422 body (`{"message": ..., "errors": [...]}`), or the start of the body when it is not JSON. */
2373
+ function githubMessage(details) {
2374
+ const raw = String(details ?? "").trim();
2375
+ try {
2376
+ const body = JSON.parse(raw);
2377
+ const errors = Array.isArray(body.errors) ? body.errors.map((e) => JSON.stringify(e)).join(", ") : "";
2378
+ const message = typeof body.message === "string" ? body.message : raw;
2379
+ return errors ? `${message}: ${errors}` : message;
2380
+ } catch {
2381
+ return raw.slice(0, 300);
2382
+ }
2383
+ }
2384
+ /** The organization's property definitions, or `undefined` when they cannot be read (permission, an older client). */
2385
+ async function orgSchema(client, repo) {
2386
+ try {
2387
+ return await client.properties.orgSchema(repo.split("/")[0]);
2388
+ } catch {
2389
+ return;
2390
+ }
2391
+ }
2392
+ /**
2393
+ * The values `values` holds that the organization's property definitions do not allow, one sentence each, or
2394
+ * `undefined` when the definitions cannot be read (the token lacks the organization's custom properties permission, or
2395
+ * the organization defines none). `client` should be the organization-scoped one when there is one, since reading the
2396
+ * definitions is an organization permission a repository token often lacks. Read-only.
2397
+ */
2398
+ async function checkPropertyValues(client, repo, values) {
2399
+ const schema = await orgSchema(client, repo);
2400
+ return schema ? rejectedProperties(values, schema) : void 0;
2401
+ }
2402
+ /**
2403
+ * Sets the repo's custom properties. When GitHub answers 422 the error says which value it refused and what to do
2404
+ * about it: the values are compared with the organization's property definitions (read-only, with `schemaClient`, the
2405
+ * organization-scoped client when there is one), GitHub's own message is added, and each value GitHub says a property
2406
+ * does not allow gets the fix, which does not need the definitions to be readable. One refused value fails the whole
2407
+ * request, so none of the properties is set.
2408
+ */
2409
+ async function syncProperties(client, repo, values, schemaClient = client) {
2410
+ try {
2411
+ await client.properties.setProperties(repo, values);
2412
+ } catch (err) {
2413
+ if (!(err instanceof ProviderApiError$1) || err.status !== 422) throw err;
2414
+ const problems = await checkPropertyValues(schemaClient, repo, values) ?? [];
2415
+ const said = githubMessage(err.details);
2416
+ const fixes = propertyFixHints(said);
2417
+ throw new Error(`GitHub refused the custom properties (422), so none was set: ${problems.length > 0 ? problems.join("; ") : "no value differs from the organization's definitions, or they could not be read"}. GitHub said: ${said}${fixes.length > 0 ? `. To fix it: ${fixes.join("; ")}` : ""}`, { cause: err });
2418
+ }
450
2419
  return `${Object.keys(values).length} properties set`;
451
2420
  }
452
- //#endregion
453
- //#region src/capabilities/teams.ts
2421
+ /** The values the organization's property `name` allows; `undefined` when it cannot be read, is not defined or takes any value. */
2422
+ async function getOrgPropertyValues(client, repo, name) {
2423
+ return ((await orgSchema(client, repo))?.find((p) => p.property_name === name))?.allowed_values ?? void 0;
2424
+ }
2425
+ /**
2426
+ * Adds the missing `values` to the organization's property `name` and returns them. GitHub replaces the whole
2427
+ * definition on a write, so the current one is read and sent back with the allowed values extended, in their order,
2428
+ * and nothing removed. A write is made only when something is missing.
2429
+ */
2430
+ async function addOrgPropertyValues(client, repo, name, values, viaOrgToken = true) {
2431
+ const org = repo.split("/")[0];
2432
+ const current = (await client.properties.orgSchema(org)).find((p) => p.property_name === name);
2433
+ if (!current) throw new Error(`the organization ${org} has no custom property "${name}"; create it first`);
2434
+ if (!current.allowed_values) throw new Error(`the custom property "${name}" takes any value; it has nothing to extend`);
2435
+ const have = new Set(current.allowed_values);
2436
+ const added = [...new Set(values)].filter((v) => !have.has(v));
2437
+ if (added.length === 0) return [];
2438
+ try {
2439
+ await client.properties.setOrgProperty(org, {
2440
+ ...current,
2441
+ allowed_values: [...current.allowed_values, ...added]
2442
+ });
2443
+ } catch (err) {
2444
+ if (!(err instanceof ProviderApiError$1) || err.status !== 403 && err.status !== 401) throw err;
2445
+ const token = viaOrgToken ? "the organization token (HOLOCRON_ORG_TOKEN, or the token passed with --token)" : "the admin token, because no organization token was found (set HOLOCRON_ORG_TOKEN or pass --token)";
2446
+ throw new Error(`GitHub refused to change the "${name}" definition (${err.status}): it needs the organization permission Custom properties: Read and write (admin) on ${org}, and this ran with ${token}`, { cause: err });
2447
+ }
2448
+ return added;
2449
+ }
2450
+ // src/capabilities/pull-request-checks.ts
2451
+ /** The check run the aggregate `ci` workflow posts on a pull request's head commit. */
2452
+ const AGGREGATE_CHECK = "ci / Required checks";
2453
+ const FAILED = /* @__PURE__ */ new Set([
2454
+ "failure",
2455
+ "timed_out",
2456
+ "startup_failure",
2457
+ "action_required",
2458
+ "stale"
2459
+ ]);
2460
+ const newestFirst = (a, b) => (b.started_at ?? "").localeCompare(a.started_at ?? "") || b.id - a.id;
2461
+ /** The aggregate's verdict from its runs: only the newest counts; a cancelled or unfinished run is `pending`. */
2462
+ function aggregateState(runs) {
2463
+ const newest = [...runs].sort(newestFirst)[0];
2464
+ if (!newest) return "none";
2465
+ if (newest.status !== "completed") return "pending";
2466
+ if (newest.conclusion === "success") return "success";
2467
+ if (newest.conclusion && FAILED.has(newest.conclusion)) return "failure";
2468
+ if (newest.conclusion === "cancelled") return "pending";
2469
+ return "none";
2470
+ }
2471
+ /**
2472
+ * The aggregate check of a commit and the checks that failed on it, read now (never cached, so a caller that polls sees
2473
+ * each change). The newest run of each name counts, so a job that failed and was re-run to green is not listed.
2474
+ */
2475
+ async function aggregateChecksFor(client, repo, sha) {
2476
+ const runs = await client.checks.listCheckRunsForRef(repo, sha);
2477
+ const newest = /* @__PURE__ */ new Map();
2478
+ for (const run of [...runs].sort(newestFirst)) if (!newest.has(run.name)) newest.set(run.name, run);
2479
+ return {
2480
+ state: aggregateState(runs.filter((r) => r.name === AGGREGATE_CHECK)),
2481
+ sha,
2482
+ failing: [...newest.values()].filter((r) => r.status === "completed" && r.conclusion !== null && FAILED.has(r.conclusion)).map((r) => ({
2483
+ name: r.name,
2484
+ url: r.details_url ?? r.html_url
2485
+ }))
2486
+ };
2487
+ }
2488
+ /**
2489
+ * Whether the required checks of a commit are green, for a repo with no `ci / Required checks` aggregate
2490
+ * (`ci.aggregate: "none"`). Reads the commit's check runs and, only when a status context is required, its commit
2491
+ * statuses, then lets the CLI's `requiredChecksVerdict()` decide: the rule lives there and nowhere else. Read now, never
2492
+ * cached. Optional checks that failed are listed with `required: false` and never change the state.
2493
+ */
2494
+ async function requiredChecksFor(client, repo, sha, required) {
2495
+ const checkRuns = await readCheckRuns(client, repo, sha);
2496
+ const commitStatuses = required.statuses.length > 0 ? await readCommitStatuses(client, repo, sha) : [];
2497
+ const verdict = requiredChecksVerdict({
2498
+ expected: required.expected,
2499
+ statuses: required.statuses,
2500
+ checkRuns,
2501
+ commitStatuses
2502
+ });
2503
+ const failing = verdict.failing.map((f) => ({
2504
+ name: f.name,
2505
+ ...f.url === void 0 ? {} : { url: f.url },
2506
+ required: f.required
2507
+ }));
2508
+ return {
2509
+ state: verdict.state,
2510
+ sha,
2511
+ failing,
2512
+ ...verdict.pending ? { pending: verdict.pending } : {}
2513
+ };
2514
+ }
2515
+ /** The checks of a commit: the aggregate's verdict, or with `required` the required checks'. */
2516
+ function checksForSha(client, repo, sha, required) {
2517
+ return required ? requiredChecksFor(client, repo, sha, required) : aggregateChecksFor(client, repo, sha);
2518
+ }
2519
+ /** The aggregate check of a pull request's newest commit and the checks that failed on it, read now. */
2520
+ async function readPullRequestChecks(client, repo, number) {
2521
+ return aggregateChecksFor(client, repo, (await client.pulls.getPullRequest(repo, number)).head.sha);
2522
+ }
2523
+ /** Whether the required checks of a pull request's newest commit are green, for a repo with no aggregate. */
2524
+ async function readRequiredPullRequestChecks(client, repo, number, required) {
2525
+ return requiredChecksFor(client, repo, (await client.pulls.getPullRequest(repo, number)).head.sha, required);
2526
+ }
2527
+ // src/capabilities/pull-request-state.ts
2528
+ /** The reviews that count: each reviewer's last approval, change request or dismissal (a comment changes nothing). */
2529
+ function reviewState(reviews, requested) {
2530
+ const latest = /* @__PURE__ */ new Map();
2531
+ for (const r of reviews) if (r.user && (r.state === "APPROVED" || r.state === "CHANGES_REQUESTED" || r.state === "DISMISSED")) latest.set(r.user.login, r.state);
2532
+ const states = [...latest.values()];
2533
+ if (states.includes("CHANGES_REQUESTED")) return "changes_requested";
2534
+ if (states.includes("APPROVED")) return "approved";
2535
+ return requested.length > 0 ? "review_required" : "none";
2536
+ }
2537
+ const CI = {
2538
+ success: "passing",
2539
+ failure: "failing",
2540
+ pending: "pending",
2541
+ none: "none"
2542
+ };
2543
+ /**
2544
+ * One pull request as the PR forum's post is rendered from it: the pull request, and for an open one its reviews and the
2545
+ * checks of its head commit (a finished pull request's tag needs neither, so they are not read). `undefined` for a pull
2546
+ * request that does not exist. Three reads for an open pull request, one for a closed one.
2547
+ */
2548
+ async function readPullRequestState(client, repo, number, required) {
2549
+ let pull;
2550
+ try {
2551
+ pull = await client.pulls.getPullRequest(repo, number);
2552
+ } catch (err) {
2553
+ if (err instanceof ProviderApiError && err.status === 404) return void 0;
2554
+ throw err;
2555
+ }
2556
+ const closed = pull.state === "closed";
2557
+ const requestedReviewers = (pull.requested_reviewers ?? []).map((r) => r.login);
2558
+ const [reviews, checks] = closed ? [[], void 0] : await Promise.all([client.pulls.listReviews(repo, number), checksForSha(client, repo, pull.head.sha, required)]);
2559
+ return {
2560
+ repo,
2561
+ number,
2562
+ title: pull.title,
2563
+ body: pull.body ?? "",
2564
+ url: pull.html_url,
2565
+ author: pull.user?.login ?? "unknown",
2566
+ authorIsBot: pull.user?.type === "Bot",
2567
+ draft: pull.draft ?? false,
2568
+ merged: pull.merged_at !== null,
2569
+ closed,
2570
+ createdAt: pull.created_at ?? (/* @__PURE__ */ new Date(0)).toISOString(),
2571
+ ...pull.closed_at ? { closedAt: pull.closed_at } : {},
2572
+ base: pull.base?.ref ?? "",
2573
+ requestedReviewers,
2574
+ review: reviewState(reviews, requestedReviewers),
2575
+ ci: checks ? CI[checks.state] : "none",
2576
+ mergeable: pull.mergeable_state === "dirty" ? "conflicting" : pull.mergeable_state === void 0 || pull.mergeable_state === "unknown" ? "unknown" : "clean"
2577
+ };
2578
+ }
2579
+ // src/capabilities/pull-requests.ts
2580
+ /** The GitHub pull request as the neutral {@link PullRequest}. */
2581
+ function toPullRequest(raw) {
2582
+ return {
2583
+ number: raw.number,
2584
+ title: raw.title,
2585
+ state: raw.state,
2586
+ merged: raw.merged_at !== null,
2587
+ branch: raw.head.ref,
2588
+ headSha: raw.head.sha,
2589
+ url: raw.html_url
2590
+ };
2591
+ }
2592
+ /** Whether a body already holds a closing or referencing line for the issue (any keyword, any case). */
2593
+ function names(body, issue) {
2594
+ const escaped = issue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2595
+ return new RegExp(`\\b(closes?|fix(es)?|resolves?|refs?)\\s+${escaped}(?![\\w-])`, "i").test(body);
2596
+ }
2597
+ /**
2598
+ * The body with the link line the issue's closing reference needs. GitHub reads `Closes #12` itself, so the link is
2599
+ * text, not a call; a body that already names the issue is left alone.
2600
+ */
2601
+ function withLink(body, link) {
2602
+ if (!link) return body;
2603
+ const issue = link.issue.trim();
2604
+ const ref = /^\d+$/.test(issue) ? `#${issue}` : issue;
2605
+ const text = body ?? "";
2606
+ if (names(text, ref)) return body;
2607
+ const line = `${link.keyword ?? "Refs"} ${ref}`;
2608
+ return text.trim() === "" ? line : `${text.trimEnd()}\n\n${line}`;
2609
+ }
2610
+ /** Puts the pull request (by node id) on each board of the organization found by title; a board not found or refused is returned by name. */
2611
+ async function addToBoards(client, repo, nodeId, titles) {
2612
+ const dropped = [];
2613
+ const owner = repo.slice(0, repo.indexOf("/"));
2614
+ let boards;
2615
+ try {
2616
+ boards = (await client.graphql.query(`query($owner: String!) { organization(login: $owner) { projectsV2(first: 100) { nodes { id title closed } } } }`, { owner })).organization;
2617
+ } catch {
2618
+ return titles.map((t) => `project ${t}`);
2619
+ }
2620
+ for (const title of titles) {
2621
+ const board = boards?.projectsV2.nodes.find((b) => b.title === title && !b.closed);
2622
+ if (!board) {
2623
+ dropped.push(`project ${title}`);
2624
+ continue;
2625
+ }
2626
+ try {
2627
+ await client.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
2628
+ project: board.id,
2629
+ content: nodeId
2630
+ });
2631
+ } catch {
2632
+ dropped.push(`project ${title}`);
2633
+ }
2634
+ }
2635
+ return dropped;
2636
+ }
2637
+ /**
2638
+ * Puts the fields an issue and its pull request share on the pull request (GitHub serves a pull request through
2639
+ * the issues API for these): labels and assignees are added to what is there, a milestone is found by title and
2640
+ * boards by title. What cannot be applied comes back by name; nothing is created or cleared. Boards are the
2641
+ * organization's, so they go through `boardsClient` (the organization token), not the pull request token.
2642
+ */
2643
+ async function applyFields(client, repo, pr, fields, boardsClient) {
2644
+ const dropped = [];
2645
+ const { number } = pr;
2646
+ if (fields.labels?.length) await client.issues.addLabels(repo, number, fields.labels);
2647
+ for (const label of fields.removeLabels ?? []) try {
2648
+ await client.issues.removeLabel(repo, number, label);
2649
+ } catch {}
2650
+ const patch = {};
2651
+ if (fields.assignees?.length) {
2652
+ const have = ((await client.issues.getIssue(repo, number)).assignees ?? []).map((a) => a.login);
2653
+ const want = fields.assignees.map((a) => a.replace(/^@/, ""));
2654
+ const next = [.../* @__PURE__ */ new Set([...have, ...want])];
2655
+ if (next.length !== have.length) patch.assignees = next;
2656
+ }
2657
+ if (fields.milestone) {
2658
+ const found = (await client.issues.listMilestones(repo, { state: "open" })).find((m) => m.title === fields.milestone);
2659
+ if (found) patch.milestone = found.number;
2660
+ else dropped.push(`milestone ${fields.milestone}`);
2661
+ }
2662
+ if (Object.keys(patch).length) await client.issues.updateIssue(repo, number, patch);
2663
+ if (fields.projects?.length) {
2664
+ if (pr.node_id) dropped.push(...await addToBoards(boardsClient, repo, pr.node_id, fields.projects));
2665
+ else dropped.push(...fields.projects.map((t) => `project ${t}`));
2666
+ }
2667
+ return dropped;
2668
+ }
2669
+ /**
2670
+ * Opens a draft pull request, or returns the open one for the same head, and applies the mirrored fields.
2671
+ * `boardsClient` puts it on boards (the organization token); it defaults to `client`.
2672
+ */
2673
+ async function createPullRequest(client, repo, input, boardsClient = client) {
2674
+ const existing = (await client.pulls.listOpenByHead(repo, input.head))[0];
2675
+ const created = !existing;
2676
+ const raw = existing ?? await client.pulls.createPullRequest(repo, {
2677
+ title: input.title,
2678
+ head: input.head,
2679
+ base: input.base,
2680
+ body: withLink(input.body, input.link),
2681
+ draft: input.draft ?? true
2682
+ });
2683
+ const dropped = await applyFields(client, repo, raw, input, boardsClient);
2684
+ return {
2685
+ pullRequest: toPullRequest(raw),
2686
+ created,
2687
+ draft: raw.draft ?? false,
2688
+ dropped
2689
+ };
2690
+ }
2691
+ /**
2692
+ * Changes a pull request's own fields, then the mirrored ones. A patch that names none of the own fields makes no PATCH.
2693
+ * `boardsClient` puts it on boards (the organization token); it defaults to `client`.
2694
+ */
2695
+ async function updatePullRequest(client, repo, number, patch, boardsClient = client) {
2696
+ const own = {};
2697
+ if (patch.title !== void 0) own.title = patch.title;
2698
+ if (patch.body !== void 0) own.body = patch.body;
2699
+ if (patch.base !== void 0) own.base = patch.base;
2700
+ if (patch.state !== void 0) own.state = patch.state;
2701
+ const raw = Object.keys(own).length ? await client.pulls.updatePullRequest(repo, number, own) : await client.pulls.getPullRequest(repo, number);
2702
+ const dropped = await applyFields(client, repo, raw, patch, boardsClient);
2703
+ return {
2704
+ pullRequest: toPullRequest(raw),
2705
+ created: false,
2706
+ draft: raw.draft ?? false,
2707
+ dropped
2708
+ };
2709
+ }
2710
+ /** Takes a draft out of draft; `false` when it was not a draft or is not open. */
2711
+ async function markReady(client, repo, number) {
2712
+ const raw = await client.pulls.getPullRequest(repo, number);
2713
+ if (!raw.draft || raw.state !== "open") return false;
2714
+ if (!raw.node_id) throw new Error(`pull request ${repo}#${number} has no node id to mark ready`);
2715
+ await client.pulls.markReadyForReview(raw.node_id);
2716
+ return true;
2717
+ }
2718
+ // src/capabilities/read-repo.ts
2719
+ /** The settings `setup` writes, which `GET /repos/{repo}` reports under the same names. */
2720
+ const SETTING_KEYS = [
2721
+ "allow_squash_merge",
2722
+ "allow_merge_commit",
2723
+ "allow_rebase_merge",
2724
+ "allow_auto_merge",
2725
+ "allow_update_branch",
2726
+ "delete_branch_on_merge",
2727
+ "has_issues",
2728
+ "has_discussions",
2729
+ "has_projects",
2730
+ "has_wiki"
2731
+ ];
2732
+ /** The repository's description, homepage, default branch, topics and settings, from one read. */
2733
+ async function readRepoInfo(client, repo) {
2734
+ const data = await client.repos.getRepo(repo);
2735
+ const settings = { default_branch: data.default_branch };
2736
+ for (const key of SETTING_KEYS) {
2737
+ const value = data[key];
2738
+ if (value !== void 0) settings[key] = value;
2739
+ }
2740
+ return {
2741
+ description: data.description ?? null,
2742
+ homepage: data.homepage ?? null,
2743
+ defaultBranch: data.default_branch,
2744
+ topics: data.topics ?? [],
2745
+ settings
2746
+ };
2747
+ }
2748
+ /** A ruleset reduced to what `setup` writes: its enforcement, rule types, required status checks and the app a check is pinned to. */
2749
+ function toRulesetDetail(data) {
2750
+ const rules = data.rules ?? [];
2751
+ const checks = rules.find((r) => r.type === "required_status_checks")?.parameters?.required_status_checks;
2752
+ const entries = Array.isArray(checks) ? checks : [];
2753
+ const sources = {};
2754
+ for (const entry of entries) if (typeof entry.integration_id === "number") sources[String(entry.context)] = entry.integration_id;
2755
+ return {
2756
+ name: data.name,
2757
+ enforcement: data.enforcement,
2758
+ ruleTypes: rules.map((r) => r.type),
2759
+ requiredChecks: entries.map((c) => String(c.context)),
2760
+ ...Object.keys(sources).length > 0 ? { requiredCheckSources: sources } : {}
2761
+ };
2762
+ }
2763
+ /** The value, or `undefined` when GitHub refuses the read (permission, plan, feature absent). Other errors still throw. */
2764
+ async function readable(read) {
2765
+ try {
2766
+ return await read();
2767
+ } catch (err) {
2768
+ if (err instanceof ProviderApiError$1) return void 0;
2769
+ throw err;
2770
+ }
2771
+ }
2772
+ /** Which security features are on. One GitHub refuses to report is left out, not reported as off. */
2773
+ async function readSecurity(client, repo) {
2774
+ const [data, alerts, fixes, reporting, codeScanning] = await Promise.all([
2775
+ readable(() => client.repos.getRepo(repo)),
2776
+ readable(() => client.security.vulnerabilityAlertsEnabled(repo)),
2777
+ readable(() => client.security.automatedSecurityFixesEnabled(repo)),
2778
+ readable(() => client.security.privateVulnerabilityReportingEnabled(repo)),
2779
+ readable(() => client.security.codeScanningDefaultSetupState(repo))
2780
+ ]);
2781
+ const analysis = data?.security_and_analysis;
2782
+ const on = (feature) => {
2783
+ const status = analysis?.[feature]?.status;
2784
+ return status === void 0 ? void 0 : status === "enabled";
2785
+ };
2786
+ const found = {
2787
+ vulnerabilityAlerts: alerts,
2788
+ automatedSecurityFixes: fixes,
2789
+ secretScanning: on("secret_scanning"),
2790
+ secretScanningPushProtection: on("secret_scanning_push_protection"),
2791
+ privateVulnerabilityReporting: reporting,
2792
+ codeScanningDefaultSetup: codeScanning === void 0 ? void 0 : codeScanning === "configured"
2793
+ };
2794
+ return Object.fromEntries(Object.entries(found).filter(([, v]) => v !== void 0));
2795
+ }
2796
+ // src/capabilities/relay-source.ts
2797
+ /** The events a webhook subscribes to when the layout names none: the one the Dependabot relay source carries. */
2798
+ const DEFAULT_RELAY_EVENTS = ["dependabot_alert"];
2799
+ /** A repository name, `owner/name`, made of the characters GitHub allows. */
2800
+ const REPOSITORY$1 = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
2801
+ /** An organization login. */
2802
+ const ORGANIZATION = /^[A-Za-z0-9][A-Za-z0-9-]*$/;
2803
+ /**
2804
+ * Where a relay source's one webhook lives. A webhook has one URL, so a source covers one place, not a list: a single
2805
+ * repository (`scope: ["owner/name"]`, or the plugin's own repository when `scope` is absent) or an organization
2806
+ * (`options: { org: "name" }` with no `scope`). Both together, more than one repository and anything that is not
2807
+ * `owner/name` are a problem the caller reports, never a guess.
2808
+ */
2809
+ function relayTarget(input, defaultRepo) {
2810
+ const org = input.options?.org;
2811
+ if (org !== void 0) {
2812
+ if (typeof org !== "string" || !ORGANIZATION.test(org)) return { problem: `relay source ${input.source}: \`options.org\` must be an organization login` };
2813
+ if (input.scope !== void 0 && input.scope.length > 0) return { problem: `relay source ${input.source}: name a repository in \`scope\` or an organization in \`options.org\`, not both` };
2814
+ return {
2815
+ scope: {
2816
+ kind: "organization",
2817
+ org
2818
+ },
2819
+ label: `organization ${org}`
2820
+ };
2821
+ }
2822
+ const scope = input.scope ?? [];
2823
+ if (scope.length > 1) return { problem: `relay source ${input.source}: a webhook has one URL, so \`scope\` names one repository, not ${scope.length}; use \`options.org\` for an organization` };
2824
+ const repo = scope[0] ?? defaultRepo;
2825
+ if (!REPOSITORY$1.test(repo)) return { problem: `relay source ${input.source}: \`scope\` must be one repository as \`owner/name\`${scope.length === 0 ? " (the plugin has no repository to default to)" : ""}` };
2826
+ return {
2827
+ scope: {
2828
+ kind: "repo",
2829
+ repo
2830
+ },
2831
+ label: `repository ${repo}`
2832
+ };
2833
+ }
2834
+ /** Whether two event lists subscribe to the same events. */
2835
+ function sameEvents(a, b) {
2836
+ return a.length === b.length && [...a].sort().every((event, i) => event === [...b].sort()[i]);
2837
+ }
2838
+ /** The sentence for a token GitHub refuses, which GitHub answers as a 403 or, for a hidden resource, a 404. */
2839
+ function accessTodo(label, scope) {
2840
+ return `GitHub refused the webhook call for ${label}: the token needs ${scope.kind === "organization" ? "Organization permission Webhooks: read and write (classic: admin:org_hook)" : "Repository permission Webhooks: read and write (classic: admin:repo_hook)"}, or add the webhook in the settings yourself and set the secret on the Worker`;
2841
+ }
2842
+ /**
2843
+ * Makes the GitHub webhook for a relay source (spec `tech-relay-sources`, issue #2531). The webhook is found by its
2844
+ * `config.url`; when absent it is made with the secret the caller offers (GitHub never returns it, so it is returned
2845
+ * only now), and an existing one has only its events and `active` flag brought in line. Nothing is deleted and an
2846
+ * adopted webhook keeps the secret the Worker has.
2847
+ */
2848
+ async function ensureRelaySource(client, defaultRepo, input) {
2849
+ const target = relayTarget(input, defaultRepo);
2850
+ if ("problem" in target) return {
2851
+ created: false,
2852
+ updated: [],
2853
+ todo: [target.problem]
2854
+ };
2855
+ const events = input.events && input.events.length > 0 ? input.events : DEFAULT_RELAY_EVENTS;
2856
+ try {
2857
+ const found = (await client.hooks.listHooks(target.scope)).find((hook) => hook.config.url === input.url);
2858
+ if (!found) {
2859
+ if (!input.secret) return {
2860
+ created: false,
2861
+ updated: [],
2862
+ todo: [`no signing secret was offered for the ${target.label} webhook, so none was made`]
2863
+ };
2864
+ await client.hooks.createHook(target.scope, {
2865
+ url: input.url,
2866
+ secret: input.secret,
2867
+ events
2868
+ });
2869
+ return {
2870
+ created: true,
2871
+ updated: [],
2872
+ secret: input.secret
2873
+ };
2874
+ }
2875
+ const updated = [];
2876
+ const patch = {};
2877
+ if (!sameEvents(found.events, events)) {
2878
+ patch.events = events;
2879
+ updated.push("events");
2880
+ }
2881
+ if (!found.active) {
2882
+ patch.active = true;
2883
+ updated.push("active");
2884
+ }
2885
+ if (updated.length > 0) await client.hooks.updateHook(target.scope, found.id, patch);
2886
+ return {
2887
+ created: false,
2888
+ updated
2889
+ };
2890
+ } catch (err) {
2891
+ if (err instanceof ProviderApiError && (err.status === 403 || err.status === 404)) return {
2892
+ created: false,
2893
+ updated: [],
2894
+ todo: [accessTodo(target.label, target.scope)]
2895
+ };
2896
+ throw err;
2897
+ }
2898
+ }
2899
+ /** Reads the webhook back without changing anything: whether it exists, is active and what it subscribes to. The secret is never readable. */
2900
+ async function inspectRelaySource(client, defaultRepo, input) {
2901
+ const target = relayTarget(input, defaultRepo);
2902
+ if ("problem" in target) throw new Error(target.problem);
2903
+ const found = (await client.hooks.listHooks(target.scope)).find((hook) => hook.config.url === input.url);
2904
+ if (!found) return { exists: false };
2905
+ return {
2906
+ exists: true,
2907
+ enabled: found.active,
2908
+ events: found.events,
2909
+ ...target.scope.kind === "repo" ? { scope: [target.scope.repo] } : {}
2910
+ };
2911
+ }
2912
+ // src/capabilities/teams.ts
2913
+ /** Turns a team entry into slug and permission form; a bare slug gets `push`. */
454
2914
  function normalizeTeamEntry(entry) {
455
2915
  if (typeof entry === "string") return {
456
2916
  slug: entry,
@@ -458,6 +2918,7 @@ function normalizeTeamEntry(entry) {
458
2918
  };
459
2919
  return entry;
460
2920
  }
2921
+ /** Grants each team access to the repo and reports the outcome; throws when every team fails. */
461
2922
  async function syncTeams(client, repo, teams) {
462
2923
  const [org = "", name = ""] = repo.split("/", 2);
463
2924
  const normalized = teams.map(normalizeTeamEntry);
@@ -470,17 +2931,121 @@ async function syncTeams(client, repo, teams) {
470
2931
  }
471
2932
  return `${succeeded} team${succeeded === 1 ? "" : "s"} synced`;
472
2933
  }
473
- //#endregion
474
- //#region src/capabilities/topics.ts
2934
+ // src/capabilities/topics.ts
475
2935
  async function syncTopics(client, repo, topics) {
476
2936
  await client.topics.setTopics(repo, topics);
477
2937
  return `${topics.length} topics set`;
478
2938
  }
479
- //#endregion
480
- //#region src/capabilities/source.ts
2939
+ // src/capabilities/variables.ts
2940
+ /** GitHub's rule for a variable name: letters, digits and underscores, not starting with a digit or `GITHUB_`. */
2941
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
2942
+ /** Longest name GitHub accepts. */
2943
+ const MAX_NAME = 256;
2944
+ function assertNames(names) {
2945
+ for (const name of names) if (!NAME.test(name) || name.length > MAX_NAME || name.toUpperCase().startsWith("GITHUB_")) throw new Error(`invalid variable name ${JSON.stringify(name)}: use letters, digits and underscores (at most ${MAX_NAME}), not starting with a digit or GITHUB_`);
2946
+ }
2947
+ /** GitHub treats variable names as case-insensitive, so every comparison goes through this. */
2948
+ const key = (name) => name.toUpperCase();
2949
+ /**
2950
+ * Bring one scope's variables in line with the declaration: create what is missing, update what differs, leave what
2951
+ * already matches. Variables that exist but are not declared are left alone, or deleted with `prune`, except an
2952
+ * organization variable limited to selected repositories, which this client cannot manage and so is never deleted.
2953
+ * Returns a one-line summary, naming the ones left so drift is visible. In a dry run it only describes the changes.
2954
+ */
2955
+ async function reconcile(client, repo, scope, wanted, opts) {
2956
+ assertNames(wanted.map((w) => w.name));
2957
+ const existing = new Map((await client.variables.listVariables(repo, scope)).map((v) => [key(v.name), v]));
2958
+ const counts = {
2959
+ created: 0,
2960
+ updated: 0,
2961
+ unchanged: 0,
2962
+ deleted: 0
2963
+ };
2964
+ for (const want of wanted) {
2965
+ const have = existing.get(key(want.name));
2966
+ const body = {
2967
+ name: want.name,
2968
+ value: want.value
2969
+ };
2970
+ if (want.visibility) body["visibility"] = want.visibility;
2971
+ if (!have) {
2972
+ if (opts.dryRun) {
2973
+ counts.created++;
2974
+ continue;
2975
+ }
2976
+ try {
2977
+ await client.variables.createVariable(repo, scope, body);
2978
+ counts.created++;
2979
+ continue;
2980
+ } catch (err) {
2981
+ if (!(err instanceof ProviderApiError && (err.status === 409 || err.status === 422))) throw err;
2982
+ }
2983
+ } else if (have.value === want.value && (!want.visibility || have.visibility === want.visibility)) {
2984
+ counts.unchanged++;
2985
+ continue;
2986
+ }
2987
+ if (!opts.dryRun) await client.variables.updateVariable(repo, scope, have?.name ?? want.name, body);
2988
+ counts.updated++;
2989
+ }
2990
+ const declared = new Set(wanted.map((w) => key(w.name)));
2991
+ const undeclared = [...existing.entries()].filter(([k]) => !declared.has(k)).map(([, v]) => v);
2992
+ const unmanaged = undeclared.filter((v) => v.visibility === "selected");
2993
+ if (opts.prune) for (const v of undeclared.filter((u) => u.visibility !== "selected")) {
2994
+ if (!opts.dryRun) await client.variables.deleteVariable(repo, scope, v.name);
2995
+ counts.deleted++;
2996
+ }
2997
+ const parts = opts.dryRun ? [
2998
+ `would create ${counts.created}`,
2999
+ `would update ${counts.updated}`,
3000
+ `${counts.unchanged} unchanged`
3001
+ ] : [
3002
+ `${counts.created} created`,
3003
+ `${counts.updated} updated`,
3004
+ `${counts.unchanged} unchanged`
3005
+ ];
3006
+ if (counts.deleted > 0) parts.push(`${counts.deleted} ${opts.dryRun ? "would be deleted" : "deleted"}`);
3007
+ const left = opts.prune ? unmanaged : undeclared;
3008
+ if (left.length > 0) {
3009
+ const why = opts.prune ? "limited to selected repositories, not managed" : "not declared, left alone";
3010
+ parts.push(`${left.length} ${why}: ${left.map((v) => v.name).join(", ")}`);
3011
+ }
3012
+ return parts.join(", ");
3013
+ }
3014
+ /** Reconcile a repository's Actions variables. */
3015
+ function syncVariables(client, repo, variables, opts = {}) {
3016
+ return reconcile(client, repo, { kind: "repo" }, Object.entries(variables).map(([name, value]) => ({
3017
+ name,
3018
+ value
3019
+ })), {
3020
+ prune: opts.prune === true,
3021
+ dryRun: opts.dryRun === true
3022
+ });
3023
+ }
3024
+ /** Reconcile an organization's Actions variables. `repo` is only the coordinate the client is bound to. */
3025
+ function syncOrgVariables(client, repo, org, variables, opts = {}) {
3026
+ const wanted = Object.entries(variables).map(([name, v]) => ({
3027
+ name,
3028
+ value: v.value,
3029
+ visibility: v.visibility
3030
+ }));
3031
+ return reconcile(client, repo, {
3032
+ kind: "organization",
3033
+ org
3034
+ }, wanted, {
3035
+ prune: opts.prune === true,
3036
+ dryRun: opts.dryRun === true
3037
+ });
3038
+ }
3039
+ // src/capabilities/source.ts
3040
+ /**
3041
+ * The GitHub implementation of the `source` capability: repo settings, rulesets, branch protection, security
3042
+ * features and local workflow files.
3043
+ */
481
3044
  var GitHubSource = class {
482
3045
  client;
3046
+ /** Capability key, always `"source"`. */
483
3047
  key = "source";
3048
+ /** Provider name, always `"github"`. */
484
3049
  providerName = "github";
485
3050
  owner;
486
3051
  name;
@@ -488,6 +3053,8 @@ var GitHubSource = class {
488
3053
  repoRoot;
489
3054
  workflowDir;
490
3055
  orgClient;
3056
+ userSyncClient;
3057
+ pullsClient;
491
3058
  baseUrl;
492
3059
  fetchImpl;
493
3060
  constructor(client, opts) {
@@ -496,15 +3063,36 @@ var GitHubSource = class {
496
3063
  this.owner = owner;
497
3064
  this.name = name;
498
3065
  this.repo = opts.repo;
499
- this.repoRoot = opts.repoRoot;
500
- this.workflowDir = join(opts.repoRoot, ".github", "workflows");
3066
+ this.repoRoot = findRootSync(opts.repoRoot, ".git", {
3067
+ fallback: "start",
3068
+ realpath: true
3069
+ });
3070
+ this.workflowDir = join(this.repoRoot, ".github", "workflows");
501
3071
  this.orgClient = opts.orgClient;
3072
+ this.userSyncClient = opts.userSyncClient;
3073
+ this.pullsClient = opts.pullsClient;
502
3074
  this.baseUrl = opts.baseUrl;
503
3075
  this.fetchImpl = opts.fetch;
504
3076
  }
3077
+ /**
3078
+ * Makes the GitHub webhook for a relay source: on one repository with the admin token, or on the organization
3079
+ * (`options.org`) with the organization token. Found by URL, events and `active` brought in line, nothing deleted.
3080
+ */
3081
+ async ensureRelaySource(input) {
3082
+ return ensureRelaySource(this.relayClient(input), this.repo, input);
3083
+ }
3084
+ /** Reads the relay source's webhook back, changing nothing. GitHub never returns the secret, so `hasSecret` is left out. */
3085
+ async inspectRelaySource(input) {
3086
+ return inspectRelaySource(this.relayClient(input), this.repo, input);
3087
+ }
3088
+ /** The organization token for an organization's webhook, the repository one otherwise. */
3089
+ relayClient(input) {
3090
+ return input.options?.org !== void 0 ? this.orgClient ?? this.client : this.client;
3091
+ }
505
3092
  async whoami() {
506
3093
  return { login: (await this.client.user.getCurrentUser()).login };
507
3094
  }
3095
+ /** Returns the repo's owner, name and default branch. */
508
3096
  async getRepo() {
509
3097
  const data = await this.client.repos.getRepo(this.repo);
510
3098
  return {
@@ -513,27 +3101,34 @@ var GitHubSource = class {
513
3101
  defaultBranch: data.default_branch
514
3102
  };
515
3103
  }
3104
+ /** Lists the repo's rulesets. */
516
3105
  async listRulesets() {
517
3106
  return this.client.rulesets.listRulesets(this.repo);
518
3107
  }
3108
+ /** Creates a ruleset from the given payload. */
519
3109
  async createRuleset(payload) {
520
3110
  return this.client.rulesets.createRuleset(this.repo, payload);
521
3111
  }
3112
+ /** Updates the ruleset with the given id from the payload. */
522
3113
  async updateRuleset(id, payload) {
523
3114
  return this.client.rulesets.updateRuleset(this.repo, id, payload);
524
3115
  }
3116
+ /** Updates the repo's settings. */
525
3117
  async updateRepoSettings(settings) {
526
3118
  await this.client.repos.updateRepo(this.repo, settings);
527
3119
  }
528
3120
  async protectBranch(branch, payload) {
529
3121
  await this.client.branches.protectBranch(this.repo, branch, payload);
530
3122
  }
3123
+ /** Enables Dependabot vulnerability alerts. */
531
3124
  async enableVulnerabilityAlerts() {
532
3125
  await this.client.security.enableVulnerabilityAlerts(this.repo);
533
3126
  }
3127
+ /** Enables Dependabot automated security fixes. */
534
3128
  async enableAutomatedSecurityFixes() {
535
3129
  await this.client.security.enableAutomatedSecurityFixes(this.repo);
536
3130
  }
3131
+ /** Enables secret scanning. */
537
3132
  async enableSecretScanning() {
538
3133
  await this.client.security.enableSecretScanning(this.repo);
539
3134
  }
@@ -546,9 +3141,11 @@ var GitHubSource = class {
546
3141
  async enableDependencyGraph() {
547
3142
  await this.client.security.enableDependencyGraph(this.repo);
548
3143
  }
3144
+ /** Enables private vulnerability reporting. */
549
3145
  async enablePrivateVulnerabilityReporting() {
550
3146
  await this.client.security.enablePrivateVulnerabilityReporting(this.repo);
551
3147
  }
3148
+ /** Lists the `.yml` and `.yaml` files in `.github/workflows`, sorted by name; empty when the folder is missing. */
552
3149
  async listWorkflowFiles() {
553
3150
  try {
554
3151
  return (await readdir(this.workflowDir)).filter((e) => e.endsWith(".yml") || e.endsWith(".yaml")).sort();
@@ -557,6 +3154,7 @@ var GitHubSource = class {
557
3154
  throw err;
558
3155
  }
559
3156
  }
3157
+ /** Reads a workflow file's text, or `null` when it does not exist. */
560
3158
  async readWorkflowFile(name) {
561
3159
  try {
562
3160
  return await readFile(join(this.workflowDir, name), "utf8");
@@ -565,10 +3163,12 @@ var GitHubSource = class {
565
3163
  throw err;
566
3164
  }
567
3165
  }
3166
+ /** Writes a workflow file, creating `.github/workflows` first when needed. */
568
3167
  async writeWorkflowFile(name, contents) {
569
3168
  await ensureDir(this.workflowDir);
570
3169
  await writeFile(join(this.workflowDir, name), contents, "utf8");
571
3170
  }
3171
+ /** Removes a workflow file; a file that is already gone is not an error. */
572
3172
  async removeWorkflowFile(name) {
573
3173
  try {
574
3174
  await rm(join(this.workflowDir, name));
@@ -582,17 +3182,92 @@ var GitHubSource = class {
582
3182
  await ensureDir(dirname(full));
583
3183
  await writeFile(full, contents, "utf8");
584
3184
  }
585
- async syncLabels(canonical, stale) {
586
- return syncLabels(this.client, this.repo, canonical, stale);
3185
+ async syncLabels(canonical, stale) {
3186
+ return syncLabels(this.client, this.repo, canonical, stale);
3187
+ }
3188
+ async ensureLabels(labels) {
3189
+ return ensureLabels(this.client, this.repo, labels);
3190
+ }
3191
+ async syncProperties(values) {
3192
+ return syncProperties(this.client, this.repo, values, this.orgClient ?? this.client);
3193
+ }
3194
+ async getOrgPropertyValues(name) {
3195
+ return getOrgPropertyValues(this.orgClient ?? this.client, this.repo, name);
3196
+ }
3197
+ async addOrgPropertyValues(name, values) {
3198
+ return addOrgPropertyValues(this.orgClient ?? this.client, this.repo, name, values, this.orgClient !== void 0);
3199
+ }
3200
+ async checkPropertyValues(values) {
3201
+ return checkPropertyValues(this.orgClient ?? this.client, this.repo, values);
3202
+ }
3203
+ async syncTeams(teams) {
3204
+ return syncTeams(this.orgClient ?? this.client, this.repo, teams);
3205
+ }
3206
+ async teamMembers(teamSlug, org = this.owner) {
3207
+ return (await (this.orgClient ?? this.client).teams.members(org, teamSlug)).map((m) => ({
3208
+ id: String(m.id),
3209
+ login: m.login
3210
+ }));
3211
+ }
3212
+ async readFile(path, repo = this.repo) {
3213
+ return readRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, repo, path);
3214
+ }
3215
+ async writeFile(path, content, opts) {
3216
+ return writeRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, opts.repo ?? this.repo, path, content, opts);
3217
+ }
3218
+ async syncTopics(topics) {
3219
+ return syncTopics(this.client, this.repo, topics);
3220
+ }
3221
+ async syncVariables(variables, opts) {
3222
+ return syncVariables(this.client, this.repo, variables, opts);
3223
+ }
3224
+ async syncOrgVariables(org, variables, opts) {
3225
+ if (!this.orgClient) throw new Error("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron new token github.org <token>`");
3226
+ return syncOrgVariables(this.orgClient, this.repo, org, variables, opts);
3227
+ }
3228
+ async listVariables() {
3229
+ const found = await this.client.variables.listVariables(this.repo, { kind: "repo" });
3230
+ return Object.fromEntries(found.map((v) => [v.name, v.value]));
3231
+ }
3232
+ async listOrgVariables(org) {
3233
+ if (!this.orgClient) throw new MissingTokenError("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron new token github.org <token>`");
3234
+ const found = await this.orgClient.variables.listVariables(this.repo, {
3235
+ kind: "organization",
3236
+ org
3237
+ });
3238
+ return Object.fromEntries(found.map((v) => [v.name, {
3239
+ value: v.value,
3240
+ visibility: v.visibility ?? "all"
3241
+ }]));
3242
+ }
3243
+ async getRepoInfo() {
3244
+ return readRepoInfo(this.client, this.repo);
3245
+ }
3246
+ async getProperties() {
3247
+ const found = await this.client.properties.getValues(this.repo);
3248
+ return Object.fromEntries(found.flatMap((p) => p.value === null ? [] : [[p.property_name, p.value]]));
3249
+ }
3250
+ async listLabels() {
3251
+ return (await this.client.labels.listLabels(this.repo)).map((l) => ({
3252
+ name: l.name,
3253
+ color: l.color,
3254
+ description: l.description ?? ""
3255
+ }));
587
3256
  }
588
- async syncProperties(values) {
589
- return syncProperties(this.client, this.repo, values);
3257
+ async countIssues(query, repo) {
3258
+ return this.client.issues.countSearch(repo ?? this.repo, query);
590
3259
  }
591
- async syncTeams(teams) {
592
- return syncTeams(this.orgClient ?? this.client, this.repo, teams);
3260
+ async listTeamAccess() {
3261
+ return (await (this.orgClient ?? this.client).teams.listForRepo(this.repo)).map((t) => ({
3262
+ slug: t.slug,
3263
+ permission: t.permission
3264
+ }));
593
3265
  }
594
- async syncTopics(topics) {
595
- return syncTopics(this.client, this.repo, topics);
3266
+ async getRulesetDetail(id) {
3267
+ return toRulesetDetail(await this.client.rulesets.getRuleset(this.repo, id));
3268
+ }
3269
+ async getSecurity() {
3270
+ return readSecurity(this.client, this.repo);
596
3271
  }
597
3272
  async syncDescription(description) {
598
3273
  await this.client.repos.updateRepo(this.repo, { description });
@@ -602,16 +3277,64 @@ var GitHubSource = class {
602
3277
  await this.client.repos.updateRepo(this.repo, { homepage });
603
3278
  return "homepage updated";
604
3279
  }
3280
+ /** The client for pull request calls: the pull requests token's, else the repository client. */
3281
+ get pullClient() {
3282
+ return this.pullsClient ?? this.client;
3283
+ }
605
3284
  async getPullRequest(number, repo) {
606
- const raw = await this.client.pulls.getPullRequest(repo ?? this.repo, number);
607
- return {
608
- number: raw.number,
609
- title: raw.title,
610
- state: raw.state,
611
- merged: raw.merged_at !== null,
612
- branch: raw.head.ref,
613
- url: raw.html_url
614
- };
3285
+ return toPullRequest(await this.pullClient.pulls.getPullRequest(repo ?? this.repo, number));
3286
+ }
3287
+ async listPullRequests(state, repo) {
3288
+ return (await this.pullClient.pulls.listPullRequests(repo ?? this.repo, state)).map(toPullRequest);
3289
+ }
3290
+ async readPullRequestState(number, repo, required) {
3291
+ return readPullRequestState(this.pullClient, repo ?? this.repo, number, required);
3292
+ }
3293
+ async listBranches(repo) {
3294
+ return (await this.client.branches.listBranches(repo ?? this.repo)).map((b) => ({
3295
+ name: b.name,
3296
+ sha: b.commit.sha
3297
+ }));
3298
+ }
3299
+ async deleteBranch(name, repo) {
3300
+ try {
3301
+ await this.client.branches.removeBranch(repo ?? this.repo, name);
3302
+ } catch (err) {
3303
+ if (err instanceof ProviderApiError && err.status === 422 && String(err.details).includes("does not exist")) return;
3304
+ throw err;
3305
+ }
3306
+ }
3307
+ async listPullRequestCommits(number, repo) {
3308
+ return (await this.pullClient.pulls.listCommits(repo ?? this.repo, number)).map((commit) => commit.sha);
3309
+ }
3310
+ async listPullRequestFiles(number, repo) {
3311
+ const files = await this.pullClient.pulls.listFiles(repo ?? this.repo, number);
3312
+ return [...new Set(files.flatMap((f) => f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]))];
3313
+ }
3314
+ async createPullRequest(input, repo) {
3315
+ return createPullRequest(this.pullClient, repo ?? this.repo, input, this.orgClient ?? this.pullClient);
3316
+ }
3317
+ async updatePullRequest(number, patch, repo) {
3318
+ return updatePullRequest(this.pullClient, repo ?? this.repo, number, patch, this.orgClient ?? this.pullClient);
3319
+ }
3320
+ async markReady(number, repo) {
3321
+ return markReady(this.pullClient, repo ?? this.repo, number);
3322
+ }
3323
+ async getPullRequestChecks(number, repo, required) {
3324
+ if (required) return readRequiredPullRequestChecks(this.pullClient, repo ?? this.repo, number, required);
3325
+ return readPullRequestChecks(this.pullClient, repo ?? this.repo, number);
3326
+ }
3327
+ async listCheckRuns(ref, repo) {
3328
+ return readCheckRuns(this.client, repo ?? this.repo, ref);
3329
+ }
3330
+ async listCommitStatuses(ref, repo) {
3331
+ return readCommitStatuses(this.client, repo ?? this.repo, ref);
3332
+ }
3333
+ async createCheckRun(sha, name, write, repo) {
3334
+ return postCheckRun(this.client, repo ?? this.repo, sha, name, write);
3335
+ }
3336
+ async updateCheckRun(id, write, repo) {
3337
+ return patchCheckRun(this.client, repo ?? this.repo, id, write);
615
3338
  }
616
3339
  async configurePages(config, token) {
617
3340
  const pagesClient = createGitHubClient$1({
@@ -650,18 +3373,1192 @@ async function ensureDir(path) {
650
3373
  throw err;
651
3374
  }
652
3375
  }
653
- //#endregion
654
- //#region src/verify-token.ts
3376
+ // src/probes/issue-types/github-api.ts
3377
+ const PAGE = 100;
3378
+ const PROJECTS_OF = `query($ids: [ID!]!) { nodes(ids: $ids) { ... on Issue { id projectItems(first: 20) { nodes { project { id } } } } } }`;
3379
+ const ADD_ITEM = `mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`;
3380
+ const ISSUE_TYPES = `query($org: String!) { organization(login: $org) { issueTypes(first: 50) { nodes { name } } } }`;
3381
+ function toItem(issue) {
3382
+ return {
3383
+ number: issue.number,
3384
+ title: issue.title,
3385
+ state: issue.state,
3386
+ labels: issue.labels.map((l) => l.name),
3387
+ type: issue.type?.name ?? null,
3388
+ milestone: issue.milestone ?? null,
3389
+ nodeId: issue.node_id ?? "",
3390
+ isPullRequest: issue.pull_request !== void 0,
3391
+ createdAt: issue.created_at ?? ""
3392
+ };
3393
+ }
3394
+ /**
3395
+ * The backfill's reads and writes over the GitHub client. `client` reads and writes issues (the `github.issues` token);
3396
+ * `orgClient` reads and writes the organization's projects (the `github.org` token). Each method is the one call, or the
3397
+ * fixed few, its name says, so the probe's logic is tested against a fake of {@link BackfillApi} and this stays thin.
3398
+ */
3399
+ function createBackfillApi(client, orgClient, repo) {
3400
+ const org = repo.split("/")[0];
3401
+ const projects = new GitHubProjects(orgClient.graphql, { repo });
3402
+ let fieldList;
3403
+ const fields = async () => fieldList ??= client.issueFields.list(org);
3404
+ return {
3405
+ async list(page) {
3406
+ return (await client.issues.listIssues(repo, {
3407
+ state: "all",
3408
+ sort: "created",
3409
+ direction: "asc",
3410
+ per_page: PAGE,
3411
+ page
3412
+ })).map(toItem);
3413
+ },
3414
+ async get(number) {
3415
+ return toItem(await client.issues.getIssue(repo, number));
3416
+ },
3417
+ async parent(number) {
3418
+ const parent = await client.issues.getParent(repo, number);
3419
+ return parent ? {
3420
+ number: parent.number,
3421
+ milestone: parent.milestone?.number ?? null
3422
+ } : null;
3423
+ },
3424
+ async labelNames() {
3425
+ return new Set((await client.labels.listLabels(repo)).map((l) => l.name.toLowerCase()));
3426
+ },
3427
+ async milestoneNumber(title) {
3428
+ return (await client.issues.listMilestones(repo, { state: "all" })).find((m) => m.title.toLowerCase() === title.toLowerCase())?.number;
3429
+ },
3430
+ async projectId(title) {
3431
+ return (await projects.find(org, title))?.id;
3432
+ },
3433
+ async projectsOf(nodeIds) {
3434
+ const data = await orgClient.graphql.query(PROJECTS_OF, { ids: nodeIds });
3435
+ const out = /* @__PURE__ */ new Map();
3436
+ for (const node of data.nodes) if (node?.id) out.set(node.id, (node.projectItems?.nodes ?? []).map((i) => i.project.id));
3437
+ return out;
3438
+ },
3439
+ async fieldNames() {
3440
+ try {
3441
+ return new Set((await fields()).map((f) => f.name.toLowerCase()));
3442
+ } catch (err) {
3443
+ const why = fieldRefusal(err);
3444
+ if (why === void 0) throw err;
3445
+ return why;
3446
+ }
3447
+ },
3448
+ async fieldValues(number) {
3449
+ const byId = new Map((await fields()).map((f) => [f.id, f.name.toLowerCase()]));
3450
+ const values = await client.issueFields.values(repo, number);
3451
+ return new Set(values.map((v) => v.issue_field_name?.toLowerCase() ?? byId.get(v.issue_field_id) ?? ""));
3452
+ },
3453
+ async files(number) {
3454
+ return (await client.pulls.listFiles(repo, number)).map((f) => f.filename);
3455
+ },
3456
+ async typeNames() {
3457
+ const data = await orgClient.graphql.query(ISSUE_TYPES, { org });
3458
+ return new Set((data.organization?.issueTypes?.nodes ?? []).map((t) => t.name));
3459
+ },
3460
+ async readFile(path) {
3461
+ return (await readRepoFile(client, repo, path))?.content ?? null;
3462
+ },
3463
+ async setType(number, type) {
3464
+ await client.issues.updateIssue(repo, number, { type });
3465
+ },
3466
+ async addLabels(number, labels) {
3467
+ await client.issues.addLabels(repo, number, labels);
3468
+ },
3469
+ async setMilestone(number, milestone) {
3470
+ await client.issues.updateIssue(repo, number, { milestone });
3471
+ },
3472
+ async addToProject(projectId, nodeId) {
3473
+ await orgClient.graphql.query(ADD_ITEM, {
3474
+ project: projectId,
3475
+ content: nodeId
3476
+ });
3477
+ }
3478
+ };
3479
+ }
3480
+ // src/probes/issue-types/gather.ts
3481
+ /** Whether a day (`YYYY-MM-DD`) is before the start of the window. */
3482
+ const before = (item, since) => since !== void 0 && item.createdAt.slice(0, 10) < since;
3483
+ /** The issues named by `--issues`, past the cursor, at most `limit` of them. */
3484
+ async function named(api, options, isRateLimited) {
3485
+ const numbers = [...new Set(options.issues)].sort((a, b) => a - b).filter((n) => n > options.after);
3486
+ const out = {
3487
+ items: [],
3488
+ more: numbers.length > options.limit,
3489
+ rateLimited: false,
3490
+ pullRequestsSkipped: 0
3491
+ };
3492
+ for (const number of numbers.slice(0, options.limit)) try {
3493
+ const item = await api.get(number);
3494
+ if (item.isPullRequest && !options.pullRequests) out.pullRequestsSkipped++;
3495
+ else out.items.push(item);
3496
+ } catch (err) {
3497
+ if (!isRateLimited(err)) throw err;
3498
+ return {
3499
+ ...out,
3500
+ more: true,
3501
+ rateLimited: true
3502
+ };
3503
+ }
3504
+ return out;
3505
+ }
3506
+ /**
3507
+ * The items one run looks at: with `--issues` those numbers, otherwise every issue of the repository oldest first, a
3508
+ * page at a time, past the `--after` cursor and on or after `--since`, until `--limit` are kept. Issue numbers rise with
3509
+ * creation, so the last number read is a cursor the next run can resume from. A rate limit ends the read with what it has.
3510
+ */
3511
+ async function gather(api, options, isRateLimited) {
3512
+ if (options.issues) return named(api, options, isRateLimited);
3513
+ const out = {
3514
+ items: [],
3515
+ more: false,
3516
+ rateLimited: false,
3517
+ pullRequestsSkipped: 0
3518
+ };
3519
+ try {
3520
+ for (let page = 1;; page++) {
3521
+ const batch = await api.list(page);
3522
+ if (batch.length === 0) return out;
3523
+ for (const item of batch) {
3524
+ if (item.number <= options.after || before(item, options.since)) continue;
3525
+ if (item.isPullRequest && !options.pullRequests) {
3526
+ out.pullRequestsSkipped++;
3527
+ continue;
3528
+ }
3529
+ if (out.items.length >= options.limit) return {
3530
+ ...out,
3531
+ more: true
3532
+ };
3533
+ out.items.push(item);
3534
+ }
3535
+ }
3536
+ } catch (err) {
3537
+ if (!isRateLimited(err)) throw err;
3538
+ return {
3539
+ ...out,
3540
+ more: true,
3541
+ rateLimited: true
3542
+ };
3543
+ }
3544
+ }
3545
+ // src/probes/issue-types/kinds.ts
3546
+ /** The kind labels and the Type each one means (spec `tech-github-area-labels`, decision 3). */
3547
+ const DEFAULT_MAIN_KINDS = {
3548
+ bug: "Bug",
3549
+ enhancement: "Feature",
3550
+ chore: "Task"
3551
+ };
3552
+ /** The other kind labels, which mean Task only when none of the main ones is on the issue (issue #2494). */
3553
+ const DEFAULT_FALLBACK_KINDS = Object.fromEntries([
3554
+ "ci",
3555
+ "documentation",
3556
+ "refactor",
3557
+ "test",
3558
+ "performance",
3559
+ "dependencies"
3560
+ ].map((label) => [label, "Task"]));
3561
+ const lowered = (table) => Object.fromEntries(Object.entries(table).map(([label, type]) => [label.toLowerCase(), type]));
3562
+ /** The tables a run uses: what `repo.labels` sets, else the defaults, table by table. */
3563
+ function resolveKinds(config) {
3564
+ return {
3565
+ main: config.kinds ? lowered(config.kinds) : DEFAULT_MAIN_KINDS,
3566
+ fallback: config.fallbackKinds ? lowered(config.fallbackKinds) : DEFAULT_FALLBACK_KINDS
3567
+ };
3568
+ }
3569
+ /** The Types the tables name that `known` (the organization's Types) lacks, each with the labels that use it. */
3570
+ function unknownTypes(kinds, known) {
3571
+ const byType = /* @__PURE__ */ new Map();
3572
+ for (const [label, type] of [...Object.entries(kinds.main), ...Object.entries(kinds.fallback)]) if (!known.has(type)) byType.set(type, [...byType.get(type) ?? [], label]);
3573
+ return [...byType].map(([type, labels]) => ({
3574
+ type,
3575
+ labels
3576
+ }));
3577
+ }
3578
+ // src/probes/issue-types/plan-type.ts
3579
+ /** The labels of an issue that `table` knows, each once (lower case), in the issue's order. */
3580
+ const matching = (labels, table) => [...new Set(labels.map((l) => l.toLowerCase()).filter((l) => Object.hasOwn(table, l)))];
3581
+ /**
3582
+ * The Type an issue gets from its kind labels. One that has a Type keeps it, whatever its labels say. Otherwise the main
3583
+ * table decides (`bug`, `enhancement`, `chore` by default), and only an issue with none of those looks at the fallback
3584
+ * table (`ci`, `documentation`, `refactor`, `test`, `performance`, `dependencies`, all Task by default; #2494). Labels
3585
+ * that point to one Type set it, however many they are; labels that point to two different Types are `ambiguous` and left
3586
+ * for a person (the spec's rule: the probe never picks between two kinds); one with no label in either table has no source.
3587
+ */
3588
+ function planType(item, kinds) {
3589
+ if (item.type) return { skip: "typed" };
3590
+ for (const table of [kinds.main, kinds.fallback]) {
3591
+ const found = matching(item.labels, table);
3592
+ if (found.length === 0) continue;
3593
+ if (new Set(found.map((l) => table[l])).size > 1) return {
3594
+ skip: "ambiguous",
3595
+ labels: found
3596
+ };
3597
+ return { set: table[found[0]] };
3598
+ }
3599
+ return { skip: "no-kind-label" };
3600
+ }
3601
+ // src/probes/issue-types/report.ts
3602
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
3603
+ const GROUPS = [
3604
+ ["project", "a project"],
3605
+ ["milestone", "a milestone"],
3606
+ ["priority", "a Priority"],
3607
+ ["effort", "an Effort"]
3608
+ ];
3609
+ /** The command the maintainer runs to continue, from the cursor. */
3610
+ function resumeCommand(options, cursor) {
3611
+ const flags = ["--after", String(cursor)];
3612
+ if (options.issues) flags.push("--issues", options.issues.join(","));
3613
+ if (options.since) flags.push("--since", options.since);
3614
+ flags.push("--limit", String(options.limit));
3615
+ if (options.repo) flags.push("--repo", options.repo);
3616
+ if (options.milestone) flags.push("--milestone", options.milestone);
3617
+ if (options.project) flags.push("--project", options.project);
3618
+ if (options.pullRequests) flags.push("--pull-requests");
3619
+ return `holocron probe github issue-types -- ${flags.join(" ")}`;
3620
+ }
3621
+ /** Prints the counts, what was left for a person, the lists of what is still missing and how to go on. */
3622
+ function reportBackfill(ctx, input) {
3623
+ const { tally, options, dryRun, more, rateLimited, fields } = input;
3624
+ const verb = dryRun ? "would be set" : "set";
3625
+ ctx.say({
3626
+ status: "heading",
3627
+ label: "Backfill"
3628
+ });
3629
+ const passed = tally.pullRequestsSkipped;
3630
+ ctx.say({
3631
+ status: "info",
3632
+ label: "summary",
3633
+ detail: `read ${plural(tally.examined, "item")}` + (tally.pullRequestsRead > 0 ? ` (${plural(tally.pullRequestsRead, "pull request")})` : "") + `; ${dryRun ? "would change" : "changed"} ${tally.changed}; passed over ${plural(passed, "pull request")}${passed > 0 ? " (give --pull-requests to include them)" : ""}; ${plural(tally.failed, "failure")}` + (more ? `; ${rateLimited ? "stopped by GitHub's rate limit" : `stopped at the limit of ${options.limit}`}, more remain` : "; the window is finished")
3634
+ });
3635
+ const types = Object.entries(tally.typeSet).map(([name, n]) => `${name} ${n}`).join(", ");
3636
+ ctx.say({
3637
+ status: "info",
3638
+ label: "Type",
3639
+ detail: `${types || "none"} ${verb}; ${tally.typed} already typed, ${tally.noKind} with no label that maps to a Type, ${tally.ambiguous.length} with two kind labels`
3640
+ });
3641
+ for (const a of tally.ambiguous) ctx.say({
3642
+ status: "info",
3643
+ label: `#${a.number}`,
3644
+ detail: `has ${a.labels.join(" and ")}: left for a person to choose`
3645
+ });
3646
+ ctx.say({
3647
+ status: "info",
3648
+ label: "area labels",
3649
+ detail: `added to ${plural(tally.areaLabelsAdded, "item")}`
3650
+ });
3651
+ for (const label of tally.missingAreaLabels) ctx.say({
3652
+ status: "info",
3653
+ label,
3654
+ detail: "wanted but the repository has no such label: run `holocron setup` first"
3655
+ });
3656
+ ctx.say({
3657
+ status: "info",
3658
+ label: "milestone",
3659
+ detail: `${verb} on ${tally.milestoneSet.parent + tally.milestoneSet.explicit} (${tally.milestoneSet.parent} from a parent, ${tally.milestoneSet.explicit} from --milestone)`
3660
+ });
3661
+ ctx.say({
3662
+ status: "info",
3663
+ label: "project",
3664
+ detail: `${plural(tally.projectSet, "issue")} ${dryRun ? "would be added" : "added"} from --project`
3665
+ });
3666
+ ctx.say({
3667
+ status: "heading",
3668
+ label: `Still lacking, among the ${plural(tally.examined, "item")} read${dryRun ? ", after the changes above" : ""}`
3669
+ });
3670
+ if (tally.skippedFields !== void 0) ctx.say({
3671
+ status: "fail",
3672
+ label: "Priority, Effort",
3673
+ detail: `NOT checked, so the lists below are incomplete: the token (github.issues) was refused reading the organization issue fields (${tally.skippedFields})`
3674
+ });
3675
+ for (const [group, noun] of GROUPS) {
3676
+ if (!(group === "project" || group === "milestone" || fields.includes(group))) continue;
3677
+ const items = tally.lacking[group];
3678
+ ctx.say({
3679
+ status: "info",
3680
+ label: `without ${noun}`,
3681
+ detail: `${items.length} of ${plural(tally.examined, "item")} read`
3682
+ });
3683
+ for (const item of items) ctx.say({
3684
+ status: "info",
3685
+ label: `#${item.number}`,
3686
+ detail: `${item.state}: ${item.title}`
3687
+ });
3688
+ }
3689
+ if (more && tally.last !== void 0) ctx.say({
3690
+ status: "info",
3691
+ label: "resume",
3692
+ detail: `${rateLimited ? "GitHub's rate limit stopped the run" : "the limit was reached"}; to continue: ${resumeCommand(options, tally.last)}`
3693
+ });
3694
+ else if (more) ctx.say({
3695
+ status: "info",
3696
+ label: "resume",
3697
+ detail: "GitHub's rate limit stopped the run before it finished one item; run it again later"
3698
+ });
3699
+ else ctx.say({
3700
+ status: "info",
3701
+ label: "resume",
3702
+ detail: "the window is finished"
3703
+ });
3704
+ }
3705
+ // src/probes/issue-types/backfill.ts
3706
+ /** The numbers the report is made of. */
3707
+ const emptyTally = () => ({
3708
+ examined: 0,
3709
+ pullRequestsSkipped: 0,
3710
+ typeSet: {},
3711
+ typed: 0,
3712
+ noKind: 0,
3713
+ ambiguous: [],
3714
+ areaLabelsAdded: 0,
3715
+ missingAreaLabels: /* @__PURE__ */ new Set(),
3716
+ milestoneSet: {
3717
+ parent: 0,
3718
+ explicit: 0
3719
+ },
3720
+ projectSet: 0,
3721
+ lacking: {
3722
+ project: [],
3723
+ milestone: [],
3724
+ priority: [],
3725
+ effort: []
3726
+ },
3727
+ failed: 0,
3728
+ changed: 0,
3729
+ pullRequestsRead: 0,
3730
+ last: void 0,
3731
+ skippedFields: void 0
3732
+ });
3733
+ /** How many changes the tally holds, to tell whether one item added any. */
3734
+ const changes = (t) => Object.values(t.typeSet).reduce((a, b) => a + b, 0) + t.areaLabelsAdded + t.milestoneSet.parent + t.milestoneSet.explicit + t.projectSet;
3735
+ /** How an issue is named in a row. */
3736
+ const labelOf = (item) => `#${item.number}`;
3737
+ /** Reads what the run needs before it starts: labels, the named milestone and project, the organization's issue fields. Says why and returns nothing when a name does not exist. */
3738
+ async function prepare(run, tally) {
3739
+ const { api, ctx, options } = run;
3740
+ const known = await api.typeNames();
3741
+ const unknown = unknownTypes(run.kinds, known);
3742
+ for (const { type, labels } of unknown) ctx.say({
3743
+ status: "fail",
3744
+ label: "Type",
3745
+ detail: `${type} (for ${labels.join(", ")}) is not an issue Type of this organization; its Types are ${[...known].join(", ") || "none"}`
3746
+ });
3747
+ if (unknown.length > 0) return void 0;
3748
+ const setup = {
3749
+ labelNames: await api.labelNames(),
3750
+ fields: []
3751
+ };
3752
+ if (options.milestone !== void 0) {
3753
+ setup.milestone = await api.milestoneNumber(options.milestone);
3754
+ if (setup.milestone === void 0) {
3755
+ ctx.say({
3756
+ status: "fail",
3757
+ label: "milestone",
3758
+ detail: `${options.milestone} is not a milestone of this repository`
3759
+ });
3760
+ return;
3761
+ }
3762
+ }
3763
+ if (options.project !== void 0) {
3764
+ setup.projectId = await api.projectId(options.project);
3765
+ if (setup.projectId === void 0) {
3766
+ ctx.say({
3767
+ status: "fail",
3768
+ label: "project",
3769
+ detail: `${options.project} is not a project of this organization`
3770
+ });
3771
+ return;
3772
+ }
3773
+ }
3774
+ const names = await api.fieldNames();
3775
+ if (typeof names === "string") tally.skippedFields = names;
3776
+ else setup.fields = ["priority", "effort"].filter((f) => names.has(f));
3777
+ return setup;
3778
+ }
3779
+ /** Does one issue or pull request; throws for a rate limit or a failed request, which the caller tells apart. */
3780
+ async function handle(run, setup, tally, item, projects) {
3781
+ const { api, ctx, areas, options } = run;
3782
+ const n = item.number;
3783
+ const wanted = item.isPullRequest ? areaLabelsForFiles(await api.files(n), areas.areas) : areaLabelsForTitle(item.title, areas.scopes);
3784
+ const have = new Set(item.labels.map((l) => l.toLowerCase()));
3785
+ const add = [];
3786
+ for (const label of wanted) {
3787
+ if (have.has(label.toLowerCase())) continue;
3788
+ if (setup.labelNames.has(label.toLowerCase())) add.push(label);
3789
+ else tally.missingAreaLabels.add(label);
3790
+ }
3791
+ if (add.length > 0) {
3792
+ await ctx.write(`add ${add.join(", ")} to ${labelOf(item)}`, () => api.addLabels(n, add));
3793
+ tally.areaLabelsAdded++;
3794
+ }
3795
+ if (item.isPullRequest) return;
3796
+ const type = planType(item, run.kinds);
3797
+ if ("set" in type) {
3798
+ await ctx.write(`set Type ${type.set} on ${labelOf(item)}`, () => api.setType(n, type.set));
3799
+ tally.typeSet[type.set] = (tally.typeSet[type.set] ?? 0) + 1;
3800
+ } else if (type.skip === "typed") tally.typed++;
3801
+ else if (type.skip === "no-kind-label") tally.noKind++;
3802
+ else tally.ambiguous.push({
3803
+ number: n,
3804
+ labels: type.labels
3805
+ });
3806
+ let milestone = item.milestone !== null;
3807
+ if (!milestone) {
3808
+ const parent = await api.parent(n);
3809
+ const fromParent = parent?.milestone;
3810
+ const target = fromParent ?? setup.milestone;
3811
+ if (target !== void 0) {
3812
+ const source = typeof fromParent === "number" ? "parent" : "explicit";
3813
+ const why = source === "parent" ? `from its parent #${parent?.number}` : `from --milestone ${options.milestone}`;
3814
+ await ctx.write(`set milestone on ${labelOf(item)} ${why}`, () => api.setMilestone(n, target));
3815
+ tally.milestoneSet[source]++;
3816
+ milestone = true;
3817
+ }
3818
+ }
3819
+ if (!milestone) tally.lacking.milestone.push(item);
3820
+ let onProject = projects.length > 0;
3821
+ if (!onProject && setup.projectId !== void 0) {
3822
+ const id = setup.projectId;
3823
+ await ctx.write(`add ${labelOf(item)} to project ${options.project}`, () => api.addToProject(id, item.nodeId));
3824
+ tally.projectSet++;
3825
+ onProject = true;
3826
+ }
3827
+ if (!onProject) tally.lacking.project.push(item);
3828
+ if (setup.fields.length > 0) {
3829
+ const values = await api.fieldValues(n);
3830
+ for (const field of setup.fields) if (!values.has(field)) tally.lacking[field].push(item);
3831
+ }
3832
+ }
3833
+ /**
3834
+ * The backfill of `holocron probe github issue-types` (spec `tech-github-area-labels`, rollout item 5): reads a window of
3835
+ * issues, and for each adds what it can derive and nothing else.
3836
+ *
3837
+ * - **Type** from the kind labels (`bug`, `enhancement`, `chore`, else Task for `ci`, `documentation`, `refactor`, `test`,
3838
+ * `performance`, `dependencies`); one that has a Type keeps it, one with two kind labels
3839
+ * is listed and left.
3840
+ * - **Area labels** from the title's scope, or, for a pull request with `--pull-requests`, from its changed files; only
3841
+ * added, and only when the label exists (`holocron setup` makes them).
3842
+ * - **Milestone** from the issue's parent, else `--milestone` for an issue in the window named by `--issues` or `--since`.
3843
+ * - **Project** from `--project` for such an issue that is on no project.
3844
+ *
3845
+ * Nothing is overwritten and no label is removed. Priority and Effort are never set, only listed when missing. Every
3846
+ * change goes through `ctx.write`, so `--dry-run` says `would ...` and writes nothing. A rate limit ends the run with the
3847
+ * cursor to resume from; any other failure is a row for that issue and the run goes on.
3848
+ */
3849
+ async function runBackfill(run) {
3850
+ const { ctx, api, options } = run;
3851
+ const tally = emptyTally();
3852
+ const setup = await prepare(run, tally);
3853
+ if (!setup) return;
3854
+ const read = await gather(api, options, run.isRateLimited);
3855
+ tally.pullRequestsSkipped = read.pullRequestsSkipped;
3856
+ const projects = /* @__PURE__ */ new Map();
3857
+ const ids = read.items.filter((i) => !i.isPullRequest).map((i) => i.nodeId);
3858
+ try {
3859
+ for (let at = 0; at < ids.length; at += 100) for (const [id, found] of await api.projectsOf(ids.slice(at, at + 100))) projects.set(id, found);
3860
+ } catch (err) {
3861
+ if (!run.isRateLimited(err)) throw err;
3862
+ read.rateLimited = true;
3863
+ read.more = true;
3864
+ read.items.length = 0;
3865
+ }
3866
+ let stopped = read.rateLimited;
3867
+ for (const item of read.items) {
3868
+ const before = changes(tally);
3869
+ try {
3870
+ await handle(run, setup, tally, item, projects.get(item.nodeId) ?? []);
3871
+ if (changes(tally) > before) tally.changed++;
3872
+ } catch (err) {
3873
+ if (run.isRateLimited(err)) {
3874
+ stopped = true;
3875
+ break;
3876
+ }
3877
+ ctx.say({
3878
+ status: "fail",
3879
+ label: labelOf(item),
3880
+ detail: errorMessage(err)
3881
+ });
3882
+ tally.failed++;
3883
+ }
3884
+ tally.examined++;
3885
+ if (item.isPullRequest) tally.pullRequestsRead++;
3886
+ tally.last = item.number;
3887
+ }
3888
+ reportBackfill(ctx, {
3889
+ tally,
3890
+ options,
3891
+ dryRun: ctx.dryRun,
3892
+ more: read.more || stopped,
3893
+ rateLimited: stopped,
3894
+ fields: setup.fields
3895
+ });
3896
+ }
3897
+ const VALUED = [
3898
+ "--issues",
3899
+ "--since",
3900
+ "--after",
3901
+ "--limit",
3902
+ "--milestone",
3903
+ "--project",
3904
+ "--repo"
3905
+ ];
3906
+ const INTEGER = /^\d+$/;
3907
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
3908
+ const MAX_RANGE = 1e3;
3909
+ const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
3910
+ /** `12,15,20-23` to `[12, 15, 20, 21, 22, 23]`, or `undefined` for text that is not such a list. */
3911
+ function numbersOf(text) {
3912
+ const out = [];
3913
+ for (const part of text.split(",")) {
3914
+ const [from, to, ...rest] = part.trim().split("-");
3915
+ if (rest.length > 0 || !INTEGER.test(from)) return void 0;
3916
+ const end = to === void 0 ? Number(from) : INTEGER.test(to) ? Number(to) : -1;
3917
+ if (end < Number(from) || end - Number(from) > MAX_RANGE) return void 0;
3918
+ for (let n = Number(from); n <= end; n++) out.push(n);
3919
+ }
3920
+ return out;
3921
+ }
3922
+ /** The words after `issue-types`, read into options, or the one thing wrong with them. */
3923
+ function parseArgs(args) {
3924
+ const options = {
3925
+ after: 0,
3926
+ limit: 100,
3927
+ pullRequests: false,
3928
+ repos: []
3929
+ };
3930
+ for (let i = 0; i < args.length; i++) {
3931
+ const flag = args[i];
3932
+ if (flag === "--pull-requests") {
3933
+ options.pullRequests = true;
3934
+ continue;
3935
+ }
3936
+ if (!VALUED.includes(flag)) return {
3937
+ ok: false,
3938
+ message: `unknown argument ${flag}`
3939
+ };
3940
+ const value = args[++i];
3941
+ if (value === void 0 || value.startsWith("--")) return {
3942
+ ok: false,
3943
+ message: `${flag} needs a value`
3944
+ };
3945
+ if (flag === "--issues") {
3946
+ const issues = numbersOf(value);
3947
+ if (!issues) return {
3948
+ ok: false,
3949
+ message: `--issues takes numbers and ranges such as 12,15,20-25, not ${value}`
3950
+ };
3951
+ options.issues = issues;
3952
+ } else if (flag === "--since") {
3953
+ if (!DAY.test(value)) return {
3954
+ ok: false,
3955
+ message: `--since takes a day as YYYY-MM-DD, not ${value}`
3956
+ };
3957
+ options.since = value;
3958
+ } else if (flag === "--after") {
3959
+ if (!INTEGER.test(value)) return {
3960
+ ok: false,
3961
+ message: `--after takes a whole number, not ${value}`
3962
+ };
3963
+ options.after = Number(value);
3964
+ } else if (flag === "--limit") {
3965
+ if (!INTEGER.test(value) || Number(value) < 1) return {
3966
+ ok: false,
3967
+ message: `--limit takes a whole number of at least 1, not ${value}`
3968
+ };
3969
+ options.limit = Number(value);
3970
+ } else if (flag === "--repo") {
3971
+ if (!REPOSITORY.test(value)) return {
3972
+ ok: false,
3973
+ message: `--repo takes owner/name, not ${value}`
3974
+ };
3975
+ if (!options.repos.includes(value)) options.repos.push(value);
3976
+ } else if (flag === "--milestone") options.milestone = value;
3977
+ else options.project = value;
3978
+ }
3979
+ if ((options.milestone || options.project) && !options.issues && !options.since) return {
3980
+ ok: false,
3981
+ message: "--milestone and --project need a window to apply to: name it with --issues or --since"
3982
+ };
3983
+ if (options.repos.length > 1 && (options.issues || options.after > 0)) return {
3984
+ ok: false,
3985
+ message: "--issues and --after are numbers of one repository, so they cannot go with more than one --repo"
3986
+ };
3987
+ return {
3988
+ ok: true,
3989
+ options
3990
+ };
3991
+ }
3992
+ // src/probes/issue-types/repo-areas.ts
3993
+ /** Where a repository without a `package.json` declares `repo.labels` (the `repo` area file, spec `tech-holocron-directory`). */
3994
+ const AREA_FILE_JSON = ".holocron/repo.json";
3995
+ const AREA_FILE_TS = ".holocron/repo.ts";
3996
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3997
+ /** `repo.labels.areas` and `scopes` as the mapping reads them, or `undefined` for a shape it cannot use. */
3998
+ function areaMap(labels) {
3999
+ if (!isRecord(labels) || !isRecord(labels.areas) || Object.keys(labels.areas).length === 0) return void 0;
4000
+ const areas = labels.areas;
4001
+ if (!Object.values(areas).every((p) => Array.isArray(p) && p.every((x) => typeof x === "string"))) return void 0;
4002
+ const scopes = isRecord(labels.scopes) ? labels.scopes : {};
4003
+ if (!Object.values(scopes).every((a) => typeof a === "string")) return void 0;
4004
+ return {
4005
+ areas,
4006
+ scopes
4007
+ };
4008
+ }
4009
+ const none = (detail) => ({
4010
+ areas: {},
4011
+ row: {
4012
+ status: "info",
4013
+ label: "area labels",
4014
+ detail
4015
+ }
4016
+ });
4017
+ /**
4018
+ * The area labels another repository declares (spec `tech-backfill-config-mapping`), read from its own
4019
+ * `.holocron/repo.json`. A `.holocron/repo.ts` is TypeScript, which only Sentinel's remote config reader evaluates and a
4020
+ * plugin cannot reach, so that repository gets a skipped row and no area step; so does one with no declaration. Never
4021
+ * throws for a missing or unusable file: the Type step of the repository still runs.
4022
+ */
4023
+ async function readRepoAreas(api) {
4024
+ const json = await api.readFile(AREA_FILE_JSON);
4025
+ if (json !== null) {
4026
+ let parsed;
4027
+ try {
4028
+ parsed = JSON.parse(json);
4029
+ } catch (err) {
4030
+ return {
4031
+ areas: {},
4032
+ row: {
4033
+ status: "fail",
4034
+ label: "area labels",
4035
+ detail: `${AREA_FILE_JSON} is not JSON (${errorMessage(err)})`
4036
+ }
4037
+ };
4038
+ }
4039
+ const found = areaMap(isRecord(parsed) ? parsed.labels : void 0);
4040
+ return found ? {
4041
+ areas: found,
4042
+ row: {
4043
+ status: "info",
4044
+ label: "area labels",
4045
+ detail: `read from ${AREA_FILE_JSON}`
4046
+ }
4047
+ } : none(`skipped: ${AREA_FILE_JSON} declares no usable \`labels.areas\`, so no area labels are added`);
4048
+ }
4049
+ if (await api.readFile(AREA_FILE_TS) !== null) return none(`skipped: its areas are in ${AREA_FILE_TS}, which is TypeScript the probe cannot evaluate (only Sentinel's config reader does); no area labels are added`);
4050
+ return none(`skipped: it has no ${AREA_FILE_JSON} or ${AREA_FILE_TS}, so no area labels are added`);
4051
+ }
4052
+ // src/probes/issue-types/issue-types.ts
4053
+ /**
4054
+ * `holocron probe github issue-types`: the one-time backfill of spec `tech-github-area-labels` (rollout item 5), a writer
4055
+ * the maintainer runs. It sets the Type of an issue from its kind labels, adds `area:<name>` labels, fills a milestone
4056
+ * and a project where a source exists, and ends with the list of every issue it read that still lacks a project, a
4057
+ * milestone, a Priority or an Effort. See `backfill.ts` for the rules. Run it with `--dry-run` first.
4058
+ *
4059
+ * The kind labels and the repositories come from `repo.labels` (`kinds`, `fallbackKinds`, `repos`) and `--repo`, and a
4060
+ * repository other than this one has its area labels read from its own `.holocron/repo.json` (spec
4061
+ * `tech-backfill-config-mapping`).
4062
+ *
4063
+ * Not verified against the live API: writing an issue's Type, adding an issue to a project, reading the organization's
4064
+ * issue Types, and the endpoints that read an issue's field values and parent.
4065
+ */
4066
+ function issueTypesProbe(ctx) {
4067
+ return {
4068
+ summary: "Backfill issues: set Type from the kind labels, add area labels, fill milestone and project where a source exists, and list what still lacks a project, milestone, Priority or Effort. Never overwrites a value. Run with --dry-run first.",
4069
+ writes: true,
4070
+ async run(probe) {
4071
+ const parsed = parseArgs(probe.args ?? []);
4072
+ if (!parsed.ok) {
4073
+ probe.say({
4074
+ status: "fail",
4075
+ label: "arguments",
4076
+ detail: parsed.message
4077
+ });
4078
+ return;
4079
+ }
4080
+ const named = parsed.options.repos;
4081
+ const repos = named.length > 0 ? named : ctx.config.repos?.length ? ctx.config.repos : [ctx.repo];
4082
+ const kinds = resolveKinds(ctx.config);
4083
+ for (const repo of repos) {
4084
+ if (repos.length > 1) probe.say({
4085
+ status: "heading",
4086
+ label: repo
4087
+ });
4088
+ try {
4089
+ const api = ctx.makeApi(repo);
4090
+ let areas = ctx.config;
4091
+ if (repo.toLowerCase() !== ctx.repo.toLowerCase()) {
4092
+ const found = await readRepoAreas(api);
4093
+ probe.say(found.row);
4094
+ areas = found.areas;
4095
+ }
4096
+ await runBackfill({
4097
+ ctx: probe,
4098
+ api,
4099
+ options: {
4100
+ ...parsed.options,
4101
+ repo: named.length > 0 || repos.length > 1 ? repo : void 0
4102
+ },
4103
+ areas,
4104
+ kinds,
4105
+ isRateLimited
4106
+ });
4107
+ } catch (err) {
4108
+ probe.say({
4109
+ status: "fail",
4110
+ label: "issue-types",
4111
+ detail: errorMessage(err)
4112
+ });
4113
+ }
4114
+ }
4115
+ }
4116
+ };
4117
+ }
4118
+ // src/probes/token/expectations.ts
4119
+ /**
4120
+ * The same rules in every layer that runs the workflow: a laptop (`local` inherits `dev`) and CI, and the `agent` layer
4121
+ * for a token an agent may hold (spec `tech-agent-secrets`), which has the same rules and its own value.
4122
+ */
4123
+ function everywhere(rules, layers = {}) {
4124
+ return { permissions: {
4125
+ local: rules,
4126
+ dev: rules,
4127
+ ci: rules,
4128
+ ...layers.agent ? { agent: rules } : {}
4129
+ } };
4130
+ }
4131
+ /**
4132
+ * `rules` everywhere, plus a permission only a person at a terminal needs: `local` and `dev` must have `held`, and `ci`
4133
+ * must not have `ci` (a workflow's token needs no more than it uses).
4134
+ */
4135
+ function withoutInCi(rules, held, ci) {
4136
+ return { permissions: {
4137
+ local: {
4138
+ ...rules,
4139
+ ...held
4140
+ },
4141
+ dev: {
4142
+ ...rules,
4143
+ ...held
4144
+ },
4145
+ ci: {
4146
+ ...rules,
4147
+ ...ci
4148
+ }
4149
+ } };
4150
+ }
4151
+ /**
4152
+ * What each GitHub token is meant to carry, by its `envName`, the same as the GitHub tokens table in
4153
+ * `docs/src/content/docs/tokens.mdx`. This is the plugin's `tokens` declaration, read through `tokenExpectations()`;
4154
+ * change it and that table together.
4155
+ *
4156
+ * Every token CI uses (the `sync-repo`, `sync-secrets`, `reconcile-projects` and `check-tokens` workflows read all of
4157
+ * them) is declared with the same permissions in `local`, `dev` and `ci`, so the probe checks that a `ci` token is no
4158
+ * broader than its `dev` one rather than assuming a split the workflows do not allow. The release token is held by CI
4159
+ * only, so it has no `local` or `dev` entry. A narrow token must not reach administration or secrets; the admin token
4160
+ * must not reach organization secrets (that is `HOLOCRON_SECRETS_TOKEN`'s alone).
4161
+ */
4162
+ const EXPECTED = {
4163
+ HOLOCRON_READ_TOKEN: everywhere({
4164
+ contents: "required",
4165
+ actions: "required",
4166
+ administration: "absent",
4167
+ secrets: "absent",
4168
+ environments: "absent"
4169
+ }, { agent: true }),
4170
+ HOLOCRON_ISSUES_TOKEN: everywhere({
4171
+ issues: "required",
4172
+ administration: "absent",
4173
+ secrets: "absent",
4174
+ environments: "absent"
4175
+ }, { agent: true }),
4176
+ HOLOCRON_PULLS_TOKEN: { permissions: { agent: {
4177
+ "pull-requests": "required",
4178
+ contents: "required",
4179
+ administration: "absent",
4180
+ secrets: "absent",
4181
+ environments: "absent",
4182
+ actions: "absent"
4183
+ } } },
4184
+ HOLOCRON_SYNC_TOKEN: everywhere({
4185
+ actions: "required",
4186
+ contents: "required",
4187
+ "pull-requests": "required",
4188
+ administration: "absent",
4189
+ secrets: "absent"
4190
+ }),
4191
+ HOLOCRON_RELEASE_TOKEN: { permissions: { ci: {
4192
+ contents: "required",
4193
+ issues: "required",
4194
+ "pull-requests": "required",
4195
+ administration: "absent",
4196
+ secrets: "absent"
4197
+ } } },
4198
+ HOLOCRON_ADMIN_TOKEN: withoutInCi({
4199
+ administration: "required",
4200
+ secrets: "required",
4201
+ environments: "required",
4202
+ issues: "required",
4203
+ "custom-properties": "required",
4204
+ "actions-variables": "required",
4205
+ "org-secrets": "absent"
4206
+ }, { webhooks: "required" }, { webhooks: "absent" }),
4207
+ HOLOCRON_SECRETS_TOKEN: everywhere({
4208
+ "org-secrets": "required",
4209
+ administration: "absent"
4210
+ }),
4211
+ HOLOCRON_DEPLOY_TOKEN: everywhere({
4212
+ pages: "required",
4213
+ administration: "required",
4214
+ secrets: "absent",
4215
+ "org-secrets": "absent"
4216
+ }),
4217
+ HOLOCRON_USER_SYNC_TOKEN: everywhere({
4218
+ "user-sync-contents": "required",
4219
+ administration: "absent",
4220
+ secrets: "absent"
4221
+ }),
4222
+ HOLOCRON_ORG_TOKEN: withoutInCi({
4223
+ administration: "required",
4224
+ "org-members": "required",
4225
+ "org-variables": "required",
4226
+ "org-secrets": "absent"
4227
+ }, { "org-webhooks": "required" }, { "org-webhooks": "absent" })
4228
+ };
4229
+ // src/tokens.ts
4230
+ /** The page that makes a fine-grained personal access token, where every token of this plugin is made. */
4231
+ const TOKEN_PAGE = "https://github.com/settings/personal-access-tokens/new";
4232
+ /** Adds what a layer's token must and must not be able to do (`EXPECTED`, by `envName`) and where it is made to a token. */
4233
+ function declared(token) {
4234
+ return {
4235
+ ...token,
4236
+ page: TOKEN_PAGE,
4237
+ expect: EXPECTED[token.envName]
4238
+ };
4239
+ }
4240
+ /**
4241
+ * Every token this plugin takes, for `holocron doctor tokens`, with what each layer's token must and must not be able
4242
+ * to do. The release token is `optional`: only CI's release workflow reads it (from the org secret), so a development
4243
+ * environment has no reason to hold it. So is the pull requests token: only the `agent` layer holds it, because a person
4244
+ * has the admin token the `source` capability falls back to.
4245
+ */
4246
+ const tokens = [
4247
+ declared(resolveReadToken.token),
4248
+ declared(resolveIssuesToken.token),
4249
+ declared({
4250
+ ...resolvePullsToken.token,
4251
+ optional: true
4252
+ }),
4253
+ declared(resolveSyncToken.token),
4254
+ declared({
4255
+ ...resolveReleaseToken.token,
4256
+ optional: true
4257
+ }),
4258
+ declared(resolveAdminToken.token),
4259
+ declared(resolveSecretsToken.token),
4260
+ declared(resolveDeployToken.token),
4261
+ declared(resolveUserSyncToken.token),
4262
+ declared(resolveOrgToken.token)
4263
+ ];
4264
+ // src/probes/token/parse-token-args.ts
4265
+ /** Reads the words after the probe name: `--layer <word>` and `--token-name <VAR>`, in either spelling. */
4266
+ function parseTokenArgs(args) {
4267
+ let layer;
4268
+ let tokenName;
4269
+ for (let i = 0; i < args.length; i++) {
4270
+ const arg = args[i];
4271
+ if (arg === "--layer") layer = args[++i];
4272
+ else if (arg.startsWith("--layer=")) layer = arg.slice(8);
4273
+ else if (arg === "--token-name") tokenName = args[++i];
4274
+ else if (arg.startsWith("--token-name=")) tokenName = arg.slice(13);
4275
+ }
4276
+ return {
4277
+ ...layer ? { layer } : {},
4278
+ ...tokenName ? { tokenName } : {}
4279
+ };
4280
+ }
4281
+ // src/probes/token/permissions.ts
4282
+ /**
4283
+ * Every permission the GitHub plugin's tokens are declared against, by the name the declaration uses, with one read
4284
+ * that needs it. A read proves the token can see the area, not that it can write to it: GitHub exposes no list of a
4285
+ * fine-grained token's permissions, so the write half of `read/write` is taken from the permission table in
4286
+ * `docs/src/content/docs/tokens.mdx`. On a public repository the `contents`, `actions`, `issues`, `pull-requests` and `environments`
4287
+ * reads succeed for any token, so only the other permissions can prove a permission absent. Names with more than one
4288
+ * word are hyphenated, not underscored: `holocron probe docs tokens` strips `_` (Markdown emphasis) from a table cell
4289
+ * before it compares the id with the declaration.
4290
+ */
4291
+ const PERMISSIONS = {
4292
+ contents: {
4293
+ label: "Contents",
4294
+ path: "/repos/{r}/contents",
4295
+ publicRead: true
4296
+ },
4297
+ actions: {
4298
+ label: "Actions",
4299
+ path: "/repos/{r}/actions/runs?per_page=1",
4300
+ publicRead: true
4301
+ },
4302
+ issues: {
4303
+ label: "Issues",
4304
+ path: "/repos/{r}/issues?per_page=1",
4305
+ publicRead: true
4306
+ },
4307
+ "pull-requests": {
4308
+ label: "Pull requests",
4309
+ path: "/repos/{r}/pulls?per_page=1",
4310
+ publicRead: true
4311
+ },
4312
+ administration: {
4313
+ label: "Administration",
4314
+ path: "/repos/{r}/actions/permissions"
4315
+ },
4316
+ secrets: {
4317
+ label: "Secrets",
4318
+ path: "/repos/{r}/actions/secrets?per_page=1"
4319
+ },
4320
+ environments: {
4321
+ label: "Environments",
4322
+ path: "/repos/{r}/environments?per_page=1",
4323
+ publicRead: true
4324
+ },
4325
+ "actions-variables": {
4326
+ label: "Variables",
4327
+ path: "/repos/{r}/actions/variables?per_page=1"
4328
+ },
4329
+ "custom-properties": {
4330
+ label: "Custom properties",
4331
+ path: "/repos/{r}/properties/values"
4332
+ },
4333
+ pages: {
4334
+ label: "Pages",
4335
+ path: "/repos/{r}/pages"
4336
+ },
4337
+ webhooks: {
4338
+ label: "Webhooks",
4339
+ path: "/repos/{r}/hooks?per_page=1"
4340
+ },
4341
+ "org-webhooks": {
4342
+ label: "Organization: Webhooks",
4343
+ path: "/orgs/{o}/hooks?per_page=1"
4344
+ },
4345
+ "org-members": {
4346
+ label: "Organization: Members",
4347
+ path: "/orgs/{o}/members?per_page=1"
4348
+ },
4349
+ "org-variables": {
4350
+ label: "Organization: Variables",
4351
+ path: "/orgs/{o}/actions/variables?per_page=1"
4352
+ },
4353
+ "org-secrets": {
4354
+ label: "Organization: Secrets",
4355
+ path: "/orgs/{o}/actions/secrets?per_page=1"
4356
+ },
4357
+ "issue-fields": {
4358
+ label: "Organization: Issue fields",
4359
+ path: "/orgs/{o}/issue-fields"
4360
+ },
4361
+ "issue-types": {
4362
+ label: "Organization: Issue types",
4363
+ path: "/orgs/{o}/issue-types"
4364
+ },
4365
+ "user-sync-contents": {
4366
+ label: "Contents (.github-private)",
4367
+ path: "/repos/{o}/.github-private/contents"
4368
+ }
4369
+ };
4370
+ // src/probes/token/token.ts
4371
+ /** The token checked when none is named: the one the plugin reads with by default. */
4372
+ const DEFAULT_TOKEN = "HOLOCRON_READ_TOKEN";
4373
+ /** Does one GET with the token; the response headers are returned for the caller that wants them. */
4374
+ async function get(ctx, token, path) {
4375
+ return ctx.fetch(`${ctx.baseUrl}${path}`, { headers: {
4376
+ authorization: `Bearer ${token}`,
4377
+ accept: "application/vnd.github+json",
4378
+ "x-github-api-version": "2022-11-28",
4379
+ "user-agent": "holocron-probe"
4380
+ } });
4381
+ }
4382
+ /**
4383
+ * One read for one permission. GitHub answers a token without the permission with a 403, or a 404 for something it will
4384
+ * not admit exists, so both are `none`; a 2xx is `has`. Any other status, or a request that did not go through, is an
4385
+ * `error`, which is a failure whatever the layer expects.
4386
+ */
4387
+ async function reach(ctx, token, permission) {
4388
+ const [owner = ""] = ctx.repo.split("/");
4389
+ const path = PERMISSIONS[permission].path.replaceAll("{r}", ctx.repo).replaceAll("{o}", owner);
4390
+ try {
4391
+ const res = await get(ctx, token, path);
4392
+ if (res.ok) return {
4393
+ kind: "has",
4394
+ detail: `read ${path.split("?")[0]}`
4395
+ };
4396
+ if (res.status === 403 || res.status === 404) return {
4397
+ kind: "none",
4398
+ detail: `no access (${res.status})`
4399
+ };
4400
+ return {
4401
+ kind: "error",
4402
+ detail: `${res.status} ${res.statusText}`.trim()
4403
+ };
4404
+ } catch (err) {
4405
+ return {
4406
+ kind: "error",
4407
+ detail: errorMessage(err)
4408
+ };
4409
+ }
4410
+ }
4411
+ /**
4412
+ * One row for what was tried. With no rule it only describes (`ok` for access, `info` for none). Under a layer's rule it
4413
+ * judges: a required permission the token lacks fails, and one the layer must not have fails when the token has it; a
4414
+ * permission that is rightly absent is a bare `ok`.
4415
+ */
4416
+ function rowFor({ label, permission, outcome }, rule) {
4417
+ if (outcome.kind === "error") return {
4418
+ status: "fail",
4419
+ label,
4420
+ detail: outcome.detail
4421
+ };
4422
+ const has = outcome.kind === "has";
4423
+ if (rule === "required") return {
4424
+ status: has ? "ok" : "fail",
4425
+ label,
4426
+ detail: outcome.detail
4427
+ };
4428
+ if (rule === "absent" && has && PERMISSIONS[permission].publicRead) return {
4429
+ status: "info",
4430
+ label,
4431
+ detail: `${outcome.detail}, which any token can on a public repository: not proof either way`
4432
+ };
4433
+ if (rule === "absent") return has ? {
4434
+ status: "fail",
4435
+ label,
4436
+ detail: outcome.detail
4437
+ } : {
4438
+ status: "ok",
4439
+ label
4440
+ };
4441
+ return {
4442
+ status: has ? "ok" : "info",
4443
+ label,
4444
+ detail: outcome.detail
4445
+ };
4446
+ }
655
4447
  /**
656
- * `verifyToken` — plugin-level export used by `holocron auth set` +
657
- * `holocron auth check`. Hits `GET /user` and translates the response
658
- * into the normalized `VerifyTokenResult` shape.
4448
+ * The `token` probe: `holocron probe github token` tries each permission Holocron uses with one of the plugin's nine
4449
+ * tokens and reports which ones the token reaches. It only reads (one GET per permission), so it changes nothing, and a
4450
+ * read proves the token can see an area, not that it can write there.
659
4451
  *
660
- * Kept as a standalone function (not a capability method) so the auth
661
- * command can call it without initializing the full plugin — plugin
662
- * construction requires an already-resolved token, which is exactly
663
- * what we don't have yet at bootstrap time.
4452
+ * GitHub lists scopes only for a classic token (the `X-OAuth-Scopes` header on any response), so a classic token's scopes
4453
+ * are shown. A fine-grained token has no list, so the permissions are found by trying them; the first row says which kind
4454
+ * was read. With `--environment <layer>` the CLI runs the probe once for each token the Environment holds and hands it
4455
+ * `--token-name <envName>` (and the token itself as `cliToken`); by hand, `--token-name` picks which token the plugin
4456
+ * resolves (default `HOLOCRON_READ_TOKEN`).
4457
+ *
4458
+ * With no layer the token is only described. When the CLI passes `--layer` (because `--environment` named `ci`, `dev` or
4459
+ * `local`), the results are judged against what that token is meant to carry in that layer (the plugin's `tokens`
4460
+ * declaration, read with `tokenExpectations()`) and shown in two groups, what it should have and what it should not,
4461
+ * where a missing or extra permission fails. A judged token also gets a `Rotation` group: its expiry (GitHub's
4462
+ * `github-authentication-token-expiration` header) against the layer's rotation, failing under 14 days left.
664
4463
  */
4464
+ function tokenProbe(ctx) {
4465
+ return {
4466
+ summary: "Try each GitHub permission Holocron uses (contents, actions, issues, administration, secrets, ...) with one of the plugin's tokens and report which it reaches; for a ci or dev Environment, check it against what that layer should carry. Read-only.",
4467
+ writes: false,
4468
+ acceptsToken: true,
4469
+ async run(probe) {
4470
+ const { layer, tokenName } = parseTokenArgs(probe.args ?? []);
4471
+ const envName = tokenName ?? DEFAULT_TOKEN;
4472
+ const token = ctx.resolve(envName);
4473
+ if (token === void 0) {
4474
+ probe.say({
4475
+ status: "fail",
4476
+ label: envName,
4477
+ detail: `not a GitHub token; use one of: ${ctx.tokenNames.join(", ")}`
4478
+ });
4479
+ return;
4480
+ }
4481
+ probe.secret(token);
4482
+ let identity;
4483
+ try {
4484
+ identity = await get(ctx, token, "/user");
4485
+ } catch (err) {
4486
+ probe.say({
4487
+ status: "fail",
4488
+ label: "token",
4489
+ detail: errorMessage(err)
4490
+ });
4491
+ return;
4492
+ }
4493
+ if (identity.status === 401) {
4494
+ probe.say({
4495
+ status: "fail",
4496
+ label: "token",
4497
+ detail: "rejected by GitHub (401): expired, revoked or not a token"
4498
+ });
4499
+ return;
4500
+ }
4501
+ const scopes = identity.headers.get("x-oauth-scopes");
4502
+ const expiresAt = parseTokenExpiration(identity.headers.get("github-authentication-token-expiration"));
4503
+ probe.say({
4504
+ status: "ok",
4505
+ label: "token",
4506
+ detail: scopes === null ? "fine-grained (GitHub lists no permissions for one, so each is tried with a read)" : `classic (scopes: ${scopes === "" ? "none" : scopes}); each permission is also tried with a read`
4507
+ });
4508
+ const declared = layer ? tokenExpectations(tokens, {
4509
+ layer,
4510
+ envName
4511
+ })[0] : void 0;
4512
+ if (layer && !declared) probe.say({
4513
+ status: "info",
4514
+ label: layer,
4515
+ detail: "no expectations are declared for this token there, so it is only described"
4516
+ });
4517
+ const rules = declared?.rules ?? {};
4518
+ const names = declared ? Object.keys(rules) : Object.keys(PERMISSIONS);
4519
+ const tried = [];
4520
+ for (const permission of names) tried.push({
4521
+ label: PERMISSIONS[permission].label,
4522
+ permission,
4523
+ outcome: await reach(ctx, token, permission)
4524
+ });
4525
+ if (!declared) {
4526
+ for (const t of tried) probe.say(rowFor(t, void 0));
4527
+ return;
4528
+ }
4529
+ for (const [heading, rule] of [["Should have", "required"], ["Should not have", "absent"]]) {
4530
+ const inGroup = tried.filter((t) => rules[t.permission] === rule);
4531
+ if (inGroup.length === 0) continue;
4532
+ probe.say({
4533
+ status: "heading",
4534
+ label: heading
4535
+ });
4536
+ for (const t of inGroup) probe.say(rowFor(t, rule));
4537
+ }
4538
+ probe.say({
4539
+ status: "heading",
4540
+ label: "Rotation"
4541
+ });
4542
+ for (const r of tokenRotationRows(expiresAt ? { expiresAt } : {}, declared.rotation, (ctx.now ?? (() => /* @__PURE__ */ new Date()))())) probe.say(r);
4543
+ }
4544
+ };
4545
+ }
4546
+ // src/token-resolvers.ts
4547
+ /** Each token's resolver by its environment variable (`HOLOCRON_ADMIN_TOKEN`), which is what `--token-name` carries. */
4548
+ const TOKEN_RESOLVERS = {
4549
+ HOLOCRON_READ_TOKEN: resolveReadToken,
4550
+ HOLOCRON_ISSUES_TOKEN: resolveIssuesToken,
4551
+ HOLOCRON_PULLS_TOKEN: resolvePullsToken,
4552
+ HOLOCRON_SYNC_TOKEN: resolveSyncToken,
4553
+ HOLOCRON_RELEASE_TOKEN: resolveReleaseToken,
4554
+ HOLOCRON_ADMIN_TOKEN: resolveAdminToken,
4555
+ HOLOCRON_SECRETS_TOKEN: resolveSecretsToken,
4556
+ HOLOCRON_DEPLOY_TOKEN: resolveDeployToken,
4557
+ HOLOCRON_USER_SYNC_TOKEN: resolveUserSyncToken,
4558
+ HOLOCRON_ORG_TOKEN: resolveOrgToken
4559
+ };
4560
+ // src/verify-token.ts
4561
+ /** Checks a token against `GET /user` and returns who it belongs to, or why it failed. */
665
4562
  async function verifyToken(token, opts = {}) {
666
4563
  const client = createGitHubClient({
667
4564
  token,
@@ -669,43 +4566,91 @@ async function verifyToken(token, opts = {}) {
669
4566
  fetch: opts.fetch
670
4567
  });
671
4568
  try {
672
- const me = await client.user.getCurrentUser();
4569
+ const { user: me, expiresAt } = await client.user.getCurrentUserWithExpiry();
673
4570
  return {
674
4571
  ok: true,
675
- subject: `user @ ${me.login ?? me.email ?? "unknown"}`
4572
+ subject: `user @ ${me.login ?? me.email ?? "unknown"}`,
4573
+ ...expiresAt ? { expiresAt } : {}
676
4574
  };
677
4575
  } catch (err) {
678
4576
  return {
679
4577
  ok: false,
680
- message: err instanceof Error ? err.message : String(err)
4578
+ message: errorMessage(err)
681
4579
  };
682
4580
  }
683
4581
  }
684
- //#endregion
685
- //#region src/index.ts
686
- function source(ctx, orgClient) {
4582
+ /**
4583
+ * GitHub's `whoami`. The plugin holds nine tokens, so the one described is the option `whoamiToken` (an environment
4584
+ * variable name such as `HOLOCRON_ADMIN_TOKEN`, set through `--with whoamiToken=...`), default `HOLOCRON_READ_TOKEN`.
4585
+ * The first row says which token that is and why; the rest are `whoamiAction()`'s, over that token's declaration only.
4586
+ * An unknown name is a failing row listing the known ones. GitHub sends a token's expiry on the `GET /user` response,
4587
+ * which `verifyToken` already reads, so no separate lifetime call is made.
4588
+ */
4589
+ function whoamiToken(options, deps) {
4590
+ const name = options.whoamiToken ?? "HOLOCRON_READ_TOKEN";
4591
+ const how = options.whoamiToken === void 0 ? "the default" : "chosen by the whoamiToken option";
4592
+ const resolver = deps.resolvers[name];
4593
+ return async (ctx) => {
4594
+ if (!resolver) return [{
4595
+ id: "github:whoami:token",
4596
+ title: "github token",
4597
+ status: "fail",
4598
+ detail: `${name} is not a GitHub token of this plugin`,
4599
+ problems: [`known: ${Object.keys(deps.resolvers).join(", ")}`]
4600
+ }];
4601
+ const action = deps.build({
4602
+ provider: "github",
4603
+ token: () => resolver(options),
4604
+ tokens: deps.tokens.filter((t) => t.envName === name),
4605
+ proveWith: `holocron probe github token --environment <layer> (or --token-name ${name})`
4606
+ });
4607
+ return [{
4608
+ id: "github:whoami:token",
4609
+ title: "token",
4610
+ status: "ok",
4611
+ detail: `${name} (${how}; the plugin holds ${Object.keys(deps.resolvers).length} tokens)`,
4612
+ problems: []
4613
+ }, ...await action(ctx)];
4614
+ };
4615
+ }
4616
+ // src/index.ts
4617
+ /** Builds the `source` capability; the optional clients cover org-level, user-sync and pull request access. */
4618
+ function source(ctx, orgClient, userSyncClient, pullsClient) {
687
4619
  return new GitHubSource(ctx.client, {
688
4620
  repo: ctx.repo,
689
4621
  repoRoot: ctx.repoRoot,
690
4622
  orgClient,
4623
+ userSyncClient,
4624
+ pullsClient,
691
4625
  baseUrl: ctx.options.baseUrl,
692
4626
  fetch: ctx.options.fetch
693
4627
  });
694
4628
  }
695
- function secrets(ctx) {
696
- return new GitHubSecrets(ctx.client, { repo: ctx.repo });
4629
+ /** Builds the `secrets` capability; the optional client handles organization secrets. */
4630
+ function secrets(ctx, orgClient) {
4631
+ return new GitHubSecrets(ctx.client, { repo: ctx.repo }, orgClient);
697
4632
  }
4633
+ /** Builds the `environments` capability. */
698
4634
  function environments(ctx) {
699
4635
  return new GitHubEnvironments(ctx.client, { repo: ctx.repo });
700
4636
  }
4637
+ /** Builds the `ci` capability. */
701
4638
  function ci(ctx) {
702
4639
  return new GitHubCi(ctx.client, { repo: ctx.repo });
703
4640
  }
704
- function issues(ctx) {
4641
+ /** Builds the `issues` capability, passing the lifecycle labels when configured. */
4642
+ function issues(ctx, orgClient) {
705
4643
  const opts = { repo: ctx.repo };
706
4644
  if (ctx.options.labels !== void 0) opts.labels = ctx.options.labels;
4645
+ if (ctx.options.issueTypes !== void 0) opts.issueTypes = ctx.options.issueTypes;
4646
+ if (orgClient) opts.orgClient = orgClient;
707
4647
  return new GitHubIssues(ctx.client, opts);
708
4648
  }
4649
+ /** Builds the `projects` capability: GitHub Projects v2 over GraphQL, with items keyed relative to the configured repo. */
4650
+ function projects(ctx) {
4651
+ return new GitHubProjects(ctx.client.graphql, { repo: ctx.repo }, commitChecksReader(ctx.client));
4652
+ }
4653
+ /** Creates the plugin, resolving a token per capability when it is first used. */
709
4654
  function createPlugin(options) {
710
4655
  function makeCtx(resolver) {
711
4656
  const token = resolver(options);
@@ -720,6 +4665,64 @@ function createPlugin(options) {
720
4665
  repoRoot: options.repoRoot ?? process.cwd()
721
4666
  };
722
4667
  }
4668
+ /** A token, or undefined when that feature token is simply not configured. */
4669
+ function tryResolve(resolver) {
4670
+ try {
4671
+ return resolver(options);
4672
+ } catch (err) {
4673
+ if (err instanceof AuthError) return void 0;
4674
+ throw err;
4675
+ }
4676
+ }
4677
+ /**
4678
+ * Organization secrets need an org-resource-owner token (`github.secrets`);
4679
+ * repo and environment secrets need `github.admin`. Each scope prefers its own
4680
+ * token and falls back to the other, so a setup with only one of them keeps
4681
+ * working, and an explicit `--token` serves both. With neither configured this
4682
+ * fails exactly as the admin-token capabilities do.
4683
+ */
4684
+ function makeSecrets() {
4685
+ const secretsToken = tryResolve(resolveSecretsToken);
4686
+ const adminToken = tryResolve(resolveAdminToken);
4687
+ if (!secretsToken && !adminToken) resolveAdminToken(options);
4688
+ const clientFor = (token) => createGitHubClient$1({
4689
+ token,
4690
+ baseUrl: options.baseUrl,
4691
+ fetch: options.fetch
4692
+ });
4693
+ const repoClient = clientFor(adminToken ?? secretsToken);
4694
+ const orgClient = clientFor(secretsToken ?? adminToken);
4695
+ return secrets({
4696
+ options,
4697
+ client: repoClient,
4698
+ repo: options.repo,
4699
+ repoRoot: options.repoRoot ?? process.cwd()
4700
+ }, orgClient);
4701
+ }
4702
+ /**
4703
+ * Repository settings need the admin token; opening and changing pull requests need only `github.pulls`. Each prefers
4704
+ * its own token and falls back to the other, so a setup with only the admin token keeps working, and an agent that
4705
+ * holds only the pull requests token can still open pull requests (a settings call then answers 403). With neither
4706
+ * configured this fails exactly as the admin-token capabilities do.
4707
+ */
4708
+ function makeSource() {
4709
+ const adminToken = tryResolve(resolveAdminToken);
4710
+ const pullsToken = tryResolve(resolvePullsToken);
4711
+ if (!adminToken && !pullsToken) resolveAdminToken(options);
4712
+ const clientFor = (token) => createGitHubClient$1({
4713
+ token,
4714
+ baseUrl: options.baseUrl,
4715
+ fetch: options.fetch
4716
+ });
4717
+ const repoClient = clientFor(adminToken ?? pullsToken);
4718
+ const pullsClient = clientFor(pullsToken ?? adminToken);
4719
+ return source({
4720
+ options,
4721
+ client: repoClient,
4722
+ repo: options.repo,
4723
+ repoRoot: options.repoRoot ?? process.cwd()
4724
+ }, makeOrgClient(), makeUserSyncClient(), pullsClient);
4725
+ }
723
4726
  function makeOrgClient() {
724
4727
  try {
725
4728
  const token = resolveOrgToken(options);
@@ -732,21 +4735,65 @@ function createPlugin(options) {
732
4735
  return;
733
4736
  }
734
4737
  }
4738
+ /** The token for the user-sync files; undefined when it is not configured, and the org token is used instead. */
4739
+ function makeUserSyncClient() {
4740
+ const token = tryResolve(resolveUserSyncToken);
4741
+ return token ? createGitHubClient$1({
4742
+ token,
4743
+ baseUrl: options.baseUrl,
4744
+ fetch: options.fetch
4745
+ }) : void 0;
4746
+ }
735
4747
  return {
736
4748
  name: "@theholocron/holocron-plugin-github",
4749
+ probes: {
4750
+ token: tokenProbe({
4751
+ repo: options.repo,
4752
+ baseUrl: (options.baseUrl ?? "https://api.github.com").replace(/\/$/, ""),
4753
+ fetch: options.fetch ?? fetch,
4754
+ resolve: (envName) => TOKEN_RESOLVERS[envName]?.(options),
4755
+ tokenNames: Object.keys(TOKEN_RESOLVERS)
4756
+ }),
4757
+ "issue-types": issueTypesProbe({
4758
+ makeApi: (repo) => createBackfillApi(makeCtx(resolveIssuesToken).client, makeCtx(resolveOrgToken).client, repo),
4759
+ repo: options.repo,
4760
+ config: options.areaLabels ?? {}
4761
+ }),
4762
+ connection: connectionProbe({
4763
+ provider: "GitHub",
4764
+ url: options.baseUrl ?? "https://api.github.com",
4765
+ fetch: options.fetch,
4766
+ token: () => resolveReadToken(options),
4767
+ verify: (token) => verifyToken(token, {
4768
+ baseUrl: options.baseUrl,
4769
+ fetch: options.fetch
4770
+ })
4771
+ })
4772
+ },
4773
+ whoami: whoamiToken(options, {
4774
+ resolvers: TOKEN_RESOLVERS,
4775
+ tokens,
4776
+ build: (input) => whoamiAction({
4777
+ ...input,
4778
+ verify: (token) => verifyToken(token, {
4779
+ baseUrl: options.baseUrl,
4780
+ fetch: options.fetch
4781
+ })
4782
+ })
4783
+ }),
737
4784
  capabilities: {
738
- source: () => source(makeCtx(resolveAdminToken), makeOrgClient()),
4785
+ source: () => makeSource(),
739
4786
  ci: () => ci(makeCtx(resolveReadToken)),
740
- secrets: () => secrets(makeCtx(resolveAdminToken)),
4787
+ secrets: () => makeSecrets(),
741
4788
  environments: () => environments(makeCtx(resolveAdminToken)),
742
- issues: () => issues(makeCtx(resolveIssuesToken))
4789
+ issues: () => issues(makeCtx(resolveIssuesToken), makeOrgClient),
4790
+ projects: () => projects(makeCtx(resolveOrgToken))
743
4791
  }
744
4792
  };
745
4793
  }
746
4794
  /**
747
- * One-line hint printed by `holocron auth set github` when no token
4795
+ * One-line hint printed by `holocron new token github` when no token
748
4796
  * is supplied or the supplied token is rejected.
749
4797
  */
750
- const AUTH_HINT = "generate fine-grained Personal Access Tokens at https://github.com/settings/tokens (one per feature — see docs/tokens.md for required scopes per operation), then run: holocron auth set github.<feature> <PAT>";
751
- //#endregion
752
- export { AUTH_HINT, AuthError, GitHubCi, GitHubEnvironments, GitHubIssues, GitHubSecrets, GitHubSource, ci, createFeatureResolver, createGitHubClient, createPlugin, encryptSecret, environments, issues, normalizeTeamEntry, resolveAdminToken, resolveDeployToken, resolveIssuesToken, resolveOrgToken, resolveReadToken, resolveReleaseToken, resolveSyncToken, secrets, source, syncLabels, syncTeams, verifyToken };
4798
+ const AUTH_HINT = "generate fine-grained Personal Access Tokens at https://github.com/settings/tokens (one per feature — see docs/tokens.md for required scopes per operation), then run: holocron new token github.<feature> <PAT>";
4799
+ export { AUTH_HINT, AuthError, GitHubCi, GitHubEnvironments, GitHubIssues, GitHubProjects, GitHubSecrets, GitHubSource, ci, createFeatureResolver, createGitHubClient, createPlugin, encryptSecret, environments, issues, normalizeTeamEntry, projects, resolveAdminToken, resolveDeployToken, resolveIssuesToken, resolveOrgToken, resolvePullsToken, resolveReadToken, resolveReleaseToken, resolveSecretsToken, resolveSyncToken, resolveUserSyncToken, secrets, source, syncLabels, syncTeams, tokens, verifyToken };