pollhook 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +251 -2
  3. package/dist/adapters/branch-protection.js +42 -0
  4. package/dist/adapters/check-run.js +23 -0
  5. package/dist/adapters/check-suite.js +23 -0
  6. package/dist/adapters/code-scanning-alert.js +34 -0
  7. package/dist/adapters/commit-comment.js +20 -0
  8. package/dist/adapters/common.js +36 -0
  9. package/dist/adapters/dependabot-alert.js +26 -0
  10. package/dist/adapters/deploy-key.js +34 -0
  11. package/dist/adapters/deployment-protection-rule.js +60 -0
  12. package/dist/adapters/deployment-review.js +48 -0
  13. package/dist/adapters/deployment-status.js +30 -0
  14. package/dist/adapters/deployment.js +20 -0
  15. package/dist/adapters/dispatch.js +53 -0
  16. package/dist/adapters/fork.js +20 -0
  17. package/dist/adapters/issue-comment.js +25 -0
  18. package/dist/adapters/issues.js +45 -0
  19. package/dist/adapters/label.js +33 -0
  20. package/dist/adapters/member.js +38 -0
  21. package/dist/adapters/membership.js +57 -0
  22. package/dist/adapters/milestone.js +48 -0
  23. package/dist/adapters/page-build.js +29 -0
  24. package/dist/adapters/pull-request-review-comment.js +30 -0
  25. package/dist/adapters/pull-request-review.js +35 -0
  26. package/dist/adapters/pull-request.js +50 -0
  27. package/dist/adapters/push.js +78 -0
  28. package/dist/adapters/refs.js +94 -0
  29. package/dist/adapters/release.js +33 -0
  30. package/dist/adapters/repository-advisory.js +27 -0
  31. package/dist/adapters/repository-ruleset.js +33 -0
  32. package/dist/adapters/repository.js +71 -0
  33. package/dist/adapters/secret-scanning-alert.js +33 -0
  34. package/dist/adapters/security-and-analysis.js +24 -0
  35. package/dist/adapters/status.js +33 -0
  36. package/dist/adapters/team.js +34 -0
  37. package/dist/adapters/vulnerability-alert.js +17 -0
  38. package/dist/adapters/workflow-job.js +33 -0
  39. package/dist/adapters/workflow-run.js +34 -0
  40. package/dist/cli/args.js +54 -0
  41. package/dist/cli/commands.js +146 -0
  42. package/dist/cli/docs.js +55 -0
  43. package/dist/cli/format.js +23 -0
  44. package/dist/cli/rpc.js +57 -0
  45. package/dist/cli/spec.js +86 -0
  46. package/dist/cli/usage.js +7 -0
  47. package/dist/cli.js +33 -0
  48. package/dist/config/tuning.js +47 -0
  49. package/dist/config.js +125 -0
  50. package/dist/daemon/context.js +1 -0
  51. package/dist/daemon/handlers.js +102 -0
  52. package/dist/daemon/runtime.js +71 -0
  53. package/dist/daemon/waiter.js +48 -0
  54. package/dist/daemon/watch.js +27 -0
  55. package/dist/daemon.js +83 -0
  56. package/dist/db/cursors.js +16 -0
  57. package/dist/db/deliveries.js +55 -0
  58. package/dist/db/durations.js +36 -0
  59. package/dist/db/schema.js +40 -0
  60. package/dist/db/snapshots.js +36 -0
  61. package/dist/db/store.js +71 -0
  62. package/dist/db.js +1 -0
  63. package/dist/delivery.js +57 -0
  64. package/dist/github.js +175 -0
  65. package/dist/poller/refs.js +36 -0
  66. package/dist/poller/schedule.js +28 -0
  67. package/dist/poller/status.js +33 -0
  68. package/dist/poller.js +160 -0
  69. package/dist/registry.js +86 -0
  70. package/dist/types.js +1 -0
  71. package/dist/util.js +45 -0
  72. package/dist/waits.js +114 -0
  73. package/package.json +39 -4
@@ -0,0 +1,33 @@
1
+ import { sha256 } from "../util.js";
2
+ import { observe, repoAndSender } from "./common.js";
3
+ function actionFor(previous, current) {
4
+ if (!previous)
5
+ return current.draft ? "created" : "published";
6
+ if (previous.draft === true && current.draft === false)
7
+ return "published";
8
+ if (previous.prerelease === false && current.prerelease === true)
9
+ return "prereleased";
10
+ if (previous.prerelease === true && current.prerelease === false)
11
+ return "released";
12
+ return "edited";
13
+ }
14
+ export const release = {
15
+ name: "release",
16
+ intervalFloorMs: 60_000,
17
+ async poll(ctx) {
18
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/releases?per_page=30`, {
19
+ etagKey: `releases:${ctx.repo}`,
20
+ });
21
+ if (result.notModified || !result.data)
22
+ return;
23
+ const meta = await repoAndSender(ctx);
24
+ for (const item of result.data) {
25
+ const state = `${item.draft}:${item.prerelease}:${item.published_at}:${item.tag_name}:${sha256(`${item.name ?? ""}\n${item.body ?? ""}`)}`;
26
+ const { changed, prev } = observe(ctx, "release", String(item.id), state, item);
27
+ if (!changed)
28
+ continue;
29
+ const action = actionFor(prev?.data, item);
30
+ ctx.emit("release", action, String(item.id), { action, release: item, repository: meta.repository, sender: meta.sender }, `${state}:${action}`);
31
+ }
32
+ },
33
+ };
@@ -0,0 +1,27 @@
1
+ import { observe, repoAndSender } from "./common.js";
2
+ export const repositoryAdvisory = {
3
+ name: "repository_advisory",
4
+ intervalFloorMs: 300_000,
5
+ async poll(ctx) {
6
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/security-advisories?per_page=100`, {
7
+ etagKey: `advisories:${ctx.repo}`,
8
+ });
9
+ if (result.notModified || !result.data)
10
+ return;
11
+ const meta = await repoAndSender(ctx);
12
+ for (const advisory of result.data) {
13
+ const key = String(advisory.ghsa_id);
14
+ const state = `${advisory.state}:${advisory.updated_at}:${advisory.severity ?? ""}`;
15
+ const { changed, prev } = observe(ctx, "repository_advisory", key, state, advisory);
16
+ if (!changed)
17
+ continue;
18
+ const action = !prev ? "published" : advisory.state === "closed" ? "closed" : "updated";
19
+ ctx.emit("repository_advisory", action, key, {
20
+ action,
21
+ repository_advisory: advisory,
22
+ repository: meta.repository,
23
+ sender: meta.sender,
24
+ }, `${state}:${action}`);
25
+ }
26
+ },
27
+ };
@@ -0,0 +1,33 @@
1
+ import { sha256 } from "../util.js";
2
+ import { observe, repoAndSender } from "./common.js";
3
+ const DELETED = "deleted";
4
+ function stateFor(ruleset) {
5
+ return sha256(JSON.stringify(ruleset));
6
+ }
7
+ export const repositoryRuleset = {
8
+ name: "repository_ruleset",
9
+ intervalFloorMs: 300_000,
10
+ async poll(ctx) {
11
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/rulesets?per_page=100`, {
12
+ etagKey: `rulesets:${ctx.repo}`,
13
+ });
14
+ if (result.notModified || !result.data)
15
+ return;
16
+ const meta = await repoAndSender(ctx);
17
+ const current = new Set(result.data.map((ruleset) => String(ruleset.id)));
18
+ for (const ruleset of result.data) {
19
+ const state = stateFor(ruleset);
20
+ const { changed, prev } = observe(ctx, "repository_ruleset", String(ruleset.id), state, ruleset);
21
+ if (!changed)
22
+ continue;
23
+ const action = prev && prev.state !== DELETED ? "edited" : "created";
24
+ ctx.emit("repository_ruleset", action, String(ruleset.id), { action, ruleset, repository: meta.repository, sender: meta.sender }, `${state}:${action}`);
25
+ }
26
+ for (const row of ctx.db.listSnapshots(ctx.repo, "repository_ruleset")) {
27
+ if (row.state === DELETED || current.has(row.key))
28
+ continue;
29
+ ctx.db.putSnapshot(ctx.repo, "repository_ruleset", row.key, DELETED, row.data);
30
+ ctx.emit("repository_ruleset", "deleted", row.key, { action: "deleted", ruleset: row.data, repository: meta.repository, sender: meta.sender }, `deleted:${row.state}`);
31
+ }
32
+ },
33
+ };
@@ -0,0 +1,71 @@
1
+ import { sha256 } from "../util.js";
2
+ import { observe } from "./common.js";
3
+ function stateFor(repo) {
4
+ return sha256([
5
+ repo.full_name,
6
+ repo.private,
7
+ repo.visibility ?? "",
8
+ repo.description ?? "",
9
+ repo.default_branch,
10
+ repo.archived,
11
+ repo.disabled,
12
+ (repo.topics ?? []).join(","),
13
+ repo.homepage ?? "",
14
+ ].join("|"));
15
+ }
16
+ async function fetchRepo(ctx, scope) {
17
+ return ctx.gh.get(`/repos/${ctx.repo}`, { etagKey: `repo:${scope}:${ctx.repo}` });
18
+ }
19
+ export const repository = {
20
+ name: "repository",
21
+ intervalFloorMs: 60_000,
22
+ async poll(ctx) {
23
+ const result = await fetchRepo(ctx, "repository");
24
+ if (result.notModified || !result.data)
25
+ return;
26
+ const current = result.data;
27
+ const state = stateFor(current);
28
+ const { changed, prev } = observe(ctx, "repository", ctx.repo, state, current);
29
+ if (!changed)
30
+ return;
31
+ const sender = await ctx.gh.sender();
32
+ const previous = prev?.data;
33
+ const actions = [];
34
+ if (previous) {
35
+ if (previous.full_name !== current.full_name)
36
+ actions.push("renamed");
37
+ if (previous.archived !== current.archived) {
38
+ actions.push(current.archived ? "archived" : "unarchived");
39
+ }
40
+ if (previous.private !== current.private || previous.visibility !== current.visibility) {
41
+ actions.push(current.private ? "privatized" : "publicized");
42
+ }
43
+ if (previous.description !== current.description)
44
+ actions.push("edited");
45
+ }
46
+ else {
47
+ actions.push("edited");
48
+ }
49
+ for (const action of actions) {
50
+ ctx.emit("repository", action, ctx.repo, { action, repository: current, sender }, `${state}:${action}`);
51
+ }
52
+ },
53
+ };
54
+ export const publicEvent = {
55
+ name: "public",
56
+ intervalFloorMs: 60_000,
57
+ async poll(ctx) {
58
+ const result = await fetchRepo(ctx, "public");
59
+ if (result.notModified || !result.data)
60
+ return;
61
+ const current = result.data;
62
+ const state = stateFor(current);
63
+ const { changed, prev } = observe(ctx, "public", ctx.repo, state, current);
64
+ if (!changed || !prev)
65
+ return;
66
+ if (prev.data.private !== true || current.private !== false)
67
+ return;
68
+ const sender = await ctx.gh.sender();
69
+ ctx.emit("public", null, ctx.repo, { repository: current, sender }, state);
70
+ },
71
+ };
@@ -0,0 +1,33 @@
1
+ import { observeAlerts } from "./common.js";
2
+ const STATES = ["open", "resolved"];
3
+ function actionFor(previous, current) {
4
+ if (!previous)
5
+ return "created";
6
+ if (previous.state !== current.state) {
7
+ return current.state === "open" ? "reopened" : "resolved";
8
+ }
9
+ if (previous.validation_status !== current.validation_status)
10
+ return "validated";
11
+ return "edited";
12
+ }
13
+ export const secretScanningAlert = {
14
+ name: "secret_scanning_alert",
15
+ intervalFloorMs: 300_000,
16
+ async poll(ctx) {
17
+ const alerts = [];
18
+ const seen = new Set();
19
+ for (const state of STATES) {
20
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/secret-scanning/alerts?state=${state}&per_page=100`, { etagKey: `secret-scanning:${state}:${ctx.repo}` });
21
+ if (result.notModified || !result.data)
22
+ continue;
23
+ for (const alert of result.data) {
24
+ const key = String(alert.number);
25
+ if (seen.has(key))
26
+ continue;
27
+ seen.add(key);
28
+ alerts.push(alert);
29
+ }
30
+ }
31
+ await observeAlerts(ctx, "secret_scanning_alert", alerts, actionFor, (alert) => `${alert.state}:${alert.validation_status ?? ""}:${alert.updated_at}`);
32
+ },
33
+ };
@@ -0,0 +1,24 @@
1
+ import { sha256 } from "../util.js";
2
+ import { observe, repoAndSender } from "./common.js";
3
+ export const securityAndAnalysis = {
4
+ name: "security_and_analysis",
5
+ intervalFloorMs: 300_000,
6
+ async poll(ctx) {
7
+ const result = await ctx.gh.get(`/repos/${ctx.repo}`, {
8
+ etagKey: `repo:security_and_analysis:${ctx.repo}`,
9
+ });
10
+ if (result.notModified || !result.data)
11
+ return;
12
+ const current = result.data.security_and_analysis ?? {};
13
+ const state = sha256(JSON.stringify(current));
14
+ const { changed, prev } = observe(ctx, "security_and_analysis", ctx.repo, state, current);
15
+ if (!changed || !prev)
16
+ return;
17
+ const meta = await repoAndSender(ctx);
18
+ ctx.emit("security_and_analysis", null, ctx.repo, {
19
+ changes: { security_and_analysis: { from: prev.data, to: current } },
20
+ repository: meta.repository,
21
+ sender: meta.sender,
22
+ }, state);
23
+ },
24
+ };
@@ -0,0 +1,33 @@
1
+ import { observe, repoAndSender } from "./common.js";
2
+ export const commitStatus = {
3
+ name: "status",
4
+ intervalFloorMs: 30_000,
5
+ async poll(ctx) {
6
+ if (ctx.refs.length === 0)
7
+ return;
8
+ const meta = await repoAndSender(ctx);
9
+ for (const ref of ctx.refs) {
10
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/commits/${encodeURIComponent(ref)}/statuses?per_page=100`, { etagKey: `statuses:${ctx.repo}:${ref}` });
11
+ if (result.notModified || !result.data)
12
+ continue;
13
+ for (const status of result.data) {
14
+ const state = `${status.state}:${status.updated_at}`;
15
+ const { changed } = observe(ctx, "status", String(status.id), state, status);
16
+ if (!changed)
17
+ continue;
18
+ ctx.emit("status", null, String(status.id), {
19
+ id: status.id,
20
+ sha: status.sha,
21
+ state: status.state,
22
+ context: status.context,
23
+ description: status.description,
24
+ target_url: status.target_url,
25
+ created_at: status.created_at,
26
+ updated_at: status.updated_at,
27
+ repository: meta.repository,
28
+ sender: meta.sender,
29
+ }, state);
30
+ }
31
+ }
32
+ },
33
+ };
@@ -0,0 +1,34 @@
1
+ import { sha256 } from "../util.js";
2
+ import { observe } from "./common.js";
3
+ const DELETED = "deleted";
4
+ export const team = {
5
+ name: "team",
6
+ scope: "org",
7
+ intervalFloorMs: 300_000,
8
+ async poll(ctx) {
9
+ if (!ctx.org)
10
+ return;
11
+ const result = await ctx.gh.get(`/orgs/${ctx.org}/teams?per_page=100`, {
12
+ etagKey: `teams:${ctx.org}`,
13
+ });
14
+ if (result.notModified || !result.data)
15
+ return;
16
+ const sender = await ctx.gh.sender();
17
+ const organization = { login: ctx.org };
18
+ const current = new Set(result.data.map((item) => String(item.id)));
19
+ for (const item of result.data) {
20
+ const state = sha256(JSON.stringify(item));
21
+ const { changed, prev } = observe(ctx, "team", String(item.id), state, item);
22
+ if (!changed)
23
+ continue;
24
+ const action = prev && prev.state !== DELETED ? "edited" : "created";
25
+ ctx.emit("team", action, String(item.id), { action, team: item, organization, sender }, `${state}:${action}`);
26
+ }
27
+ for (const row of ctx.db.listSnapshots(ctx.repo, "team")) {
28
+ if (row.state === DELETED || current.has(row.key))
29
+ continue;
30
+ ctx.db.putSnapshot(ctx.repo, "team", row.key, DELETED, row.data);
31
+ ctx.emit("team", "deleted", row.key, { action: "deleted", team: row.data, organization, sender }, `deleted:${row.state}`);
32
+ }
33
+ },
34
+ };
@@ -0,0 +1,17 @@
1
+ import { observe, repoAndSender } from "./common.js";
2
+ export const vulnerabilityAlert = {
3
+ name: "repository_vulnerability_alert",
4
+ intervalFloorMs: 300_000,
5
+ async poll(ctx) {
6
+ const enabled = await ctx.gh.probe(`/repos/${ctx.repo}/vulnerability-alerts`);
7
+ const state = enabled ? "enabled" : "disabled";
8
+ const { changed, prev } = observe(ctx, "repository_vulnerability_alert", ctx.repo, state, {
9
+ enabled,
10
+ });
11
+ if (!changed || !prev)
12
+ return;
13
+ const meta = await repoAndSender(ctx);
14
+ const action = enabled ? "enable" : "disable";
15
+ ctx.emit("repository_vulnerability_alert", action, ctx.repo, { action, repository: meta.repository, sender: meta.sender }, state);
16
+ },
17
+ };
@@ -0,0 +1,33 @@
1
+ import { observe, repoAndSender } from "./common.js";
2
+ const MAX_ACTIVE_RUNS = 5;
3
+ export const workflowJob = {
4
+ name: "workflow_job",
5
+ intervalFloorMs: 30_000,
6
+ async poll(ctx) {
7
+ const active = ctx.db
8
+ .listSnapshots(ctx.repo, "workflow_run")
9
+ .filter((row) => row.data?.status !== "completed")
10
+ .slice(0, MAX_ACTIVE_RUNS);
11
+ if (active.length === 0)
12
+ return;
13
+ const meta = await repoAndSender(ctx);
14
+ for (const row of active) {
15
+ const runId = String(row.data?.id ?? row.key);
16
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/actions/runs/${runId}/jobs?per_page=100`, { etagKey: `jobs:${ctx.repo}:${runId}` });
17
+ if (result.notModified || !result.data)
18
+ continue;
19
+ for (const job of result.data.jobs) {
20
+ const state = `${job.run_attempt}:${job.status}:${job.conclusion}:${job.completed_at}`;
21
+ const { changed } = observe(ctx, "workflow_job", String(job.id), state, job);
22
+ if (!changed)
23
+ continue;
24
+ const action = job.status === "completed"
25
+ ? "completed"
26
+ : job.status === "in_progress"
27
+ ? "in_progress"
28
+ : "queued";
29
+ ctx.emit("workflow_job", action, String(job.id), { action, workflow_job: job, repository: meta.repository, sender: meta.sender }, state);
30
+ }
31
+ }
32
+ },
33
+ };
@@ -0,0 +1,34 @@
1
+ import { observe, repoAndSender } from "./common.js";
2
+ export const workflowRun = {
3
+ name: "workflow_run",
4
+ intervalFloorMs: 10_000,
5
+ async poll(ctx) {
6
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/actions/runs?per_page=50`, {
7
+ etagKey: `runs:${ctx.repo}`,
8
+ });
9
+ if (result.notModified || !result.data)
10
+ return;
11
+ const meta = await repoAndSender(ctx);
12
+ for (const run of result.data.workflow_runs) {
13
+ const state = `${run.run_attempt}:${run.status}:${run.conclusion}`;
14
+ if (run.status === "completed")
15
+ recordDuration(ctx, run);
16
+ const { changed } = observe(ctx, "workflow_run", String(run.id), state, run);
17
+ if (!changed)
18
+ continue;
19
+ const action = run.status === "completed"
20
+ ? "completed"
21
+ : run.status === "in_progress"
22
+ ? "in_progress"
23
+ : "requested";
24
+ ctx.emit("workflow_run", action, String(run.id), { action, workflow_run: run, repository: meta.repository, sender: meta.sender }, state);
25
+ }
26
+ },
27
+ };
28
+ function recordDuration(ctx, run) {
29
+ const start = Date.parse(run.run_started_at ?? run.created_at ?? "");
30
+ const end = Date.parse(run.updated_at ?? "");
31
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start)
32
+ return;
33
+ ctx.durations.record(ctx.repo, String(run.id), String(run.workflow_id ?? run.name ?? ""), end - start);
34
+ }
@@ -0,0 +1,54 @@
1
+ const VALUE_FLAGS = new Set([
2
+ "--config",
3
+ "--repo",
4
+ "--timeout",
5
+ "--until",
6
+ "--limit",
7
+ "--event",
8
+ "--match",
9
+ ]);
10
+ export function valueFlag(args, name) {
11
+ const index = args.indexOf(name);
12
+ return index >= 0 ? args[index + 1] : undefined;
13
+ }
14
+ export function values(args, name) {
15
+ const result = [];
16
+ for (let index = 0; index < args.length; index++) {
17
+ if (args[index] === name && args[index + 1] !== undefined)
18
+ result.push(args[index + 1]);
19
+ }
20
+ return result;
21
+ }
22
+ export function positionals(args) {
23
+ const result = [];
24
+ for (let index = 0; index < args.length; index++) {
25
+ const arg = args[index];
26
+ if (VALUE_FLAGS.has(arg)) {
27
+ index += 1;
28
+ continue;
29
+ }
30
+ if (arg.startsWith("--"))
31
+ continue;
32
+ result.push(arg);
33
+ }
34
+ return result;
35
+ }
36
+ export function parseDuration(value, fallbackMs) {
37
+ if (!value)
38
+ return fallbackMs;
39
+ const match = /^(\d+)(s|m|h)?$/.exec(value);
40
+ if (!match)
41
+ throw new Error(`invalid --timeout ${value}`);
42
+ const amount = Number(match[1]);
43
+ const unit = match[2] ?? "s";
44
+ if (unit === "h")
45
+ return amount * 3_600_000;
46
+ if (unit === "m")
47
+ return amount * 60_000;
48
+ return amount * 1000;
49
+ }
50
+ export function required(value, name) {
51
+ if (value === undefined || value === "")
52
+ throw new Error(`missing ${name}`);
53
+ return value;
54
+ }
@@ -0,0 +1,146 @@
1
+ import { parseDuration, positionals, required, valueFlag, values } from "./args.js";
2
+ import { rpc } from "./rpc.js";
3
+ import { USAGE } from "./usage.js";
4
+ const UNTIL = new Set(["merged", "closed", "reviewed", "conflict"]);
5
+ const handlers = {
6
+ status: statusCommand,
7
+ events: eventsCommand,
8
+ deliveries: deliveriesCommand,
9
+ run: runCommand,
10
+ checks: checksCommand,
11
+ pr: prCommand,
12
+ pages: pagesCommand,
13
+ wait: waitCommand,
14
+ cleanup: cleanupCommand,
15
+ poke: pokeCommand,
16
+ };
17
+ export async function dispatchCommand(config, command, args) {
18
+ const handler = handlers[command];
19
+ if (!handler) {
20
+ process.stderr.write(`unknown command ${command}\n\n${USAGE}`);
21
+ return 2;
22
+ }
23
+ return handler(config, args);
24
+ }
25
+ async function statusCommand(config, args) {
26
+ const body = unwrap(await rpc(config, { op: "status" }));
27
+ if (args.includes("--json"))
28
+ process.stdout.write(`${JSON.stringify(body)}\n`);
29
+ else
30
+ printStatus(body);
31
+ return 0;
32
+ }
33
+ async function eventsCommand(config) {
34
+ const body = unwrap(await rpc(config, { op: "events" }));
35
+ for (const event of body) {
36
+ process.stdout.write(`${event.event}\t${event.intervalFloorSeconds}s\n`);
37
+ }
38
+ return 0;
39
+ }
40
+ async function deliveriesCommand(config, args) {
41
+ const body = unwrap(await rpc(config, {
42
+ op: "deliveries",
43
+ limit: Number(valueFlag(args, "--limit") ?? 20),
44
+ repo: valueFlag(args, "--repo"),
45
+ }));
46
+ for (const delivery of body)
47
+ process.stdout.write(`${JSON.stringify(delivery)}\n`);
48
+ return 0;
49
+ }
50
+ async function runCommand(config, args) {
51
+ const id = required(positionals(args)[0], "run id");
52
+ const request = { kind: "run", repo: repoFor(config, args), id };
53
+ return finishWait(await waitFor(config, request, args));
54
+ }
55
+ async function checksCommand(config, args) {
56
+ const pr = Number(required(positionals(args)[0], "pull request number"));
57
+ const request = { kind: "checks", repo: repoFor(config, args), pr };
58
+ return finishWait(await waitFor(config, request, args));
59
+ }
60
+ async function prCommand(config, args) {
61
+ const pr = Number(required(positionals(args)[0], "pull request number"));
62
+ const request = {
63
+ kind: "pr",
64
+ repo: repoFor(config, args),
65
+ pr,
66
+ until: untilFlag(args),
67
+ };
68
+ return finishWait(await waitFor(config, request, args));
69
+ }
70
+ async function pagesCommand(config, args) {
71
+ const sha = required(positionals(args)[0], "commit sha");
72
+ const request = { kind: "pages", repo: repoFor(config, args), sha };
73
+ return finishWait(await waitFor(config, request, args));
74
+ }
75
+ async function waitCommand(config, args) {
76
+ const event = valueFlag(args, "--event");
77
+ if (!event)
78
+ throw new Error("--event is required");
79
+ const request = {
80
+ kind: "event",
81
+ repo: valueFlag(args, "--repo"),
82
+ event,
83
+ match: parseMatches(args),
84
+ };
85
+ return finishWait(await waitFor(config, request, args));
86
+ }
87
+ async function pokeCommand(config, args) {
88
+ unwrap(await rpc(config, { op: "poke", repo: valueFlag(args, "--repo") }));
89
+ return 0;
90
+ }
91
+ function cleanupCommand() {
92
+ process.stdout.write("pollhook creates no GitHub webhooks; nothing to clean up\n");
93
+ return Promise.resolve(0);
94
+ }
95
+ function untilFlag(args) {
96
+ const until = valueFlag(args, "--until");
97
+ if (!until || !UNTIL.has(until)) {
98
+ throw new Error("--until must be one of merged, closed, reviewed, conflict");
99
+ }
100
+ return until;
101
+ }
102
+ function parseMatches(args) {
103
+ const match = {};
104
+ for (const pair of values(args, "--match")) {
105
+ const [key, ...rest] = pair.split("=");
106
+ if (!key || rest.length === 0)
107
+ throw new Error(`--match must look like key=value, got ${pair}`);
108
+ match[key] = rest.join("=");
109
+ }
110
+ return match;
111
+ }
112
+ async function waitFor(config, request, args) {
113
+ return rpc(config, {
114
+ op: "wait",
115
+ request,
116
+ timeoutMs: parseDuration(valueFlag(args, "--timeout"), 30 * 60_000),
117
+ });
118
+ }
119
+ function finishWait(response) {
120
+ process.stdout.write(`${JSON.stringify(unwrap(response))}\n`);
121
+ return response.exitCode ?? 2;
122
+ }
123
+ function unwrap(response) {
124
+ if (!response.ok)
125
+ throw new Error(response.error ?? "request failed");
126
+ return response.body;
127
+ }
128
+ function repoFor(config, args) {
129
+ const explicit = valueFlag(args, "--repo");
130
+ if (explicit)
131
+ return explicit;
132
+ if (config.repos.length === 1)
133
+ return config.repos[0].repo;
134
+ throw new Error("multiple repositories configured: pass --repo");
135
+ }
136
+ function printStatus(body) {
137
+ for (const repo of body.repos) {
138
+ const error = repo.lastError ? ` error=${repo.lastError}` : "";
139
+ const degraded = repo.degraded?.length
140
+ ? ` degraded=${repo.degraded.map((item) => item.event).join(",")}`
141
+ : "";
142
+ process.stdout.write(`${repo.repo} events=${repo.events.length} last_poll=${repo.lastPollAt ?? "-"} next_poll=${repo.nextPollAt ?? "-"} last_event=${repo.lastEventAt ?? "-"}${error}${degraded}\n`);
143
+ }
144
+ process.stdout.write(`quota ${body.quota.remaining}/${body.quota.limit} remaining, resets ${body.quota.resetAt ?? "-"}\n`);
145
+ process.stdout.write(`deliveries ${body.deliveries}, waiters ${body.waiters}, pid ${body.pid}\n`);
146
+ }
@@ -0,0 +1,55 @@
1
+ import { COMMANDS, EXIT_CODES, invocation } from "./spec.js";
2
+ export const START = "<!-- cli:start -->";
3
+ export const END = "<!-- cli:end -->";
4
+ function cell(text) {
5
+ return text.replaceAll("|", "\\|");
6
+ }
7
+ export function cliMarkdown() {
8
+ const lines = [START, "", "| Command | What it does |", "| --- | --- |"];
9
+ for (const command of COMMANDS) {
10
+ lines.push(`| \`${cell(invocation(command))}\` | ${cell(command.summary)} |`);
11
+ }
12
+ lines.push("", "Flags:", "");
13
+ for (const command of COMMANDS) {
14
+ if (!command.flags?.length)
15
+ continue;
16
+ lines.push(`- \`pollhook ${command.name}\`: ${command.flags.map((flag) => `\`${flag.flag}\` ${flag.description}`).join("; ")}`);
17
+ }
18
+ lines.push("", `Exit codes: ${EXIT_CODES.map((code) => `\`${code.flag}\` ${code.description}`).join(", ")}.`, "", END);
19
+ return lines.join("\n");
20
+ }
21
+ export function replaceSection(readme, block) {
22
+ const start = readme.indexOf(START);
23
+ const end = readme.indexOf(END);
24
+ if (start < 0 || end < start)
25
+ throw new Error(`README is missing the ${START} ... ${END} markers`);
26
+ return `${readme.slice(0, start)}${block}${readme.slice(end + END.length)}`;
27
+ }
28
+ export const TOC_START = "<!-- toc:start -->";
29
+ export const TOC_END = "<!-- toc:end -->";
30
+ export function tocMarkdown(readme) {
31
+ const lines = [TOC_START, ""];
32
+ for (const heading of readme.matchAll(/^## (.+)$/gm)) {
33
+ const title = heading[1].trim();
34
+ if (title.toLowerCase() === "table of contents")
35
+ continue;
36
+ lines.push(`1. [${title}](#${slug(title)})`);
37
+ }
38
+ lines.push("", TOC_END);
39
+ return lines.join("\n");
40
+ }
41
+ function slug(title) {
42
+ return title
43
+ .toLowerCase()
44
+ .replace(/[^\w\s-]/g, "")
45
+ .trim()
46
+ .replace(/\s+/g, "-");
47
+ }
48
+ export function replaceToc(readme) {
49
+ const start = readme.indexOf(TOC_START);
50
+ const end = readme.indexOf(TOC_END);
51
+ if (start < 0 || end < start)
52
+ throw new Error(`README is missing the ${TOC_START} ... ${TOC_END} markers`);
53
+ const block = tocMarkdown(readme);
54
+ return `${readme.slice(0, start)}${block}${readme.slice(end + TOC_END.length)}`;
55
+ }
@@ -0,0 +1,23 @@
1
+ import { formatDuration } from "../util.js";
2
+ const NAME_LIMIT = 40;
3
+ export function brief(delivery) {
4
+ const time = new Date(delivery.createdAt).toTimeString().slice(0, 8);
5
+ return [time, delivery.repo, delivery.event, delivery.action, delivery.key, ...details(delivery)]
6
+ .filter(Boolean)
7
+ .join(" ");
8
+ }
9
+ function details(delivery) {
10
+ const subject = (delivery.payload?.[delivery.event] ?? {});
11
+ const name = truncate(subject.name ?? subject.display_title ?? subject.title);
12
+ const conclusion = delivery.action === "completed" ? subject.conclusion : null;
13
+ const started = subject.run_started_at ?? subject.started_at;
14
+ const elapsed = delivery.action === "in_progress" && typeof started === "string"
15
+ ? formatDuration(Date.now() - Date.parse(started))
16
+ : null;
17
+ return [name, conclusion, elapsed].filter((value) => typeof value === "string" && value.length > 0);
18
+ }
19
+ function truncate(value) {
20
+ if (typeof value !== "string" || value.length === 0)
21
+ return null;
22
+ return value.length > NAME_LIMIT ? `${value.slice(0, NAME_LIMIT - 1)}…` : value;
23
+ }