@theholocron/holocron-plugin-github 5.0.0-alpha.39 → 5.0.0-alpha.391

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,74 @@
1
1
  import { createRequire } from "node:module";
2
+ import { AuthError, MissingTokenError, ProviderApiError, connectionProbe, createFeatureResolver, pickByCreation, readKeysLimited, reportProgress } from "@theholocron/cli";
2
3
  import { createGitHubClient, createGitHubClient as createGitHubClient$1 } from "@theholocron/github-client";
3
- import { AuthError, createFeatureResolver } from "@theholocron/cli";
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
+ /** Resolves the token for syncing repo files and settings (`HOLOCRON_SYNC_TOKEN`, keyring key `github.sync`). */
15
21
  const resolveSyncToken = createFeatureResolver({
16
22
  envName: "HOLOCRON_SYNC_TOKEN",
17
23
  keyringKey: "github.sync"
18
24
  });
25
+ /** Resolves the token for release operations (`HOLOCRON_RELEASE_TOKEN`, keyring key `github.release`). */
19
26
  const resolveReleaseToken = createFeatureResolver({
20
27
  envName: "HOLOCRON_RELEASE_TOKEN",
21
28
  keyringKey: "github.release"
22
29
  });
30
+ /** Resolves the repo-scoped admin token (`HOLOCRON_ADMIN_TOKEN`, keyring key `github.admin`). */
23
31
  const resolveAdminToken = createFeatureResolver({
24
32
  envName: "HOLOCRON_ADMIN_TOKEN",
25
33
  keyringKey: "github.admin"
26
34
  });
35
+ /** Resolves the org-level secrets token (`HOLOCRON_SECRETS_TOKEN`, keyring key `github.secrets`). */
36
+ const resolveSecretsToken = createFeatureResolver({
37
+ envName: "HOLOCRON_SECRETS_TOKEN",
38
+ keyringKey: "github.secrets"
39
+ });
40
+ /** Resolves the token for deployment operations (`HOLOCRON_DEPLOY_TOKEN`, keyring key `github.deploy`). */
27
41
  const resolveDeployToken = createFeatureResolver({
28
42
  envName: "HOLOCRON_DEPLOY_TOKEN",
29
43
  keyringKey: "github.deploy"
30
44
  });
45
+ /**
46
+ * Resolves the token for the user-sync files in the org's private config repo (`HOLOCRON_USER_SYNC_TOKEN`, keyring
47
+ * key `github.user-sync`).
48
+ */
49
+ const resolveUserSyncToken = createFeatureResolver({
50
+ envName: "HOLOCRON_USER_SYNC_TOKEN",
51
+ keyringKey: "github.user-sync"
52
+ });
53
+ /** Resolves the org-level token (`HOLOCRON_ORG_TOKEN`, keyring key `github.org`). */
31
54
  const resolveOrgToken = createFeatureResolver({
32
55
  envName: "HOLOCRON_ORG_TOKEN",
33
56
  keyringKey: "github.org"
34
57
  });
35
- //#endregion
36
- //#region src/capabilities/ci.ts
58
+ // src/capabilities/ci.ts
59
+ /** The GitHub implementation of the `ci` capability, backed by GitHub Actions workflow runs. */
37
60
  var GitHubCi = class {
38
61
  client;
39
62
  opts;
63
+ /** Capability key, always `"ci"`. */
40
64
  key = "ci";
65
+ /** Provider name, always `"github"`. */
41
66
  providerName = "github";
42
67
  constructor(client, opts) {
43
68
  this.client = client;
44
69
  this.opts = opts;
45
70
  }
71
+ /** Lists workflow runs for the repo, optionally filtered by branch, status and limit. */
46
72
  async listRuns(filter) {
47
73
  return (await this.client.workflows.listRuns(this.opts.repo, {
48
74
  branch: filter?.branch,
@@ -50,6 +76,7 @@ var GitHubCi = class {
50
76
  status: filter?.status
51
77
  })).map((r) => this.mapRun(r));
52
78
  }
79
+ /** Fetches one workflow run by id. */
53
80
  async getRun(id) {
54
81
  const raw = await this.client.workflows.getRun(this.opts.repo, id);
55
82
  return this.mapRun(raw);
@@ -77,17 +104,20 @@ var GitHubCi = class {
77
104
  }
78
105
  }
79
106
  };
80
- //#endregion
81
- //#region src/capabilities/environments.ts
107
+ // src/capabilities/environments.ts
108
+ /** The GitHub implementation of the `environments` capability, managing a repo's deployment environments. */
82
109
  var GitHubEnvironments = class {
83
110
  client;
84
111
  opts;
112
+ /** Capability key, always `"environments"`. */
85
113
  key = "environments";
114
+ /** Provider name, always `"github"`. */
86
115
  providerName = "github";
87
116
  constructor(client, opts) {
88
117
  this.client = client;
89
118
  this.opts = opts;
90
119
  }
120
+ /** Lists the repo's environments with their wait timer, self-review rule and required reviewers. */
91
121
  async listEnvironments() {
92
122
  return (await this.client.environments.listEnvironments(this.opts.repo)).map((e) => ({
93
123
  name: e.name,
@@ -96,6 +126,7 @@ var GitHubEnvironments = class {
96
126
  reviewers: this.flattenReviewers(e.protection_rules)
97
127
  }));
98
128
  }
129
+ /** Creates or updates an environment, sending only the settings the given environment defines. */
99
130
  async upsertEnvironment(env) {
100
131
  const body = {};
101
132
  if (env.waitTimer !== void 0) body.wait_timer = env.waitTimer;
@@ -106,6 +137,7 @@ var GitHubEnvironments = class {
106
137
  }));
107
138
  await this.client.environments.upsertEnvironment(this.opts.repo, env.name, body);
108
139
  }
140
+ /** Deletes the named environment. */
109
141
  async deleteEnvironment(name) {
110
142
  await this.client.environments.deleteEnvironment(this.opts.repo, name);
111
143
  }
@@ -119,11 +151,344 @@ var GitHubEnvironments = class {
119
151
  }));
120
152
  }
121
153
  };
122
- //#endregion
123
- //#region src/capabilities/issues.ts
154
+ // src/capabilities/issues-migration.ts
155
+ /**
156
+ * Export and import of GitHub issues for `holocron migrate`.
157
+ *
158
+ * GitHub holds less than a planning tool, so what does not fit is named in each result's `dropped` list rather than
159
+ * lost quietly:
160
+ * - priority is a label (`priority: high`), because on GitHub it lives in a project field, not on the issue;
161
+ * - an import cannot backdate an issue or a comment, and cannot post as someone else, so the original date and
162
+ * author go in the text;
163
+ * - an import does not set parent or blocked-by links (they need GraphQL node ids of issues made in the same run);
164
+ * - an assignee is not mapped (a Linear user is not a GitHub login).
165
+ * A migrated issue ends with `<!-- holocron:migrated-from <url> -->`, which is how a second run finds it.
166
+ */
167
+ const MARKER = /<!-- holocron:migrated-from (\S+) -->/;
168
+ const PRIORITY_LABEL = /^priority\s*[:/-]\s*(urgent|high|medium|low)$/i;
169
+ const LINK_QUERY = `query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) {
170
+ issue(number: $number) { parent { number } blockedBy(first: 50) { nodes { number } } } } }`;
171
+ /** Splits `priority: high` labels from the rest. */
172
+ function splitLabels(names) {
173
+ let priority;
174
+ const labels = [];
175
+ for (const name of names) {
176
+ const match = PRIORITY_LABEL.exec(name);
177
+ if (match) priority = match[1].toLowerCase();
178
+ else labels.push(name);
179
+ }
180
+ return {
181
+ labels,
182
+ ...priority ? { priority } : {}
183
+ };
184
+ }
185
+ function categoryOf(issue) {
186
+ if (issue.state === "closed") return "done";
187
+ const names = issue.labels.map((l) => l.name.toLowerCase());
188
+ if (names.some((n) => n === "status:in-review" || n === "status: in review")) return "in-review";
189
+ if (names.some((n) => n === "status:in-progress" || n === "status: in progress")) return "in-progress";
190
+ return "open";
191
+ }
192
+ /** How many issues an export fetches at once. GitHub's secondary rate limit punishes bursts of requests, not volume. */
193
+ const EXPORT_CONCURRENCY = 4;
194
+ /** Runs `fn` over `items`, at most `limit` at a time, and returns the results in the order of `items`. */
195
+ async function mapLimit(items, limit, fn) {
196
+ const results = new Array(items.length);
197
+ let next = 0;
198
+ const worker = async () => {
199
+ while (next < items.length) {
200
+ const at = next++;
201
+ results[at] = await fn(items[at]);
202
+ }
203
+ };
204
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
205
+ return results;
206
+ }
207
+ /** GitHub's own answer to a burst of requests (403 or 429 naming the secondary limit) becomes a message that says what to do. */
208
+ function explainSecondaryLimit(err) {
209
+ 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.");
210
+ return err;
211
+ }
212
+ /**
213
+ * Reads the issues `selector` names, with their comments, priority label, parent and blockers.
214
+ *
215
+ * With `limit`, only that many survivors of the other filters are read, from the `order` end of the creation order. A
216
+ * list of keys is sorted by issue number (which rises with creation in one repository) before anything is fetched, then
217
+ * fetched a few at a time until enough are kept; a listing already carries `created_at`, so it is cut before the
218
+ * per-issue comment and link requests. `info.matched` receives how many the selection matched before the cut.
219
+ */
220
+ async function exportIssues(client, repo, selector, info = {}) {
221
+ return readIssues(client, repo, selector, info).catch((err) => {
222
+ throw explainSecondaryLimit(err);
223
+ });
224
+ }
225
+ async function readIssues(client, repo, selector, info) {
226
+ const [owner = "", name = ""] = repo.split("/", 2);
227
+ const since = selector.since ? Date.parse(selector.since) : void 0;
228
+ const survives = (i) => !i.pull_request && !(selector.openOnly && i.state === "closed") && (since === void 0 || Date.parse(i.updated_at) >= since);
229
+ const { limit, order = "oldest" } = selector;
230
+ let issues;
231
+ if (selector.keys) {
232
+ const fetch = (k) => client.issues.getIssue(repo, parseNumber(k));
233
+ info.matched = selector.keys.length;
234
+ issues = limit === void 0 ? (await mapLimit(selector.keys, EXPORT_CONCURRENCY, fetch)).filter(survives) : await readKeysLimited({
235
+ keys: selector.keys,
236
+ order,
237
+ limit,
238
+ concurrency: EXPORT_CONCURRENCY,
239
+ fetch,
240
+ keep: survives
241
+ });
242
+ } else {
243
+ let raw;
244
+ if (selector.milestone) {
245
+ const milestone = await findMilestone(client, repo, selector.milestone);
246
+ if (!milestone) throw new Error(`Milestone "${selector.milestone}" not found in ${repo}.`);
247
+ raw = await listAll(client, repo, { milestone: String(milestone.number) });
248
+ } else if (selector.all) raw = await listAll(client, repo, {});
249
+ else throw new Error("export needs keys, a milestone or all");
250
+ issues = raw.filter(survives);
251
+ info.matched = issues.length;
252
+ if (limit !== void 0) issues = pickByCreation(issues, (i) => i.created_at ?? i.updated_at, order, limit);
253
+ }
254
+ const records = [];
255
+ for (const issue of issues) {
256
+ reportProgress(info.onProgress, records.length, issues.length);
257
+ const comments = await client.issues.listComments(repo, issue.number);
258
+ const links = (await client.graphql.query(LINK_QUERY, {
259
+ owner,
260
+ name,
261
+ number: issue.number
262
+ }).catch(() => void 0))?.repository.issue;
263
+ const { labels, priority } = splitLabels(issue.labels.map((l) => l.name));
264
+ const body = issue.body?.replace(MARKER, "").trimEnd();
265
+ const migratedFrom = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
266
+ records.push({
267
+ key: `#${issue.number}`,
268
+ url: issue.html_url,
269
+ title: issue.title,
270
+ ...body ? { body } : {},
271
+ statusCategory: categoryOf(issue),
272
+ closed: issue.state === "closed",
273
+ ...priority ? { priority } : {},
274
+ labels: labels.filter((l) => !l.toLowerCase().startsWith("status:")),
275
+ ...issue.assignee ? { assignee: {
276
+ id: issue.assignee.login,
277
+ displayName: issue.assignee.name ?? issue.assignee.login,
278
+ ...issue.assignee.email ? { emailAddress: issue.assignee.email } : {}
279
+ } } : {},
280
+ ...issue.milestone ? { milestone: issue.milestone.title } : {},
281
+ ...links?.parent ? { parent: `#${links.parent.number}` } : {},
282
+ blockedBy: (links?.blockedBy.nodes ?? []).map((n) => `#${n.number}`),
283
+ comments: comments.map((c) => ({
284
+ ...c.user ? { author: c.user.login } : {},
285
+ body: c.body,
286
+ createdAt: c.created_at
287
+ })),
288
+ createdAt: issue.created_at ?? issue.updated_at,
289
+ updatedAt: issue.updated_at,
290
+ ...migratedFrom ? { migratedFrom } : {}
291
+ });
292
+ }
293
+ reportProgress(info.onProgress, records.length, issues.length);
294
+ return records;
295
+ }
296
+ /** Makes the records as issues, skipping any whose source address an earlier run already recorded. */
297
+ async function importIssues(client, repo, records, options = {}) {
298
+ const existing = /* @__PURE__ */ new Map();
299
+ for (const issue of await listAll(client, repo, {})) {
300
+ const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
301
+ if (url) existing.set(url, issue.number);
302
+ }
303
+ const results = [];
304
+ const tick = () => reportProgress(options.onProgress, results.length, records.length);
305
+ for (const record of records) {
306
+ const found = existing.get(record.url);
307
+ if (found !== void 0) {
308
+ results.push({
309
+ source: record.key,
310
+ key: `#${found}`,
311
+ created: false,
312
+ dropped: []
313
+ });
314
+ tick();
315
+ continue;
316
+ }
317
+ const dropped = droppedFor(record);
318
+ if (options.dryRun) {
319
+ results.push({
320
+ source: record.key,
321
+ created: true,
322
+ dropped
323
+ });
324
+ tick();
325
+ continue;
326
+ }
327
+ const number = await createFromRecord(client, repo, record, options);
328
+ results.push({
329
+ source: record.key,
330
+ key: `#${number}`,
331
+ created: true,
332
+ dropped
333
+ });
334
+ tick();
335
+ }
336
+ return results;
337
+ }
338
+ /** What GitHub cannot hold of this record, for the report. */
339
+ function droppedFor(record) {
340
+ const dropped = ["createdAt (GitHub sets it; the original date is in the text)"];
341
+ if (record.assignee) dropped.push("assignee (not mapped)");
342
+ if (record.parent) dropped.push("parent (not set on GitHub)");
343
+ if (record.blockedBy.length > 0) dropped.push("blockedBy (not set on GitHub)");
344
+ return dropped;
345
+ }
346
+ /** The labels a record becomes on GitHub: its own, plus `priority: <level>` (GitHub's priority is a label). */
347
+ function labelsFor(record) {
348
+ return [...record.labels, ...record.priority && record.priority !== "none" ? [`priority: ${record.priority}`] : []];
349
+ }
350
+ /** The text a comment gets when it is copied: GitHub cannot post as another author or backdate. */
351
+ function renderComment(comment) {
352
+ return `${comment.author ? `**${comment.author}**` : "Someone"} commented on ${comment.createdAt}:\n\n${comment.body}`;
353
+ }
354
+ /** Makes one issue from a record, with its comments, and closes it when the record is closed; returns its number. */
355
+ async function createFromRecord(client, repo, record, options) {
356
+ const milestoneName = options.milestone ?? record.milestone;
357
+ const milestone = milestoneName ? await ensureMilestone(client, repo, milestoneName) : void 0;
358
+ const labels = labelsFor(record);
359
+ const created = await client.issues.createIssue(repo, {
360
+ title: record.title,
361
+ body: withProvenance(record),
362
+ ...labels.length > 0 ? { labels } : {},
363
+ ...milestone !== void 0 ? { milestone } : {}
364
+ });
365
+ for (const comment of record.comments) await client.issues.createComment(repo, created.number, renderComment(comment));
366
+ if (record.closed) await client.issues.updateIssue(repo, created.number, {
367
+ state: "closed",
368
+ state_reason: "completed"
369
+ });
370
+ return created.number;
371
+ }
372
+ /** The text of a migrated issue: the record's body, then where it came from and the marker a second run looks for. */
373
+ function withProvenance(record) {
374
+ return `${record.body ? `${record.body}\n\n` : ""}---\n_Migrated from [${record.key}](${record.url}); created ${record.createdAt}._\n<!-- holocron:migrated-from ${record.url} -->`;
375
+ }
376
+ function parseNumber(key) {
377
+ const n = key.trim().replace(/^.*#/, "");
378
+ if (!/^\d+$/.test(n)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
379
+ return parseInt(n, 10);
380
+ }
381
+ async function listAll(client, repo, extra) {
382
+ const all = [];
383
+ for (let page = 1;; page++) {
384
+ const batch = await client.issues.listIssues(repo, {
385
+ state: "all",
386
+ per_page: 100,
387
+ page,
388
+ ...extra
389
+ });
390
+ all.push(...batch);
391
+ if (batch.length < 100) return all;
392
+ }
393
+ }
394
+ async function findMilestone(client, repo, ref) {
395
+ return (await client.issues.listMilestones(repo, { state: "all" })).find((m) => String(m.number) === ref || m.title.toLowerCase() === ref.toLowerCase());
396
+ }
397
+ async function ensureMilestone(client, repo, title) {
398
+ return (await findMilestone(client, repo, title))?.number ?? (await client.issues.createMilestone(repo, title)).number;
399
+ }
400
+ // src/capabilities/issues-sync.ts
401
+ const COMMENT_HEADER = /^(?:\*\*.*?\*\*|Someone) commented on (\S+?):\n/;
402
+ /** Whether GitHub is asking to be left alone: a 429, or a 403 that says it is a rate limit. */
403
+ function isRateLimited(err) {
404
+ return err instanceof ProviderApiError && (err.status === 429 || err.status === 403 && /rate limit/i.test(`${err.message} ${String(err.details)}`));
405
+ }
406
+ const normalize = (text) => text.replace(/\r\n/g, "\n").trim();
407
+ const sorted = (names) => names.map((n) => n.toLowerCase()).sort().join("\n");
408
+ /** Makes the records missing from the repo and updates the ones an earlier run made. See the file comment. */
409
+ async function syncIssues(client, repo, records, options = {}) {
410
+ const existing = /* @__PURE__ */ new Map();
411
+ for (const issue of await listAll(client, repo, {})) {
412
+ const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
413
+ if (url) existing.set(url, issue);
414
+ }
415
+ const results = [];
416
+ for (const record of records) try {
417
+ const found = existing.get(record.url);
418
+ results.push(found ? await update(client, repo, found, record, options) : await create(client, repo, record, options));
419
+ reportProgress(options.onProgress, results.length, records.length);
420
+ } catch (err) {
421
+ if (isRateLimited(err)) return results;
422
+ throw err;
423
+ }
424
+ return results;
425
+ }
426
+ async function create(client, repo, record, options) {
427
+ const dropped = droppedFor(record);
428
+ if (options.dryRun) return {
429
+ source: record.key,
430
+ created: true,
431
+ updated: false,
432
+ changes: [],
433
+ dropped
434
+ };
435
+ const number = await createFromRecord(client, repo, record, options);
436
+ return {
437
+ source: record.key,
438
+ key: `#${number}`,
439
+ created: true,
440
+ updated: false,
441
+ changes: [],
442
+ dropped
443
+ };
444
+ }
445
+ async function update(client, repo, issue, record, options) {
446
+ const patch = {};
447
+ const changes = [];
448
+ if (issue.title !== record.title) {
449
+ patch.title = record.title;
450
+ changes.push("title");
451
+ }
452
+ const body = withProvenance(record);
453
+ if (normalize(issue.body) !== normalize(body)) {
454
+ patch.body = body;
455
+ changes.push("description");
456
+ }
457
+ if (issue.state === "closed" !== record.closed) {
458
+ patch.state = record.closed ? "closed" : "open";
459
+ if (record.closed) patch.state_reason = "completed";
460
+ changes.push("state");
461
+ }
462
+ const current = issue.labels.map((l) => l.name);
463
+ const finalLabels = [...labelsFor(record), ...current.filter((n) => n.toLowerCase().startsWith("status:"))];
464
+ if (sorted(finalLabels) !== sorted(current)) {
465
+ patch.labels = finalLabels;
466
+ changes.push("labels");
467
+ }
468
+ const comments = await client.issues.listComments(repo, issue.number);
469
+ const seen = new Set(comments.map((c) => COMMENT_HEADER.exec(c.body)?.[1]));
470
+ const missing = record.comments.filter((c) => !seen.has(c.createdAt));
471
+ if (missing.length > 0) changes.push("comments");
472
+ if (!options.dryRun) {
473
+ if (Object.keys(patch).length > 0) await client.issues.updateIssue(repo, issue.number, patch);
474
+ for (const comment of missing) await client.issues.createComment(repo, issue.number, renderComment(comment));
475
+ }
476
+ return {
477
+ source: record.key,
478
+ key: `#${issue.number}`,
479
+ created: false,
480
+ updated: changes.length > 0,
481
+ changes,
482
+ dropped: droppedFor(record)
483
+ };
484
+ }
485
+ // src/capabilities/issues.ts
486
+ /** The GitHub implementation of the `issues` capability, backed by GitHub Issues and status labels. */
124
487
  var GitHubIssues = class {
125
488
  client;
489
+ /** Capability key, always `"issues"`. */
126
490
  key = "issues";
491
+ /** Provider name, always `"github"`. */
127
492
  providerName = "github";
128
493
  owner;
129
494
  repoName;
@@ -145,6 +510,7 @@ var GitHubIssues = class {
145
510
  ...raw.email ? { emailAddress: raw.email } : {}
146
511
  };
147
512
  }
513
+ /** Searches the repo's issues, newest update first, leaving out pull requests. */
148
514
  async search(filter) {
149
515
  const params = {
150
516
  state: filter.openOnly ? "open" : "all",
@@ -164,11 +530,13 @@ var GitHubIssues = class {
164
530
  assignee: params.assignee
165
531
  })).filter((i) => !i.pull_request).map((i) => this.mapIssue(i));
166
532
  }
533
+ /** Fetches one issue by its key. */
167
534
  async get(key) {
168
535
  const number = parseIssueNumber(key, this.owner, this.repoName);
169
536
  const raw = await this.client.issues.getIssue(this.repo, number);
170
537
  return this.mapIssue(raw);
171
538
  }
539
+ /** Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. */
172
540
  async create(input) {
173
541
  const body = { title: input.summary };
174
542
  if (input.body) body.body = input.body;
@@ -216,10 +584,12 @@ var GitHubIssues = class {
216
584
  via: `label set to ${targetLabel}`
217
585
  };
218
586
  }
587
+ /** Adds a comment to the issue with the given key. */
219
588
  async comment(key, body) {
220
589
  const number = parseIssueNumber(key, this.owner, this.repoName);
221
590
  await this.client.issues.createComment(this.repo, number, body);
222
591
  }
592
+ /** Checks the authenticated user, the repo and the label-backed lifecycle slots, and reports what resolves. */
223
593
  async doctor() {
224
594
  const me = await this.getMyself();
225
595
  const repo = await this.client.repos.getRepo(this.repo);
@@ -288,6 +658,18 @@ var GitHubIssues = class {
288
658
  lifecycle
289
659
  };
290
660
  }
661
+ /** Reads issues with their comments, priority label, parent and blockers, for `holocron migrate`. */
662
+ export(selector, info) {
663
+ return exportIssues(this.client, this.repo, selector, info);
664
+ }
665
+ /** Makes the records as issues; one already made by an earlier run is skipped. */
666
+ import(records, options) {
667
+ return importIssues(this.client, this.repo, records, options);
668
+ }
669
+ /** Like `import`, and it also updates what an earlier import or sync made, for `holocron sync issues`. */
670
+ sync(records, options) {
671
+ return syncIssues(this.client, this.repo, records, options);
672
+ }
291
673
  async resolveMilestone(ref) {
292
674
  if (/^\d+$/.test(ref)) return parseInt(ref, 10);
293
675
  const match = (await this.client.issues.listMilestones(this.repo, { state: "all" })).find((m) => m.title.toLowerCase() === ref.toLowerCase());
@@ -337,8 +719,584 @@ function parseIssueNumber(key, owner, repoName) {
337
719
  if (!/^\d+$/.test(num)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
338
720
  return parseInt(num, 10);
339
721
  }
340
- //#endregion
341
- //#region src/sodium.ts
722
+ // src/capabilities/projects.ts
723
+ /** The name of the single select field that holds an item's status. */
724
+ const STATUS_FIELD = "Status";
725
+ /** The name of the field `move` carries over besides the status. */
726
+ const PRIORITY_FIELD = "Priority";
727
+ const P_LEVELS = {
728
+ p0: "urgent",
729
+ p1: "high",
730
+ p2: "medium",
731
+ p3: "low"
732
+ };
733
+ /** The neutral priority a `Priority` option stands for, by its name; undefined for a name that is not one of them. */
734
+ function priorityOf(value) {
735
+ const name = value?.trim().toLowerCase();
736
+ if (name === "urgent" || name === "high" || name === "medium" || name === "low") return name;
737
+ return name ? P_LEVELS[name] : void 0;
738
+ }
739
+ const PROJECT_FIELDS = "id number title closed url";
740
+ const BOARD_QUERY = `query($id: ID!) { node(id: $id) { ... on ProjectV2 {
741
+ ${PROJECT_FIELDS}
742
+ fields(first: 100) { nodes {
743
+ ... on ProjectV2FieldCommon { id name dataType }
744
+ ... on ProjectV2SingleSelectField { options { id name color description } }
745
+ } }
746
+ views(first: 50) { nodes { id name layout filter groupByFields(first: 5) { nodes { ... on ProjectV2FieldCommon { name } } } } }
747
+ workflows(first: 50) { nodes { id name enabled } }
748
+ } } }`;
749
+ const ITEMS_QUERY = `query($id: ID!, $after: String) { node(id: $id) { ... on ProjectV2 {
750
+ items(first: 100, after: $after) {
751
+ pageInfo { hasNextPage endCursor }
752
+ nodes {
753
+ id
754
+ fieldValues(first: 30) { nodes { ... on ProjectV2ItemFieldSingleSelectValue { name field { ... on ProjectV2FieldCommon { name } } } } }
755
+ content {
756
+ __typename
757
+ ... on Issue { id number title state repository { nameWithOwner } blockedBy(first: 50) { nodes { number state repository { nameWithOwner } } } }
758
+ ... on PullRequest { id number title state repository { nameWithOwner } }
759
+ }
760
+ }
761
+ }
762
+ } } }`;
763
+ const LIST_QUERY = `query($owner: String!, $after: String) { organization(login: $owner) { id projectsV2(first: 100, after: $after) {
764
+ pageInfo { hasNextPage endCursor }
765
+ nodes { ${PROJECT_FIELDS} }
766
+ } } }`;
767
+ const OWNER_QUERY = "query($owner: String!) { organization(login: $owner) { id } }";
768
+ const SET_VALUE = `mutation($project: ID!, $item: ID!, $field: ID!, $option: String!) {
769
+ updateProjectV2ItemFieldValue(input: { projectId: $project, itemId: $item, fieldId: $field, value: { singleSelectOptionId: $option } }) { projectV2Item { id } }
770
+ }`;
771
+ const UPDATE_OPTIONS = `mutation($field: ID!, $options: [ProjectV2SingleSelectFieldOptionInput!]!) {
772
+ updateProjectV2Field(input: { fieldId: $field, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
773
+ }`;
774
+ const DATA_TYPES = {
775
+ single_select: "SINGLE_SELECT",
776
+ text: "TEXT",
777
+ number: "NUMBER",
778
+ date: "DATE",
779
+ iteration: "ITERATION"
780
+ };
781
+ function fieldTypeOf(dataType) {
782
+ return Object.keys(DATA_TYPES).find((t) => DATA_TYPES[t] === dataType);
783
+ }
784
+ function toSummary(n) {
785
+ return {
786
+ id: n.id,
787
+ number: n.number,
788
+ name: n.title,
789
+ url: n.url,
790
+ closed: n.closed
791
+ };
792
+ }
793
+ function toOptionInput(o) {
794
+ return {
795
+ ...o.id ? { id: o.id } : {},
796
+ name: o.name,
797
+ color: (o.color ?? "GRAY").toUpperCase(),
798
+ description: o.description ?? ""
799
+ };
800
+ }
801
+ /** The GitHub implementation of the `projects` capability, backed by Projects v2. */
802
+ var GitHubProjects = class {
803
+ graphql;
804
+ /** Capability key, always `"projects"`. */
805
+ key = "projects";
806
+ /** Provider name, always `"github"`. */
807
+ providerName = "github";
808
+ repo;
809
+ constructor(graphql, opts) {
810
+ this.graphql = graphql;
811
+ this.repo = opts.repo;
812
+ }
813
+ /** Every board of the organization, open and closed. */
814
+ async list(owner) {
815
+ const boards = [];
816
+ let after = null;
817
+ for (;;) {
818
+ const page = (await this.graphql.query(LIST_QUERY, {
819
+ owner,
820
+ after
821
+ })).organization.projectsV2;
822
+ boards.push(...page.nodes.map(toSummary));
823
+ if (!page.pageInfo.hasNextPage) return boards;
824
+ after = page.pageInfo.endCursor;
825
+ }
826
+ }
827
+ /** The open board with exactly this name. */
828
+ async find(owner, name) {
829
+ return (await this.list(owner)).find((b) => !b.closed && b.name === name);
830
+ }
831
+ /**
832
+ * Makes a board. With `template.source` naming an open board it is copied (fields, options, views and automation
833
+ * rules, no items); otherwise the board is created and brought in line with the template.
834
+ */
835
+ async create(owner, name, template) {
836
+ const ownerId = await this.ownerId(owner);
837
+ const source = template.source ? await this.find(owner, template.source) : void 0;
838
+ if (source) return toSummary((await this.graphql.query(`mutation($project: ID!, $owner: ID!, $title: String!) {
839
+ copyProjectV2(input: { projectId: $project, ownerId: $owner, title: $title, includeDraftIssues: false }) { projectV2 { ${PROJECT_FIELDS} } }
840
+ }`, {
841
+ project: source.id,
842
+ owner: ownerId,
843
+ title: name
844
+ })).copyProjectV2.projectV2);
845
+ const board = toSummary((await this.graphql.query(`mutation($owner: ID!, $title: String!) {
846
+ createProjectV2(input: { ownerId: $owner, title: $title }) { projectV2 { ${PROJECT_FIELDS} } }
847
+ }`, {
848
+ owner: ownerId,
849
+ title: name
850
+ })).createProjectV2.projectV2);
851
+ await this.ensure(owner, board, template);
852
+ return board;
853
+ }
854
+ /** Closes the board; `updateProjectV2` with `closed: true` is the only way, and reversible. */
855
+ async close(_owner, board) {
856
+ await this.graphql.query(`mutation($project: ID!) { updateProjectV2(input: { projectId: $project, closed: true }) { projectV2 { id } } }`, { project: board.id });
857
+ }
858
+ /** The live board: statuses, other fields, views and automation rules. */
859
+ async read(_owner, board) {
860
+ const raw = await this.readRaw(board.id);
861
+ const status = raw.fields.find((f) => f.name === STATUS_FIELD);
862
+ const fields = [];
863
+ for (const f of raw.fields) {
864
+ const type = fieldTypeOf(f.dataType);
865
+ if (!type || f.name === STATUS_FIELD) continue;
866
+ fields.push({
867
+ name: f.name,
868
+ type,
869
+ ...f.options ? { options: f.options.map((o) => o.name) } : {}
870
+ });
871
+ }
872
+ const views = [];
873
+ for (const v of raw.views) {
874
+ const layout = v.layout === "BOARD_LAYOUT" ? "board" : v.layout === "TABLE_LAYOUT" ? "table" : void 0;
875
+ if (!layout) continue;
876
+ views.push({
877
+ name: v.name,
878
+ layout,
879
+ ...v.filter ? { filter: v.filter } : {},
880
+ ...v.groupBy[0] ? { groupBy: v.groupBy[0] } : {}
881
+ });
882
+ }
883
+ return {
884
+ board: raw.summary,
885
+ statuses: (status?.options ?? []).map((o) => o.name),
886
+ fields,
887
+ views,
888
+ rules: raw.rules.map(({ name, enabled }) => ({
889
+ name,
890
+ enabled
891
+ }))
892
+ };
893
+ }
894
+ /**
895
+ * Brings the board in line with the template. Never deletes a field, option or view, and never sends an option
896
+ * list without ids. Stops (throws) when the status field cannot be read.
897
+ */
898
+ async ensure(_owner, board, template) {
899
+ const raw = await this.readRaw(board.id);
900
+ const status = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
901
+ 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`);
902
+ const changes = [];
903
+ const todos = [];
904
+ const statusChanges = await this.ensureOptions(board, status, template.statuses.map((s) => ({
905
+ name: s.name,
906
+ color: s.color,
907
+ description: s.description
908
+ })));
909
+ changes.push(...statusChanges.map((c) => `status ${c}`));
910
+ for (const want of template.fields) {
911
+ const have = raw.fields.find((f) => f.name === want.name);
912
+ if (!have) {
913
+ await this.createField(board.id, want);
914
+ changes.push(`field ${want.name} created`);
915
+ continue;
916
+ }
917
+ if (fieldTypeOf(have.dataType) !== want.type) {
918
+ todos.push(`field "${want.name}" is ${have.dataType} but the template says ${want.type}; change it by hand`);
919
+ continue;
920
+ }
921
+ if (want.type === "single_select" && have.options && want.options) {
922
+ const diff = await this.ensureOptions(board, have, want.options.map((name) => ({ name })));
923
+ changes.push(...diff.map((c) => `field ${want.name} option ${c}`));
924
+ }
925
+ }
926
+ for (const want of template.views) {
927
+ const have = raw.views.find((v) => v.name === want.name);
928
+ const layout = want.layout === "board" ? "BOARD_LAYOUT" : "TABLE_LAYOUT";
929
+ let viewId = have?.id;
930
+ if (!viewId) {
931
+ viewId = await this.createView(board.id, want.name, layout);
932
+ changes.push(`view ${want.name} created`);
933
+ } else if (have && have.layout !== layout) {
934
+ await this.updateView(viewId, { layout });
935
+ changes.push(`view ${want.name} layout set to ${want.layout}`);
936
+ }
937
+ if (want.filter !== void 0 && want.filter !== (have?.filter ?? "")) {
938
+ await this.updateView(viewId, { filter: want.filter });
939
+ changes.push(`view ${want.name} filter set`);
940
+ }
941
+ 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`);
942
+ }
943
+ for (const rule of template.rules ?? []) {
944
+ const have = raw.rules.find((r) => r.name === rule);
945
+ if (!have) todos.push(`create the automation rule "${rule}"; the API cannot create one`);
946
+ else if (!have.enabled) todos.push(`turn on the automation rule "${rule}"; the API cannot switch one`);
947
+ }
948
+ return {
949
+ created: false,
950
+ changes,
951
+ todos
952
+ };
953
+ }
954
+ /**
955
+ * Makes a single select field hold the wanted options in order, every existing one sent with its id. Options the
956
+ * template does not mention stay, after the wanted ones. Returns what changed (`Blocked added`, `order set`).
957
+ */
958
+ async ensureOptions(board, field, wanted) {
959
+ /* v8 ignore next -- every caller passes a field it found with options; the fallback only satisfies the type */
960
+ const existing = field.options ?? [];
961
+ const next = [];
962
+ const changes = [];
963
+ for (const w of wanted) {
964
+ const have = existing.find((o) => o.name === w.name);
965
+ if (have) {
966
+ next.push({
967
+ id: have.id,
968
+ name: have.name,
969
+ color: (w.color ?? have.color).toUpperCase(),
970
+ description: w.description ?? have.description
971
+ });
972
+ if (next[next.length - 1].color !== have.color || next[next.length - 1].description !== have.description) changes.push(`${have.name} updated`);
973
+ } else {
974
+ next.push({
975
+ name: w.name,
976
+ color: (w.color ?? "GRAY").toUpperCase(),
977
+ description: w.description ?? ""
978
+ });
979
+ changes.push(`${w.name} added`);
980
+ }
981
+ }
982
+ for (const have of existing) if (!next.some((n) => n.id === have.id)) next.push({ ...have });
983
+ const sameOrder = next.length === existing.length && next.every((n, i) => n.id === existing[i]?.id);
984
+ if (changes.length === 0 && sameOrder) return [];
985
+ if (sameOrder === false && !changes.some((c) => c.endsWith("added"))) changes.push("order set");
986
+ const before = await this.fetchItems(board.id);
987
+ const snapshot = /* @__PURE__ */ new Map();
988
+ for (const item of before) {
989
+ const value = item.values[field.name];
990
+ if (value) snapshot.set(item.id, value);
991
+ }
992
+ await this.graphql.query(UPDATE_OPTIONS, {
993
+ field: field.id,
994
+ options: next.map(toOptionInput)
995
+ });
996
+ const afterField = (await this.readRaw(board.id)).fields.find((f) => f.id === field.id);
997
+ const afterItems = await this.fetchItems(board.id);
998
+ const afterValues = new Map(afterItems.map((i) => [i.id, i.values[field.name]]));
999
+ const lost = [...snapshot].filter(([itemId]) => !afterValues.get(itemId));
1000
+ if (lost.length > 0) {
1001
+ let restored = 0;
1002
+ for (const [itemId, name] of lost) {
1003
+ const option = afterField?.options?.find((o) => o.name === name);
1004
+ if (!option) continue;
1005
+ await this.graphql.query(SET_VALUE, {
1006
+ project: board.id,
1007
+ item: itemId,
1008
+ field: field.id,
1009
+ option: option.id
1010
+ });
1011
+ restored++;
1012
+ }
1013
+ throw new Error(`updating "${field.name}" on board "${board.name}" blanked ${lost.length} item value(s); wrote ${restored} back by option name`);
1014
+ }
1015
+ return changes;
1016
+ }
1017
+ async createField(projectId, want) {
1018
+ await this.graphql.query(`mutation($project: ID!, $name: String!, $type: ProjectV2CustomFieldType!, $options: [ProjectV2SingleSelectFieldOptionInput!]) {
1019
+ createProjectV2Field(input: { projectId: $project, name: $name, dataType: $type, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
1020
+ }`, {
1021
+ project: projectId,
1022
+ name: want.name,
1023
+ type: DATA_TYPES[want.type],
1024
+ options: want.type === "single_select" ? (want.options ?? []).map((name) => toOptionInput({ name })) : void 0
1025
+ });
1026
+ }
1027
+ async createView(projectId, name, layout) {
1028
+ return (await this.graphql.query(`mutation($project: ID!, $name: String!, $layout: ProjectV2ViewLayout!) {
1029
+ createProjectV2View(input: { projectId: $project, name: $name, layout: $layout }) { projectV2View { id } }
1030
+ }`, {
1031
+ project: projectId,
1032
+ name,
1033
+ layout
1034
+ })).createProjectV2View.projectV2View.id;
1035
+ }
1036
+ async updateView(viewId, change) {
1037
+ await this.graphql.query(`mutation($view: ID!, $layout: ProjectV2ViewLayout, $filter: String) {
1038
+ updateProjectV2View(input: { viewId: $view, layout: $layout, filter: $filter }) { projectV2View { id } }
1039
+ }`, {
1040
+ view: viewId,
1041
+ layout: change.layout,
1042
+ filter: change.filter
1043
+ });
1044
+ }
1045
+ /** The board's issues and pull requests with their status, whether they are open and their open blockers. */
1046
+ async items(_owner, board, template) {
1047
+ const categories = new Map(template.statuses.map((s) => [s.name, s.category]));
1048
+ return (await this.fetchItems(board.id)).map((i) => {
1049
+ const status = i.values[STATUS_FIELD];
1050
+ const category = status ? categories.get(status) : void 0;
1051
+ const priority = priorityOf(i.values[PRIORITY_FIELD]);
1052
+ return {
1053
+ key: this.keyOf(i.repo, i.number),
1054
+ title: i.title,
1055
+ open: i.open,
1056
+ ...status ? { status } : {},
1057
+ ...category ? { category } : {},
1058
+ blockedBy: i.blockers.map((b) => this.keyOf(b.repo, b.number)),
1059
+ ...priority ? { priority } : {}
1060
+ };
1061
+ });
1062
+ }
1063
+ /** Puts an item in a status; `transitioned` is false when it already is there. */
1064
+ async setStatus(_owner, board, key, status) {
1065
+ const ref = this.parseKey(key);
1066
+ const field = (await this.readRaw(board.id)).fields.find((f) => f.name === STATUS_FIELD && f.options);
1067
+ const option = field?.options?.find((o) => o.name === status);
1068
+ if (!field || !option) throw new Error(`board "${board.name}" has no status "${status}"`);
1069
+ const item = (await this.fetchItems(board.id)).find((i) => i.repo === ref.repo && i.number === ref.number);
1070
+ if (!item) throw new Error(`${key} is not on board "${board.name}"`);
1071
+ if (item.values[STATUS_FIELD] === status) return {
1072
+ transitioned: false,
1073
+ status
1074
+ };
1075
+ await this.graphql.query(SET_VALUE, {
1076
+ project: board.id,
1077
+ item: item.id,
1078
+ field: field.id,
1079
+ option: option.id
1080
+ });
1081
+ return {
1082
+ transitioned: true,
1083
+ status,
1084
+ via: "project field set"
1085
+ };
1086
+ }
1087
+ /**
1088
+ * Puts the open items of `from` on `to` with their status and priority, only where the target has no value;
1089
+ * closed and merged ones stay, and are set to the template's done status when theirs is not a done one.
1090
+ */
1091
+ async move(_owner, from, to, template) {
1092
+ const report = {
1093
+ moved: [],
1094
+ kept: [],
1095
+ left: []
1096
+ };
1097
+ const [source, target, fromRaw, toRaw] = await Promise.all([
1098
+ this.fetchItems(from.id),
1099
+ this.fetchItems(to.id),
1100
+ this.readRaw(from.id),
1101
+ this.readRaw(to.id)
1102
+ ]);
1103
+ const done = template.statuses.find((s) => s.category === "done")?.name;
1104
+ const doneNames = new Set(template.statuses.filter((s) => s.category === "done").map((s) => s.name));
1105
+ const carried = [STATUS_FIELD, PRIORITY_FIELD];
1106
+ for (const item of source) {
1107
+ const key = this.keyOf(item.repo, item.number);
1108
+ if (!item.open) {
1109
+ const current = item.values[STATUS_FIELD];
1110
+ if (done && (!current || !doneNames.has(current))) await this.setOption(from.id, fromRaw, item.id, STATUS_FIELD, done);
1111
+ report.left.push(key);
1112
+ continue;
1113
+ }
1114
+ let targetItem = target.find((t) => t.contentId === item.contentId);
1115
+ if (targetItem) report.kept.push(key);
1116
+ else {
1117
+ const data = await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
1118
+ project: to.id,
1119
+ content: item.contentId
1120
+ });
1121
+ targetItem = {
1122
+ ...item,
1123
+ id: data.addProjectV2ItemById.item.id,
1124
+ values: {}
1125
+ };
1126
+ report.moved.push(key);
1127
+ }
1128
+ for (const name of carried) {
1129
+ const value = item.values[name];
1130
+ if (value && !targetItem.values[name]) await this.setOption(to.id, toRaw, targetItem.id, name, value);
1131
+ }
1132
+ }
1133
+ return report;
1134
+ }
1135
+ /**
1136
+ * Puts issues on the board (`addProjectV2ItemById`, the content id the issue's node id) and sets Status and Priority
1137
+ * through the single select update, only where the item has no value yet. A status or priority with no option on
1138
+ * the board is reported in `dropped`; no option is ever created, so no value is cleared.
1139
+ */
1140
+ async addItems(_owner, board, items, template) {
1141
+ const raw = await this.readRaw(board.id);
1142
+ const onBoard = await this.fetchItems(board.id);
1143
+ const statusField = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
1144
+ const priorityField = raw.fields.find((f) => f.name === PRIORITY_FIELD && f.options);
1145
+ const results = [];
1146
+ for (const input of items) {
1147
+ const ref = this.parseKey(input.key);
1148
+ let current = onBoard.find((i) => i.repo === ref.repo && i.number === ref.number);
1149
+ const added = !current;
1150
+ if (!current) current = {
1151
+ id: (await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
1152
+ project: board.id,
1153
+ content: await this.nodeId(ref)
1154
+ })).addProjectV2ItemById.item.id,
1155
+ contentId: "",
1156
+ repo: ref.repo,
1157
+ number: ref.number,
1158
+ title: "",
1159
+ open: true,
1160
+ values: {},
1161
+ blockers: []
1162
+ };
1163
+ const dropped = [];
1164
+ if (input.status !== void 0 || input.category !== void 0) {
1165
+ const name = this.statusFor(input, template, statusField?.options);
1166
+ if (!name) dropped.push(`status ${input.status ?? input.category} (no matching option on the board)`);
1167
+ else if (!current.values[STATUS_FIELD]) await this.setOption(board.id, raw, current.id, STATUS_FIELD, name);
1168
+ }
1169
+ if (input.priority !== void 0 && input.priority !== "none") {
1170
+ const option = priorityField?.options?.find((o) => priorityOf(o.name) === input.priority);
1171
+ if (!option) dropped.push(`priority ${input.priority} (no matching option on the board)`);
1172
+ else if (!current.values[PRIORITY_FIELD]) await this.setOption(board.id, raw, current.id, PRIORITY_FIELD, option.name);
1173
+ }
1174
+ results.push({
1175
+ key: input.key,
1176
+ added,
1177
+ dropped
1178
+ });
1179
+ }
1180
+ return results;
1181
+ }
1182
+ /** The board's own status for an input: the option named like its status, else the template's status of its category. */
1183
+ statusFor(input, template, options) {
1184
+ const has = (name) => options?.find((o) => o.name.toLowerCase() === name.toLowerCase())?.name;
1185
+ const named = input.status === void 0 ? void 0 : has(input.status);
1186
+ if (named) return named;
1187
+ const byCategory = template.statuses.find((s) => s.category === input.category);
1188
+ return byCategory ? has(byCategory.name) : void 0;
1189
+ }
1190
+ /** The node id of an issue, which `addProjectV2ItemById` takes as the content id. */
1191
+ async nodeId(ref) {
1192
+ const [owner, name] = ref.repo.split("/");
1193
+ const id = (await this.graphql.query(`query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { id } } }`, {
1194
+ owner,
1195
+ name,
1196
+ number: ref.number
1197
+ })).repository?.issue?.id;
1198
+ if (!id) throw new Error(`issue ${ref.repo}#${ref.number} not found`);
1199
+ return id;
1200
+ }
1201
+ /** A `holocron doctor` smoke check: how many boards the token sees in the configured repository's organization. */
1202
+ async whoami() {
1203
+ try {
1204
+ return {
1205
+ ok: true,
1206
+ boards: (await this.list(this.repo.split("/")[0] ?? "")).length
1207
+ };
1208
+ } catch {
1209
+ return {
1210
+ ok: false,
1211
+ boards: 0
1212
+ };
1213
+ }
1214
+ }
1215
+ /** Sets a single select value by option name; a field or option the board lacks is skipped. */
1216
+ async setOption(projectId, raw, itemId, fieldName, optionName) {
1217
+ const field = raw.fields.find((f) => f.name === fieldName && f.options);
1218
+ const option = field?.options?.find((o) => o.name === optionName);
1219
+ if (!field || !option) return;
1220
+ await this.graphql.query(SET_VALUE, {
1221
+ project: projectId,
1222
+ item: itemId,
1223
+ field: field.id,
1224
+ option: option.id
1225
+ });
1226
+ }
1227
+ async ownerId(owner) {
1228
+ return (await this.graphql.query(OWNER_QUERY, { owner })).organization.id;
1229
+ }
1230
+ async readRaw(id) {
1231
+ const n = (await this.graphql.query(BOARD_QUERY, { id })).node;
1232
+ if (!n) throw new Error(`board ${id} not found`);
1233
+ return {
1234
+ summary: toSummary(n),
1235
+ fields: n.fields.nodes.filter((f) => f.id).map((f) => ({
1236
+ id: f.id,
1237
+ name: f.name,
1238
+ dataType: f.dataType,
1239
+ ...f.options ? { options: f.options } : {}
1240
+ })),
1241
+ views: n.views.nodes.map((v) => ({
1242
+ id: v.id,
1243
+ name: v.name,
1244
+ layout: v.layout,
1245
+ filter: v.filter,
1246
+ groupBy: (v.groupByFields?.nodes ?? []).map((g) => g.name)
1247
+ })),
1248
+ rules: n.workflows.nodes.map((w) => ({
1249
+ id: w.id,
1250
+ name: w.name,
1251
+ enabled: w.enabled
1252
+ }))
1253
+ };
1254
+ }
1255
+ async fetchItems(id) {
1256
+ const items = [];
1257
+ let after = null;
1258
+ for (;;) {
1259
+ const page = (await this.graphql.query(ITEMS_QUERY, {
1260
+ id,
1261
+ after
1262
+ })).node.items;
1263
+ for (const n of page.nodes) {
1264
+ const c = n.content;
1265
+ if (!c || !c.repository) continue;
1266
+ const values = {};
1267
+ for (const v of n.fieldValues.nodes) if (v.name && v.field?.name) values[v.field.name] = v.name;
1268
+ items.push({
1269
+ id: n.id,
1270
+ contentId: c.id,
1271
+ repo: c.repository.nameWithOwner,
1272
+ number: c.number,
1273
+ title: c.title,
1274
+ open: c.state === "OPEN",
1275
+ values,
1276
+ blockers: (c.blockedBy?.nodes ?? []).filter((b) => b.state === "OPEN").map((b) => ({
1277
+ repo: b.repository.nameWithOwner,
1278
+ number: b.number
1279
+ }))
1280
+ });
1281
+ }
1282
+ if (!page.pageInfo.hasNextPage) return items;
1283
+ after = page.pageInfo.endCursor;
1284
+ }
1285
+ }
1286
+ keyOf(repo, number) {
1287
+ return repo === this.repo ? `#${number}` : `${repo}#${number}`;
1288
+ }
1289
+ parseKey(key) {
1290
+ const m = /^(?:([^#\s]+))?#?(\d+)$/.exec(key.trim());
1291
+ const hasRepo = key.includes("#") && m?.[1];
1292
+ if (!m) throw new Error(`not an issue key: ${key}`);
1293
+ return {
1294
+ repo: hasRepo ? m[1] : this.repo,
1295
+ number: Number(m[2])
1296
+ };
1297
+ }
1298
+ };
1299
+ // src/sodium.ts
342
1300
  /**
343
1301
  * libsodium sealed-box encryption for GitHub Actions secrets.
344
1302
  *
@@ -369,32 +1327,46 @@ async function encryptSecret(publicKeyBase64, value) {
369
1327
  const ciphertext = sodium.crypto_box_seal(plaintext, publicKey);
370
1328
  return sodium.to_base64(ciphertext, sodium.base64_variants.ORIGINAL);
371
1329
  }
372
- //#endregion
373
- //#region src/capabilities/secrets.ts
1330
+ // src/capabilities/secrets.ts
1331
+ /** The GitHub implementation of the `secrets` capability, covering repository, environment and organization secrets. */
374
1332
  var GitHubSecrets = class {
375
1333
  client;
376
1334
  opts;
1335
+ orgClient;
1336
+ /** Capability key, always `"secrets"`. */
377
1337
  key = "secrets";
1338
+ /** Provider name, always `"github"`. */
378
1339
  providerName = "github";
379
- constructor(client, opts) {
1340
+ /**
1341
+ * `client` handles repo and environment scopes; `orgClient`, when given, handles
1342
+ * the organization scope. They differ when a dedicated org-only token exists:
1343
+ * it can write org secrets but not repo ones, and `github.admin` is the reverse.
1344
+ */
1345
+ constructor(client, opts, orgClient) {
380
1346
  this.client = client;
381
1347
  this.opts = opts;
1348
+ this.orgClient = orgClient;
1349
+ }
1350
+ clientFor(scope) {
1351
+ return scope.kind === "organization" ? this.orgClient ?? this.client : this.client;
382
1352
  }
383
1353
  async listSecrets(scope) {
384
- return this.client.secrets.listSecrets(this.opts.repo, toGHScope(scope));
1354
+ return this.clientFor(scope).secrets.listSecrets(this.opts.repo, toGHScope(scope));
385
1355
  }
386
1356
  async setSecret(scope, name, value) {
387
1357
  const ghScope = toGHScope(scope);
388
- const pk = await this.client.secrets.getPublicKey(this.opts.repo, ghScope);
1358
+ const client = this.clientFor(scope);
1359
+ const pk = await client.secrets.getPublicKey(this.opts.repo, ghScope);
389
1360
  const body = {
390
1361
  encrypted_value: await encryptSecret(pk.key, value),
391
1362
  key_id: pk.key_id
392
1363
  };
393
1364
  if (scope.kind === "organization") body.visibility = "all";
394
- await this.client.secrets.putSecret(this.opts.repo, ghScope, name, body);
1365
+ await client.secrets.putSecret(this.opts.repo, ghScope, name, body);
395
1366
  }
1367
+ /** Deletes the named secret in the given scope. */
396
1368
  async deleteSecret(scope, name) {
397
- await this.client.secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
1369
+ await this.clientFor(scope).secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
398
1370
  }
399
1371
  };
400
1372
  function toGHScope(scope) {
@@ -404,8 +1376,46 @@ function toGHScope(scope) {
404
1376
  };
405
1377
  return scope;
406
1378
  }
407
- //#endregion
408
- //#region src/capabilities/labels.ts
1379
+ // src/capabilities/files.ts
1380
+ /** Reads one file; `null` when it does not exist. `version` is the blob sha `writeFile` needs to replace exactly this one. */
1381
+ /** A fine-grained token only reaches the repositories and permissions it was given; say which one is missing. */
1382
+ function noAccess(repo, action, cause) {
1383
+ return new Error(`the token cannot ${action} files in ${repo} (403): give the user-sync token (HOLOCRON_USER_SYNC_TOKEN, or holocron auth set github.user-sync) access to that repository with Contents: ${action === "read" ? "read" : "read and write"}`, { cause });
1384
+ }
1385
+ async function readRepoFile(client, repo, path) {
1386
+ try {
1387
+ const file = await client.git.getContents(repo, path);
1388
+ if (file.encoding !== "base64") throw new Error(`${repo}/${path}: unexpected encoding \`${file.encoding}\``);
1389
+ return {
1390
+ content: Buffer.from(file.content, "base64").toString("utf-8"),
1391
+ version: file.sha
1392
+ };
1393
+ } catch (err) {
1394
+ if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "read", err);
1395
+ if (!(err instanceof ProviderApiError && err.status === 404)) throw err;
1396
+ }
1397
+ try {
1398
+ await client.repos.getRepo(repo);
1399
+ } catch (err) {
1400
+ 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 });
1401
+ throw err;
1402
+ }
1403
+ return null;
1404
+ }
1405
+ /** Creates or replaces one file in a commit; GitHub refuses (409) a `version` that has since changed. */
1406
+ async function writeRepoFile(client, repo, path, content, opts) {
1407
+ try {
1408
+ await client.git.putContents(repo, path, {
1409
+ message: opts.message,
1410
+ content,
1411
+ ...opts.version ? { sha: opts.version } : {}
1412
+ });
1413
+ } catch (err) {
1414
+ if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "write", err);
1415
+ throw err;
1416
+ }
1417
+ }
1418
+ // src/capabilities/labels.ts
409
1419
  /**
410
1420
  * Idempotently synchronise a repo's labels to the canonical set.
411
1421
  *
@@ -443,14 +1453,202 @@ async function syncLabels(client, repo, canonical, stale) {
443
1453
  }
444
1454
  return `${created} created, ${updated} updated, ${deleted} deleted`;
445
1455
  }
446
- //#endregion
447
- //#region src/capabilities/properties.ts
448
- async function syncProperties(client, repo, values) {
449
- await client.properties.setProperties(repo, values);
1456
+ // src/capabilities/property-fix-hints.ts
1457
+ /** GitHub's wording when a custom property value is not one the organization's definition allows. */
1458
+ const NOT_ALLOWED = /Value '([^']+)' is not allowed for property '([^']+)'/g;
1459
+ /**
1460
+ * What to do about each value GitHub says an organization custom property does not allow, one sentence per property,
1461
+ * read from GitHub's own message so it works even when the organization's definitions cannot be read. The values
1462
+ * belong to the organization's definition, not to the repository, so the fix is to add them there: a repository cannot
1463
+ * make its own value allowed. Empty when GitHub's message names no such value.
1464
+ */
1465
+ function propertyFixHints(githubMessage) {
1466
+ const byProperty = /* @__PURE__ */ new Map();
1467
+ for (const [, value, property] of githubMessage.matchAll(NOT_ALLOWED)) {
1468
+ const values = byProperty.get(property) ?? [];
1469
+ if (!values.includes(value)) values.push(value);
1470
+ byProperty.set(property, values);
1471
+ }
1472
+ 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 repo setup again`);
1473
+ }
1474
+ // src/capabilities/rejected-properties.ts
1475
+ /** The values `repo setup` sends for `true_false` properties; anything else is rejected. */
1476
+ const BOOLEANS = /* @__PURE__ */ new Set(["true", "false"]);
1477
+ /**
1478
+ * What is wrong with `values` when compared with the organization's property definitions, one sentence per
1479
+ * problem, in the order the properties are given: a property the organization does not define, a value a
1480
+ * `single_select` or `multi_select` property does not allow, or a `true_false` property that is not `true` or
1481
+ * `false`. A `string` or `url` property has nothing to check here. Empty when every value fits its definition.
1482
+ */
1483
+ function rejectedProperties(values, schema) {
1484
+ const byName = new Map(schema.map((property) => [property.property_name, property]));
1485
+ const problems = [];
1486
+ for (const [name, value] of Object.entries(values)) {
1487
+ const definition = byName.get(name);
1488
+ if (!definition) {
1489
+ problems.push(`${name} is not a custom property of the organization`);
1490
+ continue;
1491
+ }
1492
+ const sent = Array.isArray(value) ? value : [value];
1493
+ if (definition.value_type === "true_false") {
1494
+ for (const item of sent.filter((item) => !BOOLEANS.has(item))) problems.push(`${name} is "${item}", but it takes only true or false`);
1495
+ continue;
1496
+ }
1497
+ const allowed = definition.allowed_values ?? [];
1498
+ if (definition.value_type !== "single_select" && definition.value_type !== "multi_select") continue;
1499
+ 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(", ")})`);
1500
+ }
1501
+ return problems;
1502
+ }
1503
+ // src/capabilities/properties.ts
1504
+ /** GitHub's own message from a 422 body (`{"message": ..., "errors": [...]}`), or the start of the body when it is not JSON. */
1505
+ function githubMessage(details) {
1506
+ const raw = String(details ?? "").trim();
1507
+ try {
1508
+ const body = JSON.parse(raw);
1509
+ const errors = Array.isArray(body.errors) ? body.errors.map((e) => JSON.stringify(e)).join(", ") : "";
1510
+ const message = typeof body.message === "string" ? body.message : raw;
1511
+ return errors ? `${message}: ${errors}` : message;
1512
+ } catch {
1513
+ return raw.slice(0, 300);
1514
+ }
1515
+ }
1516
+ /** The organization's property definitions, or `undefined` when they cannot be read (permission, an older client). */
1517
+ async function orgSchema(client, repo) {
1518
+ try {
1519
+ return await client.properties.orgSchema(repo.split("/")[0]);
1520
+ } catch {
1521
+ return;
1522
+ }
1523
+ }
1524
+ /**
1525
+ * The values `values` holds that the organization's property definitions do not allow, one sentence each, or
1526
+ * `undefined` when the definitions cannot be read (the token lacks the organization's custom properties permission, or
1527
+ * the organization defines none). `client` should be the organization-scoped one when there is one, since reading the
1528
+ * definitions is an organization permission a repository token often lacks. Read-only.
1529
+ */
1530
+ async function checkPropertyValues(client, repo, values) {
1531
+ const schema = await orgSchema(client, repo);
1532
+ return schema ? rejectedProperties(values, schema) : void 0;
1533
+ }
1534
+ /**
1535
+ * Sets the repo's custom properties. When GitHub answers 422 the error says which value it refused and what to do
1536
+ * about it: the values are compared with the organization's property definitions (read-only, with `schemaClient`, the
1537
+ * organization-scoped client when there is one), GitHub's own message is added, and each value GitHub says a property
1538
+ * does not allow gets the fix, which does not need the definitions to be readable. One refused value fails the whole
1539
+ * request, so none of the properties is set.
1540
+ */
1541
+ async function syncProperties(client, repo, values, schemaClient = client) {
1542
+ try {
1543
+ await client.properties.setProperties(repo, values);
1544
+ } catch (err) {
1545
+ if (!(err instanceof ProviderApiError$1) || err.status !== 422) throw err;
1546
+ const problems = await checkPropertyValues(schemaClient, repo, values) ?? [];
1547
+ const said = githubMessage(err.details);
1548
+ const fixes = propertyFixHints(said);
1549
+ 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 });
1550
+ }
450
1551
  return `${Object.keys(values).length} properties set`;
451
1552
  }
452
- //#endregion
453
- //#region src/capabilities/teams.ts
1553
+ /** The values the organization's property `name` allows; `undefined` when it cannot be read, is not defined or takes any value. */
1554
+ async function getOrgPropertyValues(client, repo, name) {
1555
+ return ((await orgSchema(client, repo))?.find((p) => p.property_name === name))?.allowed_values ?? void 0;
1556
+ }
1557
+ /**
1558
+ * Adds the missing `values` to the organization's property `name` and returns them. GitHub replaces the whole
1559
+ * definition on a write, so the current one is read and sent back with the allowed values extended, in their order,
1560
+ * and nothing removed. A write is made only when something is missing.
1561
+ */
1562
+ async function addOrgPropertyValues(client, repo, name, values) {
1563
+ const org = repo.split("/")[0];
1564
+ const current = (await client.properties.orgSchema(org)).find((p) => p.property_name === name);
1565
+ if (!current) throw new Error(`the organization ${org} has no custom property "${name}"; create it first`);
1566
+ if (!current.allowed_values) throw new Error(`the custom property "${name}" takes any value; it has nothing to extend`);
1567
+ const have = new Set(current.allowed_values);
1568
+ const added = [...new Set(values)].filter((v) => !have.has(v));
1569
+ if (added.length === 0) return [];
1570
+ await client.properties.setOrgProperty(org, {
1571
+ ...current,
1572
+ allowed_values: [...current.allowed_values, ...added]
1573
+ });
1574
+ return added;
1575
+ }
1576
+ // src/capabilities/read-repo.ts
1577
+ /** The settings `repo setup` writes, which `GET /repos/{repo}` reports under the same names. */
1578
+ const SETTING_KEYS = [
1579
+ "allow_squash_merge",
1580
+ "allow_merge_commit",
1581
+ "allow_rebase_merge",
1582
+ "allow_auto_merge",
1583
+ "allow_update_branch",
1584
+ "delete_branch_on_merge",
1585
+ "has_issues",
1586
+ "has_discussions",
1587
+ "has_projects",
1588
+ "has_wiki"
1589
+ ];
1590
+ /** The repository's description, homepage, default branch, topics and settings, from one read. */
1591
+ async function readRepoInfo(client, repo) {
1592
+ const data = await client.repos.getRepo(repo);
1593
+ const settings = { default_branch: data.default_branch };
1594
+ for (const key of SETTING_KEYS) {
1595
+ const value = data[key];
1596
+ if (value !== void 0) settings[key] = value;
1597
+ }
1598
+ return {
1599
+ description: data.description ?? null,
1600
+ homepage: data.homepage ?? null,
1601
+ defaultBranch: data.default_branch,
1602
+ topics: data.topics ?? [],
1603
+ settings
1604
+ };
1605
+ }
1606
+ /** A ruleset reduced to what `repo setup` writes: its enforcement, rule types and required status checks. */
1607
+ function toRulesetDetail(data) {
1608
+ const rules = data.rules ?? [];
1609
+ const checks = rules.find((r) => r.type === "required_status_checks")?.parameters?.required_status_checks;
1610
+ return {
1611
+ name: data.name,
1612
+ enforcement: data.enforcement,
1613
+ ruleTypes: rules.map((r) => r.type),
1614
+ requiredChecks: Array.isArray(checks) ? checks.map((c) => String(c.context)) : []
1615
+ };
1616
+ }
1617
+ /** The value, or `undefined` when GitHub refuses the read (permission, plan, feature absent). Other errors still throw. */
1618
+ async function readable(read) {
1619
+ try {
1620
+ return await read();
1621
+ } catch (err) {
1622
+ if (err instanceof ProviderApiError$1) return void 0;
1623
+ throw err;
1624
+ }
1625
+ }
1626
+ /** Which security features are on. One GitHub refuses to report is left out, not reported as off. */
1627
+ async function readSecurity(client, repo) {
1628
+ const [data, alerts, fixes, reporting, codeScanning] = await Promise.all([
1629
+ readable(() => client.repos.getRepo(repo)),
1630
+ readable(() => client.security.vulnerabilityAlertsEnabled(repo)),
1631
+ readable(() => client.security.automatedSecurityFixesEnabled(repo)),
1632
+ readable(() => client.security.privateVulnerabilityReportingEnabled(repo)),
1633
+ readable(() => client.security.codeScanningDefaultSetupState(repo))
1634
+ ]);
1635
+ const analysis = data?.security_and_analysis;
1636
+ const on = (feature) => {
1637
+ const status = analysis?.[feature]?.status;
1638
+ return status === void 0 ? void 0 : status === "enabled";
1639
+ };
1640
+ const found = {
1641
+ vulnerabilityAlerts: alerts,
1642
+ automatedSecurityFixes: fixes,
1643
+ secretScanning: on("secret_scanning"),
1644
+ secretScanningPushProtection: on("secret_scanning_push_protection"),
1645
+ privateVulnerabilityReporting: reporting,
1646
+ codeScanningDefaultSetup: codeScanning === void 0 ? void 0 : codeScanning === "configured"
1647
+ };
1648
+ return Object.fromEntries(Object.entries(found).filter(([, v]) => v !== void 0));
1649
+ }
1650
+ // src/capabilities/teams.ts
1651
+ /** Turns a team entry into slug and permission form; a bare slug gets `push`. */
454
1652
  function normalizeTeamEntry(entry) {
455
1653
  if (typeof entry === "string") return {
456
1654
  slug: entry,
@@ -458,6 +1656,7 @@ function normalizeTeamEntry(entry) {
458
1656
  };
459
1657
  return entry;
460
1658
  }
1659
+ /** Grants each team access to the repo and reports the outcome; throws when every team fails. */
461
1660
  async function syncTeams(client, repo, teams) {
462
1661
  const [org = "", name = ""] = repo.split("/", 2);
463
1662
  const normalized = teams.map(normalizeTeamEntry);
@@ -470,17 +1669,132 @@ async function syncTeams(client, repo, teams) {
470
1669
  }
471
1670
  return `${succeeded} team${succeeded === 1 ? "" : "s"} synced`;
472
1671
  }
473
- //#endregion
474
- //#region src/capabilities/topics.ts
1672
+ // src/capabilities/topics.ts
475
1673
  async function syncTopics(client, repo, topics) {
476
1674
  await client.topics.setTopics(repo, topics);
477
1675
  return `${topics.length} topics set`;
478
1676
  }
479
- //#endregion
480
- //#region src/capabilities/source.ts
1677
+ // src/capabilities/variables.ts
1678
+ /** GitHub's rule for a variable name: letters, digits and underscores, not starting with a digit or `GITHUB_`. */
1679
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
1680
+ /** Longest name GitHub accepts. */
1681
+ const MAX_NAME = 256;
1682
+ function assertNames(names) {
1683
+ 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_`);
1684
+ }
1685
+ /** GitHub treats variable names as case-insensitive, so every comparison goes through this. */
1686
+ const key = (name) => name.toUpperCase();
1687
+ /**
1688
+ * Bring one scope's variables in line with the declaration: create what is missing, update what differs, leave what
1689
+ * already matches. Variables that exist but are not declared are left alone, or deleted with `prune`, except an
1690
+ * organization variable limited to selected repositories, which this client cannot manage and so is never deleted.
1691
+ * Returns a one-line summary, naming the ones left so drift is visible. In a dry run it only describes the changes.
1692
+ */
1693
+ async function reconcile(client, repo, scope, wanted, opts) {
1694
+ assertNames(wanted.map((w) => w.name));
1695
+ const existing = new Map((await client.variables.listVariables(repo, scope)).map((v) => [key(v.name), v]));
1696
+ const counts = {
1697
+ created: 0,
1698
+ updated: 0,
1699
+ unchanged: 0,
1700
+ deleted: 0
1701
+ };
1702
+ for (const want of wanted) {
1703
+ const have = existing.get(key(want.name));
1704
+ const body = {
1705
+ name: want.name,
1706
+ value: want.value
1707
+ };
1708
+ if (want.visibility) body["visibility"] = want.visibility;
1709
+ if (!have) {
1710
+ if (opts.dryRun) {
1711
+ counts.created++;
1712
+ continue;
1713
+ }
1714
+ try {
1715
+ await client.variables.createVariable(repo, scope, body);
1716
+ counts.created++;
1717
+ continue;
1718
+ } catch (err) {
1719
+ if (!(err instanceof ProviderApiError && (err.status === 409 || err.status === 422))) throw err;
1720
+ }
1721
+ } else if (have.value === want.value && (!want.visibility || have.visibility === want.visibility)) {
1722
+ counts.unchanged++;
1723
+ continue;
1724
+ }
1725
+ if (!opts.dryRun) await client.variables.updateVariable(repo, scope, have?.name ?? want.name, body);
1726
+ counts.updated++;
1727
+ }
1728
+ const declared = new Set(wanted.map((w) => key(w.name)));
1729
+ const undeclared = [...existing.entries()].filter(([k]) => !declared.has(k)).map(([, v]) => v);
1730
+ const unmanaged = undeclared.filter((v) => v.visibility === "selected");
1731
+ if (opts.prune) for (const v of undeclared.filter((u) => u.visibility !== "selected")) {
1732
+ if (!opts.dryRun) await client.variables.deleteVariable(repo, scope, v.name);
1733
+ counts.deleted++;
1734
+ }
1735
+ const parts = opts.dryRun ? [
1736
+ `would create ${counts.created}`,
1737
+ `would update ${counts.updated}`,
1738
+ `${counts.unchanged} unchanged`
1739
+ ] : [
1740
+ `${counts.created} created`,
1741
+ `${counts.updated} updated`,
1742
+ `${counts.unchanged} unchanged`
1743
+ ];
1744
+ if (counts.deleted > 0) parts.push(`${counts.deleted} ${opts.dryRun ? "would be deleted" : "deleted"}`);
1745
+ const left = opts.prune ? unmanaged : undeclared;
1746
+ if (left.length > 0) {
1747
+ const why = opts.prune ? "limited to selected repositories, not managed" : "not declared, left alone";
1748
+ parts.push(`${left.length} ${why}: ${left.map((v) => v.name).join(", ")}`);
1749
+ }
1750
+ return parts.join(", ");
1751
+ }
1752
+ /** Reconcile a repository's Actions variables. */
1753
+ function syncVariables(client, repo, variables, opts = {}) {
1754
+ return reconcile(client, repo, { kind: "repo" }, Object.entries(variables).map(([name, value]) => ({
1755
+ name,
1756
+ value
1757
+ })), {
1758
+ prune: opts.prune === true,
1759
+ dryRun: opts.dryRun === true
1760
+ });
1761
+ }
1762
+ /** Reconcile an organization's Actions variables. `repo` is only the coordinate the client is bound to. */
1763
+ function syncOrgVariables(client, repo, org, variables, opts = {}) {
1764
+ const wanted = Object.entries(variables).map(([name, v]) => ({
1765
+ name,
1766
+ value: v.value,
1767
+ visibility: v.visibility
1768
+ }));
1769
+ return reconcile(client, repo, {
1770
+ kind: "organization",
1771
+ org
1772
+ }, wanted, {
1773
+ prune: opts.prune === true,
1774
+ dryRun: opts.dryRun === true
1775
+ });
1776
+ }
1777
+ // src/capabilities/source.ts
1778
+ function toPullRequest(raw) {
1779
+ return {
1780
+ number: raw.number,
1781
+ title: raw.title,
1782
+ state: raw.state,
1783
+ merged: raw.merged_at !== null,
1784
+ branch: raw.head.ref,
1785
+ headSha: raw.head.sha,
1786
+ url: raw.html_url
1787
+ };
1788
+ }
1789
+ /**
1790
+ * The GitHub implementation of the `source` capability: repo settings, rulesets, branch protection, security
1791
+ * features and local workflow files.
1792
+ */
481
1793
  var GitHubSource = class {
482
1794
  client;
1795
+ /** Capability key, always `"source"`. */
483
1796
  key = "source";
1797
+ /** Provider name, always `"github"`. */
484
1798
  providerName = "github";
485
1799
  owner;
486
1800
  name;
@@ -488,6 +1802,7 @@ var GitHubSource = class {
488
1802
  repoRoot;
489
1803
  workflowDir;
490
1804
  orgClient;
1805
+ userSyncClient;
491
1806
  baseUrl;
492
1807
  fetchImpl;
493
1808
  constructor(client, opts) {
@@ -496,15 +1811,20 @@ var GitHubSource = class {
496
1811
  this.owner = owner;
497
1812
  this.name = name;
498
1813
  this.repo = opts.repo;
499
- this.repoRoot = opts.repoRoot;
500
- this.workflowDir = join(opts.repoRoot, ".github", "workflows");
1814
+ this.repoRoot = findRootSync(opts.repoRoot, ".git", {
1815
+ fallback: "start",
1816
+ realpath: true
1817
+ });
1818
+ this.workflowDir = join(this.repoRoot, ".github", "workflows");
501
1819
  this.orgClient = opts.orgClient;
1820
+ this.userSyncClient = opts.userSyncClient;
502
1821
  this.baseUrl = opts.baseUrl;
503
1822
  this.fetchImpl = opts.fetch;
504
1823
  }
505
1824
  async whoami() {
506
1825
  return { login: (await this.client.user.getCurrentUser()).login };
507
1826
  }
1827
+ /** Returns the repo's owner, name and default branch. */
508
1828
  async getRepo() {
509
1829
  const data = await this.client.repos.getRepo(this.repo);
510
1830
  return {
@@ -513,27 +1833,34 @@ var GitHubSource = class {
513
1833
  defaultBranch: data.default_branch
514
1834
  };
515
1835
  }
1836
+ /** Lists the repo's rulesets. */
516
1837
  async listRulesets() {
517
1838
  return this.client.rulesets.listRulesets(this.repo);
518
1839
  }
1840
+ /** Creates a ruleset from the given payload. */
519
1841
  async createRuleset(payload) {
520
1842
  return this.client.rulesets.createRuleset(this.repo, payload);
521
1843
  }
1844
+ /** Updates the ruleset with the given id from the payload. */
522
1845
  async updateRuleset(id, payload) {
523
1846
  return this.client.rulesets.updateRuleset(this.repo, id, payload);
524
1847
  }
1848
+ /** Updates the repo's settings. */
525
1849
  async updateRepoSettings(settings) {
526
1850
  await this.client.repos.updateRepo(this.repo, settings);
527
1851
  }
528
1852
  async protectBranch(branch, payload) {
529
1853
  await this.client.branches.protectBranch(this.repo, branch, payload);
530
1854
  }
1855
+ /** Enables Dependabot vulnerability alerts. */
531
1856
  async enableVulnerabilityAlerts() {
532
1857
  await this.client.security.enableVulnerabilityAlerts(this.repo);
533
1858
  }
1859
+ /** Enables Dependabot automated security fixes. */
534
1860
  async enableAutomatedSecurityFixes() {
535
1861
  await this.client.security.enableAutomatedSecurityFixes(this.repo);
536
1862
  }
1863
+ /** Enables secret scanning. */
537
1864
  async enableSecretScanning() {
538
1865
  await this.client.security.enableSecretScanning(this.repo);
539
1866
  }
@@ -546,9 +1873,11 @@ var GitHubSource = class {
546
1873
  async enableDependencyGraph() {
547
1874
  await this.client.security.enableDependencyGraph(this.repo);
548
1875
  }
1876
+ /** Enables private vulnerability reporting. */
549
1877
  async enablePrivateVulnerabilityReporting() {
550
1878
  await this.client.security.enablePrivateVulnerabilityReporting(this.repo);
551
1879
  }
1880
+ /** Lists the `.yml` and `.yaml` files in `.github/workflows`, sorted by name; empty when the folder is missing. */
552
1881
  async listWorkflowFiles() {
553
1882
  try {
554
1883
  return (await readdir(this.workflowDir)).filter((e) => e.endsWith(".yml") || e.endsWith(".yaml")).sort();
@@ -557,6 +1886,7 @@ var GitHubSource = class {
557
1886
  throw err;
558
1887
  }
559
1888
  }
1889
+ /** Reads a workflow file's text, or `null` when it does not exist. */
560
1890
  async readWorkflowFile(name) {
561
1891
  try {
562
1892
  return await readFile(join(this.workflowDir, name), "utf8");
@@ -565,10 +1895,12 @@ var GitHubSource = class {
565
1895
  throw err;
566
1896
  }
567
1897
  }
1898
+ /** Writes a workflow file, creating `.github/workflows` first when needed. */
568
1899
  async writeWorkflowFile(name, contents) {
569
1900
  await ensureDir(this.workflowDir);
570
1901
  await writeFile(join(this.workflowDir, name), contents, "utf8");
571
1902
  }
1903
+ /** Removes a workflow file; a file that is already gone is not an error. */
572
1904
  async removeWorkflowFile(name) {
573
1905
  try {
574
1906
  await rm(join(this.workflowDir, name));
@@ -586,14 +1918,83 @@ var GitHubSource = class {
586
1918
  return syncLabels(this.client, this.repo, canonical, stale);
587
1919
  }
588
1920
  async syncProperties(values) {
589
- return syncProperties(this.client, this.repo, values);
1921
+ return syncProperties(this.client, this.repo, values, this.orgClient ?? this.client);
1922
+ }
1923
+ async getOrgPropertyValues(name) {
1924
+ return getOrgPropertyValues(this.orgClient ?? this.client, this.repo, name);
1925
+ }
1926
+ async addOrgPropertyValues(name, values) {
1927
+ return addOrgPropertyValues(this.orgClient ?? this.client, this.repo, name, values);
1928
+ }
1929
+ async checkPropertyValues(values) {
1930
+ return checkPropertyValues(this.orgClient ?? this.client, this.repo, values);
590
1931
  }
591
1932
  async syncTeams(teams) {
592
1933
  return syncTeams(this.orgClient ?? this.client, this.repo, teams);
593
1934
  }
1935
+ async teamMembers(teamSlug, org = this.owner) {
1936
+ return (await (this.orgClient ?? this.client).teams.members(org, teamSlug)).map((m) => ({
1937
+ id: String(m.id),
1938
+ login: m.login
1939
+ }));
1940
+ }
1941
+ async readFile(path, repo = this.repo) {
1942
+ return readRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, repo, path);
1943
+ }
1944
+ async writeFile(path, content, opts) {
1945
+ return writeRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, opts.repo ?? this.repo, path, content, opts);
1946
+ }
594
1947
  async syncTopics(topics) {
595
1948
  return syncTopics(this.client, this.repo, topics);
596
1949
  }
1950
+ async syncVariables(variables, opts) {
1951
+ return syncVariables(this.client, this.repo, variables, opts);
1952
+ }
1953
+ async syncOrgVariables(org, variables, opts) {
1954
+ if (!this.orgClient) throw new Error("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron auth set github.org <token>`");
1955
+ return syncOrgVariables(this.orgClient, this.repo, org, variables, opts);
1956
+ }
1957
+ async listVariables() {
1958
+ const found = await this.client.variables.listVariables(this.repo, { kind: "repo" });
1959
+ return Object.fromEntries(found.map((v) => [v.name, v.value]));
1960
+ }
1961
+ async listOrgVariables(org) {
1962
+ if (!this.orgClient) throw new MissingTokenError("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron auth set github.org <token>`");
1963
+ const found = await this.orgClient.variables.listVariables(this.repo, {
1964
+ kind: "organization",
1965
+ org
1966
+ });
1967
+ return Object.fromEntries(found.map((v) => [v.name, {
1968
+ value: v.value,
1969
+ visibility: v.visibility ?? "all"
1970
+ }]));
1971
+ }
1972
+ async getRepoInfo() {
1973
+ return readRepoInfo(this.client, this.repo);
1974
+ }
1975
+ async getProperties() {
1976
+ const found = await this.client.properties.getValues(this.repo);
1977
+ return Object.fromEntries(found.flatMap((p) => p.value === null ? [] : [[p.property_name, p.value]]));
1978
+ }
1979
+ async listLabels() {
1980
+ return (await this.client.labels.listLabels(this.repo)).map((l) => ({
1981
+ name: l.name,
1982
+ color: l.color,
1983
+ description: l.description ?? ""
1984
+ }));
1985
+ }
1986
+ async listTeamAccess() {
1987
+ return (await (this.orgClient ?? this.client).teams.listForRepo(this.repo)).map((t) => ({
1988
+ slug: t.slug,
1989
+ permission: t.permission
1990
+ }));
1991
+ }
1992
+ async getRulesetDetail(id) {
1993
+ return toRulesetDetail(await this.client.rulesets.getRuleset(this.repo, id));
1994
+ }
1995
+ async getSecurity() {
1996
+ return readSecurity(this.client, this.repo);
1997
+ }
597
1998
  async syncDescription(description) {
598
1999
  await this.client.repos.updateRepo(this.repo, { description });
599
2000
  return "description updated";
@@ -603,15 +2004,27 @@ var GitHubSource = class {
603
2004
  return "homepage updated";
604
2005
  }
605
2006
  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
- };
2007
+ return toPullRequest(await this.client.pulls.getPullRequest(repo ?? this.repo, number));
2008
+ }
2009
+ async listPullRequests(state, repo) {
2010
+ return (await this.client.pulls.listPullRequests(repo ?? this.repo, state)).map(toPullRequest);
2011
+ }
2012
+ async listBranches(repo) {
2013
+ return (await this.client.branches.listBranches(repo ?? this.repo)).map((b) => ({
2014
+ name: b.name,
2015
+ sha: b.commit.sha
2016
+ }));
2017
+ }
2018
+ async deleteBranch(name, repo) {
2019
+ try {
2020
+ await this.client.branches.removeBranch(repo ?? this.repo, name);
2021
+ } catch (err) {
2022
+ if (err instanceof ProviderApiError && err.status === 422 && String(err.details).includes("does not exist")) return;
2023
+ throw err;
2024
+ }
2025
+ }
2026
+ async listPullRequestCommits(number, repo) {
2027
+ return (await this.client.pulls.listCommits(repo ?? this.repo, number)).map((commit) => commit.sha);
615
2028
  }
616
2029
  async configurePages(config, token) {
617
2030
  const pagesClient = createGitHubClient$1({
@@ -650,18 +2063,8 @@ async function ensureDir(path) {
650
2063
  throw err;
651
2064
  }
652
2065
  }
653
- //#endregion
654
- //#region src/verify-token.ts
655
- /**
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.
659
- *
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.
664
- */
2066
+ // src/verify-token.ts
2067
+ /** Checks a token against `GET /user` and returns who it belongs to, or why it failed. */
665
2068
  async function verifyToken(token, opts = {}) {
666
2069
  const client = createGitHubClient({
667
2070
  token,
@@ -669,49 +2072,61 @@ async function verifyToken(token, opts = {}) {
669
2072
  fetch: opts.fetch
670
2073
  });
671
2074
  try {
672
- const me = await client.user.getCurrentUser();
2075
+ const { user: me, expiresAt } = await client.user.getCurrentUserWithExpiry();
673
2076
  return {
674
2077
  ok: true,
675
- subject: `user @ ${me.login ?? me.email ?? "unknown"}`
2078
+ subject: `user @ ${me.login ?? me.email ?? "unknown"}`,
2079
+ ...expiresAt ? { expiresAt } : {}
676
2080
  };
677
2081
  } catch (err) {
678
2082
  return {
679
2083
  ok: false,
680
- message: err instanceof Error ? err.message : String(err)
2084
+ message: errorMessage(err)
681
2085
  };
682
2086
  }
683
2087
  }
684
- //#endregion
685
- //#region src/index.ts
686
- function source(ctx, orgClient) {
2088
+ // src/index.ts
2089
+ /** Builds the `source` capability; the optional clients cover org-level and user-sync access. */
2090
+ function source(ctx, orgClient, userSyncClient) {
687
2091
  return new GitHubSource(ctx.client, {
688
2092
  repo: ctx.repo,
689
2093
  repoRoot: ctx.repoRoot,
690
2094
  orgClient,
2095
+ userSyncClient,
691
2096
  baseUrl: ctx.options.baseUrl,
692
2097
  fetch: ctx.options.fetch
693
2098
  });
694
2099
  }
695
- function secrets(ctx) {
696
- return new GitHubSecrets(ctx.client, { repo: ctx.repo });
2100
+ /** Builds the `secrets` capability; the optional client handles organization secrets. */
2101
+ function secrets(ctx, orgClient) {
2102
+ return new GitHubSecrets(ctx.client, { repo: ctx.repo }, orgClient);
697
2103
  }
2104
+ /** Builds the `environments` capability. */
698
2105
  function environments(ctx) {
699
2106
  return new GitHubEnvironments(ctx.client, { repo: ctx.repo });
700
2107
  }
2108
+ /** Builds the `ci` capability. */
701
2109
  function ci(ctx) {
702
2110
  return new GitHubCi(ctx.client, { repo: ctx.repo });
703
2111
  }
2112
+ /** Builds the `issues` capability, passing the lifecycle labels when configured. */
704
2113
  function issues(ctx) {
705
2114
  const opts = { repo: ctx.repo };
706
2115
  if (ctx.options.labels !== void 0) opts.labels = ctx.options.labels;
707
2116
  return new GitHubIssues(ctx.client, opts);
708
2117
  }
2118
+ /** Builds the `projects` capability: GitHub Projects v2 over GraphQL, with items keyed relative to the configured repo. */
2119
+ function projects(ctx) {
2120
+ return new GitHubProjects(ctx.client.graphql, { repo: ctx.repo });
2121
+ }
2122
+ /** Creates the plugin, resolving a token per capability when it is first used. */
709
2123
  function createPlugin(options) {
710
2124
  function makeCtx(resolver) {
2125
+ const token = resolver(options);
711
2126
  return {
712
2127
  options,
713
2128
  client: createGitHubClient$1({
714
- token: resolver(options),
2129
+ token,
715
2130
  baseUrl: options.baseUrl,
716
2131
  fetch: options.fetch
717
2132
  }),
@@ -719,10 +2134,45 @@ function createPlugin(options) {
719
2134
  repoRoot: options.repoRoot ?? process.cwd()
720
2135
  };
721
2136
  }
2137
+ /** A token, or undefined when that feature token is simply not configured. */
2138
+ function tryResolve(resolver) {
2139
+ try {
2140
+ return resolver(options);
2141
+ } catch (err) {
2142
+ if (err instanceof AuthError) return void 0;
2143
+ throw err;
2144
+ }
2145
+ }
2146
+ /**
2147
+ * Organization secrets need an org-resource-owner token (`github.secrets`);
2148
+ * repo and environment secrets need `github.admin`. Each scope prefers its own
2149
+ * token and falls back to the other, so a setup with only one of them keeps
2150
+ * working, and an explicit `--token` serves both. With neither configured this
2151
+ * fails exactly as the admin-token capabilities do.
2152
+ */
2153
+ function makeSecrets() {
2154
+ const secretsToken = tryResolve(resolveSecretsToken);
2155
+ const adminToken = tryResolve(resolveAdminToken);
2156
+ if (!secretsToken && !adminToken) resolveAdminToken(options);
2157
+ const clientFor = (token) => createGitHubClient$1({
2158
+ token,
2159
+ baseUrl: options.baseUrl,
2160
+ fetch: options.fetch
2161
+ });
2162
+ const repoClient = clientFor(adminToken ?? secretsToken);
2163
+ const orgClient = clientFor(secretsToken ?? adminToken);
2164
+ return secrets({
2165
+ options,
2166
+ client: repoClient,
2167
+ repo: options.repo,
2168
+ repoRoot: options.repoRoot ?? process.cwd()
2169
+ }, orgClient);
2170
+ }
722
2171
  function makeOrgClient() {
723
2172
  try {
2173
+ const token = resolveOrgToken(options);
724
2174
  return createGitHubClient$1({
725
- token: resolveOrgToken(options),
2175
+ token,
726
2176
  baseUrl: options.baseUrl,
727
2177
  fetch: options.fetch
728
2178
  });
@@ -730,14 +2180,34 @@ function createPlugin(options) {
730
2180
  return;
731
2181
  }
732
2182
  }
2183
+ /** The token for the user-sync files; undefined when it is not configured, and the org token is used instead. */
2184
+ function makeUserSyncClient() {
2185
+ const token = tryResolve(resolveUserSyncToken);
2186
+ return token ? createGitHubClient$1({
2187
+ token,
2188
+ baseUrl: options.baseUrl,
2189
+ fetch: options.fetch
2190
+ }) : void 0;
2191
+ }
733
2192
  return {
734
2193
  name: "@theholocron/holocron-plugin-github",
2194
+ probes: { connection: connectionProbe({
2195
+ provider: "GitHub",
2196
+ url: options.baseUrl ?? "https://api.github.com",
2197
+ fetch: options.fetch,
2198
+ token: () => resolveReadToken(options),
2199
+ verify: (token) => verifyToken(token, {
2200
+ baseUrl: options.baseUrl,
2201
+ fetch: options.fetch
2202
+ })
2203
+ }) },
735
2204
  capabilities: {
736
- source: () => source(makeCtx(resolveAdminToken), makeOrgClient()),
2205
+ source: () => source(makeCtx(resolveAdminToken), makeOrgClient(), makeUserSyncClient()),
737
2206
  ci: () => ci(makeCtx(resolveReadToken)),
738
- secrets: () => secrets(makeCtx(resolveAdminToken)),
2207
+ secrets: () => makeSecrets(),
739
2208
  environments: () => environments(makeCtx(resolveAdminToken)),
740
- issues: () => issues(makeCtx(resolveIssuesToken))
2209
+ issues: () => issues(makeCtx(resolveIssuesToken)),
2210
+ projects: () => projects(makeCtx(resolveOrgToken))
741
2211
  }
742
2212
  };
743
2213
  }
@@ -746,5 +2216,16 @@ function createPlugin(options) {
746
2216
  * is supplied or the supplied token is rejected.
747
2217
  */
748
2218
  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>";
749
- //#endregion
750
- 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 };
2219
+ /** Every token this plugin takes, for `holocron doctor tokens`. */
2220
+ const tokens = [
2221
+ resolveReadToken,
2222
+ resolveIssuesToken,
2223
+ resolveSyncToken,
2224
+ resolveReleaseToken,
2225
+ resolveAdminToken,
2226
+ resolveSecretsToken,
2227
+ resolveDeployToken,
2228
+ resolveUserSyncToken,
2229
+ resolveOrgToken
2230
+ ].map((resolver) => resolver.token);
2231
+ export { AUTH_HINT, AuthError, GitHubCi, GitHubEnvironments, GitHubIssues, GitHubProjects, GitHubSecrets, GitHubSource, ci, createFeatureResolver, createGitHubClient, createPlugin, encryptSecret, environments, issues, normalizeTeamEntry, projects, resolveAdminToken, resolveDeployToken, resolveIssuesToken, resolveOrgToken, resolveReadToken, resolveReleaseToken, resolveSecretsToken, resolveSyncToken, resolveUserSyncToken, secrets, source, syncLabels, syncTeams, tokens, verifyToken };