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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Radomir Wojtera
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,252 @@
1
- # Temporary Holding Version
1
+ # pollhook
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ GitHub webhook deliveries without webhooks: a local listener that rebuilds them
4
+ from the REST API.
5
+
6
+ pollhook runs as a daemon. It polls the GitHub REST API for the repositories,
7
+ organisations and event types you subscribe to, turns observed state changes into
8
+ GitHub-shaped deliveries, and POSTs them to a local endpoint. A handler written against GitHub's
9
+ webhook contract keeps working; the delivery was reconstructed, not pushed.
10
+
11
+ ## Table of contents
12
+
13
+ <!-- toc:start -->
14
+
15
+ 1. [Why](#why)
16
+ 1. [How it works](#how-it-works)
17
+ 1. [Running](#running)
18
+ 1. [Service](#service)
19
+ 1. [CLI reference](#cli-reference)
20
+ 1. [Reading status](#reading-status)
21
+ 1. [Scheduling](#scheduling)
22
+ 1. [Fidelity](#fidelity)
23
+ 1. [Prior art](#prior-art)
24
+ 1. [Guarantees](#guarantees)
25
+ 1. [Status](#status)
26
+ 1. [Layout](#layout)
27
+ 1. [Name](#name)
28
+
29
+ <!-- toc:end -->
30
+
31
+ ## Why
32
+
33
+ Agents waiting on CI loop `gh run watch`, `gh pr checks` and `gh pr view`. Every
34
+ waiter runs its own loop, burns API calls and machine time, and only learns about
35
+ an event if it was already watching when the event fired. Nothing local can answer
36
+ "tell me when this run finishes, and exit with the right code".
37
+
38
+ The options that exist today all have a catch:
39
+
40
+ 1. `gh webhook forward` and smee.io deliver real events, but need a webhook on the
41
+ repository, admin rights to create it, and a process that is running while the
42
+ event fires. The webhook stays behind in repository settings (unverified).
43
+ 2. GitHub App delivery polling (`/app/hook/deliveries`) gives real payloads, but
44
+ needs an App installed on the repository and only covers a short retention
45
+ window. The App receives events whether or not anyone is listening.
46
+ 3. GitHub Event Streams (`gh event listen`) is a waitlisted preview and answers
47
+ `403 Event subscriptions are not enabled for this account` here.
48
+
49
+ pollhook takes the fourth path: a read-only token, the REST API, and a local
50
+ delivery contract. No admin rights, no public URL, no App, and a wait that returns
51
+ immediately for something that already finished.
52
+
53
+ ## How it works
54
+
55
+ 1. One config file lists the repositories and organisations, the event names to
56
+ subscribe to, and the delivery targets.
57
+ 2. Every event has an adapter: a REST endpoint to read, a cursor field to order
58
+ by, and a mapping from the REST resource to the webhook payload.
59
+ 3. The scheduler polls with `If-None-Match`. A `304` costs nothing against the
60
+ rate limit, so a quiet repository is close to free.
61
+ 4. An observed change becomes a delivery carrying `X-GitHub-Event`,
62
+ `X-GitHub-Delivery`, and `X-Hub-Signature-256` when a secret is configured.
63
+ Deliveries are at-least-once; a fingerprint store drops duplicates. A failing
64
+ POST target is retried five times with exponential backoff, while a 4xx answer
65
+ other than 408 or 429 is treated as permanent. The first
66
+ poll of each event records state without delivering, so a cold start never
67
+ replays history.
68
+ 5. Consumers pick their shape: an optional loopback POST target, a JSONL stream
69
+ (`pollhook emit`), or the wait commands, which block and exit `0` success,
70
+ `1` failure, `8` timeout, `2` bad arguments or daemon unreachable.
71
+
72
+ The REST resource is the source, not `/repos/{owner}/{repo}/events`. That endpoint
73
+ is a lagging feed of repository activity, not a queryable state log, and it cannot
74
+ report the current status of a run or a check.
75
+
76
+ ## Running
77
+
78
+ 1. `npm install && npm run build`, then `npm link` to put `pollhook` on PATH.
79
+ Node 24 is required; `.mise.toml` pins 24.22.3.
80
+ 2. Copy `pollhook.example.json` to `~/.config/pollhook/config.json` and set the
81
+ repository and events. An optional `orgs` array covers org-level events;
82
+ `team` and `membership` are implemented today. `intervals` sets a poll interval
83
+ per event, globally or per repository, and `strategies` picks `fixed` or
84
+ `while-active` per event. A repository's own value wins over the global one,
85
+ which wins over the target's `intervalSeconds`; the adapter floor always wins
86
+ last, so nothing polls faster than the API tolerates.
87
+ 3. Run `pollhook daemon`. The token comes from `POLLHOOK_TOKEN`, then your
88
+ `gh auth login`, then `GH_TOKEN`/`GITHUB_TOKEN`. The gh login wins over ambient
89
+ tokens because a `GITHUB_TOKEN` in the environment often belongs to something
90
+ else.
91
+ 4. The daemon reloads `config.json` on `SIGHUP` and when the file changes, so a
92
+ config edit keeps the socket and every open `emit` stream alive. A broken edit
93
+ is reported as `configError` in `status` and the previous config keeps running.
94
+ 5. Use `pollhook run <id>`, `pollhook checks <pr>`, `pollhook pr <n> --until
95
+ merged`, `pollhook pages <sha>` and `pollhook status`.
96
+ 6. `pollhook poke [--repo OWNER/NAME]` polls now instead of waiting out the
97
+ interval, which is how a run you just started shows up within a second.
98
+ 7. `pollhook emit --brief` prints one line per delivery: time, repo, event,
99
+ action, key, then the run or check name, the conclusion when it finished, and
100
+ the elapsed time while it runs. Full JSON stays the default.
101
+
102
+ The daemon serves consumers over a unix socket at
103
+ `$XDG_RUNTIME_DIR/pollhook.sock`, so it opens no port. An optional `deliver.url`
104
+ receives GitHub-shaped POSTs and must be a loopback address.
105
+
106
+ The published package ships `dist/` and a `pollhook` bin, so `npx pollhook` works
107
+ once the package is on npm.
108
+
109
+ ## Service
110
+
111
+ 1. `npm link` so `~/.local/bin/pollhook` exists. If your npm global prefix lives
112
+ elsewhere, symlink the bin into `~/.local/bin` or edit `ExecStart`.
113
+ 2. Copy `contrib/pollhook.service` to `~/.config/systemd/user/`.
114
+ 3. `systemctl --user daemon-reload && systemctl --user enable --now pollhook`.
115
+ 4. `journalctl --user -u pollhook -f` to watch it.
116
+
117
+ The unit keeps the home read-only except `~/.local/state`, and puts the mise shims
118
+ on `PATH` so `node` and `gh auth token` resolve.
119
+
120
+ ## CLI reference
121
+
122
+ <!-- cli:start -->
123
+
124
+ | Command | What it does |
125
+ | --- | --- |
126
+ | `pollhook daemon [--config PATH]` | Polls GitHub and serves consumers over a unix socket. |
127
+ | `pollhook status [--json]` | Shows last and next poll per target, quota, degraded adapters and waiters. |
128
+ | `pollhook events` | Lists every implemented event with its polling floor. |
129
+ | `pollhook deliveries [--limit N] [--repo OWNER/NAME]` | Prints recent deliveries from the state store. |
130
+ | `pollhook emit [--brief]` | Streams deliveries as JSON lines until stopped. |
131
+ | `pollhook run <run-id> [--repo OWNER/NAME] [--timeout 30m]` | Waits for a workflow run and exits with its conclusion. |
132
+ | `pollhook checks <pr> [--repo OWNER/NAME] [--timeout 30m]` | Waits for every check on a pull request's head commit. |
133
+ | `pollhook pr <pr> --until merged\|closed\|reviewed\|conflict [--repo OWNER/NAME] [--timeout 30m]` | Waits for a pull request to reach a state. |
134
+ | `pollhook pages <sha> [--repo OWNER/NAME] [--timeout 30m]` | Waits for the Pages build of a commit. |
135
+ | `pollhook wait --event EVENT [--match key=value]... [--repo OWNER/NAME] [--timeout 30m]` | Waits for any delivery matching an event and optional field matches. |
136
+ | `pollhook poke [--repo OWNER/NAME]` | Polls now instead of waiting out the interval. |
137
+ | `pollhook cleanup` | Reports that pollhook creates no webhooks. |
138
+
139
+ Flags:
140
+
141
+ - `pollhook daemon`: `--config PATH` config file, default ~/.config/pollhook/config.json
142
+ - `pollhook status`: `--json` prints the raw status body
143
+ - `pollhook deliveries`: `--limit N` how many to print, default 20; `--repo OWNER/NAME` targets one repository
144
+ - `pollhook emit`: `--brief` one human line per delivery instead of the payload
145
+ - `pollhook run`: `--repo OWNER/NAME` targets one repository; `--timeout 30m` how long to wait
146
+ - `pollhook checks`: `--repo OWNER/NAME` targets one repository; `--timeout 30m` how long to wait
147
+ - `pollhook pr`: `--until STATE` merged, closed, reviewed or conflict; `--repo OWNER/NAME` targets one repository; `--timeout 30m` how long to wait
148
+ - `pollhook pages`: `--repo OWNER/NAME` targets one repository; `--timeout 30m` how long to wait
149
+ - `pollhook wait`: `--event EVENT` event name, see `pollhook events`; `--match key=value` repeatable top-level field match; `--repo OWNER/NAME` targets one repository; `--timeout 30m` how long to wait
150
+ - `pollhook poke`: `--repo OWNER/NAME` targets one repository
151
+
152
+ Exit codes: `0` success, `1` the waited-on run, check set or pull request failed, `8` timeout, `2` bad input or daemon unreachable.
153
+
154
+ <!-- cli:end -->
155
+
156
+ ## Reading status
157
+
158
+ `pollhook status` prints one line per target:
159
+
160
+ owner/repo events=33 last_poll=... next_poll=... last_event=...
161
+ quota 4869/5000 remaining, resets ...
162
+ deliveries 60, waiters 0, pid 1234
163
+
164
+ 1. `last_poll` is the last completed round; `next_poll` is the earliest adapter
165
+ due for that target.
166
+ 2. `last_event` is the last delivery for the target.
167
+ 3. `error=` is a transient failure and disappears after a clean round.
168
+ 4. `degraded=` lists adapters that answered 403 or 404. They retry after an hour
169
+ and drop off the list when a retry succeeds.
170
+ 5. `status --json` prints the same body with the per-adapter degraded reasons.
171
+
172
+ ## Scheduling
173
+
174
+ Each adapter polls on its resolved interval, never faster than its own floor:
175
+ the repository's `intervals` entry, then the global one, then the target's
176
+ `intervalSeconds`. With `strategies: { "workflow_run": "while-active" }` the daemon
177
+ keeps the last twenty durations of every workflow and polls `workflow_run` every
178
+ 30 seconds instead of the configured interval while every running workflow is
179
+ still under half its typical duration, so a finished run is reported within one
180
+ slow round and a quiet repository still gets the fast interval. The default
181
+ strategy is `fixed`. Durations come from runs already fetched, so the estimate
182
+ costs no requests. When quota is short the daemon multiplies every interval by 3
183
+ under 15% remaining and by 10 under 5%, and a `Retry-After` on a 403 or 429 is
184
+ honoured before the next attempt.
185
+
186
+ ## Fidelity
187
+
188
+ Polling sees state; webhooks are a history of transitions. Four consequences, all
189
+ of them permanent:
190
+
191
+ 1. Transitions that leave no state behind are invisible: an object created and
192
+ deleted between two polls, a `repository_dispatch` call, a review submitted
193
+ and dismissed before the next poll.
194
+ 2. Intermediate states can be coalesced. A run may go from `queued` straight to
195
+ `completed` if it is short, and you will see one delivery instead of three.
196
+ 3. `sender` is the authenticated user or `ghost`, not necessarily the person who
197
+ acted. The REST API rarely records the actor.
198
+ 4. Some events exist only for GitHub Apps (`installation*`,
199
+ `github_app_authorization`) and some state is GraphQL-only (projects,
200
+ discussions).
201
+
202
+ Per-event fidelity is documented in [docs/events.md](docs/events.md): which fields
203
+ are guaranteed, which are inferred, and which transitions are undetectable.
204
+
205
+ ## Prior art
206
+
207
+ 1. `gh webhook forward` / smee.io: real deliveries over a relay. Needs a webhook,
208
+ has no history, and has no wait primitive.
209
+ 2. `gr2m/github-app-webhook-relay-polling`: polls an App's deliveries endpoint.
210
+ Exact payloads, but needs an App and only sees the retention window.
211
+ 3. `daveseco7/polling-to-webhook`: generic poll-and-POST. No GitHub payload
212
+ semantics, no cursor, no dedupe.
213
+ 4. Probot `receive`: replays saved payloads. Not live.
214
+ 5. `github-event-poller`, Huginn and n8n recipes over `/users/{username}/events`:
215
+ convenient ETag polling, but the feed carries 16 activity types and none of them
216
+ is CI, checks, Pages or deployments, and GitHub's own docs warn that event
217
+ latency is "anywhere from 30s to 6h". It can accelerate activity events; it
218
+ cannot answer a wait.
219
+
220
+ The bet here is narrower than "emulate GitHub": a read-only token is the lowest
221
+ possible bar, and a wait command with meaningful exit codes is the contract an
222
+ agent actually needs. Event synthesis is the mechanism, not the product.
223
+
224
+ ## Guarantees
225
+
226
+ 1. Read-only. pollhook never sends `POST`, `PUT`, `PATCH` or `DELETE` to GitHub.
227
+ 2. The control socket is a unix socket, and `deliver.url` must be loopback.
228
+ Nothing listens on a network interface.
229
+ 3. Deliveries are verifiable: with a secret configured, `X-Hub-Signature-256` is
230
+ a real HMAC of the body, so consumers validate exactly as they do for GitHub.
231
+ 4. A waiting command reads current state before it subscribes, so a run that
232
+ finished before the command started returns instantly.
233
+ 5. Payload compatibility is per field and documented, not byte-for-byte. Unknown
234
+ fields pass through when the REST object carries them.
235
+
236
+ ## Status
237
+
238
+ P0, P1, most of P2 and P3, and the deployment and protection events are
239
+ implemented and covered by 141 tests. What shipped and what comes next is in
240
+ [PROGRESS.md](PROGRESS.md); phases and acceptance criteria are in
241
+ [the issue tracker](https://github.com/radomir-dev/pollhook/issues).
242
+
243
+ ## Layout
244
+
245
+ 1. `PROGRESS.md`: what each change did, what was measured and how it was verified.
246
+ 2. `docs/events.md`: the event catalog with REST source, cursor, fidelity and phase.
247
+ 3. `pollhook.example.json`: a starting config.
248
+ 4. `contrib/pollhook.service`: the systemd user unit.
249
+
250
+ ## Name
251
+
252
+ poll + hook. The npm name is free, and no active project uses it.
@@ -0,0 +1,42 @@
1
+ import { isStatus, sha256 } from "../util.js";
2
+ import { observe, repoAndSender } from "./common.js";
3
+ const MAX_BRANCHES = 20;
4
+ async function fetchProtection(ctx, branch) {
5
+ try {
6
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/branches/${encodeURIComponent(branch)}/protection`);
7
+ return result.data ?? null;
8
+ }
9
+ catch (error) {
10
+ if (isStatus(error, 404) || isStatus(error, 403))
11
+ return null;
12
+ throw error;
13
+ }
14
+ }
15
+ export const branchProtection = {
16
+ name: "branch_protection_configuration",
17
+ intervalFloorMs: 300_000,
18
+ async poll(ctx) {
19
+ const branches = await ctx.gh.get(`/repos/${ctx.repo}/branches?per_page=100`, {
20
+ etagKey: `branches:protection:${ctx.repo}`,
21
+ });
22
+ if (branches.notModified || !branches.data)
23
+ return;
24
+ const meta = await repoAndSender(ctx);
25
+ for (const branch of branches.data.slice(0, MAX_BRANCHES)) {
26
+ const protection = await fetchProtection(ctx, branch.name);
27
+ if (protection === null)
28
+ continue;
29
+ const state = sha256(JSON.stringify(protection));
30
+ const { changed, prev } = observe(ctx, "branch_protection_configuration", branch.name, state, protection);
31
+ if (!changed || !prev)
32
+ continue;
33
+ ctx.emit("branch_protection_configuration", "edited", branch.name, {
34
+ action: "edited",
35
+ branch: branch.name,
36
+ changes: { branch_protection: { from: prev.data, to: protection } },
37
+ repository: meta.repository,
38
+ sender: meta.sender,
39
+ }, state);
40
+ }
41
+ },
42
+ };
@@ -0,0 +1,23 @@
1
+ import { observe, repoAndSender } from "./common.js";
2
+ export const checkRun = {
3
+ name: "check_run",
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)}/check-runs?per_page=100`, { etagKey: `check-runs:${ctx.repo}:${ref}` });
11
+ if (result.notModified || !result.data)
12
+ continue;
13
+ for (const run of result.data.check_runs) {
14
+ const state = `${run.status}:${run.conclusion}:${run.completed_at}`;
15
+ const { changed } = observe(ctx, "check_run", String(run.id), state, run);
16
+ if (!changed)
17
+ continue;
18
+ const action = run.status === "completed" ? "completed" : "created";
19
+ ctx.emit("check_run", action, String(run.id), { action, check_run: run, repository: meta.repository, sender: meta.sender }, state);
20
+ }
21
+ }
22
+ },
23
+ };
@@ -0,0 +1,23 @@
1
+ import { observe, repoAndSender } from "./common.js";
2
+ export const checkSuite = {
3
+ name: "check_suite",
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)}/check-suites?per_page=100`, { etagKey: `check-suites:${ctx.repo}:${ref}` });
11
+ if (result.notModified || !result.data)
12
+ continue;
13
+ for (const suite of result.data.check_suites) {
14
+ const state = `${suite.status}:${suite.conclusion}:${suite.updated_at}`;
15
+ const { changed } = observe(ctx, "check_suite", String(suite.id), state, suite);
16
+ if (!changed)
17
+ continue;
18
+ const action = suite.status === "completed" ? "completed" : "requested";
19
+ ctx.emit("check_suite", action, String(suite.id), { action, check_suite: suite, repository: meta.repository, sender: meta.sender }, state);
20
+ }
21
+ }
22
+ },
23
+ };
@@ -0,0 +1,34 @@
1
+ import { observeAlerts } from "./common.js";
2
+ const STATES = ["open", "dismissed", "fixed"];
3
+ function actionFor(previous, current) {
4
+ if (!previous)
5
+ return "created";
6
+ if (previous.state === current.state)
7
+ return "edited";
8
+ if (current.state === "open")
9
+ return "reopened";
10
+ if (current.state === "fixed")
11
+ return "fixed";
12
+ return "closed";
13
+ }
14
+ export const codeScanningAlert = {
15
+ name: "code_scanning_alert",
16
+ intervalFloorMs: 300_000,
17
+ async poll(ctx) {
18
+ const alerts = [];
19
+ const seen = new Set();
20
+ for (const state of STATES) {
21
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/code-scanning/alerts?state=${state}&per_page=100`, { etagKey: `code-scanning:${state}:${ctx.repo}` });
22
+ if (result.notModified || !result.data)
23
+ continue;
24
+ for (const alert of result.data) {
25
+ const key = String(alert.number);
26
+ if (seen.has(key))
27
+ continue;
28
+ seen.add(key);
29
+ alerts.push(alert);
30
+ }
31
+ }
32
+ await observeAlerts(ctx, "code_scanning_alert", alerts, actionFor, (alert) => `${alert.state}:${alert.updated_at}`);
33
+ },
34
+ };
@@ -0,0 +1,20 @@
1
+ import { sha256 } from "../util.js";
2
+ import { observe, repoAndSender } from "./common.js";
3
+ export const commitComment = {
4
+ name: "commit_comment",
5
+ intervalFloorMs: 60_000,
6
+ async poll(ctx) {
7
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/comments?sort=updated&direction=desc&per_page=100`, { etagKey: `commit-comments:${ctx.repo}` });
8
+ if (result.notModified || !result.data)
9
+ return;
10
+ const meta = await repoAndSender(ctx);
11
+ for (const comment of result.data) {
12
+ const state = `${sha256(comment.body ?? "")}:${comment.updated_at}`;
13
+ const { changed, prev } = observe(ctx, "commit_comment", String(comment.id), state, comment);
14
+ if (!changed)
15
+ continue;
16
+ const action = prev ? "edited" : "created";
17
+ ctx.emit("commit_comment", action, String(comment.id), { action, comment, repository: meta.repository, sender: meta.sender }, `${state}:${action}`);
18
+ }
19
+ },
20
+ };
@@ -0,0 +1,36 @@
1
+ export async function repoAndSender(ctx) {
2
+ const [repository, sender] = await Promise.all([ctx.gh.repoInfo(ctx.repo), ctx.gh.sender()]);
3
+ return { repository, sender };
4
+ }
5
+ export function observe(ctx, event, key, state, data) {
6
+ const prev = ctx.db.getSnapshot(ctx.repo, event, key);
7
+ if (prev?.state === state)
8
+ return { changed: false, prev };
9
+ ctx.db.putSnapshot(ctx.repo, event, key, state, data);
10
+ return { changed: true, prev };
11
+ }
12
+ export async function orgAndSender(ctx) {
13
+ const sender = await ctx.gh.sender();
14
+ return { organization: { login: ctx.org ?? "" }, sender };
15
+ }
16
+ export const SUCCESS_CONCLUSIONS = new Set(["success", "neutral", "skipped"]);
17
+ export const FAILED_CONCLUSIONS = new Set([
18
+ "failure",
19
+ "timed_out",
20
+ "cancelled",
21
+ "action_required",
22
+ "stale",
23
+ ]);
24
+ export async function observeAlerts(ctx, event, alerts, toAction, stateFor) {
25
+ if (alerts.length === 0)
26
+ return;
27
+ const meta = await repoAndSender(ctx);
28
+ for (const alert of alerts) {
29
+ const state = stateFor(alert);
30
+ const { changed, prev } = observe(ctx, event, String(alert.number), state, alert);
31
+ if (!changed)
32
+ continue;
33
+ const action = toAction(prev?.data, alert);
34
+ ctx.emit(event, action, String(alert.number), { action, alert, repository: meta.repository, sender: meta.sender }, `${state}:${action}`);
35
+ }
36
+ }
@@ -0,0 +1,26 @@
1
+ import { observeAlerts } from "./common.js";
2
+ function actionFor(previous, current) {
3
+ if (!previous)
4
+ return "created";
5
+ if (previous.state === current.state)
6
+ return "edited";
7
+ if (current.state === "open")
8
+ return "reopened";
9
+ if (current.state === "dismissed")
10
+ return "dismissed";
11
+ if (current.state === "auto_dismissed")
12
+ return "auto_dismissed";
13
+ if (current.state === "fixed")
14
+ return "fixed";
15
+ return "edited";
16
+ }
17
+ export const dependabotAlert = {
18
+ name: "dependabot_alert",
19
+ intervalFloorMs: 300_000,
20
+ async poll(ctx) {
21
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/dependabot/alerts?state=open,dismissed,fixed,auto_dismissed&per_page=100`, { etagKey: `dependabot:${ctx.repo}` });
22
+ if (result.notModified || !result.data)
23
+ return;
24
+ await observeAlerts(ctx, "dependabot_alert", result.data, actionFor, (alert) => `${alert.state}:${alert.updated_at}`);
25
+ },
26
+ };
@@ -0,0 +1,34 @@
1
+ import { sha256 } from "../util.js";
2
+ import { observe, repoAndSender } from "./common.js";
3
+ const DELETED = "deleted";
4
+ function stateFor(key) {
5
+ return sha256(`${key.title}|${key.key}|${key.read_only}`);
6
+ }
7
+ export const deployKey = {
8
+ name: "deploy_key",
9
+ intervalFloorMs: 300_000,
10
+ async poll(ctx) {
11
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/keys?per_page=100`, {
12
+ etagKey: `deploy-keys:${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((key) => String(key.id)));
18
+ for (const key of result.data) {
19
+ const state = stateFor(key);
20
+ const { changed, prev } = observe(ctx, "deploy_key", String(key.id), state, key);
21
+ if (!changed)
22
+ continue;
23
+ if (prev && prev.state !== DELETED)
24
+ continue;
25
+ ctx.emit("deploy_key", "created", String(key.id), { action: "created", key, repository: meta.repository, sender: meta.sender }, state);
26
+ }
27
+ for (const row of ctx.db.listSnapshots(ctx.repo, "deploy_key")) {
28
+ if (row.state === DELETED || current.has(row.key))
29
+ continue;
30
+ ctx.db.putSnapshot(ctx.repo, "deploy_key", row.key, DELETED, row.data);
31
+ ctx.emit("deploy_key", "deleted", row.key, { action: "deleted", key: row.data, repository: meta.repository, sender: meta.sender }, `deleted:${row.state}`);
32
+ }
33
+ },
34
+ };
@@ -0,0 +1,60 @@
1
+ import { sha256 } from "../util.js";
2
+ import { observe, repoAndSender } from "./common.js";
3
+ const LIMIT = 100;
4
+ function ruleKey(environment, id) {
5
+ return `${environment}:${id}`;
6
+ }
7
+ function ruleState(rule) {
8
+ return sha256(JSON.stringify({ enabled: rule.enabled, app: rule.app?.slug ?? rule.app?.id ?? null }));
9
+ }
10
+ async function fetchRules(ctx) {
11
+ const envResult = await ctx.gh.get(`/repos/${ctx.repo}/environments?per_page=${LIMIT}`, { etagKey: `environments:${ctx.repo}` });
12
+ const rules = [];
13
+ for (const environment of envResult.data?.environments ?? []) {
14
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/environments/${encodeURIComponent(environment.name)}/deployment_protection_rules`, { etagKey: `protection-rules:${ctx.repo}:${environment.name}` });
15
+ for (const rule of result.data?.custom_deployment_protection_rules ?? []) {
16
+ rules.push({ environment: environment.name, rule });
17
+ }
18
+ }
19
+ return rules;
20
+ }
21
+ export const deploymentProtectionRule = {
22
+ name: "deployment_protection_rule",
23
+ intervalFloorMs: 300_000,
24
+ async poll(ctx) {
25
+ const rules = await fetchRules(ctx);
26
+ const meta = await repoAndSender(ctx);
27
+ const seen = new Set();
28
+ for (const { environment, rule } of rules) {
29
+ const key = ruleKey(environment, rule.id);
30
+ seen.add(key);
31
+ const state = ruleState(rule);
32
+ const { changed, prev } = observe(ctx, "deployment_protection_rule", key, state, {
33
+ environment,
34
+ rule,
35
+ });
36
+ if (!changed)
37
+ continue;
38
+ const action = prev && prev.state !== "deleted" ? "edited" : "created";
39
+ ctx.emit("deployment_protection_rule", action, key, {
40
+ action,
41
+ environment,
42
+ deployment_protection_rule: rule,
43
+ repository: meta.repository,
44
+ sender: meta.sender,
45
+ }, state);
46
+ }
47
+ for (const row of ctx.db.listSnapshots(ctx.repo, "deployment_protection_rule")) {
48
+ if (seen.has(row.key) || row.state === "deleted")
49
+ continue;
50
+ ctx.db.putSnapshot(ctx.repo, "deployment_protection_rule", row.key, "deleted", row.data);
51
+ ctx.emit("deployment_protection_rule", "deleted", row.key, {
52
+ action: "deleted",
53
+ environment: row.data?.environment ?? null,
54
+ deployment_protection_rule: row.data?.rule ?? null,
55
+ repository: meta.repository,
56
+ sender: meta.sender,
57
+ }, "deleted");
58
+ }
59
+ },
60
+ };
@@ -0,0 +1,48 @@
1
+ import { observe, repoAndSender } from "./common.js";
2
+ const MAX_ACTIVE_RUNS = 5;
3
+ async function fetchPending(ctx, runId) {
4
+ const result = await ctx.gh.get(`/repos/${ctx.repo}/actions/runs/${runId}/pending_deployments`, { etagKey: `pending-deployments:${ctx.repo}:${runId}` });
5
+ const data = result.data;
6
+ if (!data)
7
+ return [];
8
+ return Array.isArray(data) ? data : (data.pending_deployments ?? []);
9
+ }
10
+ function pendingKey(runId, deployment) {
11
+ const environment = deployment.environment?.id ?? deployment.environment?.name ?? "unknown";
12
+ return `${runId}:${environment}`;
13
+ }
14
+ export const deploymentReview = {
15
+ name: "deployment_review",
16
+ intervalFloorMs: 300_000,
17
+ async poll(ctx) {
18
+ const active = ctx.db
19
+ .listSnapshots(ctx.repo, "workflow_run")
20
+ .filter((row) => row.data?.status !== "completed")
21
+ .slice(0, MAX_ACTIVE_RUNS);
22
+ if (active.length === 0)
23
+ return;
24
+ const meta = await repoAndSender(ctx);
25
+ for (const row of active) {
26
+ const runId = String(row.data?.id ?? row.key);
27
+ const pending = await fetchPending(ctx, runId);
28
+ for (const deployment of pending) {
29
+ const key = pendingKey(runId, deployment);
30
+ const state = `${deployment.state ?? "pending"}:${deployment.comment ?? ""}`;
31
+ const { changed } = observe(ctx, "deployment_review", key, state, {
32
+ run: row.data,
33
+ deployment,
34
+ });
35
+ if (!changed)
36
+ continue;
37
+ ctx.emit("deployment_review", "requested", key, {
38
+ action: "requested",
39
+ environment: deployment.environment ?? null,
40
+ workflow_run: row.data ?? { id: runId },
41
+ pending_deployment: deployment,
42
+ repository: meta.repository,
43
+ sender: meta.sender,
44
+ }, state);
45
+ }
46
+ }
47
+ },
48
+ };
@@ -0,0 +1,30 @@
1
+ import { observe, repoAndSender } from "./common.js";
2
+ const DEPLOYMENTS = 10;
3
+ export const deploymentStatus = {
4
+ name: "deployment_status",
5
+ intervalFloorMs: 300_000,
6
+ async poll(ctx) {
7
+ const deployments = await ctx.gh.get(`/repos/${ctx.repo}/deployments?per_page=${DEPLOYMENTS}`, { etagKey: `deployments:statuses:${ctx.repo}` });
8
+ if (deployments.notModified || !deployments.data)
9
+ return;
10
+ const meta = await repoAndSender(ctx);
11
+ for (const deployment of deployments.data.slice(0, DEPLOYMENTS)) {
12
+ const statuses = await ctx.gh.get(`/repos/${ctx.repo}/deployments/${deployment.id}/statuses?per_page=20`, { etagKey: `deployment-statuses:${deployment.id}` });
13
+ if (statuses.notModified || !statuses.data)
14
+ continue;
15
+ for (const status of statuses.data) {
16
+ const state = String(status.created_at ?? status.id);
17
+ const { changed } = observe(ctx, "deployment_status", String(status.id), state, status);
18
+ if (!changed)
19
+ continue;
20
+ ctx.emit("deployment_status", "created", String(status.id), {
21
+ action: "created",
22
+ deployment,
23
+ deployment_status: status,
24
+ repository: meta.repository,
25
+ sender: meta.sender,
26
+ }, state);
27
+ }
28
+ }
29
+ },
30
+ };