@theholocron/holocron-plugin-github 5.0.0-alpha.49 → 5.0.0-alpha.490

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, tokenExpectations } 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,427 @@ var GitHubEnvironments = class {
119
151
  }));
120
152
  }
121
153
  };
122
- //#endregion
123
- //#region src/capabilities/issues.ts
154
+ // src/capabilities/issue-priority.ts
155
+ const OPTION_NAMES = {
156
+ urgent: "Urgent",
157
+ high: "High",
158
+ medium: "Medium",
159
+ low: "Low"
160
+ };
161
+ /** Whether GitHub refused for a reason about access or setup, which a run reports and goes on from. */
162
+ function refusal(err) {
163
+ if (!(err instanceof ProviderApiError)) return void 0;
164
+ if (err.status === void 0 || ![
165
+ 401,
166
+ 403,
167
+ 404,
168
+ 422
169
+ ].includes(err.status)) return void 0;
170
+ if (/rate limit/i.test(`${err.message} ${String(err.details)}`)) return void 0;
171
+ return `GitHub refused: ${err.status}`;
172
+ }
173
+ function createPrioritySetter(client, repo) {
174
+ const org = repo.split("/")[0];
175
+ let lookup;
176
+ const findField = () => lookup ??= client.issueFields.list(org).then((fields) => {
177
+ const field = fields.find((f) => f.name === "Priority" && f.data_type === "single_select");
178
+ return field ? { field } : { note: `priority field (${org} has no Priority issue field)` };
179
+ }, (err) => {
180
+ const why = refusal(err);
181
+ if (why === void 0) throw err;
182
+ return { note: `priority field (${why})` };
183
+ });
184
+ return { async set(number, level, flags = {}) {
185
+ if (!level || level === "none") return { changed: false };
186
+ const found = await findField();
187
+ if ("note" in found) return {
188
+ changed: false,
189
+ note: found.note
190
+ };
191
+ const { field } = found;
192
+ const optionName = OPTION_NAMES[level];
193
+ const option = field.options?.find((o) => o.name.toLowerCase() === optionName.toLowerCase());
194
+ if (!option) return {
195
+ changed: false,
196
+ note: `priority field (no "${optionName}" option)`
197
+ };
198
+ try {
199
+ const current = flags.isNew ? void 0 : (await client.issueFields.values(repo, number)).find((v) => v.issue_field_id === field.id);
200
+ if ((current ? current.single_select_option?.name ?? String(current.value) : void 0)?.toLowerCase() === option.name.toLowerCase()) return { changed: false };
201
+ if (flags.dryRun) return { changed: true };
202
+ if (current) await client.issueFields.deleteValue(repo, number, field.id);
203
+ await client.issueFields.addValues(repo, number, [{
204
+ field_id: field.id,
205
+ value: option.name
206
+ }]);
207
+ return { changed: true };
208
+ } catch (err) {
209
+ const why = refusal(err);
210
+ if (why === void 0) throw err;
211
+ return {
212
+ changed: false,
213
+ note: `priority field (${why})`
214
+ };
215
+ }
216
+ } };
217
+ }
218
+ // src/capabilities/issues-migration.ts
219
+ /**
220
+ * Export and import of GitHub issues for `holocron migrate`.
221
+ *
222
+ * GitHub holds less than a planning tool, so what does not fit is named in each result's `dropped` list rather than
223
+ * lost quietly:
224
+ * - priority is a label (`priority: high`), because on GitHub it lives in a project field, not on the issue;
225
+ * - an import cannot backdate an issue or a comment, and cannot post as someone else, so the original date and
226
+ * author go in the text;
227
+ * - an import does not set parent or blocked-by links (they need GraphQL node ids of issues made in the same run);
228
+ * - an assignee is not mapped (a Linear user is not a GitHub login).
229
+ * - the organization's `Priority` issue field is set from the priority (`issue-priority.ts`), beside the label.
230
+ * A migrated issue ends with `<!-- holocron:migrated-from <url> -->`, which is how a second run finds it.
231
+ */
232
+ const MARKER = /<!-- holocron:migrated-from (\S+) -->/;
233
+ const PRIORITY_LABEL = /^priority\s*[:/-]\s*(urgent|high|medium|low)$/i;
234
+ const LINK_QUERY = `query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) {
235
+ issue(number: $number) { parent { number } blockedBy(first: 50) { nodes { number } } } } }`;
236
+ /** Splits `priority: high` labels from the rest. */
237
+ function splitLabels(names) {
238
+ let priority;
239
+ const labels = [];
240
+ for (const name of names) {
241
+ const match = PRIORITY_LABEL.exec(name);
242
+ if (match) priority = match[1].toLowerCase();
243
+ else labels.push(name);
244
+ }
245
+ return {
246
+ labels,
247
+ ...priority ? { priority } : {}
248
+ };
249
+ }
250
+ function categoryOf(issue) {
251
+ if (issue.state === "closed") return "done";
252
+ const names = issue.labels.map((l) => l.name.toLowerCase());
253
+ if (names.some((n) => n === "status:in-review" || n === "status: in review")) return "in-review";
254
+ if (names.some((n) => n === "status:in-progress" || n === "status: in progress")) return "in-progress";
255
+ return "open";
256
+ }
257
+ /** How many issues an export fetches at once. GitHub's secondary rate limit punishes bursts of requests, not volume. */
258
+ const EXPORT_CONCURRENCY = 4;
259
+ /** Runs `fn` over `items`, at most `limit` at a time, and returns the results in the order of `items`. */
260
+ async function mapLimit(items, limit, fn) {
261
+ const results = new Array(items.length);
262
+ let next = 0;
263
+ const worker = async () => {
264
+ while (next < items.length) {
265
+ const at = next++;
266
+ results[at] = await fn(items[at]);
267
+ }
268
+ };
269
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
270
+ return results;
271
+ }
272
+ /** GitHub's own answer to a burst of requests (403 or 429 naming the secondary limit) becomes a message that says what to do. */
273
+ function explainSecondaryLimit(err) {
274
+ 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.");
275
+ return err;
276
+ }
277
+ /**
278
+ * Reads the issues `selector` names, with their comments, priority label, parent and blockers.
279
+ *
280
+ * With `limit`, only that many survivors of the other filters are read, from the `order` end of the creation order. A
281
+ * list of keys is sorted by issue number (which rises with creation in one repository) before anything is fetched, then
282
+ * fetched a few at a time until enough are kept; a listing already carries `created_at`, so it is cut before the
283
+ * per-issue comment and link requests. `info.matched` receives how many the selection matched before the cut.
284
+ */
285
+ async function exportIssues(client, repo, selector, info = {}) {
286
+ return readIssues(client, repo, selector, info).catch((err) => {
287
+ throw explainSecondaryLimit(err);
288
+ });
289
+ }
290
+ async function readIssues(client, repo, selector, info) {
291
+ const [owner = "", name = ""] = repo.split("/", 2);
292
+ const since = selector.since ? Date.parse(selector.since) : void 0;
293
+ const survives = (i) => !i.pull_request && !(selector.openOnly && i.state === "closed") && (since === void 0 || Date.parse(i.updated_at) >= since);
294
+ const { limit, order = "oldest" } = selector;
295
+ let issues;
296
+ if (selector.keys) {
297
+ const fetch = (k) => client.issues.getIssue(repo, parseNumber(k));
298
+ info.matched = selector.keys.length;
299
+ issues = limit === void 0 ? (await mapLimit(selector.keys, EXPORT_CONCURRENCY, fetch)).filter(survives) : await readKeysLimited({
300
+ keys: selector.keys,
301
+ order,
302
+ limit,
303
+ concurrency: EXPORT_CONCURRENCY,
304
+ fetch,
305
+ keep: survives
306
+ });
307
+ } else {
308
+ let raw;
309
+ if (selector.milestone) {
310
+ const milestone = await findMilestone(client, repo, selector.milestone);
311
+ if (!milestone) throw new Error(`Milestone "${selector.milestone}" not found in ${repo}.`);
312
+ raw = await listAll(client, repo, { milestone: String(milestone.number) });
313
+ } else if (selector.all) raw = await listAll(client, repo, {});
314
+ else throw new Error("export needs keys, a milestone or all");
315
+ issues = raw.filter(survives);
316
+ info.matched = issues.length;
317
+ if (limit !== void 0) issues = pickByCreation(issues, (i) => i.created_at ?? i.updated_at, order, limit);
318
+ }
319
+ const records = [];
320
+ for (const issue of issues) {
321
+ reportProgress(info.onProgress, records.length, issues.length);
322
+ const comments = await client.issues.listComments(repo, issue.number);
323
+ const links = (await client.graphql.query(LINK_QUERY, {
324
+ owner,
325
+ name,
326
+ number: issue.number
327
+ }).catch(() => void 0))?.repository.issue;
328
+ const { labels, priority } = splitLabels(issue.labels.map((l) => l.name));
329
+ const body = issue.body?.replace(MARKER, "").trimEnd();
330
+ const migratedFrom = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
331
+ records.push({
332
+ key: `#${issue.number}`,
333
+ url: issue.html_url,
334
+ title: issue.title,
335
+ ...body ? { body } : {},
336
+ statusCategory: categoryOf(issue),
337
+ closed: issue.state === "closed",
338
+ ...priority ? { priority } : {},
339
+ labels: labels.filter((l) => !l.toLowerCase().startsWith("status:")),
340
+ ...issue.assignee ? { assignee: {
341
+ id: issue.assignee.login,
342
+ displayName: issue.assignee.name ?? issue.assignee.login,
343
+ ...issue.assignee.email ? { emailAddress: issue.assignee.email } : {}
344
+ } } : {},
345
+ ...issue.milestone ? { milestone: issue.milestone.title } : {},
346
+ ...links?.parent ? { parent: `#${links.parent.number}` } : {},
347
+ blockedBy: (links?.blockedBy.nodes ?? []).map((n) => `#${n.number}`),
348
+ comments: comments.map((c) => ({
349
+ ...c.user ? { author: c.user.login } : {},
350
+ body: c.body,
351
+ createdAt: c.created_at
352
+ })),
353
+ createdAt: issue.created_at ?? issue.updated_at,
354
+ updatedAt: issue.updated_at,
355
+ ...migratedFrom ? { migratedFrom } : {}
356
+ });
357
+ }
358
+ reportProgress(info.onProgress, records.length, issues.length);
359
+ return records;
360
+ }
361
+ /** Makes the records as issues, skipping any whose source address an earlier run already recorded. */
362
+ async function importIssues(client, repo, records, options = {}) {
363
+ const existing = /* @__PURE__ */ new Map();
364
+ for (const issue of await listAll(client, repo, {})) {
365
+ const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
366
+ if (url) existing.set(url, issue.number);
367
+ }
368
+ const priority = createPrioritySetter(client, repo);
369
+ const results = [];
370
+ const tick = () => reportProgress(options.onProgress, results.length, records.length);
371
+ for (const record of records) {
372
+ const found = existing.get(record.url);
373
+ if (found !== void 0) {
374
+ results.push({
375
+ source: record.key,
376
+ key: `#${found}`,
377
+ created: false,
378
+ dropped: []
379
+ });
380
+ tick();
381
+ continue;
382
+ }
383
+ const dropped = droppedFor(record);
384
+ if (options.dryRun) {
385
+ results.push({
386
+ source: record.key,
387
+ created: true,
388
+ dropped
389
+ });
390
+ tick();
391
+ continue;
392
+ }
393
+ const number = await createFromRecord(client, repo, record, options);
394
+ const field = await priority.set(number, record.priority, { isNew: true });
395
+ if (field.note) dropped.push(field.note);
396
+ results.push({
397
+ source: record.key,
398
+ key: `#${number}`,
399
+ created: true,
400
+ dropped
401
+ });
402
+ tick();
403
+ }
404
+ return results;
405
+ }
406
+ /** What GitHub cannot hold of this record, for the report. */
407
+ function droppedFor(record) {
408
+ const dropped = ["createdAt (GitHub sets it; the original date is in the text)"];
409
+ if (record.assignee && !record.assignee.login) dropped.push("assignee (not mapped)");
410
+ if (record.parent) dropped.push("parent (not set on GitHub)");
411
+ if (record.blockedBy.length > 0) dropped.push("blockedBy (not set on GitHub)");
412
+ return dropped;
413
+ }
414
+ /** The labels a record becomes on GitHub: its own, plus `priority: <level>` (GitHub's priority is a label). */
415
+ function labelsFor(record) {
416
+ return [...record.labels, ...record.priority && record.priority !== "none" ? [`priority: ${record.priority}`] : []];
417
+ }
418
+ /** The text a comment gets when it is copied: GitHub cannot post as another author or backdate. */
419
+ function renderComment(comment) {
420
+ return `${comment.author ? `**${comment.author}**` : "Someone"} commented on ${comment.createdAt}:\n\n${comment.body}`;
421
+ }
422
+ /** Makes one issue from a record, with its comments, and closes it when the record is closed; returns its number. */
423
+ async function createFromRecord(client, repo, record, options) {
424
+ const milestoneName = options.milestone ?? record.milestone;
425
+ const milestone = milestoneName ? await ensureMilestone(client, repo, milestoneName) : void 0;
426
+ const labels = labelsFor(record);
427
+ const created = await client.issues.createIssue(repo, {
428
+ title: record.title,
429
+ body: withProvenance(record),
430
+ ...labels.length > 0 ? { labels } : {},
431
+ ...milestone !== void 0 ? { milestone } : {},
432
+ ...record.assignee?.login ? { assignees: [record.assignee.login] } : {}
433
+ });
434
+ for (const comment of record.comments) await client.issues.createComment(repo, created.number, renderComment(comment));
435
+ if (record.closed) await client.issues.updateIssue(repo, created.number, {
436
+ state: "closed",
437
+ state_reason: "completed"
438
+ });
439
+ return created.number;
440
+ }
441
+ /** The text of a migrated issue: the record's body, then where it came from and the marker a second run looks for. */
442
+ function withProvenance(record) {
443
+ return `${record.body ? `${record.body}\n\n` : ""}---\n_Migrated from [${record.key}](${record.url}); created ${record.createdAt}._\n<!-- holocron:migrated-from ${record.url} -->`;
444
+ }
445
+ function parseNumber(key) {
446
+ const n = key.trim().replace(/^.*#/, "");
447
+ if (!/^\d+$/.test(n)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
448
+ return parseInt(n, 10);
449
+ }
450
+ async function listAll(client, repo, extra) {
451
+ const all = [];
452
+ for (let page = 1;; page++) {
453
+ const batch = await client.issues.listIssues(repo, {
454
+ state: "all",
455
+ per_page: 100,
456
+ page,
457
+ ...extra
458
+ });
459
+ all.push(...batch);
460
+ if (batch.length < 100) return all;
461
+ }
462
+ }
463
+ async function findMilestone(client, repo, ref) {
464
+ return (await client.issues.listMilestones(repo, { state: "all" })).find((m) => String(m.number) === ref || m.title.toLowerCase() === ref.toLowerCase());
465
+ }
466
+ async function ensureMilestone(client, repo, title) {
467
+ return (await findMilestone(client, repo, title))?.number ?? (await client.issues.createMilestone(repo, title)).number;
468
+ }
469
+ // src/capabilities/issues-sync.ts
470
+ const COMMENT_HEADER = /^(?:\*\*.*?\*\*|Someone) commented on (\S+?):\n/;
471
+ /** Whether GitHub is asking to be left alone: a 429, or a 403 that says it is a rate limit. */
472
+ function isRateLimited(err) {
473
+ return err instanceof ProviderApiError && (err.status === 429 || err.status === 403 && /rate limit/i.test(`${err.message} ${String(err.details)}`));
474
+ }
475
+ const normalize = (text) => text.replace(/\r\n/g, "\n").trim();
476
+ const sorted = (names) => names.map((n) => n.toLowerCase()).sort().join("\n");
477
+ /** Makes the records missing from the repo and updates the ones an earlier run made. See the file comment. */
478
+ async function syncIssues(client, repo, records, options = {}) {
479
+ const existing = /* @__PURE__ */ new Map();
480
+ for (const issue of await listAll(client, repo, {})) {
481
+ const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
482
+ if (url) existing.set(url, issue);
483
+ }
484
+ const priority = createPrioritySetter(client, repo);
485
+ const results = [];
486
+ for (const record of records) try {
487
+ const found = existing.get(record.url);
488
+ results.push(found ? await update(client, repo, found, record, options, priority) : await create(client, repo, record, options, priority));
489
+ reportProgress(options.onProgress, results.length, records.length);
490
+ } catch (err) {
491
+ if (isRateLimited(err)) return results;
492
+ throw err;
493
+ }
494
+ return results;
495
+ }
496
+ async function create(client, repo, record, options, priority) {
497
+ const dropped = droppedFor(record);
498
+ if (options.dryRun) return {
499
+ source: record.key,
500
+ created: true,
501
+ updated: false,
502
+ changes: [],
503
+ dropped
504
+ };
505
+ const number = await createFromRecord(client, repo, record, options);
506
+ const field = await priority.set(number, record.priority, { isNew: true });
507
+ if (field.note) dropped.push(field.note);
508
+ return {
509
+ source: record.key,
510
+ key: `#${number}`,
511
+ created: true,
512
+ updated: false,
513
+ changes: [],
514
+ dropped
515
+ };
516
+ }
517
+ async function update(client, repo, issue, record, options, priority) {
518
+ const patch = {};
519
+ const changes = [];
520
+ if (issue.title !== record.title) {
521
+ patch.title = record.title;
522
+ changes.push("title");
523
+ }
524
+ const body = withProvenance(record);
525
+ if (normalize(issue.body) !== normalize(body)) {
526
+ patch.body = body;
527
+ changes.push("description");
528
+ }
529
+ if (issue.state === "closed" !== record.closed) {
530
+ patch.state = record.closed ? "closed" : "open";
531
+ if (record.closed) patch.state_reason = "completed";
532
+ changes.push("state");
533
+ }
534
+ const current = issue.labels.map((l) => l.name);
535
+ const finalLabels = [...labelsFor(record), ...current.filter((n) => n.toLowerCase().startsWith("status:"))];
536
+ if (sorted(finalLabels) !== sorted(current)) {
537
+ patch.labels = finalLabels;
538
+ changes.push("labels");
539
+ }
540
+ const login = record.assignee?.login;
541
+ if (login && issue.assignee?.login.toLowerCase() !== login.toLowerCase()) {
542
+ patch.assignees = [login];
543
+ changes.push("assignee");
544
+ }
545
+ const field = await priority.set(issue.number, record.priority, { dryRun: options.dryRun });
546
+ if (field.changed) changes.push("priority field");
547
+ const comments = await client.issues.listComments(repo, issue.number);
548
+ const seen = new Set(comments.map((c) => COMMENT_HEADER.exec(c.body)?.[1]));
549
+ const missing = record.comments.filter((c) => !seen.has(c.createdAt));
550
+ if (missing.length > 0) changes.push("comments");
551
+ if (!options.dryRun) {
552
+ if (Object.keys(patch).length > 0) await client.issues.updateIssue(repo, issue.number, patch);
553
+ for (const comment of missing) await client.issues.createComment(repo, issue.number, renderComment(comment));
554
+ }
555
+ return {
556
+ source: record.key,
557
+ key: `#${issue.number}`,
558
+ created: false,
559
+ updated: changes.length > 0,
560
+ changes,
561
+ dropped: [...droppedFor(record), ...field.note ? [field.note] : []]
562
+ };
563
+ }
564
+ // src/capabilities/issues.ts
565
+ /** Issues read per request when `search` has a `text`; GitHub's largest page. */
566
+ const TEXT_PAGE_SIZE = 100;
567
+ /** Pages `search` reads for a `text` before it stops (the 2000 most recently updated issues). */
568
+ const TEXT_MAX_PAGES = 20;
569
+ /** The GitHub implementation of the `issues` capability, backed by GitHub Issues and status labels. */
124
570
  var GitHubIssues = class {
125
571
  client;
572
+ /** Capability key, always `"issues"`. */
126
573
  key = "issues";
574
+ /** Provider name, always `"github"`. */
127
575
  providerName = "github";
128
576
  owner;
129
577
  repoName;
@@ -145,7 +593,18 @@ var GitHubIssues = class {
145
593
  ...raw.email ? { emailAddress: raw.email } : {}
146
594
  };
147
595
  }
596
+ /**
597
+ * Searches the repo's issues, newest update first, leaving out pull requests.
598
+ *
599
+ * With `filter.text`, the issues are paged (newest update first, 100 a page, at most 20 pages) and compared
600
+ * client-side, without regard to case, until `limit` matches are found or the issues run out. GitHub's issue
601
+ * search (`GET /search/issues`) is deliberately not used: it indexes the words of a body, so punctuation and an
602
+ * HTML comment such as `<!-- holocron:idea notes/a.md -->` cannot be relied on to match, it is limited to 30
603
+ * requests a minute and it is eventually consistent (an issue made a moment ago may be missing). Paging has none
604
+ * of those limits, at the cost of reading up to 20 pages of a very large repository.
605
+ */
148
606
  async search(filter) {
607
+ if (filter.text) return this.searchText(filter, filter.text);
149
608
  const params = {
150
609
  state: filter.openOnly ? "open" : "all",
151
610
  sort: "updated",
@@ -164,13 +623,46 @@ var GitHubIssues = class {
164
623
  assignee: params.assignee
165
624
  })).filter((i) => !i.pull_request).map((i) => this.mapIssue(i));
166
625
  }
626
+ async searchText(filter, text) {
627
+ const needle = text.toLowerCase();
628
+ const limit = filter.limit ?? 50;
629
+ const assignee = filter.assignee === "currentUser" ? (await this.getMyself()).id : filter.assignee || void 0;
630
+ const found = [];
631
+ for (let page = 1; page <= TEXT_MAX_PAGES; page++) {
632
+ const raw = await this.client.issues.listIssues(this.repo, {
633
+ state: filter.openOnly ? "open" : "all",
634
+ sort: "updated",
635
+ direction: "desc",
636
+ per_page: TEXT_PAGE_SIZE,
637
+ page,
638
+ filter: "all",
639
+ ...assignee ? { assignee } : {}
640
+ });
641
+ for (const issue of raw) {
642
+ if (issue.pull_request) continue;
643
+ if (`${issue.title}\n${issue.body ?? ""}`.toLowerCase().includes(needle)) {
644
+ found.push(this.mapIssue(issue));
645
+ if (found.length >= limit) return found;
646
+ }
647
+ }
648
+ if (raw.length < TEXT_PAGE_SIZE) break;
649
+ }
650
+ return found;
651
+ }
652
+ /** Fetches one issue by its key. */
167
653
  async get(key) {
168
654
  const number = parseIssueNumber(key, this.owner, this.repoName);
169
655
  const raw = await this.client.issues.getIssue(this.repo, number);
170
656
  return this.mapIssue(raw);
171
657
  }
658
+ /** Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. */
172
659
  async create(input) {
173
660
  const body = { title: input.summary };
661
+ if (input.assignees?.length) {
662
+ const isMe = (a) => /^@?me$/i.test(a);
663
+ const me = input.assignees.some(isMe) ? (await this.getMyself()).id : void 0;
664
+ body.assignees = [...new Set(input.assignees.map((a) => isMe(a) && me ? me : a.replace(/^@/, "")))];
665
+ }
174
666
  if (input.body) body.body = input.body;
175
667
  if (input.labels?.length) body.labels = input.labels;
176
668
  if (input.milestone) body.milestone = await this.resolveMilestone(input.milestone);
@@ -216,10 +708,12 @@ var GitHubIssues = class {
216
708
  via: `label set to ${targetLabel}`
217
709
  };
218
710
  }
711
+ /** Adds a comment to the issue with the given key. */
219
712
  async comment(key, body) {
220
713
  const number = parseIssueNumber(key, this.owner, this.repoName);
221
714
  await this.client.issues.createComment(this.repo, number, body);
222
715
  }
716
+ /** Checks the authenticated user, the repo and the label-backed lifecycle slots, and reports what resolves. */
223
717
  async doctor() {
224
718
  const me = await this.getMyself();
225
719
  const repo = await this.client.repos.getRepo(this.repo);
@@ -288,6 +782,18 @@ var GitHubIssues = class {
288
782
  lifecycle
289
783
  };
290
784
  }
785
+ /** Reads issues with their comments, priority label, parent and blockers, for `holocron migrate`. */
786
+ export(selector, info) {
787
+ return exportIssues(this.client, this.repo, selector, info);
788
+ }
789
+ /** Makes the records as issues; one already made by an earlier run is skipped. */
790
+ import(records, options) {
791
+ return importIssues(this.client, this.repo, records, options);
792
+ }
793
+ /** Like `import`, and it also updates what an earlier import or sync made, for `holocron sync issues`. */
794
+ sync(records, options) {
795
+ return syncIssues(this.client, this.repo, records, options);
796
+ }
291
797
  async resolveMilestone(ref) {
292
798
  if (/^\d+$/.test(ref)) return parseInt(ref, 10);
293
799
  const match = (await this.client.issues.listMilestones(this.repo, { state: "all" })).find((m) => m.title.toLowerCase() === ref.toLowerCase());
@@ -337,8 +843,630 @@ function parseIssueNumber(key, owner, repoName) {
337
843
  if (!/^\d+$/.test(num)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
338
844
  return parseInt(num, 10);
339
845
  }
340
- //#endregion
341
- //#region src/sodium.ts
846
+ /** The GraphQL selection that reads an issue's closing pull requests and the aggregate check on each head commit. */
847
+ const CLOSING_PULL_REQUESTS = `closedByPullRequestsReferences(first: 5, includeClosedPrs: true) { nodes {
848
+ number state isDraft repository { nameWithOwner }
849
+ commits(last: 1) { nodes { commit { checkSuites(first: 50) { nodes {
850
+ checkRuns(first: 5, filterBy: { checkName: "ci / Required checks" }) { nodes { databaseId status conclusion startedAt } }
851
+ } } } } }
852
+ } }`;
853
+ const FAILED = /* @__PURE__ */ new Set([
854
+ "FAILURE",
855
+ "TIMED_OUT",
856
+ "STARTUP_FAILURE",
857
+ "ACTION_REQUIRED",
858
+ "STALE"
859
+ ]);
860
+ /**
861
+ * The state of the aggregate check from the runs of that name on one commit. Only the newest run counts (latest
862
+ * `startedAt`, then id), so a cancelled first batch or a re-run that went green does not hold the verdict red. A run
863
+ * that is not finished, or that was cancelled, is `pending`; one with no verdict (neutral, skipped) or none posted is `none`.
864
+ */
865
+ function aggregateChecks(runs) {
866
+ const newest = [...runs].sort((a, b) => (b.startedAt ?? "").localeCompare(a.startedAt ?? "") || b.databaseId - a.databaseId)[0];
867
+ if (!newest) return "none";
868
+ if (newest.status !== "COMPLETED") return "pending";
869
+ if (newest.conclusion === "SUCCESS") return "success";
870
+ if (newest.conclusion && FAILED.has(newest.conclusion)) return "failure";
871
+ if (newest.conclusion === "CANCELLED") return "pending";
872
+ return "none";
873
+ }
874
+ /** The neutral pull requests an issue is closed by; only an open one has its checks read, the others are `none`. */
875
+ function toBoardPullRequests(nodes, keyOf) {
876
+ return nodes.map((pr) => {
877
+ const state = pr.state === "OPEN" ? "open" : pr.state === "MERGED" ? "merged" : "closed";
878
+ const runs = (pr.commits?.nodes ?? []).flatMap((c) => c.commit.checkSuites.nodes.flatMap((suite) => suite.checkRuns.nodes));
879
+ return {
880
+ key: keyOf(pr.repository.nameWithOwner, pr.number),
881
+ state,
882
+ draft: pr.isDraft,
883
+ checks: state === "open" ? aggregateChecks(runs) : "none"
884
+ };
885
+ });
886
+ }
887
+ // src/capabilities/projects.ts
888
+ /** The name of the single select field that holds an item's status. */
889
+ const STATUS_FIELD = "Status";
890
+ /** The name of the field `move` carries over besides the status. */
891
+ const PRIORITY_FIELD = "Priority";
892
+ const P_LEVELS = {
893
+ p0: "urgent",
894
+ p1: "high",
895
+ p2: "medium",
896
+ p3: "low"
897
+ };
898
+ /** The neutral priority a `Priority` option stands for, by its name; undefined for a name that is not one of them. */
899
+ function priorityOf(value) {
900
+ const name = value?.trim().toLowerCase();
901
+ if (name === "urgent" || name === "high" || name === "medium" || name === "low") return name;
902
+ return name ? P_LEVELS[name] : void 0;
903
+ }
904
+ const PROJECT_FIELDS = "id number title closed url";
905
+ const BOARD_QUERY = `query($id: ID!) { node(id: $id) { ... on ProjectV2 {
906
+ ${PROJECT_FIELDS}
907
+ fields(first: 100) { nodes {
908
+ ... on ProjectV2FieldCommon { id name dataType }
909
+ ... on ProjectV2SingleSelectField { options { id name color description } }
910
+ } }
911
+ views(first: 50) { nodes { id name layout filter groupByFields(first: 5) { nodes { ... on ProjectV2FieldCommon { name } } } } }
912
+ workflows(first: 50) { nodes { id name enabled } }
913
+ } } }`;
914
+ const ITEMS_QUERY = `query($id: ID!, $after: String) { node(id: $id) { ... on ProjectV2 {
915
+ items(first: 100, after: $after) {
916
+ pageInfo { hasNextPage endCursor }
917
+ nodes {
918
+ id
919
+ fieldValues(first: 30) { nodes { ... on ProjectV2ItemFieldSingleSelectValue { name field { ... on ProjectV2FieldCommon { name } } } } }
920
+ content {
921
+ __typename
922
+ ... on Issue { id number title state repository { nameWithOwner } blockedBy(first: 50) { nodes { number state repository { nameWithOwner } } } ${CLOSING_PULL_REQUESTS} }
923
+ ... on PullRequest { id number title state repository { nameWithOwner } }
924
+ }
925
+ }
926
+ }
927
+ } } }`;
928
+ const LIST_QUERY = `query($owner: String!, $after: String) { organization(login: $owner) { id projectsV2(first: 100, after: $after) {
929
+ pageInfo { hasNextPage endCursor }
930
+ nodes { ${PROJECT_FIELDS} }
931
+ } } }`;
932
+ const OWNER_QUERY = "query($owner: String!) { organization(login: $owner) { id } }";
933
+ const SET_VALUE = `mutation($project: ID!, $item: ID!, $field: ID!, $option: String!) {
934
+ updateProjectV2ItemFieldValue(input: { projectId: $project, itemId: $item, fieldId: $field, value: { singleSelectOptionId: $option } }) { projectV2Item { id } }
935
+ }`;
936
+ const UPDATE_OPTIONS = `mutation($field: ID!, $options: [ProjectV2SingleSelectFieldOptionInput!]!) {
937
+ updateProjectV2Field(input: { fieldId: $field, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
938
+ }`;
939
+ const DATA_TYPES = {
940
+ single_select: "SINGLE_SELECT",
941
+ text: "TEXT",
942
+ number: "NUMBER",
943
+ date: "DATE",
944
+ iteration: "ITERATION"
945
+ };
946
+ function fieldTypeOf(dataType) {
947
+ return Object.keys(DATA_TYPES).find((t) => DATA_TYPES[t] === dataType);
948
+ }
949
+ function toSummary(n) {
950
+ return {
951
+ id: n.id,
952
+ number: n.number,
953
+ name: n.title,
954
+ url: n.url,
955
+ closed: n.closed
956
+ };
957
+ }
958
+ function toOptionInput(o) {
959
+ return {
960
+ ...o.id ? { id: o.id } : {},
961
+ name: o.name,
962
+ color: (o.color ?? "GRAY").toUpperCase(),
963
+ description: o.description ?? ""
964
+ };
965
+ }
966
+ /** The GitHub implementation of the `projects` capability, backed by Projects v2. */
967
+ var GitHubProjects = class {
968
+ graphql;
969
+ /** Capability key, always `"projects"`. */
970
+ key = "projects";
971
+ /** Provider name, always `"github"`. */
972
+ providerName = "github";
973
+ repo;
974
+ constructor(graphql, opts) {
975
+ this.graphql = graphql;
976
+ this.repo = opts.repo;
977
+ }
978
+ /** Every board of the organization, open and closed. */
979
+ async list(owner) {
980
+ const boards = [];
981
+ let after = null;
982
+ for (;;) {
983
+ const page = (await this.graphql.query(LIST_QUERY, {
984
+ owner,
985
+ after
986
+ })).organization.projectsV2;
987
+ boards.push(...page.nodes.map(toSummary));
988
+ if (!page.pageInfo.hasNextPage) return boards;
989
+ after = page.pageInfo.endCursor;
990
+ }
991
+ }
992
+ /** The open board with exactly this name. */
993
+ async find(owner, name) {
994
+ return (await this.list(owner)).find((b) => !b.closed && b.name === name);
995
+ }
996
+ /**
997
+ * Makes a board. With `template.source` naming an open board it is copied (fields, options, views and automation
998
+ * rules, no items); otherwise the board is created and brought in line with the template.
999
+ */
1000
+ async create(owner, name, template) {
1001
+ const ownerId = await this.ownerId(owner);
1002
+ const source = template.source ? await this.find(owner, template.source) : void 0;
1003
+ if (source) return toSummary((await this.graphql.query(`mutation($project: ID!, $owner: ID!, $title: String!) {
1004
+ copyProjectV2(input: { projectId: $project, ownerId: $owner, title: $title, includeDraftIssues: false }) { projectV2 { ${PROJECT_FIELDS} } }
1005
+ }`, {
1006
+ project: source.id,
1007
+ owner: ownerId,
1008
+ title: name
1009
+ })).copyProjectV2.projectV2);
1010
+ const board = toSummary((await this.graphql.query(`mutation($owner: ID!, $title: String!) {
1011
+ createProjectV2(input: { ownerId: $owner, title: $title }) { projectV2 { ${PROJECT_FIELDS} } }
1012
+ }`, {
1013
+ owner: ownerId,
1014
+ title: name
1015
+ })).createProjectV2.projectV2);
1016
+ await this.ensure(owner, board, template);
1017
+ return board;
1018
+ }
1019
+ /** Closes the board; `updateProjectV2` with `closed: true` is the only way, and reversible. */
1020
+ async close(_owner, board) {
1021
+ await this.graphql.query(`mutation($project: ID!) { updateProjectV2(input: { projectId: $project, closed: true }) { projectV2 { id } } }`, { project: board.id });
1022
+ }
1023
+ /** The live board: statuses, other fields, views and automation rules. */
1024
+ async read(_owner, board) {
1025
+ const raw = await this.readRaw(board.id);
1026
+ const status = raw.fields.find((f) => f.name === STATUS_FIELD);
1027
+ const fields = [];
1028
+ for (const f of raw.fields) {
1029
+ const type = fieldTypeOf(f.dataType);
1030
+ if (!type || f.name === STATUS_FIELD) continue;
1031
+ fields.push({
1032
+ name: f.name,
1033
+ type,
1034
+ ...f.options ? { options: f.options.map((o) => o.name) } : {}
1035
+ });
1036
+ }
1037
+ const views = [];
1038
+ for (const v of raw.views) {
1039
+ const layout = v.layout === "BOARD_LAYOUT" ? "board" : v.layout === "TABLE_LAYOUT" ? "table" : void 0;
1040
+ if (!layout) continue;
1041
+ views.push({
1042
+ name: v.name,
1043
+ layout,
1044
+ ...v.filter ? { filter: v.filter } : {},
1045
+ ...v.groupBy[0] ? { groupBy: v.groupBy[0] } : {}
1046
+ });
1047
+ }
1048
+ return {
1049
+ board: raw.summary,
1050
+ statuses: (status?.options ?? []).map((o) => o.name),
1051
+ fields,
1052
+ views,
1053
+ rules: raw.rules.map(({ name, enabled }) => ({
1054
+ name,
1055
+ enabled
1056
+ }))
1057
+ };
1058
+ }
1059
+ /**
1060
+ * Brings the board in line with the template. Never deletes a field, option or view, and never sends an option
1061
+ * list without ids. Stops (throws) when the status field cannot be read.
1062
+ */
1063
+ async ensure(_owner, board, template) {
1064
+ const raw = await this.readRaw(board.id);
1065
+ const status = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
1066
+ 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`);
1067
+ const changes = [];
1068
+ const todos = [];
1069
+ const statusChanges = await this.ensureOptions(board, status, template.statuses.map((s) => ({
1070
+ name: s.name,
1071
+ color: s.color,
1072
+ description: s.description
1073
+ })));
1074
+ changes.push(...statusChanges.map((c) => `status ${c}`));
1075
+ for (const want of template.fields) {
1076
+ const have = raw.fields.find((f) => f.name === want.name);
1077
+ if (!have) {
1078
+ await this.createField(board.id, want);
1079
+ changes.push(`field ${want.name} created`);
1080
+ continue;
1081
+ }
1082
+ if (fieldTypeOf(have.dataType) !== want.type) {
1083
+ todos.push(`field "${want.name}" is ${have.dataType} but the template says ${want.type}; change it by hand`);
1084
+ continue;
1085
+ }
1086
+ if (want.type === "single_select" && have.options && want.options) {
1087
+ const diff = await this.ensureOptions(board, have, want.options.map((name) => ({ name })));
1088
+ changes.push(...diff.map((c) => `field ${want.name} option ${c}`));
1089
+ }
1090
+ }
1091
+ for (const want of template.views) {
1092
+ const have = raw.views.find((v) => v.name === want.name);
1093
+ const layout = want.layout === "board" ? "BOARD_LAYOUT" : "TABLE_LAYOUT";
1094
+ let viewId = have?.id;
1095
+ if (!viewId) {
1096
+ viewId = await this.createView(board.id, want.name, layout);
1097
+ changes.push(`view ${want.name} created`);
1098
+ } else if (have && have.layout !== layout) {
1099
+ await this.updateView(viewId, { layout });
1100
+ changes.push(`view ${want.name} layout set to ${want.layout}`);
1101
+ }
1102
+ if (want.filter !== void 0 && want.filter !== (have?.filter ?? "")) {
1103
+ await this.updateView(viewId, { filter: want.filter });
1104
+ changes.push(`view ${want.name} filter set`);
1105
+ }
1106
+ 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`);
1107
+ }
1108
+ for (const rule of template.rules ?? []) {
1109
+ const have = raw.rules.find((r) => r.name === rule);
1110
+ if (!have) todos.push(`create the automation rule "${rule}"; the API cannot create one`);
1111
+ else if (!have.enabled) todos.push(`turn on the automation rule "${rule}"; the API cannot switch one`);
1112
+ }
1113
+ return {
1114
+ created: false,
1115
+ changes,
1116
+ todos
1117
+ };
1118
+ }
1119
+ /**
1120
+ * Makes a single select field hold the wanted options in order, every existing one sent with its id. Options the
1121
+ * template does not mention stay, after the wanted ones. Returns what changed (`Blocked added`, `order set`).
1122
+ */
1123
+ async ensureOptions(board, field, wanted) {
1124
+ /* v8 ignore next -- every caller passes a field it found with options; the fallback only satisfies the type */
1125
+ const existing = field.options ?? [];
1126
+ const next = [];
1127
+ const changes = [];
1128
+ for (const w of wanted) {
1129
+ const have = existing.find((o) => o.name === w.name);
1130
+ if (have) {
1131
+ next.push({
1132
+ id: have.id,
1133
+ name: have.name,
1134
+ color: (w.color ?? have.color).toUpperCase(),
1135
+ description: w.description ?? have.description
1136
+ });
1137
+ if (next[next.length - 1].color !== have.color || next[next.length - 1].description !== have.description) changes.push(`${have.name} updated`);
1138
+ } else {
1139
+ next.push({
1140
+ name: w.name,
1141
+ color: (w.color ?? "GRAY").toUpperCase(),
1142
+ description: w.description ?? ""
1143
+ });
1144
+ changes.push(`${w.name} added`);
1145
+ }
1146
+ }
1147
+ for (const have of existing) if (!next.some((n) => n.id === have.id)) next.push({ ...have });
1148
+ const sameOrder = next.length === existing.length && next.every((n, i) => n.id === existing[i]?.id);
1149
+ if (changes.length === 0 && sameOrder) return [];
1150
+ if (sameOrder === false && !changes.some((c) => c.endsWith("added"))) changes.push("order set");
1151
+ const before = await this.fetchItems(board.id);
1152
+ const snapshot = /* @__PURE__ */ new Map();
1153
+ for (const item of before) {
1154
+ const value = item.values[field.name];
1155
+ if (value) snapshot.set(item.id, value);
1156
+ }
1157
+ await this.graphql.query(UPDATE_OPTIONS, {
1158
+ field: field.id,
1159
+ options: next.map(toOptionInput)
1160
+ });
1161
+ const afterField = (await this.readRaw(board.id)).fields.find((f) => f.id === field.id);
1162
+ const afterItems = await this.fetchItems(board.id);
1163
+ const afterValues = new Map(afterItems.map((i) => [i.id, i.values[field.name]]));
1164
+ const lost = [...snapshot].filter(([itemId]) => !afterValues.get(itemId));
1165
+ if (lost.length > 0) {
1166
+ let restored = 0;
1167
+ for (const [itemId, name] of lost) {
1168
+ const option = afterField?.options?.find((o) => o.name === name);
1169
+ if (!option) continue;
1170
+ await this.graphql.query(SET_VALUE, {
1171
+ project: board.id,
1172
+ item: itemId,
1173
+ field: field.id,
1174
+ option: option.id
1175
+ });
1176
+ restored++;
1177
+ }
1178
+ throw new Error(`updating "${field.name}" on board "${board.name}" blanked ${lost.length} item value(s); wrote ${restored} back by option name`);
1179
+ }
1180
+ return changes;
1181
+ }
1182
+ async createField(projectId, want) {
1183
+ await this.graphql.query(`mutation($project: ID!, $name: String!, $type: ProjectV2CustomFieldType!, $options: [ProjectV2SingleSelectFieldOptionInput!]) {
1184
+ createProjectV2Field(input: { projectId: $project, name: $name, dataType: $type, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
1185
+ }`, {
1186
+ project: projectId,
1187
+ name: want.name,
1188
+ type: DATA_TYPES[want.type],
1189
+ options: want.type === "single_select" ? (want.options ?? []).map((name) => toOptionInput({ name })) : void 0
1190
+ });
1191
+ }
1192
+ async createView(projectId, name, layout) {
1193
+ return (await this.graphql.query(`mutation($project: ID!, $name: String!, $layout: ProjectV2ViewLayout!) {
1194
+ createProjectV2View(input: { projectId: $project, name: $name, layout: $layout }) { projectV2View { id } }
1195
+ }`, {
1196
+ project: projectId,
1197
+ name,
1198
+ layout
1199
+ })).createProjectV2View.projectV2View.id;
1200
+ }
1201
+ async updateView(viewId, change) {
1202
+ await this.graphql.query(`mutation($view: ID!, $layout: ProjectV2ViewLayout, $filter: String) {
1203
+ updateProjectV2View(input: { viewId: $view, layout: $layout, filter: $filter }) { projectV2View { id } }
1204
+ }`, {
1205
+ view: viewId,
1206
+ layout: change.layout,
1207
+ filter: change.filter
1208
+ });
1209
+ }
1210
+ /**
1211
+ * The board's issues and pull requests with their status, whether they are open and their open blockers; an issue also
1212
+ * carries the pull requests that close it, each with the aggregate `ci / Required checks` state of its head commit.
1213
+ */
1214
+ async items(_owner, board, template) {
1215
+ const categories = new Map(template.statuses.map((s) => [s.name, s.category]));
1216
+ return (await this.fetchItems(board.id)).map((i) => {
1217
+ const status = i.values[STATUS_FIELD];
1218
+ const category = status ? categories.get(status) : void 0;
1219
+ const priority = priorityOf(i.values[PRIORITY_FIELD]);
1220
+ return {
1221
+ key: this.keyOf(i.repo, i.number),
1222
+ title: i.title,
1223
+ open: i.open,
1224
+ ...status ? { status } : {},
1225
+ ...category ? { category } : {},
1226
+ blockedBy: i.blockers.map((b) => this.keyOf(b.repo, b.number)),
1227
+ ...priority ? { priority } : {},
1228
+ ...i.closing ? { pullRequests: toBoardPullRequests(i.closing, (r, n) => this.keyOf(r, n)) } : {}
1229
+ };
1230
+ });
1231
+ }
1232
+ /** Puts an item in a status; `transitioned` is false when it already is there. */
1233
+ async setStatus(_owner, board, key, status) {
1234
+ const ref = this.parseKey(key);
1235
+ const field = (await this.readRaw(board.id)).fields.find((f) => f.name === STATUS_FIELD && f.options);
1236
+ const option = field?.options?.find((o) => o.name === status);
1237
+ if (!field || !option) throw new Error(`board "${board.name}" has no status "${status}"`);
1238
+ const item = (await this.fetchItems(board.id)).find((i) => i.repo === ref.repo && i.number === ref.number);
1239
+ if (!item) throw new Error(`${key} is not on board "${board.name}"`);
1240
+ if (item.values[STATUS_FIELD] === status) return {
1241
+ transitioned: false,
1242
+ status
1243
+ };
1244
+ await this.graphql.query(SET_VALUE, {
1245
+ project: board.id,
1246
+ item: item.id,
1247
+ field: field.id,
1248
+ option: option.id
1249
+ });
1250
+ return {
1251
+ transitioned: true,
1252
+ status,
1253
+ via: "project field set"
1254
+ };
1255
+ }
1256
+ /**
1257
+ * Puts the open items of `from` on `to` with their status and priority, only where the target has no value;
1258
+ * closed and merged ones stay, and are set to the template's done status when theirs is not a done one.
1259
+ */
1260
+ async move(_owner, from, to, template) {
1261
+ const report = {
1262
+ moved: [],
1263
+ kept: [],
1264
+ left: []
1265
+ };
1266
+ const [source, target, fromRaw, toRaw] = await Promise.all([
1267
+ this.fetchItems(from.id),
1268
+ this.fetchItems(to.id),
1269
+ this.readRaw(from.id),
1270
+ this.readRaw(to.id)
1271
+ ]);
1272
+ const done = template.statuses.find((s) => s.category === "done")?.name;
1273
+ const doneNames = new Set(template.statuses.filter((s) => s.category === "done").map((s) => s.name));
1274
+ const carried = [STATUS_FIELD, PRIORITY_FIELD];
1275
+ for (const item of source) {
1276
+ const key = this.keyOf(item.repo, item.number);
1277
+ if (!item.open) {
1278
+ const current = item.values[STATUS_FIELD];
1279
+ if (done && (!current || !doneNames.has(current))) await this.setOption(from.id, fromRaw, item.id, STATUS_FIELD, done);
1280
+ report.left.push(key);
1281
+ continue;
1282
+ }
1283
+ let targetItem = target.find((t) => t.contentId === item.contentId);
1284
+ if (targetItem) report.kept.push(key);
1285
+ else {
1286
+ const data = await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
1287
+ project: to.id,
1288
+ content: item.contentId
1289
+ });
1290
+ targetItem = {
1291
+ ...item,
1292
+ id: data.addProjectV2ItemById.item.id,
1293
+ values: {}
1294
+ };
1295
+ report.moved.push(key);
1296
+ }
1297
+ for (const name of carried) {
1298
+ const value = item.values[name];
1299
+ if (value && !targetItem.values[name]) await this.setOption(to.id, toRaw, targetItem.id, name, value);
1300
+ }
1301
+ }
1302
+ return report;
1303
+ }
1304
+ /**
1305
+ * Puts issues on the board (`addProjectV2ItemById`, the content id the issue's node id) and sets Status and Priority
1306
+ * through the single select update, only where the item has no value yet. A status or priority with no option on
1307
+ * the board is reported in `dropped`; no option is ever created, so no value is cleared.
1308
+ */
1309
+ async addItems(_owner, board, items, template) {
1310
+ const raw = await this.readRaw(board.id);
1311
+ const onBoard = await this.fetchItems(board.id);
1312
+ const statusField = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
1313
+ const priorityField = raw.fields.find((f) => f.name === PRIORITY_FIELD && f.options);
1314
+ const results = [];
1315
+ for (const input of items) {
1316
+ const ref = this.parseKey(input.key);
1317
+ let current = onBoard.find((i) => i.repo === ref.repo && i.number === ref.number);
1318
+ const added = !current;
1319
+ if (!current) current = {
1320
+ id: (await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
1321
+ project: board.id,
1322
+ content: await this.nodeId(ref)
1323
+ })).addProjectV2ItemById.item.id,
1324
+ contentId: "",
1325
+ repo: ref.repo,
1326
+ number: ref.number,
1327
+ title: "",
1328
+ open: true,
1329
+ values: {},
1330
+ blockers: []
1331
+ };
1332
+ const dropped = [];
1333
+ if (input.status !== void 0 || input.category !== void 0) {
1334
+ const name = this.statusFor(input, template, statusField?.options);
1335
+ if (!name) dropped.push(`status ${input.status ?? input.category} (no matching option on the board)`);
1336
+ else if (!current.values[STATUS_FIELD]) await this.setOption(board.id, raw, current.id, STATUS_FIELD, name);
1337
+ }
1338
+ if (input.priority !== void 0 && input.priority !== "none") {
1339
+ const option = priorityField?.options?.find((o) => priorityOf(o.name) === input.priority);
1340
+ if (!option) dropped.push(`priority ${input.priority} (no matching option on the board)`);
1341
+ else if (!current.values[PRIORITY_FIELD]) await this.setOption(board.id, raw, current.id, PRIORITY_FIELD, option.name);
1342
+ }
1343
+ results.push({
1344
+ key: input.key,
1345
+ added,
1346
+ dropped
1347
+ });
1348
+ }
1349
+ return results;
1350
+ }
1351
+ /** The board's own status for an input: the option named like its status, else the template's status of its category. */
1352
+ statusFor(input, template, options) {
1353
+ const has = (name) => options?.find((o) => o.name.toLowerCase() === name.toLowerCase())?.name;
1354
+ const named = input.status === void 0 ? void 0 : has(input.status);
1355
+ if (named) return named;
1356
+ const byCategory = template.statuses.find((s) => s.category === input.category);
1357
+ return byCategory ? has(byCategory.name) : void 0;
1358
+ }
1359
+ /** The node id of an issue, which `addProjectV2ItemById` takes as the content id. */
1360
+ async nodeId(ref) {
1361
+ const [owner, name] = ref.repo.split("/");
1362
+ const id = (await this.graphql.query(`query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { id } } }`, {
1363
+ owner,
1364
+ name,
1365
+ number: ref.number
1366
+ })).repository?.issue?.id;
1367
+ if (!id) throw new Error(`issue ${ref.repo}#${ref.number} not found`);
1368
+ return id;
1369
+ }
1370
+ /** A `holocron doctor` smoke check: how many boards the token sees in the configured repository's organization. */
1371
+ async whoami() {
1372
+ try {
1373
+ return {
1374
+ ok: true,
1375
+ boards: (await this.list(this.repo.split("/")[0] ?? "")).length
1376
+ };
1377
+ } catch {
1378
+ return {
1379
+ ok: false,
1380
+ boards: 0
1381
+ };
1382
+ }
1383
+ }
1384
+ /** Sets a single select value by option name; a field or option the board lacks is skipped. */
1385
+ async setOption(projectId, raw, itemId, fieldName, optionName) {
1386
+ const field = raw.fields.find((f) => f.name === fieldName && f.options);
1387
+ const option = field?.options?.find((o) => o.name === optionName);
1388
+ if (!field || !option) return;
1389
+ await this.graphql.query(SET_VALUE, {
1390
+ project: projectId,
1391
+ item: itemId,
1392
+ field: field.id,
1393
+ option: option.id
1394
+ });
1395
+ }
1396
+ async ownerId(owner) {
1397
+ return (await this.graphql.query(OWNER_QUERY, { owner })).organization.id;
1398
+ }
1399
+ async readRaw(id) {
1400
+ const n = (await this.graphql.query(BOARD_QUERY, { id })).node;
1401
+ if (!n) throw new Error(`board ${id} not found`);
1402
+ return {
1403
+ summary: toSummary(n),
1404
+ fields: n.fields.nodes.filter((f) => f.id).map((f) => ({
1405
+ id: f.id,
1406
+ name: f.name,
1407
+ dataType: f.dataType,
1408
+ ...f.options ? { options: f.options } : {}
1409
+ })),
1410
+ views: n.views.nodes.map((v) => ({
1411
+ id: v.id,
1412
+ name: v.name,
1413
+ layout: v.layout,
1414
+ filter: v.filter,
1415
+ groupBy: (v.groupByFields?.nodes ?? []).map((g) => g.name)
1416
+ })),
1417
+ rules: n.workflows.nodes.map((w) => ({
1418
+ id: w.id,
1419
+ name: w.name,
1420
+ enabled: w.enabled
1421
+ }))
1422
+ };
1423
+ }
1424
+ async fetchItems(id) {
1425
+ const items = [];
1426
+ let after = null;
1427
+ for (;;) {
1428
+ const page = (await this.graphql.query(ITEMS_QUERY, {
1429
+ id,
1430
+ after
1431
+ })).node.items;
1432
+ for (const n of page.nodes) {
1433
+ const c = n.content;
1434
+ if (!c || !c.repository) continue;
1435
+ const values = {};
1436
+ for (const v of n.fieldValues.nodes) if (v.name && v.field?.name) values[v.field.name] = v.name;
1437
+ items.push({
1438
+ id: n.id,
1439
+ contentId: c.id,
1440
+ repo: c.repository.nameWithOwner,
1441
+ number: c.number,
1442
+ title: c.title,
1443
+ open: c.state === "OPEN",
1444
+ values,
1445
+ blockers: (c.blockedBy?.nodes ?? []).filter((b) => b.state === "OPEN").map((b) => ({
1446
+ repo: b.repository.nameWithOwner,
1447
+ number: b.number
1448
+ })),
1449
+ ...c.closedByPullRequestsReferences ? { closing: c.closedByPullRequestsReferences.nodes } : {}
1450
+ });
1451
+ }
1452
+ if (!page.pageInfo.hasNextPage) return items;
1453
+ after = page.pageInfo.endCursor;
1454
+ }
1455
+ }
1456
+ keyOf(repo, number) {
1457
+ return repo === this.repo ? `#${number}` : `${repo}#${number}`;
1458
+ }
1459
+ parseKey(key) {
1460
+ const m = /^(?:([^#\s]+))?#?(\d+)$/.exec(key.trim());
1461
+ const hasRepo = key.includes("#") && m?.[1];
1462
+ if (!m) throw new Error(`not an issue key: ${key}`);
1463
+ return {
1464
+ repo: hasRepo ? m[1] : this.repo,
1465
+ number: Number(m[2])
1466
+ };
1467
+ }
1468
+ };
1469
+ // src/sodium.ts
342
1470
  /**
343
1471
  * libsodium sealed-box encryption for GitHub Actions secrets.
344
1472
  *
@@ -369,32 +1497,86 @@ async function encryptSecret(publicKeyBase64, value) {
369
1497
  const ciphertext = sodium.crypto_box_seal(plaintext, publicKey);
370
1498
  return sodium.to_base64(ciphertext, sodium.base64_variants.ORIGINAL);
371
1499
  }
372
- //#endregion
373
- //#region src/capabilities/secrets.ts
1500
+ // src/capabilities/secrets.ts
1501
+ /** The GitHub implementation of the `secrets` capability, covering repository, environment and organization secrets. */
374
1502
  var GitHubSecrets = class {
375
1503
  client;
376
1504
  opts;
1505
+ orgClient;
1506
+ /** Capability key, always `"secrets"`. */
377
1507
  key = "secrets";
1508
+ /** Provider name, always `"github"`. */
378
1509
  providerName = "github";
379
- constructor(client, opts) {
1510
+ /**
1511
+ * `client` handles repo and environment scopes; `orgClient`, when given, handles
1512
+ * the organization scope. They differ when a dedicated org-only token exists:
1513
+ * it can write org secrets but not repo ones, and `github.admin` is the reverse.
1514
+ */
1515
+ constructor(client, opts, orgClient) {
380
1516
  this.client = client;
381
1517
  this.opts = opts;
1518
+ this.orgClient = orgClient;
1519
+ }
1520
+ /** Repository name to numeric id, so one run asks GitHub once per repository however many secrets name it. */
1521
+ repoIds = /* @__PURE__ */ new Map();
1522
+ clientFor(scope) {
1523
+ return scope.kind === "organization" ? this.orgClient ?? this.client : this.client;
382
1524
  }
383
1525
  async listSecrets(scope) {
384
- return this.client.secrets.listSecrets(this.opts.repo, toGHScope(scope));
1526
+ return this.clientFor(scope).secrets.listSecrets(this.opts.repo, toGHScope(scope));
385
1527
  }
386
1528
  async setSecret(scope, name, value) {
387
1529
  const ghScope = toGHScope(scope);
388
- const pk = await this.client.secrets.getPublicKey(this.opts.repo, ghScope);
1530
+ const client = this.clientFor(scope);
1531
+ const readers = scope.kind === "organization" ? await this.readers(scope) : {};
1532
+ const pk = await client.secrets.getPublicKey(this.opts.repo, ghScope);
389
1533
  const body = {
390
1534
  encrypted_value: await encryptSecret(pk.key, value),
391
1535
  key_id: pk.key_id
392
1536
  };
393
- if (scope.kind === "organization") body.visibility = "all";
394
- await this.client.secrets.putSecret(this.opts.repo, ghScope, name, body);
1537
+ Object.assign(body, readers);
1538
+ await client.secrets.putSecret(this.opts.repo, ghScope, name, body);
395
1539
  }
1540
+ /**
1541
+ * Who can read each organization secret, by name (never a value): `selected` ones come with the names of their
1542
+ * repositories. Any other scope has no visibility and gives `{}`.
1543
+ */
1544
+ async listSecretAccess(scope) {
1545
+ if (scope.kind !== "organization") return {};
1546
+ const client = this.clientFor(scope);
1547
+ const found = {};
1548
+ for (const info of await client.secrets.listOrgSecretInfo(scope.name)) found[info.name] = info.visibility === "selected" ? {
1549
+ visibility: "selected",
1550
+ repos: await client.secrets.listSelectedRepositories(scope.name, info.name)
1551
+ } : { visibility: info.visibility };
1552
+ return found;
1553
+ }
1554
+ /** The `visibility` (and repository ids) of an organization write. No `visibility` keeps the older default, `all`. */
1555
+ async readers(scope) {
1556
+ const visibility = scope.visibility ?? "all";
1557
+ if (visibility !== "selected") return { visibility };
1558
+ if (!scope.repos?.length) throw new Error(`organization secret with visibility "selected" needs a non-empty repos list`);
1559
+ const ids = [];
1560
+ for (const name of scope.repos) ids.push(await this.repoId(scope.name, name));
1561
+ return {
1562
+ visibility,
1563
+ selected_repository_ids: ids
1564
+ };
1565
+ }
1566
+ repoId(org, name) {
1567
+ const full = `${org}/${name}`;
1568
+ let id = this.repoIds.get(full);
1569
+ if (!id) {
1570
+ id = this.client.repos.getRepo(full).then((repo) => repo.id, (err) => {
1571
+ throw new Error(`could not resolve repository ${full}: ${err instanceof Error ? err.message : String(err)}`);
1572
+ });
1573
+ this.repoIds.set(full, id);
1574
+ }
1575
+ return id;
1576
+ }
1577
+ /** Deletes the named secret in the given scope. */
396
1578
  async deleteSecret(scope, name) {
397
- await this.client.secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
1579
+ await this.clientFor(scope).secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
398
1580
  }
399
1581
  };
400
1582
  function toGHScope(scope) {
@@ -404,8 +1586,46 @@ function toGHScope(scope) {
404
1586
  };
405
1587
  return scope;
406
1588
  }
407
- //#endregion
408
- //#region src/capabilities/labels.ts
1589
+ // src/capabilities/files.ts
1590
+ /** Reads one file; `null` when it does not exist. `version` is the blob sha `writeFile` needs to replace exactly this one. */
1591
+ /** A fine-grained token only reaches the repositories and permissions it was given; say which one is missing. */
1592
+ function noAccess(repo, action, cause) {
1593
+ 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 });
1594
+ }
1595
+ async function readRepoFile(client, repo, path) {
1596
+ try {
1597
+ const file = await client.git.getContents(repo, path);
1598
+ if (file.encoding !== "base64") throw new Error(`${repo}/${path}: unexpected encoding \`${file.encoding}\``);
1599
+ return {
1600
+ content: Buffer.from(file.content, "base64").toString("utf-8"),
1601
+ version: file.sha
1602
+ };
1603
+ } catch (err) {
1604
+ if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "read", err);
1605
+ if (!(err instanceof ProviderApiError && err.status === 404)) throw err;
1606
+ }
1607
+ try {
1608
+ await client.repos.getRepo(repo);
1609
+ } catch (err) {
1610
+ 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 });
1611
+ throw err;
1612
+ }
1613
+ return null;
1614
+ }
1615
+ /** Creates or replaces one file in a commit; GitHub refuses (409) a `version` that has since changed. */
1616
+ async function writeRepoFile(client, repo, path, content, opts) {
1617
+ try {
1618
+ await client.git.putContents(repo, path, {
1619
+ message: opts.message,
1620
+ content,
1621
+ ...opts.version ? { sha: opts.version } : {}
1622
+ });
1623
+ } catch (err) {
1624
+ if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "write", err);
1625
+ throw err;
1626
+ }
1627
+ }
1628
+ // src/capabilities/labels.ts
409
1629
  /**
410
1630
  * Idempotently synchronise a repo's labels to the canonical set.
411
1631
  *
@@ -443,14 +1663,208 @@ async function syncLabels(client, repo, canonical, stale) {
443
1663
  }
444
1664
  return `${created} created, ${updated} updated, ${deleted} deleted`;
445
1665
  }
446
- //#endregion
447
- //#region src/capabilities/properties.ts
448
- async function syncProperties(client, repo, values) {
449
- await client.properties.setProperties(repo, values);
1666
+ // src/capabilities/property-fix-hints.ts
1667
+ /** GitHub's wording when a custom property value is not one the organization's definition allows. */
1668
+ const NOT_ALLOWED = /Value '([^']+)' is not allowed for property '([^']+)'/g;
1669
+ /**
1670
+ * What to do about each value GitHub says an organization custom property does not allow, one sentence per property,
1671
+ * read from GitHub's own message so it works even when the organization's definitions cannot be read. The values
1672
+ * belong to the organization's definition, not to the repository, so the fix is to add them there: a repository cannot
1673
+ * make its own value allowed. Empty when GitHub's message names no such value.
1674
+ */
1675
+ function propertyFixHints(githubMessage) {
1676
+ const byProperty = /* @__PURE__ */ new Map();
1677
+ for (const [, value, property] of githubMessage.matchAll(NOT_ALLOWED)) {
1678
+ const values = byProperty.get(property) ?? [];
1679
+ if (!values.includes(value)) values.push(value);
1680
+ byProperty.set(property, values);
1681
+ }
1682
+ 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`);
1683
+ }
1684
+ // src/capabilities/rejected-properties.ts
1685
+ /** The values `setup` sends for `true_false` properties; anything else is rejected. */
1686
+ const BOOLEANS = /* @__PURE__ */ new Set(["true", "false"]);
1687
+ /**
1688
+ * What is wrong with `values` when compared with the organization's property definitions, one sentence per
1689
+ * problem, in the order the properties are given: a property the organization does not define, a value a
1690
+ * `single_select` or `multi_select` property does not allow, or a `true_false` property that is not `true` or
1691
+ * `false`. A `string` or `url` property has nothing to check here. Empty when every value fits its definition.
1692
+ */
1693
+ function rejectedProperties(values, schema) {
1694
+ const byName = new Map(schema.map((property) => [property.property_name, property]));
1695
+ const problems = [];
1696
+ for (const [name, value] of Object.entries(values)) {
1697
+ const definition = byName.get(name);
1698
+ if (!definition) {
1699
+ problems.push(`${name} is not a custom property of the organization`);
1700
+ continue;
1701
+ }
1702
+ const sent = Array.isArray(value) ? value : [value];
1703
+ if (definition.value_type === "true_false") {
1704
+ for (const item of sent.filter((item) => !BOOLEANS.has(item))) problems.push(`${name} is "${item}", but it takes only true or false`);
1705
+ continue;
1706
+ }
1707
+ const allowed = definition.allowed_values ?? [];
1708
+ if (definition.value_type !== "single_select" && definition.value_type !== "multi_select") continue;
1709
+ 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(", ")})`);
1710
+ }
1711
+ return problems;
1712
+ }
1713
+ // src/capabilities/properties.ts
1714
+ /** GitHub's own message from a 422 body (`{"message": ..., "errors": [...]}`), or the start of the body when it is not JSON. */
1715
+ function githubMessage(details) {
1716
+ const raw = String(details ?? "").trim();
1717
+ try {
1718
+ const body = JSON.parse(raw);
1719
+ const errors = Array.isArray(body.errors) ? body.errors.map((e) => JSON.stringify(e)).join(", ") : "";
1720
+ const message = typeof body.message === "string" ? body.message : raw;
1721
+ return errors ? `${message}: ${errors}` : message;
1722
+ } catch {
1723
+ return raw.slice(0, 300);
1724
+ }
1725
+ }
1726
+ /** The organization's property definitions, or `undefined` when they cannot be read (permission, an older client). */
1727
+ async function orgSchema(client, repo) {
1728
+ try {
1729
+ return await client.properties.orgSchema(repo.split("/")[0]);
1730
+ } catch {
1731
+ return;
1732
+ }
1733
+ }
1734
+ /**
1735
+ * The values `values` holds that the organization's property definitions do not allow, one sentence each, or
1736
+ * `undefined` when the definitions cannot be read (the token lacks the organization's custom properties permission, or
1737
+ * the organization defines none). `client` should be the organization-scoped one when there is one, since reading the
1738
+ * definitions is an organization permission a repository token often lacks. Read-only.
1739
+ */
1740
+ async function checkPropertyValues(client, repo, values) {
1741
+ const schema = await orgSchema(client, repo);
1742
+ return schema ? rejectedProperties(values, schema) : void 0;
1743
+ }
1744
+ /**
1745
+ * Sets the repo's custom properties. When GitHub answers 422 the error says which value it refused and what to do
1746
+ * about it: the values are compared with the organization's property definitions (read-only, with `schemaClient`, the
1747
+ * organization-scoped client when there is one), GitHub's own message is added, and each value GitHub says a property
1748
+ * does not allow gets the fix, which does not need the definitions to be readable. One refused value fails the whole
1749
+ * request, so none of the properties is set.
1750
+ */
1751
+ async function syncProperties(client, repo, values, schemaClient = client) {
1752
+ try {
1753
+ await client.properties.setProperties(repo, values);
1754
+ } catch (err) {
1755
+ if (!(err instanceof ProviderApiError$1) || err.status !== 422) throw err;
1756
+ const problems = await checkPropertyValues(schemaClient, repo, values) ?? [];
1757
+ const said = githubMessage(err.details);
1758
+ const fixes = propertyFixHints(said);
1759
+ 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 });
1760
+ }
450
1761
  return `${Object.keys(values).length} properties set`;
451
1762
  }
452
- //#endregion
453
- //#region src/capabilities/teams.ts
1763
+ /** The values the organization's property `name` allows; `undefined` when it cannot be read, is not defined or takes any value. */
1764
+ async function getOrgPropertyValues(client, repo, name) {
1765
+ return ((await orgSchema(client, repo))?.find((p) => p.property_name === name))?.allowed_values ?? void 0;
1766
+ }
1767
+ /**
1768
+ * Adds the missing `values` to the organization's property `name` and returns them. GitHub replaces the whole
1769
+ * definition on a write, so the current one is read and sent back with the allowed values extended, in their order,
1770
+ * and nothing removed. A write is made only when something is missing.
1771
+ */
1772
+ async function addOrgPropertyValues(client, repo, name, values, viaOrgToken = true) {
1773
+ const org = repo.split("/")[0];
1774
+ const current = (await client.properties.orgSchema(org)).find((p) => p.property_name === name);
1775
+ if (!current) throw new Error(`the organization ${org} has no custom property "${name}"; create it first`);
1776
+ if (!current.allowed_values) throw new Error(`the custom property "${name}" takes any value; it has nothing to extend`);
1777
+ const have = new Set(current.allowed_values);
1778
+ const added = [...new Set(values)].filter((v) => !have.has(v));
1779
+ if (added.length === 0) return [];
1780
+ try {
1781
+ await client.properties.setOrgProperty(org, {
1782
+ ...current,
1783
+ allowed_values: [...current.allowed_values, ...added]
1784
+ });
1785
+ } catch (err) {
1786
+ if (!(err instanceof ProviderApiError$1) || err.status !== 403 && err.status !== 401) throw err;
1787
+ 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)";
1788
+ 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 });
1789
+ }
1790
+ return added;
1791
+ }
1792
+ // src/capabilities/read-repo.ts
1793
+ /** The settings `setup` writes, which `GET /repos/{repo}` reports under the same names. */
1794
+ const SETTING_KEYS = [
1795
+ "allow_squash_merge",
1796
+ "allow_merge_commit",
1797
+ "allow_rebase_merge",
1798
+ "allow_auto_merge",
1799
+ "allow_update_branch",
1800
+ "delete_branch_on_merge",
1801
+ "has_issues",
1802
+ "has_discussions",
1803
+ "has_projects",
1804
+ "has_wiki"
1805
+ ];
1806
+ /** The repository's description, homepage, default branch, topics and settings, from one read. */
1807
+ async function readRepoInfo(client, repo) {
1808
+ const data = await client.repos.getRepo(repo);
1809
+ const settings = { default_branch: data.default_branch };
1810
+ for (const key of SETTING_KEYS) {
1811
+ const value = data[key];
1812
+ if (value !== void 0) settings[key] = value;
1813
+ }
1814
+ return {
1815
+ description: data.description ?? null,
1816
+ homepage: data.homepage ?? null,
1817
+ defaultBranch: data.default_branch,
1818
+ topics: data.topics ?? [],
1819
+ settings
1820
+ };
1821
+ }
1822
+ /** A ruleset reduced to what `setup` writes: its enforcement, rule types and required status checks. */
1823
+ function toRulesetDetail(data) {
1824
+ const rules = data.rules ?? [];
1825
+ const checks = rules.find((r) => r.type === "required_status_checks")?.parameters?.required_status_checks;
1826
+ return {
1827
+ name: data.name,
1828
+ enforcement: data.enforcement,
1829
+ ruleTypes: rules.map((r) => r.type),
1830
+ requiredChecks: Array.isArray(checks) ? checks.map((c) => String(c.context)) : []
1831
+ };
1832
+ }
1833
+ /** The value, or `undefined` when GitHub refuses the read (permission, plan, feature absent). Other errors still throw. */
1834
+ async function readable(read) {
1835
+ try {
1836
+ return await read();
1837
+ } catch (err) {
1838
+ if (err instanceof ProviderApiError$1) return void 0;
1839
+ throw err;
1840
+ }
1841
+ }
1842
+ /** Which security features are on. One GitHub refuses to report is left out, not reported as off. */
1843
+ async function readSecurity(client, repo) {
1844
+ const [data, alerts, fixes, reporting, codeScanning] = await Promise.all([
1845
+ readable(() => client.repos.getRepo(repo)),
1846
+ readable(() => client.security.vulnerabilityAlertsEnabled(repo)),
1847
+ readable(() => client.security.automatedSecurityFixesEnabled(repo)),
1848
+ readable(() => client.security.privateVulnerabilityReportingEnabled(repo)),
1849
+ readable(() => client.security.codeScanningDefaultSetupState(repo))
1850
+ ]);
1851
+ const analysis = data?.security_and_analysis;
1852
+ const on = (feature) => {
1853
+ const status = analysis?.[feature]?.status;
1854
+ return status === void 0 ? void 0 : status === "enabled";
1855
+ };
1856
+ const found = {
1857
+ vulnerabilityAlerts: alerts,
1858
+ automatedSecurityFixes: fixes,
1859
+ secretScanning: on("secret_scanning"),
1860
+ secretScanningPushProtection: on("secret_scanning_push_protection"),
1861
+ privateVulnerabilityReporting: reporting,
1862
+ codeScanningDefaultSetup: codeScanning === void 0 ? void 0 : codeScanning === "configured"
1863
+ };
1864
+ return Object.fromEntries(Object.entries(found).filter(([, v]) => v !== void 0));
1865
+ }
1866
+ // src/capabilities/teams.ts
1867
+ /** Turns a team entry into slug and permission form; a bare slug gets `push`. */
454
1868
  function normalizeTeamEntry(entry) {
455
1869
  if (typeof entry === "string") return {
456
1870
  slug: entry,
@@ -458,6 +1872,7 @@ function normalizeTeamEntry(entry) {
458
1872
  };
459
1873
  return entry;
460
1874
  }
1875
+ /** Grants each team access to the repo and reports the outcome; throws when every team fails. */
461
1876
  async function syncTeams(client, repo, teams) {
462
1877
  const [org = "", name = ""] = repo.split("/", 2);
463
1878
  const normalized = teams.map(normalizeTeamEntry);
@@ -470,17 +1885,132 @@ async function syncTeams(client, repo, teams) {
470
1885
  }
471
1886
  return `${succeeded} team${succeeded === 1 ? "" : "s"} synced`;
472
1887
  }
473
- //#endregion
474
- //#region src/capabilities/topics.ts
1888
+ // src/capabilities/topics.ts
475
1889
  async function syncTopics(client, repo, topics) {
476
1890
  await client.topics.setTopics(repo, topics);
477
1891
  return `${topics.length} topics set`;
478
1892
  }
479
- //#endregion
480
- //#region src/capabilities/source.ts
1893
+ // src/capabilities/variables.ts
1894
+ /** GitHub's rule for a variable name: letters, digits and underscores, not starting with a digit or `GITHUB_`. */
1895
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
1896
+ /** Longest name GitHub accepts. */
1897
+ const MAX_NAME = 256;
1898
+ function assertNames(names) {
1899
+ 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_`);
1900
+ }
1901
+ /** GitHub treats variable names as case-insensitive, so every comparison goes through this. */
1902
+ const key = (name) => name.toUpperCase();
1903
+ /**
1904
+ * Bring one scope's variables in line with the declaration: create what is missing, update what differs, leave what
1905
+ * already matches. Variables that exist but are not declared are left alone, or deleted with `prune`, except an
1906
+ * organization variable limited to selected repositories, which this client cannot manage and so is never deleted.
1907
+ * Returns a one-line summary, naming the ones left so drift is visible. In a dry run it only describes the changes.
1908
+ */
1909
+ async function reconcile(client, repo, scope, wanted, opts) {
1910
+ assertNames(wanted.map((w) => w.name));
1911
+ const existing = new Map((await client.variables.listVariables(repo, scope)).map((v) => [key(v.name), v]));
1912
+ const counts = {
1913
+ created: 0,
1914
+ updated: 0,
1915
+ unchanged: 0,
1916
+ deleted: 0
1917
+ };
1918
+ for (const want of wanted) {
1919
+ const have = existing.get(key(want.name));
1920
+ const body = {
1921
+ name: want.name,
1922
+ value: want.value
1923
+ };
1924
+ if (want.visibility) body["visibility"] = want.visibility;
1925
+ if (!have) {
1926
+ if (opts.dryRun) {
1927
+ counts.created++;
1928
+ continue;
1929
+ }
1930
+ try {
1931
+ await client.variables.createVariable(repo, scope, body);
1932
+ counts.created++;
1933
+ continue;
1934
+ } catch (err) {
1935
+ if (!(err instanceof ProviderApiError && (err.status === 409 || err.status === 422))) throw err;
1936
+ }
1937
+ } else if (have.value === want.value && (!want.visibility || have.visibility === want.visibility)) {
1938
+ counts.unchanged++;
1939
+ continue;
1940
+ }
1941
+ if (!opts.dryRun) await client.variables.updateVariable(repo, scope, have?.name ?? want.name, body);
1942
+ counts.updated++;
1943
+ }
1944
+ const declared = new Set(wanted.map((w) => key(w.name)));
1945
+ const undeclared = [...existing.entries()].filter(([k]) => !declared.has(k)).map(([, v]) => v);
1946
+ const unmanaged = undeclared.filter((v) => v.visibility === "selected");
1947
+ if (opts.prune) for (const v of undeclared.filter((u) => u.visibility !== "selected")) {
1948
+ if (!opts.dryRun) await client.variables.deleteVariable(repo, scope, v.name);
1949
+ counts.deleted++;
1950
+ }
1951
+ const parts = opts.dryRun ? [
1952
+ `would create ${counts.created}`,
1953
+ `would update ${counts.updated}`,
1954
+ `${counts.unchanged} unchanged`
1955
+ ] : [
1956
+ `${counts.created} created`,
1957
+ `${counts.updated} updated`,
1958
+ `${counts.unchanged} unchanged`
1959
+ ];
1960
+ if (counts.deleted > 0) parts.push(`${counts.deleted} ${opts.dryRun ? "would be deleted" : "deleted"}`);
1961
+ const left = opts.prune ? unmanaged : undeclared;
1962
+ if (left.length > 0) {
1963
+ const why = opts.prune ? "limited to selected repositories, not managed" : "not declared, left alone";
1964
+ parts.push(`${left.length} ${why}: ${left.map((v) => v.name).join(", ")}`);
1965
+ }
1966
+ return parts.join(", ");
1967
+ }
1968
+ /** Reconcile a repository's Actions variables. */
1969
+ function syncVariables(client, repo, variables, opts = {}) {
1970
+ return reconcile(client, repo, { kind: "repo" }, Object.entries(variables).map(([name, value]) => ({
1971
+ name,
1972
+ value
1973
+ })), {
1974
+ prune: opts.prune === true,
1975
+ dryRun: opts.dryRun === true
1976
+ });
1977
+ }
1978
+ /** Reconcile an organization's Actions variables. `repo` is only the coordinate the client is bound to. */
1979
+ function syncOrgVariables(client, repo, org, variables, opts = {}) {
1980
+ const wanted = Object.entries(variables).map(([name, v]) => ({
1981
+ name,
1982
+ value: v.value,
1983
+ visibility: v.visibility
1984
+ }));
1985
+ return reconcile(client, repo, {
1986
+ kind: "organization",
1987
+ org
1988
+ }, wanted, {
1989
+ prune: opts.prune === true,
1990
+ dryRun: opts.dryRun === true
1991
+ });
1992
+ }
1993
+ // src/capabilities/source.ts
1994
+ function toPullRequest(raw) {
1995
+ return {
1996
+ number: raw.number,
1997
+ title: raw.title,
1998
+ state: raw.state,
1999
+ merged: raw.merged_at !== null,
2000
+ branch: raw.head.ref,
2001
+ headSha: raw.head.sha,
2002
+ url: raw.html_url
2003
+ };
2004
+ }
2005
+ /**
2006
+ * The GitHub implementation of the `source` capability: repo settings, rulesets, branch protection, security
2007
+ * features and local workflow files.
2008
+ */
481
2009
  var GitHubSource = class {
482
2010
  client;
2011
+ /** Capability key, always `"source"`. */
483
2012
  key = "source";
2013
+ /** Provider name, always `"github"`. */
484
2014
  providerName = "github";
485
2015
  owner;
486
2016
  name;
@@ -488,6 +2018,7 @@ var GitHubSource = class {
488
2018
  repoRoot;
489
2019
  workflowDir;
490
2020
  orgClient;
2021
+ userSyncClient;
491
2022
  baseUrl;
492
2023
  fetchImpl;
493
2024
  constructor(client, opts) {
@@ -496,15 +2027,20 @@ var GitHubSource = class {
496
2027
  this.owner = owner;
497
2028
  this.name = name;
498
2029
  this.repo = opts.repo;
499
- this.repoRoot = opts.repoRoot;
500
- this.workflowDir = join(opts.repoRoot, ".github", "workflows");
2030
+ this.repoRoot = findRootSync(opts.repoRoot, ".git", {
2031
+ fallback: "start",
2032
+ realpath: true
2033
+ });
2034
+ this.workflowDir = join(this.repoRoot, ".github", "workflows");
501
2035
  this.orgClient = opts.orgClient;
2036
+ this.userSyncClient = opts.userSyncClient;
502
2037
  this.baseUrl = opts.baseUrl;
503
2038
  this.fetchImpl = opts.fetch;
504
2039
  }
505
2040
  async whoami() {
506
2041
  return { login: (await this.client.user.getCurrentUser()).login };
507
2042
  }
2043
+ /** Returns the repo's owner, name and default branch. */
508
2044
  async getRepo() {
509
2045
  const data = await this.client.repos.getRepo(this.repo);
510
2046
  return {
@@ -513,27 +2049,34 @@ var GitHubSource = class {
513
2049
  defaultBranch: data.default_branch
514
2050
  };
515
2051
  }
2052
+ /** Lists the repo's rulesets. */
516
2053
  async listRulesets() {
517
2054
  return this.client.rulesets.listRulesets(this.repo);
518
2055
  }
2056
+ /** Creates a ruleset from the given payload. */
519
2057
  async createRuleset(payload) {
520
2058
  return this.client.rulesets.createRuleset(this.repo, payload);
521
2059
  }
2060
+ /** Updates the ruleset with the given id from the payload. */
522
2061
  async updateRuleset(id, payload) {
523
2062
  return this.client.rulesets.updateRuleset(this.repo, id, payload);
524
2063
  }
2064
+ /** Updates the repo's settings. */
525
2065
  async updateRepoSettings(settings) {
526
2066
  await this.client.repos.updateRepo(this.repo, settings);
527
2067
  }
528
2068
  async protectBranch(branch, payload) {
529
2069
  await this.client.branches.protectBranch(this.repo, branch, payload);
530
2070
  }
2071
+ /** Enables Dependabot vulnerability alerts. */
531
2072
  async enableVulnerabilityAlerts() {
532
2073
  await this.client.security.enableVulnerabilityAlerts(this.repo);
533
2074
  }
2075
+ /** Enables Dependabot automated security fixes. */
534
2076
  async enableAutomatedSecurityFixes() {
535
2077
  await this.client.security.enableAutomatedSecurityFixes(this.repo);
536
2078
  }
2079
+ /** Enables secret scanning. */
537
2080
  async enableSecretScanning() {
538
2081
  await this.client.security.enableSecretScanning(this.repo);
539
2082
  }
@@ -546,9 +2089,11 @@ var GitHubSource = class {
546
2089
  async enableDependencyGraph() {
547
2090
  await this.client.security.enableDependencyGraph(this.repo);
548
2091
  }
2092
+ /** Enables private vulnerability reporting. */
549
2093
  async enablePrivateVulnerabilityReporting() {
550
2094
  await this.client.security.enablePrivateVulnerabilityReporting(this.repo);
551
2095
  }
2096
+ /** Lists the `.yml` and `.yaml` files in `.github/workflows`, sorted by name; empty when the folder is missing. */
552
2097
  async listWorkflowFiles() {
553
2098
  try {
554
2099
  return (await readdir(this.workflowDir)).filter((e) => e.endsWith(".yml") || e.endsWith(".yaml")).sort();
@@ -557,6 +2102,7 @@ var GitHubSource = class {
557
2102
  throw err;
558
2103
  }
559
2104
  }
2105
+ /** Reads a workflow file's text, or `null` when it does not exist. */
560
2106
  async readWorkflowFile(name) {
561
2107
  try {
562
2108
  return await readFile(join(this.workflowDir, name), "utf8");
@@ -565,10 +2111,12 @@ var GitHubSource = class {
565
2111
  throw err;
566
2112
  }
567
2113
  }
2114
+ /** Writes a workflow file, creating `.github/workflows` first when needed. */
568
2115
  async writeWorkflowFile(name, contents) {
569
2116
  await ensureDir(this.workflowDir);
570
2117
  await writeFile(join(this.workflowDir, name), contents, "utf8");
571
2118
  }
2119
+ /** Removes a workflow file; a file that is already gone is not an error. */
572
2120
  async removeWorkflowFile(name) {
573
2121
  try {
574
2122
  await rm(join(this.workflowDir, name));
@@ -586,14 +2134,83 @@ var GitHubSource = class {
586
2134
  return syncLabels(this.client, this.repo, canonical, stale);
587
2135
  }
588
2136
  async syncProperties(values) {
589
- return syncProperties(this.client, this.repo, values);
2137
+ return syncProperties(this.client, this.repo, values, this.orgClient ?? this.client);
2138
+ }
2139
+ async getOrgPropertyValues(name) {
2140
+ return getOrgPropertyValues(this.orgClient ?? this.client, this.repo, name);
2141
+ }
2142
+ async addOrgPropertyValues(name, values) {
2143
+ return addOrgPropertyValues(this.orgClient ?? this.client, this.repo, name, values, this.orgClient !== void 0);
2144
+ }
2145
+ async checkPropertyValues(values) {
2146
+ return checkPropertyValues(this.orgClient ?? this.client, this.repo, values);
590
2147
  }
591
2148
  async syncTeams(teams) {
592
2149
  return syncTeams(this.orgClient ?? this.client, this.repo, teams);
593
2150
  }
2151
+ async teamMembers(teamSlug, org = this.owner) {
2152
+ return (await (this.orgClient ?? this.client).teams.members(org, teamSlug)).map((m) => ({
2153
+ id: String(m.id),
2154
+ login: m.login
2155
+ }));
2156
+ }
2157
+ async readFile(path, repo = this.repo) {
2158
+ return readRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, repo, path);
2159
+ }
2160
+ async writeFile(path, content, opts) {
2161
+ return writeRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, opts.repo ?? this.repo, path, content, opts);
2162
+ }
594
2163
  async syncTopics(topics) {
595
2164
  return syncTopics(this.client, this.repo, topics);
596
2165
  }
2166
+ async syncVariables(variables, opts) {
2167
+ return syncVariables(this.client, this.repo, variables, opts);
2168
+ }
2169
+ async syncOrgVariables(org, variables, opts) {
2170
+ if (!this.orgClient) throw new Error("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron new token github.org <token>`");
2171
+ return syncOrgVariables(this.orgClient, this.repo, org, variables, opts);
2172
+ }
2173
+ async listVariables() {
2174
+ const found = await this.client.variables.listVariables(this.repo, { kind: "repo" });
2175
+ return Object.fromEntries(found.map((v) => [v.name, v.value]));
2176
+ }
2177
+ async listOrgVariables(org) {
2178
+ if (!this.orgClient) throw new MissingTokenError("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron new token github.org <token>`");
2179
+ const found = await this.orgClient.variables.listVariables(this.repo, {
2180
+ kind: "organization",
2181
+ org
2182
+ });
2183
+ return Object.fromEntries(found.map((v) => [v.name, {
2184
+ value: v.value,
2185
+ visibility: v.visibility ?? "all"
2186
+ }]));
2187
+ }
2188
+ async getRepoInfo() {
2189
+ return readRepoInfo(this.client, this.repo);
2190
+ }
2191
+ async getProperties() {
2192
+ const found = await this.client.properties.getValues(this.repo);
2193
+ return Object.fromEntries(found.flatMap((p) => p.value === null ? [] : [[p.property_name, p.value]]));
2194
+ }
2195
+ async listLabels() {
2196
+ return (await this.client.labels.listLabels(this.repo)).map((l) => ({
2197
+ name: l.name,
2198
+ color: l.color,
2199
+ description: l.description ?? ""
2200
+ }));
2201
+ }
2202
+ async listTeamAccess() {
2203
+ return (await (this.orgClient ?? this.client).teams.listForRepo(this.repo)).map((t) => ({
2204
+ slug: t.slug,
2205
+ permission: t.permission
2206
+ }));
2207
+ }
2208
+ async getRulesetDetail(id) {
2209
+ return toRulesetDetail(await this.client.rulesets.getRuleset(this.repo, id));
2210
+ }
2211
+ async getSecurity() {
2212
+ return readSecurity(this.client, this.repo);
2213
+ }
597
2214
  async syncDescription(description) {
598
2215
  await this.client.repos.updateRepo(this.repo, { description });
599
2216
  return "description updated";
@@ -603,15 +2220,27 @@ var GitHubSource = class {
603
2220
  return "homepage updated";
604
2221
  }
605
2222
  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
- };
2223
+ return toPullRequest(await this.client.pulls.getPullRequest(repo ?? this.repo, number));
2224
+ }
2225
+ async listPullRequests(state, repo) {
2226
+ return (await this.client.pulls.listPullRequests(repo ?? this.repo, state)).map(toPullRequest);
2227
+ }
2228
+ async listBranches(repo) {
2229
+ return (await this.client.branches.listBranches(repo ?? this.repo)).map((b) => ({
2230
+ name: b.name,
2231
+ sha: b.commit.sha
2232
+ }));
2233
+ }
2234
+ async deleteBranch(name, repo) {
2235
+ try {
2236
+ await this.client.branches.removeBranch(repo ?? this.repo, name);
2237
+ } catch (err) {
2238
+ if (err instanceof ProviderApiError && err.status === 422 && String(err.details).includes("does not exist")) return;
2239
+ throw err;
2240
+ }
2241
+ }
2242
+ async listPullRequestCommits(number, repo) {
2243
+ return (await this.client.pulls.listCommits(repo ?? this.repo, number)).map((commit) => commit.sha);
615
2244
  }
616
2245
  async configurePages(config, token) {
617
2246
  const pagesClient = createGitHubClient$1({
@@ -650,18 +2279,386 @@ async function ensureDir(path) {
650
2279
  throw err;
651
2280
  }
652
2281
  }
653
- //#endregion
654
- //#region src/verify-token.ts
2282
+ // src/probes/token/expectations.ts
2283
+ /** The same rules in every layer that runs the workflow: a laptop (`local` inherits `dev`) and CI. */
2284
+ function everywhere(rules) {
2285
+ return { permissions: {
2286
+ local: rules,
2287
+ dev: rules,
2288
+ ci: rules
2289
+ } };
2290
+ }
2291
+ /**
2292
+ * What each GitHub token is meant to carry, by its `envName`, the same as the GitHub tokens table in
2293
+ * `docs/src/content/docs/tokens.mdx`. This is the plugin's `tokens` declaration, read through `tokenExpectations()`;
2294
+ * change it and that table together.
2295
+ *
2296
+ * Every token CI uses (the `sync-repo`, `sync-secrets`, `reconcile-projects` and `check-tokens` workflows read all of
2297
+ * them) is declared with the same permissions in `local`, `dev` and `ci`, so the probe checks that a `ci` token is no
2298
+ * broader than its `dev` one rather than assuming a split the workflows do not allow. The release token is held by CI
2299
+ * only, so it has no `local` or `dev` entry. A narrow token must not reach administration or secrets; the admin token
2300
+ * must not reach organization secrets (that is `HOLOCRON_SECRETS_TOKEN`'s alone).
2301
+ */
2302
+ const EXPECTED = {
2303
+ HOLOCRON_READ_TOKEN: everywhere({
2304
+ contents: "required",
2305
+ actions: "required",
2306
+ administration: "absent",
2307
+ secrets: "absent",
2308
+ environments: "absent"
2309
+ }),
2310
+ HOLOCRON_ISSUES_TOKEN: everywhere({
2311
+ issues: "required",
2312
+ administration: "absent",
2313
+ secrets: "absent",
2314
+ environments: "absent"
2315
+ }),
2316
+ HOLOCRON_SYNC_TOKEN: everywhere({
2317
+ actions: "required",
2318
+ contents: "required",
2319
+ "pull-requests": "required",
2320
+ administration: "absent",
2321
+ secrets: "absent"
2322
+ }),
2323
+ HOLOCRON_RELEASE_TOKEN: { permissions: { ci: {
2324
+ contents: "required",
2325
+ issues: "required",
2326
+ "pull-requests": "required",
2327
+ administration: "absent",
2328
+ secrets: "absent"
2329
+ } } },
2330
+ HOLOCRON_ADMIN_TOKEN: everywhere({
2331
+ administration: "required",
2332
+ secrets: "required",
2333
+ environments: "required",
2334
+ issues: "required",
2335
+ "custom-properties": "required",
2336
+ "actions-variables": "required",
2337
+ "org-secrets": "absent"
2338
+ }),
2339
+ HOLOCRON_SECRETS_TOKEN: everywhere({
2340
+ "org-secrets": "required",
2341
+ administration: "absent"
2342
+ }),
2343
+ HOLOCRON_DEPLOY_TOKEN: everywhere({
2344
+ pages: "required",
2345
+ administration: "required",
2346
+ secrets: "absent",
2347
+ "org-secrets": "absent"
2348
+ }),
2349
+ HOLOCRON_USER_SYNC_TOKEN: everywhere({
2350
+ "user-sync-contents": "required",
2351
+ administration: "absent",
2352
+ secrets: "absent"
2353
+ }),
2354
+ HOLOCRON_ORG_TOKEN: everywhere({
2355
+ administration: "required",
2356
+ "org-members": "required",
2357
+ "org-variables": "required",
2358
+ "org-secrets": "absent"
2359
+ })
2360
+ };
2361
+ // src/tokens.ts
2362
+ /** Adds what a layer's token must and must not be able to do (`EXPECTED`, by `envName`) to a token. */
2363
+ function declared(token) {
2364
+ return {
2365
+ ...token,
2366
+ expect: EXPECTED[token.envName]
2367
+ };
2368
+ }
2369
+ /**
2370
+ * Every token this plugin takes, for `holocron doctor tokens`, with what each layer's token must and must not be able
2371
+ * to do. The release token is `optional`: only CI's release workflow reads it (from the org secret), so a development
2372
+ * environment has no reason to hold it.
2373
+ */
2374
+ const tokens = [
2375
+ declared(resolveReadToken.token),
2376
+ declared(resolveIssuesToken.token),
2377
+ declared(resolveSyncToken.token),
2378
+ declared({
2379
+ ...resolveReleaseToken.token,
2380
+ optional: true
2381
+ }),
2382
+ declared(resolveAdminToken.token),
2383
+ declared(resolveSecretsToken.token),
2384
+ declared(resolveDeployToken.token),
2385
+ declared(resolveUserSyncToken.token),
2386
+ declared(resolveOrgToken.token)
2387
+ ];
2388
+ // src/probes/token/parse-token-args.ts
2389
+ /** Reads the words after the probe name: `--layer <word>` and `--token-name <VAR>`, in either spelling. */
2390
+ function parseTokenArgs(args) {
2391
+ let layer;
2392
+ let tokenName;
2393
+ for (let i = 0; i < args.length; i++) {
2394
+ const arg = args[i];
2395
+ if (arg === "--layer") layer = args[++i];
2396
+ else if (arg.startsWith("--layer=")) layer = arg.slice(8);
2397
+ else if (arg === "--token-name") tokenName = args[++i];
2398
+ else if (arg.startsWith("--token-name=")) tokenName = arg.slice(13);
2399
+ }
2400
+ return {
2401
+ ...layer ? { layer } : {},
2402
+ ...tokenName ? { tokenName } : {}
2403
+ };
2404
+ }
2405
+ // src/probes/token/permissions.ts
2406
+ /**
2407
+ * Every permission the GitHub plugin's tokens are declared against, by the name the declaration uses, with one read
2408
+ * 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
2409
+ * fine-grained token's permissions, so the write half of `read/write` is taken from the permission table in
2410
+ * `docs/src/content/docs/tokens.mdx`. On a public repository the `contents`, `actions`, `issues`, `pull-requests` and `environments`
2411
+ * reads succeed for any token, so only the other permissions can prove a permission absent. Names with more than one
2412
+ * word are hyphenated, not underscored: `holocron probe docs tokens` strips `_` (Markdown emphasis) from a table cell
2413
+ * before it compares the id with the declaration.
2414
+ */
2415
+ const PERMISSIONS = {
2416
+ contents: {
2417
+ label: "Contents",
2418
+ path: "/repos/{r}/contents",
2419
+ publicRead: true
2420
+ },
2421
+ actions: {
2422
+ label: "Actions",
2423
+ path: "/repos/{r}/actions/runs?per_page=1",
2424
+ publicRead: true
2425
+ },
2426
+ issues: {
2427
+ label: "Issues",
2428
+ path: "/repos/{r}/issues?per_page=1",
2429
+ publicRead: true
2430
+ },
2431
+ "pull-requests": {
2432
+ label: "Pull requests",
2433
+ path: "/repos/{r}/pulls?per_page=1",
2434
+ publicRead: true
2435
+ },
2436
+ administration: {
2437
+ label: "Administration",
2438
+ path: "/repos/{r}/actions/permissions"
2439
+ },
2440
+ secrets: {
2441
+ label: "Secrets",
2442
+ path: "/repos/{r}/actions/secrets?per_page=1"
2443
+ },
2444
+ environments: {
2445
+ label: "Environments",
2446
+ path: "/repos/{r}/environments?per_page=1",
2447
+ publicRead: true
2448
+ },
2449
+ "actions-variables": {
2450
+ label: "Variables",
2451
+ path: "/repos/{r}/actions/variables?per_page=1"
2452
+ },
2453
+ "custom-properties": {
2454
+ label: "Custom properties",
2455
+ path: "/repos/{r}/properties/values"
2456
+ },
2457
+ pages: {
2458
+ label: "Pages",
2459
+ path: "/repos/{r}/pages"
2460
+ },
2461
+ "org-members": {
2462
+ label: "Organization: Members",
2463
+ path: "/orgs/{o}/members?per_page=1"
2464
+ },
2465
+ "org-variables": {
2466
+ label: "Organization: Variables",
2467
+ path: "/orgs/{o}/actions/variables?per_page=1"
2468
+ },
2469
+ "org-secrets": {
2470
+ label: "Organization: Secrets",
2471
+ path: "/orgs/{o}/actions/secrets?per_page=1"
2472
+ },
2473
+ "user-sync-contents": {
2474
+ label: "Contents (.github-private)",
2475
+ path: "/repos/{o}/.github-private/contents"
2476
+ }
2477
+ };
2478
+ // src/probes/token/token.ts
2479
+ /** The token checked when none is named: the one the plugin reads with by default. */
2480
+ const DEFAULT_TOKEN = "HOLOCRON_READ_TOKEN";
2481
+ /** Does one GET with the token; the response headers are returned for the caller that wants them. */
2482
+ async function get(ctx, token, path) {
2483
+ return ctx.fetch(`${ctx.baseUrl}${path}`, { headers: {
2484
+ authorization: `Bearer ${token}`,
2485
+ accept: "application/vnd.github+json",
2486
+ "x-github-api-version": "2022-11-28",
2487
+ "user-agent": "holocron-probe"
2488
+ } });
2489
+ }
2490
+ /**
2491
+ * One read for one permission. GitHub answers a token without the permission with a 403, or a 404 for something it will
2492
+ * not admit exists, so both are `none`; a 2xx is `has`. Any other status, or a request that did not go through, is an
2493
+ * `error`, which is a failure whatever the layer expects.
2494
+ */
2495
+ async function reach(ctx, token, permission) {
2496
+ const [owner = ""] = ctx.repo.split("/");
2497
+ const path = PERMISSIONS[permission].path.replaceAll("{r}", ctx.repo).replaceAll("{o}", owner);
2498
+ try {
2499
+ const res = await get(ctx, token, path);
2500
+ if (res.ok) return {
2501
+ kind: "has",
2502
+ detail: `read ${path.split("?")[0]}`
2503
+ };
2504
+ if (res.status === 403 || res.status === 404) return {
2505
+ kind: "none",
2506
+ detail: `no access (${res.status})`
2507
+ };
2508
+ return {
2509
+ kind: "error",
2510
+ detail: `${res.status} ${res.statusText}`.trim()
2511
+ };
2512
+ } catch (err) {
2513
+ return {
2514
+ kind: "error",
2515
+ detail: errorMessage(err)
2516
+ };
2517
+ }
2518
+ }
655
2519
  /**
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.
2520
+ * One row for what was tried. With no rule it only describes (`ok` for access, `info` for none). Under a layer's rule it
2521
+ * judges: a required permission the token lacks fails, and one the layer must not have fails when the token has it; a
2522
+ * permission that is rightly absent is a bare `ok`.
2523
+ */
2524
+ function rowFor({ label, permission, outcome }, rule) {
2525
+ if (outcome.kind === "error") return {
2526
+ status: "fail",
2527
+ label,
2528
+ detail: outcome.detail
2529
+ };
2530
+ const has = outcome.kind === "has";
2531
+ if (rule === "required") return {
2532
+ status: has ? "ok" : "fail",
2533
+ label,
2534
+ detail: outcome.detail
2535
+ };
2536
+ if (rule === "absent" && has && PERMISSIONS[permission].publicRead) return {
2537
+ status: "info",
2538
+ label,
2539
+ detail: `${outcome.detail}, which any token can on a public repository: not proof either way`
2540
+ };
2541
+ if (rule === "absent") return has ? {
2542
+ status: "fail",
2543
+ label,
2544
+ detail: outcome.detail
2545
+ } : {
2546
+ status: "ok",
2547
+ label
2548
+ };
2549
+ return {
2550
+ status: has ? "ok" : "info",
2551
+ label,
2552
+ detail: outcome.detail
2553
+ };
2554
+ }
2555
+ /**
2556
+ * The `token` probe: `holocron probe github token` tries each permission Holocron uses with one of the plugin's nine
2557
+ * tokens and reports which ones the token reaches. It only reads (one GET per permission), so it changes nothing, and a
2558
+ * read proves the token can see an area, not that it can write there.
2559
+ *
2560
+ * GitHub lists scopes only for a classic token (the `X-OAuth-Scopes` header on any response), so a classic token's scopes
2561
+ * are shown. A fine-grained token has no list, so the permissions are found by trying them; the first row says which kind
2562
+ * was read. With `--environment <layer>` the CLI runs the probe once for each token the Environment holds and hands it
2563
+ * `--token-name <envName>` (and the token itself as `cliToken`); by hand, `--token-name` picks which token the plugin
2564
+ * resolves (default `HOLOCRON_READ_TOKEN`).
659
2565
  *
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.
2566
+ * With no layer the token is only described. When the CLI passes `--layer` (because `--environment` named `ci`, `dev` or
2567
+ * `local`), the results are judged against what that token is meant to carry in that layer (the plugin's `tokens`
2568
+ * declaration, read with `tokenExpectations()`) and shown in two groups, what it should have and what it should not,
2569
+ * where a missing or extra permission fails.
664
2570
  */
2571
+ function tokenProbe(ctx) {
2572
+ return {
2573
+ 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.",
2574
+ writes: false,
2575
+ acceptsToken: true,
2576
+ async run(probe) {
2577
+ const { layer, tokenName } = parseTokenArgs(probe.args ?? []);
2578
+ const envName = tokenName ?? DEFAULT_TOKEN;
2579
+ const token = ctx.resolve(envName);
2580
+ if (token === void 0) {
2581
+ probe.say({
2582
+ status: "fail",
2583
+ label: envName,
2584
+ detail: `not a GitHub token; use one of: ${ctx.tokenNames.join(", ")}`
2585
+ });
2586
+ return;
2587
+ }
2588
+ probe.secret(token);
2589
+ let identity;
2590
+ try {
2591
+ identity = await get(ctx, token, "/user");
2592
+ } catch (err) {
2593
+ probe.say({
2594
+ status: "fail",
2595
+ label: "token",
2596
+ detail: errorMessage(err)
2597
+ });
2598
+ return;
2599
+ }
2600
+ if (identity.status === 401) {
2601
+ probe.say({
2602
+ status: "fail",
2603
+ label: "token",
2604
+ detail: "rejected by GitHub (401): expired, revoked or not a token"
2605
+ });
2606
+ return;
2607
+ }
2608
+ const scopes = identity.headers.get("x-oauth-scopes");
2609
+ probe.say({
2610
+ status: "ok",
2611
+ label: "token",
2612
+ 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`
2613
+ });
2614
+ const declared = layer ? tokenExpectations(tokens, {
2615
+ layer,
2616
+ envName
2617
+ })[0] : void 0;
2618
+ if (layer && !declared) probe.say({
2619
+ status: "info",
2620
+ label: layer,
2621
+ detail: "no expectations are declared for this token there, so it is only described"
2622
+ });
2623
+ const rules = declared?.rules ?? {};
2624
+ const names = declared ? Object.keys(rules) : Object.keys(PERMISSIONS);
2625
+ const tried = [];
2626
+ for (const permission of names) tried.push({
2627
+ label: PERMISSIONS[permission].label,
2628
+ permission,
2629
+ outcome: await reach(ctx, token, permission)
2630
+ });
2631
+ if (!declared) {
2632
+ for (const t of tried) probe.say(rowFor(t, void 0));
2633
+ return;
2634
+ }
2635
+ for (const [heading, rule] of [["Should have", "required"], ["Should not have", "absent"]]) {
2636
+ const inGroup = tried.filter((t) => rules[t.permission] === rule);
2637
+ if (inGroup.length === 0) continue;
2638
+ probe.say({
2639
+ status: "heading",
2640
+ label: heading
2641
+ });
2642
+ for (const t of inGroup) probe.say(rowFor(t, rule));
2643
+ }
2644
+ }
2645
+ };
2646
+ }
2647
+ // src/token-resolvers.ts
2648
+ /** Each token's resolver by its environment variable (`HOLOCRON_ADMIN_TOKEN`), which is what `--token-name` carries. */
2649
+ const TOKEN_RESOLVERS = {
2650
+ HOLOCRON_READ_TOKEN: resolveReadToken,
2651
+ HOLOCRON_ISSUES_TOKEN: resolveIssuesToken,
2652
+ HOLOCRON_SYNC_TOKEN: resolveSyncToken,
2653
+ HOLOCRON_RELEASE_TOKEN: resolveReleaseToken,
2654
+ HOLOCRON_ADMIN_TOKEN: resolveAdminToken,
2655
+ HOLOCRON_SECRETS_TOKEN: resolveSecretsToken,
2656
+ HOLOCRON_DEPLOY_TOKEN: resolveDeployToken,
2657
+ HOLOCRON_USER_SYNC_TOKEN: resolveUserSyncToken,
2658
+ HOLOCRON_ORG_TOKEN: resolveOrgToken
2659
+ };
2660
+ // src/verify-token.ts
2661
+ /** Checks a token against `GET /user` and returns who it belongs to, or why it failed. */
665
2662
  async function verifyToken(token, opts = {}) {
666
2663
  const client = createGitHubClient({
667
2664
  token,
@@ -669,49 +2666,61 @@ async function verifyToken(token, opts = {}) {
669
2666
  fetch: opts.fetch
670
2667
  });
671
2668
  try {
672
- const me = await client.user.getCurrentUser();
2669
+ const { user: me, expiresAt } = await client.user.getCurrentUserWithExpiry();
673
2670
  return {
674
2671
  ok: true,
675
- subject: `user @ ${me.login ?? me.email ?? "unknown"}`
2672
+ subject: `user @ ${me.login ?? me.email ?? "unknown"}`,
2673
+ ...expiresAt ? { expiresAt } : {}
676
2674
  };
677
2675
  } catch (err) {
678
2676
  return {
679
2677
  ok: false,
680
- message: err instanceof Error ? err.message : String(err)
2678
+ message: errorMessage(err)
681
2679
  };
682
2680
  }
683
2681
  }
684
- //#endregion
685
- //#region src/index.ts
686
- function source(ctx, orgClient) {
2682
+ // src/index.ts
2683
+ /** Builds the `source` capability; the optional clients cover org-level and user-sync access. */
2684
+ function source(ctx, orgClient, userSyncClient) {
687
2685
  return new GitHubSource(ctx.client, {
688
2686
  repo: ctx.repo,
689
2687
  repoRoot: ctx.repoRoot,
690
2688
  orgClient,
2689
+ userSyncClient,
691
2690
  baseUrl: ctx.options.baseUrl,
692
2691
  fetch: ctx.options.fetch
693
2692
  });
694
2693
  }
695
- function secrets(ctx) {
696
- return new GitHubSecrets(ctx.client, { repo: ctx.repo });
2694
+ /** Builds the `secrets` capability; the optional client handles organization secrets. */
2695
+ function secrets(ctx, orgClient) {
2696
+ return new GitHubSecrets(ctx.client, { repo: ctx.repo }, orgClient);
697
2697
  }
2698
+ /** Builds the `environments` capability. */
698
2699
  function environments(ctx) {
699
2700
  return new GitHubEnvironments(ctx.client, { repo: ctx.repo });
700
2701
  }
2702
+ /** Builds the `ci` capability. */
701
2703
  function ci(ctx) {
702
2704
  return new GitHubCi(ctx.client, { repo: ctx.repo });
703
2705
  }
2706
+ /** Builds the `issues` capability, passing the lifecycle labels when configured. */
704
2707
  function issues(ctx) {
705
2708
  const opts = { repo: ctx.repo };
706
2709
  if (ctx.options.labels !== void 0) opts.labels = ctx.options.labels;
707
2710
  return new GitHubIssues(ctx.client, opts);
708
2711
  }
2712
+ /** Builds the `projects` capability: GitHub Projects v2 over GraphQL, with items keyed relative to the configured repo. */
2713
+ function projects(ctx) {
2714
+ return new GitHubProjects(ctx.client.graphql, { repo: ctx.repo });
2715
+ }
2716
+ /** Creates the plugin, resolving a token per capability when it is first used. */
709
2717
  function createPlugin(options) {
710
2718
  function makeCtx(resolver) {
2719
+ const token = resolver(options);
711
2720
  return {
712
2721
  options,
713
2722
  client: createGitHubClient$1({
714
- token: resolver(options),
2723
+ token,
715
2724
  baseUrl: options.baseUrl,
716
2725
  fetch: options.fetch
717
2726
  }),
@@ -719,10 +2728,45 @@ function createPlugin(options) {
719
2728
  repoRoot: options.repoRoot ?? process.cwd()
720
2729
  };
721
2730
  }
2731
+ /** A token, or undefined when that feature token is simply not configured. */
2732
+ function tryResolve(resolver) {
2733
+ try {
2734
+ return resolver(options);
2735
+ } catch (err) {
2736
+ if (err instanceof AuthError) return void 0;
2737
+ throw err;
2738
+ }
2739
+ }
2740
+ /**
2741
+ * Organization secrets need an org-resource-owner token (`github.secrets`);
2742
+ * repo and environment secrets need `github.admin`. Each scope prefers its own
2743
+ * token and falls back to the other, so a setup with only one of them keeps
2744
+ * working, and an explicit `--token` serves both. With neither configured this
2745
+ * fails exactly as the admin-token capabilities do.
2746
+ */
2747
+ function makeSecrets() {
2748
+ const secretsToken = tryResolve(resolveSecretsToken);
2749
+ const adminToken = tryResolve(resolveAdminToken);
2750
+ if (!secretsToken && !adminToken) resolveAdminToken(options);
2751
+ const clientFor = (token) => createGitHubClient$1({
2752
+ token,
2753
+ baseUrl: options.baseUrl,
2754
+ fetch: options.fetch
2755
+ });
2756
+ const repoClient = clientFor(adminToken ?? secretsToken);
2757
+ const orgClient = clientFor(secretsToken ?? adminToken);
2758
+ return secrets({
2759
+ options,
2760
+ client: repoClient,
2761
+ repo: options.repo,
2762
+ repoRoot: options.repoRoot ?? process.cwd()
2763
+ }, orgClient);
2764
+ }
722
2765
  function makeOrgClient() {
723
2766
  try {
2767
+ const token = resolveOrgToken(options);
724
2768
  return createGitHubClient$1({
725
- token: resolveOrgToken(options),
2769
+ token,
726
2770
  baseUrl: options.baseUrl,
727
2771
  fetch: options.fetch
728
2772
  });
@@ -730,21 +2774,49 @@ function createPlugin(options) {
730
2774
  return;
731
2775
  }
732
2776
  }
2777
+ /** The token for the user-sync files; undefined when it is not configured, and the org token is used instead. */
2778
+ function makeUserSyncClient() {
2779
+ const token = tryResolve(resolveUserSyncToken);
2780
+ return token ? createGitHubClient$1({
2781
+ token,
2782
+ baseUrl: options.baseUrl,
2783
+ fetch: options.fetch
2784
+ }) : void 0;
2785
+ }
733
2786
  return {
734
2787
  name: "@theholocron/holocron-plugin-github",
2788
+ probes: {
2789
+ token: tokenProbe({
2790
+ repo: options.repo,
2791
+ baseUrl: (options.baseUrl ?? "https://api.github.com").replace(/\/$/, ""),
2792
+ fetch: options.fetch ?? fetch,
2793
+ resolve: (envName) => TOKEN_RESOLVERS[envName]?.(options),
2794
+ tokenNames: Object.keys(TOKEN_RESOLVERS)
2795
+ }),
2796
+ connection: connectionProbe({
2797
+ provider: "GitHub",
2798
+ url: options.baseUrl ?? "https://api.github.com",
2799
+ fetch: options.fetch,
2800
+ token: () => resolveReadToken(options),
2801
+ verify: (token) => verifyToken(token, {
2802
+ baseUrl: options.baseUrl,
2803
+ fetch: options.fetch
2804
+ })
2805
+ })
2806
+ },
735
2807
  capabilities: {
736
- source: () => source(makeCtx(resolveAdminToken), makeOrgClient()),
2808
+ source: () => source(makeCtx(resolveAdminToken), makeOrgClient(), makeUserSyncClient()),
737
2809
  ci: () => ci(makeCtx(resolveReadToken)),
738
- secrets: () => secrets(makeCtx(resolveAdminToken)),
2810
+ secrets: () => makeSecrets(),
739
2811
  environments: () => environments(makeCtx(resolveAdminToken)),
740
- issues: () => issues(makeCtx(resolveIssuesToken))
2812
+ issues: () => issues(makeCtx(resolveIssuesToken)),
2813
+ projects: () => projects(makeCtx(resolveOrgToken))
741
2814
  }
742
2815
  };
743
2816
  }
744
2817
  /**
745
- * One-line hint printed by `holocron auth set github` when no token
2818
+ * One-line hint printed by `holocron new token github` when no token
746
2819
  * is supplied or the supplied token is rejected.
747
2820
  */
748
- 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 };
2821
+ 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>";
2822
+ 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 };