@sentry/junior-github 0.301.0 → 0.303.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 (97) hide show
  1. package/dist/events-CrbJHQ0w.js +2466 -0
  2. package/dist/index.d.ts +71 -3
  3. package/dist/index.js +7294 -7881
  4. package/dist/testing.d.ts +51 -1
  5. package/dist/testing.js +1 -6
  6. package/migrations/0012_pull_request_next_action.sql +5 -0
  7. package/migrations/meta/0012_snapshot.json +434 -0
  8. package/migrations/meta/_journal.json +7 -0
  9. package/package.json +11 -13
  10. package/skills/github-code/SKILL.md +1 -1
  11. package/skills/github-code/SPEC.md +2 -2
  12. package/skills/github-code/references/workflow.md +1 -1
  13. package/dist/account-links.d.ts +0 -8
  14. package/dist/annotations.d.ts +0 -33
  15. package/dist/chunk-YUF5P5I7.js +0 -2507
  16. package/dist/clone-command.d.ts +0 -5
  17. package/dist/configured-repository.d.ts +0 -10
  18. package/dist/conversation-title-context.d.ts +0 -20
  19. package/dist/credential-support.d.ts +0 -107
  20. package/dist/db/database.d.ts +0 -5
  21. package/dist/db/schema.d.ts +0 -1403
  22. package/dist/default-branch.d.ts +0 -15
  23. package/dist/egress-policy.d.ts +0 -25
  24. package/dist/events/comment.d.ts +0 -14
  25. package/dist/events/declarations.d.ts +0 -18
  26. package/dist/events/deployment.d.ts +0 -38
  27. package/dist/events/issue.d.ts +0 -42
  28. package/dist/events/pull-request.d.ts +0 -75
  29. package/dist/events/release.d.ts +0 -42
  30. package/dist/events/repository.d.ts +0 -23
  31. package/dist/events/resource-url.d.ts +0 -5
  32. package/dist/events/scope.d.ts +0 -13
  33. package/dist/git-config.d.ts +0 -52
  34. package/dist/github-status.d.ts +0 -16
  35. package/dist/graphql-documents.d.ts +0 -31
  36. package/dist/images.d.ts +0 -8
  37. package/dist/issue-outcomes/store.d.ts +0 -42
  38. package/dist/merge-conflict-checks/heartbeat.d.ts +0 -27
  39. package/dist/merge-conflict-checks/store.d.ts +0 -44
  40. package/dist/merge-conflict-checks/webhooks.d.ts +0 -23
  41. package/dist/object-facts.d.ts +0 -29
  42. package/dist/permissions.d.ts +0 -6
  43. package/dist/plugin.d.ts +0 -45
  44. package/dist/pull-request-outcomes/apply.d.ts +0 -22
  45. package/dist/pull-request-outcomes/commit-composition.d.ts +0 -6
  46. package/dist/pull-request-outcomes/reconcile.d.ts +0 -41
  47. package/dist/pull-request-outcomes/store.d.ts +0 -115
  48. package/dist/pull-request-requesters/draft-reviewers.d.ts +0 -15
  49. package/dist/pull-request-requesters/store.d.ts +0 -41
  50. package/dist/pull-request-review-policy.d.ts +0 -6
  51. package/dist/receive-pack-policy.d.ts +0 -21
  52. package/dist/reply-markdown.d.ts +0 -18
  53. package/dist/sandbox-paths.d.ts +0 -4
  54. package/dist/tool-support/attribution.d.ts +0 -52
  55. package/dist/tool-support/github-api.d.ts +0 -51
  56. package/dist/tool-support/github-text.d.ts +0 -8
  57. package/dist/tool-support/pull-request-description.d.ts +0 -8
  58. package/dist/tools/clone-repository.d.ts +0 -205
  59. package/dist/tools/comment-on-issue.d.ts +0 -205
  60. package/dist/tools/comment-on-pull-request.d.ts +0 -210
  61. package/dist/tools/create-issue.d.ts +0 -218
  62. package/dist/tools/create-pull-request.d.ts +0 -240
  63. package/dist/tools/footer.d.ts +0 -17
  64. package/dist/tools/get-deployment.d.ts +0 -264
  65. package/dist/tools/get-issue.d.ts +0 -248
  66. package/dist/tools/get-pull-request.d.ts +0 -255
  67. package/dist/tools/get-release.d.ts +0 -243
  68. package/dist/tools/get-repository.d.ts +0 -226
  69. package/dist/tools/get-status.d.ts +0 -213
  70. package/dist/tools/react-to-issue.d.ts +0 -205
  71. package/dist/tools/resolve-pull-request-review-thread.d.ts +0 -206
  72. package/dist/tools/stack-pull-request.d.ts +0 -43
  73. package/dist/tools/submit-pull-request-review.d.ts +0 -216
  74. package/dist/tools/update-issue-comment.d.ts +0 -206
  75. package/dist/tools/update-issue.d.ts +0 -249
  76. package/dist/tools/update-pull-request-feedback.d.ts +0 -242
  77. package/dist/tools/update-pull-request.d.ts +0 -255
  78. package/dist/tools.d.ts +0 -13
  79. package/dist/webhooks/check-suite.d.ts +0 -94
  80. package/dist/webhooks/event-targets.d.ts +0 -44
  81. package/dist/webhooks/events.d.ts +0 -23
  82. package/dist/webhooks/fail-open-log.d.ts +0 -10
  83. package/dist/webhooks/handler.d.ts +0 -55
  84. package/dist/webhooks/installation-requests.d.ts +0 -98
  85. package/dist/webhooks/issue-outcome.d.ts +0 -11
  86. package/dist/webhooks/issue-update.d.ts +0 -8
  87. package/dist/webhooks/merge-conflict.d.ts +0 -48
  88. package/dist/webhooks/ownership.d.ts +0 -14
  89. package/dist/webhooks/pull-request-activity.d.ts +0 -11
  90. package/dist/webhooks/pull-request-match-data.d.ts +0 -31
  91. package/dist/webhooks/pull-request-outcome.d.ts +0 -16
  92. package/dist/webhooks/pull-request-people.d.ts +0 -51
  93. package/dist/webhooks/pull-request-preview.d.ts +0 -12
  94. package/dist/webhooks/pull-request-ready-reviewers.d.ts +0 -25
  95. package/dist/webhooks/pull-request-ready.d.ts +0 -31
  96. package/dist/webhooks/pull-request-review-request.d.ts +0 -32
  97. package/dist/workspace-prepare.d.ts +0 -3
@@ -1,2507 +0,0 @@
1
- // src/webhooks/events.ts
2
- import * as z6 from "zod";
3
-
4
- // src/events/deployment.ts
5
- import {
6
- eventMatchFieldsSchema as eventMatchFieldsSchema2
7
- } from "@sentry/junior-plugin-api";
8
-
9
- // src/events/scope.ts
10
- import {
11
- eventMatchFieldsSchema
12
- } from "@sentry/junior-plugin-api";
13
- import * as z from "zod";
14
- var gitHubRepoDataSchema = z.string().min(1).toLowerCase();
15
- var gitHubCommitShaDataSchema = z.string().regex(/^[0-9a-f]{40}$/i).toLowerCase();
16
- function gitHubRepoMatchFields(events) {
17
- return eventMatchFieldsSchema.parse({
18
- repo: {
19
- kind: "string",
20
- case: "lower",
21
- description: "lowercase repository as owner/repo, such as getsentry/junior",
22
- events
23
- }
24
- });
25
- }
26
- function gitHubCommitMatchFields(events) {
27
- return eventMatchFieldsSchema.parse({
28
- commitSha: {
29
- kind: "string",
30
- case: "lower",
31
- description: "full lowercase Git commit SHA",
32
- events
33
- }
34
- });
35
- }
36
-
37
- // src/events/deployment.ts
38
- var GITHUB_DEPLOYMENT_EVENTS = [
39
- "deployment.created",
40
- "deployment.queued",
41
- "deployment.pending",
42
- "deployment.in_progress",
43
- "deployment.succeeded",
44
- "deployment.failed",
45
- "deployment.error"
46
- ];
47
- var GITHUB_DEPLOYMENT_SUGGESTED_EVENTS = [
48
- "deployment.succeeded",
49
- "deployment.failed",
50
- "deployment.error"
51
- ];
52
- var GITHUB_DEPLOYMENT_MATCH_FIELDS = eventMatchFieldsSchema2.parse({
53
- ...gitHubRepoMatchFields(GITHUB_DEPLOYMENT_EVENTS),
54
- ...gitHubCommitMatchFields(GITHUB_DEPLOYMENT_EVENTS),
55
- deploymentId: {
56
- kind: "number",
57
- description: "numeric GitHub deployment id, such as 3001",
58
- events: [...GITHUB_DEPLOYMENT_EVENTS]
59
- },
60
- environment: {
61
- kind: "string",
62
- case: "lower",
63
- description: "lowercase deployment environment name, such as production",
64
- events: [...GITHUB_DEPLOYMENT_EVENTS]
65
- },
66
- workflowId: {
67
- kind: "number",
68
- description: "numeric GitHub Actions workflow id when a workflow created the deployment",
69
- events: [...GITHUB_DEPLOYMENT_EVENTS]
70
- },
71
- workflowPath: {
72
- kind: "string",
73
- description: "GitHub Actions workflow file, such as .github/workflows/deploy.yml, when a workflow created the deployment",
74
- events: [...GITHUB_DEPLOYMENT_EVENTS]
75
- }
76
- });
77
- var GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER = {
78
- format: "deployment-source:owner/repo[:environment]:<full-commit-sha>",
79
- pattern: String.raw`^deployment-source:[^\s/:#]+\/[^\s/:#]+(?::[^\s:]+)?:[0-9a-f]+$`
80
- };
81
- function gitHubDeploymentSourceResource(input) {
82
- const commitSha = input.commitSha.toLowerCase();
83
- const environment = input.environment?.trim();
84
- const repo = input.repo.toLowerCase();
85
- return {
86
- label: `GitHub deployment for ${repo} at ${commitSha.slice(0, 12)}`,
87
- namespace: "github",
88
- identifier: environment ? `deployment-source:${repo}:${encodeURIComponent(environment.toLowerCase())}:${commitSha}` : `deployment-source:${repo}:${commitSha}`
89
- };
90
- }
91
- function gitHubDeploymentSourceSubscribable(input) {
92
- if (!input.canSubscribe) return void 0;
93
- const environment = input.environment?.trim().toLowerCase();
94
- return {
95
- ...gitHubDeploymentSourceResource(input),
96
- match: {
97
- repo: gitHubRepoDataSchema.parse(input.repo),
98
- commit_sha: gitHubCommitShaDataSchema.parse(input.commitSha),
99
- ...environment ? { environment } : void 0
100
- },
101
- suggested_events: GITHUB_DEPLOYMENT_SUGGESTED_EVENTS,
102
- supported_events: [...GITHUB_DEPLOYMENT_EVENTS],
103
- type: "deployment_source"
104
- };
105
- }
106
-
107
- // src/events/issue.ts
108
- import {
109
- eventMatchFieldsSchema as eventMatchFieldsSchema4,
110
- mergeEventMatchFields
111
- } from "@sentry/junior-plugin-api";
112
-
113
- // src/events/comment.ts
114
- import {
115
- eventMatchFieldsSchema as eventMatchFieldsSchema3
116
- } from "@sentry/junior-plugin-api";
117
- function gitHubSenderMatchFields(events) {
118
- return eventMatchFieldsSchema3.parse({
119
- senderId: {
120
- kind: "number",
121
- description: "immutable numeric GitHub user id of who wrote the comment or review, or made the update; prefer over logins",
122
- events
123
- },
124
- senderLogin: {
125
- kind: "string",
126
- description: "GitHub login of who wrote the comment or review, or made the update; logins can be renamed",
127
- events
128
- }
129
- });
130
- }
131
- function gitHubCommentMatchFields(events) {
132
- return eventMatchFieldsSchema3.parse({
133
- mentionsBot: {
134
- kind: "boolean",
135
- description: "true when the comment or review mentions this GitHub App",
136
- events
137
- },
138
- ...gitHubSenderMatchFields(events)
139
- });
140
- }
141
-
142
- // src/events/issue.ts
143
- var GITHUB_ISSUE_EVENTS = [
144
- "issue.comment.created",
145
- "issue.opened",
146
- "issue.closed",
147
- "issue.reopened",
148
- "issue.updated"
149
- ];
150
- var GITHUB_ISSUE_SUGGESTED_EVENTS = [
151
- "issue.comment.created",
152
- "issue.closed",
153
- "issue.reopened",
154
- "issue.updated"
155
- ];
156
- var GITHUB_ISSUE_UPDATE_CHANGES = [
157
- "edited",
158
- "labeled",
159
- "unlabeled",
160
- "assigned",
161
- "unassigned",
162
- "milestoned",
163
- "demilestoned"
164
- ];
165
- var GITHUB_ISSUE_MATCH_FIELDS = mergeEventMatchFields(
166
- gitHubCommentMatchFields(["issue.comment.created"]),
167
- gitHubSenderMatchFields(["issue.updated"]),
168
- eventMatchFieldsSchema4.parse({
169
- ...gitHubRepoMatchFields(GITHUB_ISSUE_EVENTS),
170
- issue: {
171
- kind: "number",
172
- description: "issue number, such as 12",
173
- events: GITHUB_ISSUE_EVENTS
174
- },
175
- change: {
176
- kind: "string",
177
- enum: [...GITHUB_ISSUE_UPDATE_CHANGES],
178
- description: "what the issue update changed, such as labeled",
179
- events: ["issue.updated"]
180
- },
181
- label: {
182
- kind: "string",
183
- case: "lower",
184
- description: "lowercase name of the label that was added or removed, set only when change is labeled or unlabeled",
185
- events: ["issue.updated"]
186
- }
187
- })
188
- );
189
- var GITHUB_ISSUE_IDENTIFIER = {
190
- format: "owner/repo#number",
191
- pattern: String.raw`^[^\s/:#]+\/[^\s/:#]+#\d+$`
192
- };
193
- function gitHubIssueResource(input) {
194
- return {
195
- label: `GitHub issue ${input.repo}#${input.number}`,
196
- namespace: "github",
197
- identifier: `${input.repo.toLowerCase()}#${input.number}`
198
- };
199
- }
200
- function gitHubIssueSubscribable(input) {
201
- if (!input.canSubscribe) return void 0;
202
- return {
203
- ...gitHubIssueResource(input),
204
- match: {
205
- repo: gitHubRepoDataSchema.parse(input.repo),
206
- issue: input.number
207
- },
208
- suggested_events: GITHUB_ISSUE_SUGGESTED_EVENTS,
209
- supported_events: GITHUB_ISSUE_EVENTS,
210
- type: "issue"
211
- };
212
- }
213
-
214
- // src/events/pull-request.ts
215
- import {
216
- eventMatchFieldsSchema as eventMatchFieldsSchema5
217
- } from "@sentry/junior-plugin-api";
218
- var GITHUB_PULL_REQUEST_EVENTS = [
219
- "pull_request.checks.failed",
220
- "pull_request.checks.recovered",
221
- "pull_request.comment.created",
222
- "pull_request.opened",
223
- "pull_request.ready_for_review",
224
- "pull_request.review.approved",
225
- "pull_request.review.changes_requested",
226
- "pull_request.review.commented",
227
- "pull_request.review_comment.created",
228
- "pull_request.merged",
229
- "pull_request.closed_unmerged",
230
- "pull_request.merge_conflict"
231
- ];
232
- var STACK_CHECK = "Check if the pull request is in a stack: `gh api 'repos/OWNER/REPO/stacks?pull_request=NUMBER'`.";
233
- var STACK_CONFLICT_STEPS = "run `gh stack rebase`, resolve each conflict so that both changes stay intact, stage the files, and run `gh stack rebase --continue`. Run the checks again, run `gh stack push`, and confirm that each open pull request in the stack can merge. Report the files that had conflicts.";
234
- var PULL_REQUEST_FEEDBACK = 'When Verified details include comment_id, call github_updatePullRequestFeedback after acting on actionable feedback, with the exact repo, pull_request, comment_id, and comment_kind from Verified details, and status "addressed" or "declined".';
235
- var GITHUB_PULL_REQUEST_EVENT_GUIDANCE = {
236
- "pull_request.checks.failed": "Fix only failures that the pull request causes. Do not skip, disable, or weaken a check to make it pass.",
237
- // An approval with a body also arrives as review.commented in the same
238
- // Turn, so this guidance must not tell the agent to hold off on that body.
239
- "pull_request.review.approved": `When the approval includes actionable feedback, address it like any other review feedback. ${PULL_REQUEST_FEEDBACK}`,
240
- "pull_request.review.changes_requested": PULL_REQUEST_FEEDBACK,
241
- "pull_request.review.commented": PULL_REQUEST_FEEDBACK,
242
- "pull_request.comment.created": PULL_REQUEST_FEEDBACK,
243
- "pull_request.review_comment.created": `${PULL_REQUEST_FEEDBACK} Then resolve the thread with github_resolvePullRequestReviewThread.`,
244
- "pull_request.merge_conflict": `${STACK_CHECK} If it is, run \`gh stack checkout NUMBER\`, then ${STACK_CONFLICT_STEPS} If it is not, fetch base_branch from Verified details and merge it into the pull request branch. Do not rebase. Resolve each conflict so that both the pull request change and the base branch change stay intact. Run the checks again, push, and confirm that the pull request can merge. Report the files that had conflicts.`
245
- };
246
- function gitHubPullRequestEventGuidance(guidance) {
247
- const merged = { ...GITHUB_PULL_REQUEST_EVENT_GUIDANCE };
248
- for (const eventType of GITHUB_PULL_REQUEST_EVENTS) {
249
- const extra = guidance?.[eventType]?.trim();
250
- if (!extra) continue;
251
- const base = merged[eventType];
252
- merged[eventType] = base ? `${base} ${extra}` : extra;
253
- }
254
- return merged;
255
- }
256
- var DEFAULT_PULL_REQUEST_SUBSCRIPTION = {
257
- events: [
258
- "pull_request.checks.failed",
259
- "pull_request.closed_unmerged",
260
- "pull_request.comment.created",
261
- "pull_request.review.changes_requested",
262
- "pull_request.review.commented",
263
- "pull_request.review_comment.created"
264
- ],
265
- intent: "Maintain pull requests Junior creates. For actionable review feedback or failed checks, inspect the evidence, make scoped fixes, verify them, and push, without asking first. Reply on GitHub to review comments and questions, in the thread where they were asked. Report completed work or blockers in the originating thread. Report when the pull request closes unmerged. When a reviewer submits a review, notify the person who asked for the pull request by mentioning them, with the reviewer, the review outcome, and the pull request link. Stay silent on other events that are not feedback."
266
- };
267
- function gitHubPullRequestSubscription(config) {
268
- if (config === false) return void 0;
269
- return config ?? DEFAULT_PULL_REQUEST_SUBSCRIPTION;
270
- }
271
- var MERGE_STATE_CHECK = "Do not guess whether it can merge. Before you say anything about that, call github_getPullRequest and read its `checks`. If `checks.required` is `not_reported`, the required checks may not have started on the latest commit yet. It does not mean that none are required. If `checks.auto_merge` is true and only required checks remain, say only that it merges when they pass. If `checks.merge_state` shows that GitHub blocks it for another reason, run `gh api repos/OWNER/REPO/rules/branches/BASE` and name the rule that blocks it. Do not say that you did not merge it.";
272
- var GITHUB_PULL_REQUEST_OUTCOME_GUIDANCE = {
273
- "pull_request.review.approved": `Mention each person in People involved, or the person who asked for the pull request if that line is missing. Say who approved it and link it. Do not merge it unless asked. ${MERGE_STATE_CHECK}`,
274
- "pull_request.merged": "Mention each person in People involved, or the person who asked for the pull request if that line is missing. Say that it merged and link it."
275
- };
276
- var DRAFT_CHECKS_RECOVERED_GUIDANCE = "If the pull request is still a draft, call github_getPullRequest and read its `checks`. When `checks.required` is `passing` and no decision is open, in the pull request body or in an open review item that waits on the person who asked for it, mark it ready with github_updatePullRequest and draft false, and report that in the originating thread. When it is `failing`, fix the failing checks like a failed check. When it is `pending` or `not_reported`, stay silent: a later passing suite wakes you again. `not_reported` means the required checks may not have started on the latest commit yet, not that none are required.";
277
- function gitHubPullRequestCreateWatch(config, pullRequest) {
278
- const outcomeEvents = Object.keys(
279
- GITHUB_PULL_REQUEST_OUTCOME_GUIDANCE
280
- );
281
- return {
282
- events: [
283
- .../* @__PURE__ */ new Set([
284
- ...config.events,
285
- // GitHub sends no webhook for a new conflict, so keep the pull
286
- // request ready to merge even when the app config omits this event.
287
- "pull_request.merge_conflict",
288
- ...outcomeEvents,
289
- ...pullRequest.draft ? ["pull_request.checks.recovered"] : []
290
- ])
291
- ],
292
- guidance: pullRequest.draft ? {
293
- ...GITHUB_PULL_REQUEST_OUTCOME_GUIDANCE,
294
- "pull_request.checks.recovered": DRAFT_CHECKS_RECOVERED_GUIDANCE
295
- } : GITHUB_PULL_REQUEST_OUTCOME_GUIDANCE,
296
- intent: config.intent
297
- };
298
- }
299
- var GITHUB_PULL_REQUEST_SUGGESTED_EVENTS = [
300
- "pull_request.checks.failed",
301
- "pull_request.comment.created",
302
- "pull_request.ready_for_review",
303
- "pull_request.review.changes_requested",
304
- "pull_request.review.commented",
305
- "pull_request.review_comment.created",
306
- "pull_request.merged",
307
- "pull_request.closed_unmerged",
308
- "pull_request.merge_conflict"
309
- ];
310
- var GITHUB_PULL_REQUEST_PAYLOAD_EVENTS = GITHUB_PULL_REQUEST_EVENTS.filter(
311
- (eventType) => eventType !== "pull_request.merge_conflict"
312
- );
313
- var GITHUB_PULL_REQUEST_COMMENT_EVENTS = [
314
- "pull_request.comment.created",
315
- "pull_request.review.approved",
316
- "pull_request.review.changes_requested",
317
- "pull_request.review.commented",
318
- "pull_request.review_comment.created"
319
- ];
320
- var GITHUB_PULL_REQUEST_CHECK_EVENTS = [
321
- "pull_request.checks.failed",
322
- "pull_request.checks.recovered"
323
- ];
324
- var GITHUB_PULL_REQUEST_MATCH_FIELDS = eventMatchFieldsSchema5.parse({
325
- ...gitHubCommentMatchFields(GITHUB_PULL_REQUEST_COMMENT_EVENTS),
326
- ...gitHubRepoMatchFields(GITHUB_PULL_REQUEST_EVENTS),
327
- ...gitHubCommitMatchFields(GITHUB_PULL_REQUEST_CHECK_EVENTS),
328
- pullRequest: {
329
- kind: "number",
330
- description: "pull request number, such as 946",
331
- events: [...GITHUB_PULL_REQUEST_EVENTS]
332
- },
333
- authors: {
334
- kind: "string",
335
- list: true,
336
- description: "GitHub logins of the commit authors and Co-authored-by people, including bots such as this GitHub App",
337
- events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
338
- },
339
- headBranch: {
340
- kind: "string",
341
- description: "head branch name from the webhook",
342
- events: GITHUB_PULL_REQUEST_PAYLOAD_EVENTS.filter(
343
- (eventType) => eventType !== "pull_request.comment.created"
344
- )
345
- },
346
- isDraft: {
347
- kind: "boolean",
348
- description: "true when the pull request is a draft",
349
- events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
350
- },
351
- openerEmail: {
352
- kind: "string",
353
- description: "opener email when GitHub sends it; missing on pull requests that this GitHub App opened",
354
- events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
355
- },
356
- openerUsername: {
357
- kind: "string",
358
- description: "login of who opened the pull request; on pull requests that this GitHub App opened, the person who asked for it, missing until that person is saved",
359
- events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
360
- },
361
- openerRole: {
362
- kind: "string",
363
- description: "opener's repository role: admin, maintain, write, triage, read, none (no access, such as most bots), or a custom role name",
364
- events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
365
- }
366
- });
367
- var GITHUB_PULL_REQUEST_IDENTIFIER = {
368
- format: "owner/repo#number",
369
- pattern: String.raw`^[^\s/:#]+\/[^\s/:#]+#\d+$`
370
- };
371
- function gitHubPullRequestResource(input) {
372
- return {
373
- label: `GitHub PR ${input.repo}#${input.number}`,
374
- namespace: "github",
375
- identifier: `${input.repo.toLowerCase()}#${input.number}`
376
- };
377
- }
378
- function gitHubPullRequestSubscribable(input) {
379
- if (!input.canSubscribe) return void 0;
380
- const omitted = new Set(input.omitSuggestedEvents ?? []);
381
- const suggestedEvents = GITHUB_PULL_REQUEST_SUGGESTED_EVENTS.filter(
382
- (eventType) => !omitted.has(eventType)
383
- );
384
- return {
385
- ...gitHubPullRequestResource(input),
386
- match: {
387
- repo: gitHubRepoDataSchema.parse(input.repo),
388
- pull_request: input.number
389
- },
390
- ...suggestedEvents.length > 0 ? { suggested_events: [...suggestedEvents] } : void 0,
391
- supported_events: [...GITHUB_PULL_REQUEST_EVENTS],
392
- type: "pull_request"
393
- };
394
- }
395
-
396
- // src/events/release.ts
397
- import {
398
- eventMatchFieldsSchema as eventMatchFieldsSchema6
399
- } from "@sentry/junior-plugin-api";
400
- import * as z2 from "zod";
401
- var GITHUB_RELEASE_EVENTS = ["release.published"];
402
- var gitHubReleaseTagDataSchema = z2.string().trim().min(1).transform(
403
- (tag) => tag.replace(/[A-Z]+/g, (letters) => letters.toLowerCase())
404
- );
405
- var GITHUB_RELEASE_MATCH_FIELDS = eventMatchFieldsSchema6.parse({
406
- ...gitHubRepoMatchFields(GITHUB_RELEASE_EVENTS),
407
- tag: {
408
- kind: "string",
409
- description: "release tag with ASCII letters in lowercase, such as v1.2.0 or release/1.0",
410
- events: [...GITHUB_RELEASE_EVENTS]
411
- }
412
- });
413
- var GITHUB_RELEASE_SUGGESTED_EVENTS = ["release.published"];
414
- var GITHUB_RELEASE_SOURCE_IDENTIFIER = {
415
- format: "release-source:owner/repo[:tag]",
416
- pattern: String.raw`^release-source:[^\s/:#]+\/[^\s/:#]+(?::[^\s:]+)?$`
417
- };
418
- function gitHubReleaseSourceResource(input) {
419
- const repo = input.repo.toLowerCase();
420
- const tag = input.tag?.trim();
421
- return {
422
- label: `GitHub release for ${repo}`,
423
- namespace: "github",
424
- identifier: tag ? `release-source:${repo}:${encodeURIComponent(tag)}` : `release-source:${repo}`
425
- };
426
- }
427
- function gitHubReleaseSourceSubscribable(input) {
428
- if (!input.canSubscribe) return void 0;
429
- const tag = input.tag?.trim();
430
- return {
431
- ...gitHubReleaseSourceResource(input),
432
- match: {
433
- repo: gitHubRepoDataSchema.parse(input.repo),
434
- ...tag ? { tag: gitHubReleaseTagDataSchema.parse(tag) } : void 0
435
- },
436
- suggested_events: GITHUB_RELEASE_SUGGESTED_EVENTS,
437
- supported_events: [...GITHUB_RELEASE_EVENTS],
438
- type: "release_source"
439
- };
440
- }
441
-
442
- // src/events/repository.ts
443
- var GITHUB_REPOSITORY_IDENTIFIER = {
444
- format: "owner/repo",
445
- pattern: String.raw`^[^\s/:#]+\/[^\s/:#]+$`
446
- };
447
- function gitHubRepositoryResource(input) {
448
- return {
449
- label: `GitHub repository ${input.repo}`,
450
- namespace: "github",
451
- identifier: input.repo.toLowerCase()
452
- };
453
- }
454
- var GITHUB_REPOSITORY_EVENTS = [
455
- ...GITHUB_DEPLOYMENT_EVENTS,
456
- ...GITHUB_ISSUE_EVENTS,
457
- ...GITHUB_PULL_REQUEST_EVENTS
458
- ];
459
- var GITHUB_REPOSITORY_SUGGESTED_EVENTS = [
460
- "issue.opened",
461
- "pull_request.opened",
462
- // Label, assignee, and edit updates are too frequent across a repository.
463
- ...GITHUB_ISSUE_SUGGESTED_EVENTS.filter(
464
- (eventType) => eventType !== "issue.updated"
465
- ),
466
- ...GITHUB_PULL_REQUEST_SUGGESTED_EVENTS
467
- ];
468
- function gitHubRepositorySubscribable(input) {
469
- if (!input.canSubscribe) return void 0;
470
- return {
471
- ...gitHubRepositoryResource(input),
472
- match: { repo: gitHubRepoDataSchema.parse(input.repo) },
473
- suggested_events: [...GITHUB_REPOSITORY_SUGGESTED_EVENTS],
474
- supported_events: [...GITHUB_REPOSITORY_EVENTS],
475
- type: "repository"
476
- };
477
- }
478
-
479
- // src/webhooks/check-suite.ts
480
- import * as z4 from "zod";
481
-
482
- // src/credential-support.ts
483
- import { createPrivateKey, createSign } from "crypto";
484
-
485
- // src/permissions.ts
486
- var LEVELS = /* @__PURE__ */ new Set(["read", "write", "admin"]);
487
- var WRITE_ONLY_PERMISSIONS = /* @__PURE__ */ new Set(["profile", "workflows"]);
488
- function isLevel(value) {
489
- return LEVELS.has(value);
490
- }
491
- function normalizeScope(rawScope) {
492
- return String(rawScope).trim().replace(/-/g, "_");
493
- }
494
- function normalizePermissions(permissions) {
495
- if (permissions === void 0) {
496
- return void 0;
497
- }
498
- const entries = Object.entries(permissions);
499
- if (entries.length === 0) {
500
- throw new Error(
501
- "githubPlugin appPermissions must contain at least one permission when provided."
502
- );
503
- }
504
- const request = {};
505
- for (const [rawScope, rawLevel] of entries) {
506
- const normalizedScope = normalizeScope(rawScope);
507
- if (!normalizedScope) {
508
- throw new Error(
509
- "githubPlugin appPermissions contains an empty permission name."
510
- );
511
- }
512
- if (!/^[a-z][a-z0-9_]*$/.test(normalizedScope)) {
513
- throw new Error(
514
- `githubPlugin appPermissions contains invalid permission "${rawScope}".`
515
- );
516
- }
517
- if (!isLevel(rawLevel)) {
518
- throw new Error(
519
- `githubPlugin appPermissions.${rawScope} must be "read", "write", or "admin".`
520
- );
521
- }
522
- request[normalizedScope] = rawLevel;
523
- }
524
- return request;
525
- }
526
- function readGrantPermissions(permissions) {
527
- const readOnly = { metadata: "read" };
528
- for (const [scope, level] of Object.entries(permissions ?? {})) {
529
- if (!isLevel(level)) {
530
- throw new Error(
531
- `GitHub permission "${scope}" returned invalid level "${String(level)}".`
532
- );
533
- }
534
- if (!WRITE_ONLY_PERMISSIONS.has(scope)) {
535
- readOnly[scope] = "read";
536
- }
537
- }
538
- return readOnly;
539
- }
540
-
541
- // src/credential-support.ts
542
- var GITHUB_APP_ID_ENV = "GITHUB_APP_ID";
543
- var GITHUB_APP_PRIVATE_KEY_ENV = "GITHUB_APP_PRIVATE_KEY";
544
- var GITHUB_INSTALLATION_ID_ENV = "GITHUB_INSTALLATION_ID";
545
- var GITHUB_AUTH_TOKEN_ENV = "GITHUB_TOKEN";
546
- var GITHUB_AUTH_TOKEN_PLACEHOLDER = "ghp_host_managed_credential";
547
- var MAX_LEASE_MS = 60 * 60 * 1e3;
548
- var REFRESH_BUFFER_MS = 5 * 60 * 1e3;
549
- var USER_REFRESH_TIMEOUT_MS = 2e4;
550
- var GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES = 64 * 1024;
551
- var HTTP_READ_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
552
- var USER_TOKEN_GRANTS = /* @__PURE__ */ new Set(["user-read", "user-write"]);
553
- var CREATE_TOOL_ROUTING_GUIDANCE = "This is a tool-routing denial, not a GitHub permission failure. Do not ask the user for GitHub permissions; retry with the required tool.";
554
- var USER_WRITE_REQUIREMENTS = [
555
- "requesting GitHub user permission to perform this operation"
556
- ];
557
- var GITHUB_CREDENTIAL_DOMAINS = ["api.github.com", "github.com"];
558
- var GITHUB_ASSET_UPLOAD_CREDENTIAL_DOMAINS = [
559
- ...GITHUB_CREDENTIAL_DOMAINS,
560
- "uploads.github.com"
561
- ];
562
- var GitHubUserRefreshRejectedError = class extends Error {
563
- constructor(message) {
564
- super(message);
565
- this.name = "GitHubUserRefreshRejectedError";
566
- }
567
- };
568
- var GitHubRequestError = class extends Error {
569
- status;
570
- constructor(message, status) {
571
- super(message);
572
- this.name = "GitHubRequestError";
573
- this.status = status;
574
- }
575
- };
576
- var GitHubPluginSetupError = class extends Error {
577
- constructor(message) {
578
- super(message);
579
- this.name = "GitHubPluginSetupError";
580
- }
581
- };
582
- function isRecord(value) {
583
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
584
- }
585
- function readEnv(name) {
586
- const value = process.env[name];
587
- if (typeof value !== "string") {
588
- return void 0;
589
- }
590
- const trimmed = value.trim();
591
- return trimmed ? trimmed : void 0;
592
- }
593
- function requireEnv(name) {
594
- const value = readEnv(name);
595
- if (!value) {
596
- throw new GitHubPluginSetupError(`Missing ${name}`);
597
- }
598
- return value;
599
- }
600
- function normalizeScopeList(scopes) {
601
- return [
602
- ...new Set(
603
- (scopes ?? []).flatMap((scope) => String(scope).split(/\s+/)).map((scope) => scope.trim()).filter(Boolean)
604
- )
605
- ].sort();
606
- }
607
- function normalizeOAuthScope(scope) {
608
- const normalized = normalizeScopeList(scope ? [scope] : []);
609
- return normalized.length ? normalized.join(" ") : void 0;
610
- }
611
- function hasRequiredOAuthScope(storedScope, requiredScope) {
612
- const required = normalizeScopeList(requiredScope ? [requiredScope] : []);
613
- if (required.length === 0) {
614
- return true;
615
- }
616
- const stored = new Set(normalizeScopeList(storedScope ? [storedScope] : []));
617
- if (stored.size === 0) {
618
- return false;
619
- }
620
- return required.every((scope) => stored.has(scope));
621
- }
622
- function isGitHubApiUrl(upstreamUrl) {
623
- return upstreamUrl.hostname.toLowerCase() === "api.github.com";
624
- }
625
- function base64Url(input) {
626
- return Buffer.from(input).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
627
- }
628
- function getPrivateKey(envName) {
629
- const raw = requireEnv(envName);
630
- let key;
631
- try {
632
- key = createPrivateKey({ key: raw, format: "pem" });
633
- } catch {
634
- throw new GitHubPluginSetupError(
635
- `Invalid ${envName}: expected a PEM-encoded RSA private key`
636
- );
637
- }
638
- if (key.asymmetricKeyType !== "rsa") {
639
- throw new GitHubPluginSetupError(
640
- `Invalid ${envName}: GitHub App signing requires an RSA private key`
641
- );
642
- }
643
- return key;
644
- }
645
- function createAppJwt(appId, privateKeyEnv) {
646
- const now = Math.floor(Date.now() / 1e3);
647
- const header = { alg: "RS256", typ: "JWT" };
648
- const payload = { iat: now - 60, exp: now + 9 * 60, iss: appId };
649
- const encodedHeader = base64Url(JSON.stringify(header));
650
- const encodedPayload = base64Url(JSON.stringify(payload));
651
- const signingInput = `${encodedHeader}.${encodedPayload}`;
652
- const signer = createSign("RSA-SHA256");
653
- signer.update(signingInput);
654
- signer.end();
655
- const signature = signer.sign(getPrivateKey(privateKeyEnv)).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
656
- return `${signingInput}.${signature}`;
657
- }
658
- async function githubRequest(apiBase, path, params) {
659
- const response = await fetch(`${apiBase}${path}`, {
660
- method: params.method ?? "GET",
661
- headers: {
662
- Accept: "application/vnd.github+json",
663
- Authorization: `Bearer ${params.token}`,
664
- "X-GitHub-Api-Version": "2022-11-28",
665
- ...params.body ? { "Content-Type": "application/json" } : void 0
666
- },
667
- ...params.body ? { body: JSON.stringify(params.body) } : void 0
668
- });
669
- const text = await response.text();
670
- let parsed;
671
- if (text) {
672
- try {
673
- parsed = JSON.parse(text);
674
- } catch {
675
- parsed = void 0;
676
- }
677
- }
678
- if (!response.ok) {
679
- const message = isRecord(parsed) && typeof parsed.message === "string" ? parsed.message : `GitHub API error ${response.status}`;
680
- throw new GitHubRequestError(message, response.status);
681
- }
682
- return parsed;
683
- }
684
- function buildOAuthTokenRequest(input) {
685
- const payload = {
686
- ...input.payload,
687
- client_id: input.clientId,
688
- client_secret: input.clientSecret
689
- };
690
- return {
691
- headers: {
692
- Accept: "application/json",
693
- "Content-Type": "application/x-www-form-urlencoded"
694
- },
695
- body: new URLSearchParams(payload)
696
- };
697
- }
698
- function parseOAuthResponseJson(responseText) {
699
- if (!responseText.trim()) {
700
- return void 0;
701
- }
702
- try {
703
- return JSON.parse(responseText);
704
- } catch {
705
- return void 0;
706
- }
707
- }
708
- function oauthErrorCode(data) {
709
- return isRecord(data) && typeof data.error === "string" ? data.error : void 0;
710
- }
711
- function isRejectedRefreshError(errorCode) {
712
- return errorCode === "bad_refresh_token" || errorCode === "invalid_grant";
713
- }
714
- function parseOAuthTokenResponse(data, requestedScope) {
715
- if (!isRecord(data)) {
716
- throw new Error("OAuth token response is invalid");
717
- }
718
- if (typeof data.access_token !== "string" || !data.access_token.trim()) {
719
- throw new Error("OAuth token response missing access_token");
720
- }
721
- if (typeof data.refresh_token !== "string" || !data.refresh_token.trim()) {
722
- throw new Error("OAuth token response missing refresh_token");
723
- }
724
- let scope = normalizeOAuthScope(requestedScope);
725
- if (data.scope !== void 0) {
726
- if (typeof data.scope !== "string") {
727
- throw new Error("OAuth token response returned invalid scope");
728
- }
729
- scope = normalizeOAuthScope(data.scope) ?? scope;
730
- }
731
- const result = {
732
- accessToken: data.access_token,
733
- refreshToken: data.refresh_token,
734
- ...scope ? { scope } : void 0
735
- };
736
- if (data.expires_in !== void 0) {
737
- if (typeof data.expires_in !== "number" || !Number.isFinite(data.expires_in) || data.expires_in <= 0) {
738
- throw new Error("OAuth token response returned invalid expires_in");
739
- }
740
- result.expiresAt = Date.now() + data.expires_in * 1e3;
741
- }
742
- if (data.refresh_token_expires_in !== void 0) {
743
- if (typeof data.refresh_token_expires_in !== "number" || !Number.isFinite(data.refresh_token_expires_in) || data.refresh_token_expires_in <= 0) {
744
- throw new Error(
745
- "OAuth token response returned invalid refresh_token_expires_in"
746
- );
747
- }
748
- result.refreshTokenExpiresAt = Date.now() + data.refresh_token_expires_in * 1e3;
749
- }
750
- return result;
751
- }
752
- async function refreshUserAccessToken(input) {
753
- const clientId = requireEnv(input.clientIdEnv);
754
- const clientSecret = requireEnv(input.clientSecretEnv);
755
- const request = buildOAuthTokenRequest({
756
- clientId,
757
- clientSecret,
758
- payload: {
759
- grant_type: "refresh_token",
760
- refresh_token: input.refreshToken
761
- }
762
- });
763
- const response = await fetch("https://github.com/login/oauth/access_token", {
764
- method: "POST",
765
- headers: request.headers,
766
- body: request.body,
767
- signal: AbortSignal.timeout(USER_REFRESH_TIMEOUT_MS)
768
- });
769
- const responseText = await response.text();
770
- const responseData = parseOAuthResponseJson(responseText);
771
- const errorCode = oauthErrorCode(responseData);
772
- if (isRejectedRefreshError(errorCode)) {
773
- throw new GitHubUserRefreshRejectedError(
774
- `GitHub user token refresh rejected: ${errorCode}`
775
- );
776
- }
777
- if (!response.ok || errorCode) {
778
- throw new Error(
779
- `GitHub user token refresh failed: ${response.status}${errorCode ? ` ${errorCode}` : ""}`
780
- );
781
- }
782
- try {
783
- return parseOAuthTokenResponse(responseData, input.requestedScope);
784
- } catch (error) {
785
- if (error instanceof Error && error.message === "OAuth token response missing access_token") {
786
- throw new GitHubUserRefreshRejectedError(error.message);
787
- }
788
- throw error;
789
- }
790
- }
791
- function leaseExpiry(expiresAt) {
792
- return expiresAt ? Math.min(expiresAt, Date.now() + MAX_LEASE_MS) : Date.now() + MAX_LEASE_MS;
793
- }
794
- function isGitSmartHttpDomain(domain) {
795
- return domain.toLowerCase() === "github.com";
796
- }
797
- function authorizationFor(domain, token) {
798
- if (isGitSmartHttpDomain(domain)) {
799
- return `Basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`;
800
- }
801
- return `Bearer ${token}`;
802
- }
803
- function createCredentialLease(input) {
804
- return {
805
- type: "lease",
806
- lease: {
807
- ...input.account ? { account: input.account } : void 0,
808
- ...input.authorization ? { authorization: input.authorization } : void 0,
809
- expiresAt: new Date(input.expiresAtMs).toISOString(),
810
- headerTransforms: (input.domains ?? (input.authorization ? GITHUB_ASSET_UPLOAD_CREDENTIAL_DOMAINS : GITHUB_CREDENTIAL_DOMAINS)).map((domain) => ({
811
- domain,
812
- headers: {
813
- Authorization: authorizationFor(domain, input.token)
814
- }
815
- }))
816
- }
817
- };
818
- }
819
- function githubUserAuthorization(scope) {
820
- return {
821
- type: "oauth",
822
- provider: "github",
823
- ...scope ? { scope } : void 0
824
- };
825
- }
826
- function credentialNeeded(message, scope, allowAuthorization = true) {
827
- return {
828
- type: "needed",
829
- message,
830
- ...allowAuthorization ? { authorization: githubUserAuthorization(scope) } : void 0
831
- };
832
- }
833
- function credentialUnavailable(message) {
834
- return {
835
- type: "unavailable",
836
- message
837
- };
838
- }
839
- function parseInstallationTokenResponse(data) {
840
- if (!isRecord(data)) {
841
- throw new Error("GitHub installation token response is invalid");
842
- }
843
- const token = data.token;
844
- if (typeof token !== "string" || !token.trim()) {
845
- throw new Error("GitHub installation token response missing token");
846
- }
847
- const expiresAt = data.expires_at;
848
- const expiresAtMs = typeof expiresAt === "string" ? Date.parse(expiresAt) : Number.NaN;
849
- if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {
850
- throw new Error(
851
- "GitHub installation token response returned invalid expires_at"
852
- );
853
- }
854
- return { token, expiresAtMs };
855
- }
856
- function readInstallationPermissions(installation) {
857
- if (!isRecord(installation) || !isRecord(installation.permissions)) {
858
- throw new Error("GitHub installation response missing permissions");
859
- }
860
- return readGrantPermissions(installation.permissions);
861
- }
862
- function decodeGitHubPathSegment(value) {
863
- try {
864
- const decoded = decodeURIComponent(value).trim();
865
- return decoded && !decoded.includes("/") ? decoded : void 0;
866
- } catch {
867
- return void 0;
868
- }
869
- }
870
- function githubRepositoryFromUrl(upstreamUrl) {
871
- const segments = upstreamUrl.pathname.split("/").filter(Boolean);
872
- if (isGitHubApiUrl(upstreamUrl) && segments[0]?.toLowerCase() === "repos") {
873
- const owner2 = segments[1] ? decodeGitHubPathSegment(segments[1]) : void 0;
874
- const name2 = segments[2] ? decodeGitHubPathSegment(segments[2]) : void 0;
875
- return owner2 && name2 ? { owner: owner2, name: name2 } : void 0;
876
- }
877
- if (upstreamUrl.hostname.toLowerCase() !== "github.com") {
878
- return void 0;
879
- }
880
- const owner = segments[0] ? decodeGitHubPathSegment(segments[0]) : void 0;
881
- const rawName = segments[1]?.replace(/\.git$/i, "");
882
- const name = rawName ? decodeGitHubPathSegment(rawName) : void 0;
883
- return owner && name ? { owner, name } : void 0;
884
- }
885
- async function resolveUserAccount(tokens) {
886
- const account = await githubRequest("https://api.github.com", "/user", {
887
- token: tokens.accessToken
888
- });
889
- if (!isRecord(account)) {
890
- throw new Error("GitHub user response is invalid");
891
- }
892
- const id = account.id;
893
- const login = account.login;
894
- if (typeof id !== "number" && typeof id !== "string" || typeof login !== "string" || !login.trim()) {
895
- throw new Error("GitHub user response missing id or login");
896
- }
897
- const url = typeof account.html_url === "string" ? account.html_url : void 0;
898
- return {
899
- handle: login.trim(),
900
- id: String(id),
901
- label: login.trim(),
902
- ...url ? { url } : void 0
903
- };
904
- }
905
- async function listVerifiedUserEmails(tokens) {
906
- let emails;
907
- try {
908
- emails = await githubRequest("https://api.github.com", "/user/emails", {
909
- token: tokens.accessToken
910
- });
911
- } catch (error) {
912
- if (error instanceof GitHubRequestError && (error.status === 403 || error.status === 404)) {
913
- return [];
914
- }
915
- throw error;
916
- }
917
- if (!Array.isArray(emails)) {
918
- throw new Error("GitHub user emails response is invalid");
919
- }
920
- return emails.flatMap(
921
- (entry) => isRecord(entry) && entry.verified === true && typeof entry.email === "string" && entry.email.trim() ? [entry.email.trim()] : []
922
- );
923
- }
924
- async function tokensWithAccount(tokenSlot, stored, scope) {
925
- if (stored.account) {
926
- return { ok: true, tokens: stored };
927
- }
928
- let account;
929
- try {
930
- account = await resolveUserAccount(stored);
931
- } catch (error) {
932
- if (error instanceof GitHubRequestError && (error.status === 401 || error.status === 403)) {
933
- return {
934
- ok: false,
935
- result: credentialNeeded(
936
- "Your GitHub authorization needs to be refreshed.",
937
- scope
938
- )
939
- };
940
- }
941
- throw error;
942
- }
943
- const updated = { ...stored, account };
944
- await tokenSlot.set(updated);
945
- return { ok: true, tokens: updated };
946
- }
947
- function shouldRefreshUserToken(stored, now = Date.now()) {
948
- return stored.expiresAt !== void 0 && stored.expiresAt - now < REFRESH_BUFFER_MS;
949
- }
950
- function canUseStoredUserToken(stored) {
951
- return stored.expiresAt === void 0 || stored.expiresAt > Date.now() && !shouldRefreshUserToken(stored);
952
- }
953
- async function refreshUserTokensWithLock(tokenSlot, scope, options) {
954
- return await tokenSlot.withRefresh(async () => {
955
- const latest = await tokenSlot.get();
956
- if (!latest) {
957
- return {
958
- ok: false,
959
- result: credentialNeeded("Connect your GitHub account.", scope)
960
- };
961
- }
962
- if (!hasRequiredOAuthScope(latest.scope, scope)) {
963
- return {
964
- ok: false,
965
- result: credentialNeeded(
966
- "Your GitHub authorization needs to be refreshed.",
967
- scope
968
- )
969
- };
970
- }
971
- if (canUseStoredUserToken(latest)) {
972
- return { ok: true, tokens: latest };
973
- }
974
- let refreshed;
975
- try {
976
- refreshed = await refreshUserAccessToken({
977
- clientIdEnv: options.clientIdEnv,
978
- clientSecretEnv: options.clientSecretEnv,
979
- refreshToken: latest.refreshToken,
980
- requestedScope: latest.scope ?? scope
981
- });
982
- } catch (error) {
983
- if (!(error instanceof GitHubUserRefreshRejectedError)) {
984
- throw error;
985
- }
986
- return {
987
- ok: false,
988
- result: credentialNeeded(
989
- "Your GitHub authorization has expired.",
990
- scope
991
- )
992
- };
993
- }
994
- if (!hasRequiredOAuthScope(refreshed.scope, scope)) {
995
- return {
996
- ok: false,
997
- result: credentialNeeded(
998
- "Your GitHub authorization needs to be refreshed.",
999
- scope
1000
- )
1001
- };
1002
- }
1003
- const refreshedTokens = {
1004
- ...latest.refreshTokenExpiresAt ? { refreshTokenExpiresAt: latest.refreshTokenExpiresAt } : void 0,
1005
- ...refreshed,
1006
- ...latest.account ? { account: latest.account } : void 0
1007
- };
1008
- await tokenSlot.set(refreshedTokens);
1009
- return { ok: true, tokens: refreshedTokens };
1010
- });
1011
- }
1012
- async function issueUserCredential(ctx, options) {
1013
- const scope = options.userScope;
1014
- const tokenSlot = ctx.tokens.currentUser ?? ctx.tokens.credentialSubject;
1015
- if (!tokenSlot) {
1016
- return credentialNeeded(
1017
- "GitHub write access requires a current user or delegated user credential subject.",
1018
- scope,
1019
- false
1020
- );
1021
- }
1022
- const stored = await tokenSlot.get();
1023
- if (!stored) {
1024
- return credentialNeeded(
1025
- "GitHub write access requires user authorization.",
1026
- scope
1027
- );
1028
- }
1029
- if (!hasRequiredOAuthScope(stored.scope, scope)) {
1030
- return credentialNeeded(
1031
- "Your GitHub authorization needs to be refreshed.",
1032
- scope
1033
- );
1034
- }
1035
- const now = Date.now();
1036
- if (stored.expiresAt !== void 0 && stored.expiresAt - now < REFRESH_BUFFER_MS) {
1037
- const refreshResult = await refreshUserTokensWithLock(
1038
- tokenSlot,
1039
- scope,
1040
- options
1041
- );
1042
- if (!refreshResult.ok) {
1043
- return refreshResult.result;
1044
- }
1045
- const withAccount = await tokensWithAccount(
1046
- tokenSlot,
1047
- refreshResult.tokens,
1048
- scope
1049
- );
1050
- if (!withAccount.ok) {
1051
- return withAccount.result;
1052
- }
1053
- return createCredentialLease({
1054
- account: withAccount.tokens.account,
1055
- token: withAccount.tokens.accessToken,
1056
- expiresAtMs: leaseExpiry(withAccount.tokens.expiresAt),
1057
- authorization: githubUserAuthorization(scope)
1058
- });
1059
- }
1060
- if (stored.expiresAt === void 0 || stored.expiresAt > Date.now()) {
1061
- const withAccount = await tokensWithAccount(tokenSlot, stored, scope);
1062
- if (!withAccount.ok) {
1063
- return withAccount.result;
1064
- }
1065
- return createCredentialLease({
1066
- account: withAccount.tokens.account,
1067
- token: withAccount.tokens.accessToken,
1068
- expiresAtMs: leaseExpiry(withAccount.tokens.expiresAt),
1069
- authorization: githubUserAuthorization(scope)
1070
- });
1071
- }
1072
- return credentialNeeded("Your GitHub authorization has expired.", scope);
1073
- }
1074
- async function issueInstallationToken(options) {
1075
- const appId = requireEnv(options.appIdEnv);
1076
- const installationIdRaw = requireEnv(options.installationIdEnv);
1077
- const installationId = Number(installationIdRaw);
1078
- if (!Number.isSafeInteger(installationId) || installationId <= 0) {
1079
- throw new GitHubPluginSetupError(`Invalid ${options.installationIdEnv}`);
1080
- }
1081
- const appJwt = createAppJwt(appId, options.privateKeyEnv);
1082
- const permissions = "permissions" in options ? options.permissions : typeof options.loadPermissions === "function" ? await options.loadPermissions({ appJwt, installationId }) : void 0;
1083
- const repositories = "repositories" in options ? options.repositories : void 0;
1084
- const repositoryIds = "repositoryIds" in options ? options.repositoryIds : void 0;
1085
- const body = {
1086
- ...permissions ? { permissions } : void 0,
1087
- ...repositories ? { repositories } : void 0,
1088
- ...repositoryIds ? { repository_ids: repositoryIds } : void 0
1089
- };
1090
- const accessTokenResponse = await githubRequest(
1091
- "https://api.github.com",
1092
- `/app/installations/${installationId}/access_tokens`,
1093
- {
1094
- method: "POST",
1095
- token: appJwt,
1096
- body
1097
- }
1098
- );
1099
- const parsedToken = parseInstallationTokenResponse(accessTokenResponse);
1100
- return {
1101
- expiresAtMs: Math.min(parsedToken.expiresAtMs, Date.now() + MAX_LEASE_MS),
1102
- token: parsedToken.token
1103
- };
1104
- }
1105
- async function issueInstallationCredential(options) {
1106
- const token = await issueInstallationToken(options);
1107
- return createCredentialLease({
1108
- token: token.token,
1109
- expiresAtMs: token.expiresAtMs
1110
- });
1111
- }
1112
- async function issueGitHubCredential(ctx, options) {
1113
- const installation = {
1114
- appIdEnv: options.appIdEnv,
1115
- installationIdEnv: options.installationIdEnv,
1116
- privateKeyEnv: options.privateKeyEnv
1117
- };
1118
- try {
1119
- if (ctx.grant.name === "installation-read") {
1120
- return await issueInstallationCredential({
1121
- ...installation,
1122
- ...options.readPermissions
1123
- });
1124
- }
1125
- if (ctx.grant.name === "installation-write") {
1126
- return await issueInstallationCredential(installation);
1127
- }
1128
- if (USER_TOKEN_GRANTS.has(ctx.grant.name)) {
1129
- return await issueUserCredential(ctx, options);
1130
- }
1131
- } catch (error) {
1132
- if (error instanceof GitHubPluginSetupError) {
1133
- return credentialUnavailable(error.message);
1134
- }
1135
- throw error;
1136
- }
1137
- throw new Error(
1138
- `GitHub plugin cannot issue unknown grant "${ctx.grant.name}".`
1139
- );
1140
- }
1141
- function createPermissionCache() {
1142
- let cached;
1143
- let pending;
1144
- return async ({ appJwt, installationId }) => {
1145
- if (cached && cached.expiresAtMs > Date.now()) {
1146
- return cached.permissions;
1147
- }
1148
- pending ??= githubRequest(
1149
- "https://api.github.com",
1150
- `/app/installations/${installationId}`,
1151
- { token: appJwt }
1152
- ).then((installation) => {
1153
- const permissions = readInstallationPermissions(installation);
1154
- cached = {
1155
- expiresAtMs: Date.now() + MAX_LEASE_MS,
1156
- permissions
1157
- };
1158
- return permissions;
1159
- }).finally(() => {
1160
- pending = void 0;
1161
- });
1162
- return await pending;
1163
- };
1164
- }
1165
-
1166
- // src/webhooks/event-targets.ts
1167
- import * as z3 from "zod";
1168
- var gitHubSenderSchema = z3.object({
1169
- id: z3.number(),
1170
- login: z3.string().min(1)
1171
- });
1172
- function gitHubSenderData(sender) {
1173
- return { senderId: sender?.id, senderLogin: sender?.login };
1174
- }
1175
- function gitHubDoneBy(login) {
1176
- const handle = login?.trim();
1177
- return handle ? { doneBy: { provider: "github", handle } } : void 0;
1178
- }
1179
- function nonBlank(value) {
1180
- return value?.trim() || void 0;
1181
- }
1182
- function titleAndBodyText(item) {
1183
- const parts = [
1184
- item.title ? `Title: ${item.title}` : void 0,
1185
- nonBlank(item.body)
1186
- ].filter((part) => part !== void 0);
1187
- return parts.length > 0 ? parts.join("\n\n") : void 0;
1188
- }
1189
- function providerTime(value) {
1190
- if (!value) return void 0;
1191
- const parsed = Date.parse(value);
1192
- return Number.isFinite(parsed) ? parsed : void 0;
1193
- }
1194
- function definedValues(data) {
1195
- return Object.fromEntries(
1196
- Object.entries(data).filter(([, value]) => value !== void 0)
1197
- );
1198
- }
1199
- function gitHubEventKey(deliveryId, eventType) {
1200
- return `github:${deliveryId}:${eventType}`;
1201
- }
1202
- function pullRequestTargets(event, repo) {
1203
- const { terminal: _terminal, ...repositoryEvent } = event;
1204
- return [
1205
- event,
1206
- {
1207
- ...repositoryEvent,
1208
- identifier: gitHubRepositoryResource({ repo }).identifier
1209
- }
1210
- ];
1211
- }
1212
-
1213
- // src/webhooks/fail-open-log.ts
1214
- function logFailOpenFailure(log, message, error, metadata) {
1215
- const attributes = {
1216
- ...metadata,
1217
- errorType: error instanceof Error ? error.name : "UnknownError"
1218
- };
1219
- if (error instanceof GitHubRequestError && error.status >= 500) {
1220
- log?.warn(message, {
1221
- ...attributes,
1222
- "http.response.status_code": error.status
1223
- });
1224
- return;
1225
- }
1226
- log?.error(message, attributes);
1227
- }
1228
-
1229
- // src/webhooks/check-suite.ts
1230
- var CHECK_SUITE_PULL_REQUEST_MATCH_KEYS = /* @__PURE__ */ new Set([
1231
- "isDraft",
1232
- "openerEmail",
1233
- "openerRole",
1234
- "openerUsername"
1235
- ]);
1236
- var checkRunRepoRefSchema = z4.object({
1237
- id: z4.number(),
1238
- name: z4.string().min(1),
1239
- url: z4.string().min(1)
1240
- }).passthrough();
1241
- var checkRunPullRequestSideSchema = z4.object({
1242
- ref: z4.string().optional(),
1243
- repo: checkRunRepoRefSchema,
1244
- sha: z4.string().optional()
1245
- }).passthrough();
1246
- var checkRunPullRequestSchema = z4.object({
1247
- base: checkRunPullRequestSideSchema,
1248
- head: checkRunPullRequestSideSchema.optional(),
1249
- id: z4.number().optional(),
1250
- number: z4.number(),
1251
- url: z4.string().optional()
1252
- }).passthrough();
1253
- var repositorySchema = z4.object({
1254
- full_name: z4.string().min(1),
1255
- id: z4.number(),
1256
- name: z4.string().min(1),
1257
- owner: z4.object({ login: z4.string().min(1) }).passthrough()
1258
- }).passthrough();
1259
- var checkSuiteWebhookSchema = z4.object({
1260
- action: z4.string(),
1261
- check_suite: z4.object({
1262
- app: z4.object({
1263
- name: z4.string().optional().nullable(),
1264
- slug: z4.string().optional().nullable()
1265
- }).optional().nullable(),
1266
- conclusion: z4.string().optional().nullable(),
1267
- /** Branch name for the suite head commit when GitHub sends it. */
1268
- head_branch: z4.string().optional().nullable(),
1269
- head_sha: z4.string().optional(),
1270
- id: z4.number().optional(),
1271
- latest_check_runs_count: z4.number().optional().nullable(),
1272
- pull_requests: z4.array(checkRunPullRequestSchema)
1273
- }),
1274
- repository: repositorySchema
1275
- });
1276
- var checkRunsListResponseSchema = z4.object({
1277
- check_runs: z4.array(z4.unknown()).optional()
1278
- }).passthrough();
1279
- function isCheckSuiteRepositoryPullRequest(pullRequest, repositoryId) {
1280
- return pullRequest.base.repo.id === repositoryId;
1281
- }
1282
- function checkSuiteEventType(conclusion) {
1283
- if (conclusion === "failure" || conclusion === "timed_out") {
1284
- return "pull_request.checks.failed";
1285
- }
1286
- if (conclusion === "success") {
1287
- return "pull_request.checks.recovered";
1288
- }
1289
- return void 0;
1290
- }
1291
- function isGitHubNotFoundError(error) {
1292
- return error instanceof Error && error.name === "GitHubRequestError" && "status" in error && error.status === 404;
1293
- }
1294
- var FAILING_CHECK_CONCLUSIONS = /* @__PURE__ */ new Set([
1295
- "failure",
1296
- "timed_out",
1297
- "cancelled",
1298
- "action_required",
1299
- "startup_failure"
1300
- ]);
1301
- function buildCheckSuiteUrl(args) {
1302
- return `https://github.com/${args.repo}/commit/${args.headSha}/checks?check_suite_id=${args.checkSuiteId}`;
1303
- }
1304
- function oneLineLabel(value, maxLength = 80) {
1305
- return value.replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim().slice(0, maxLength);
1306
- }
1307
- function checkSuiteHeadBranch(value) {
1308
- const branch = value?.trim();
1309
- return branch ? branch : void 0;
1310
- }
1311
- var checkSuiteEventDataSchema = z4.object({
1312
- repo: gitHubRepoDataSchema,
1313
- pullRequest: z4.number().optional(),
1314
- commitSha: gitHubCommitShaDataSchema.optional(),
1315
- suiteConclusion: z4.string().min(1),
1316
- isDraft: z4.boolean().optional(),
1317
- openerUsername: z4.string().min(1).optional(),
1318
- openerEmail: z4.string().min(1).optional(),
1319
- headBranch: z4.string().min(1).optional(),
1320
- checkSuiteId: z4.number().optional(),
1321
- checkSuiteUrl: z4.string().min(1).optional(),
1322
- appName: z4.string().min(1).optional(),
1323
- latestCheckRunsCount: z4.number().optional(),
1324
- // Only system-set handles. Check names come from workflow YAML, so they
1325
- // go in the untrusted text.
1326
- failingChecks: z4.array(
1327
- z4.object({
1328
- conclusion: z4.string(),
1329
- htmlUrl: z4.string().optional(),
1330
- checkRunId: z4.number()
1331
- }).strict()
1332
- ).optional()
1333
- }).strict();
1334
- function buildCheckSuiteEvent(args) {
1335
- const pullRequestNumber = args.pullRequestNumber;
1336
- const resource = pullRequestNumber === void 0 ? gitHubRepositoryResource({ repo: args.repo }) : gitHubPullRequestResource({
1337
- number: pullRequestNumber,
1338
- repo: args.repo
1339
- });
1340
- const shortSha = args.headSha?.slice(0, 12);
1341
- const failingChecks = (args.failingChecks ?? []).slice(0, 12);
1342
- const failingCount = failingChecks.length;
1343
- const branchSuffix = args.headBranch ? ` on ${args.headBranch}` : "";
1344
- const incidents = args.eventType === "pull_request.checks.failed" ? args.githubIncidents ?? [] : [];
1345
- const incidentSuffix = incidents.length > 0 ? ` githubstatus.com lists ${incidents.length} open or recent GitHub incident${incidents.length === 1 ? "" : "s"}.` : "";
1346
- const trustedSummary = args.eventType === "pull_request.checks.failed" ? `${resource.label} checks failed${failingCount > 0 ? ` (${failingCount})` : ""}${shortSha ? ` for ${shortSha}` : ""}${branchSuffix}.${incidentSuffix}` : `${resource.label} check suite recovered${shortSha ? ` for ${shortSha}` : ""}${branchSuffix}.`;
1347
- const data = checkSuiteEventDataSchema.parse(
1348
- definedValues({
1349
- repo: args.repo,
1350
- pullRequest: pullRequestNumber,
1351
- // A short SHA counts as missing, so a commitSha filter does not match.
1352
- commitSha: gitHubCommitShaDataSchema.safeParse(args.headSha).data,
1353
- suiteConclusion: args.suiteConclusion,
1354
- isDraft: args.isDraft,
1355
- openerUsername: args.openerUsername,
1356
- openerEmail: args.openerEmail,
1357
- headBranch: args.headBranch,
1358
- checkSuiteId: args.checkSuiteId,
1359
- checkSuiteUrl: args.checkSuiteId !== void 0 && args.headSha ? buildCheckSuiteUrl({
1360
- checkSuiteId: args.checkSuiteId,
1361
- headSha: args.headSha,
1362
- repo: args.repo
1363
- }) : void 0,
1364
- appName: args.appName ? oneLineLabel(args.appName, 120) : void 0,
1365
- latestCheckRunsCount: args.latestCheckRunsCount,
1366
- failingChecks: args.eventType === "pull_request.checks.failed" && failingCount > 0 ? failingChecks.map((check) => ({
1367
- conclusion: check.conclusion,
1368
- ...check.htmlUrl ? { htmlUrl: check.htmlUrl } : void 0,
1369
- checkRunId: check.checkRunId
1370
- })) : void 0
1371
- })
1372
- );
1373
- const untrustedParts = args.eventType === "pull_request.checks.failed" ? failingChecks.map((check) => {
1374
- const name = oneLineLabel(check.name);
1375
- if (!name) return void 0;
1376
- return check.htmlUrl ? `${name}: ${check.htmlUrl}` : name;
1377
- }).filter((part) => part !== void 0) : [];
1378
- const untrustedSections = [
1379
- ...untrustedParts.length > 0 ? [
1380
- [`Failed checks:`, ...untrustedParts.map((part) => `- ${part}`)].join(
1381
- "\n"
1382
- )
1383
- ] : [],
1384
- ...incidents.length > 0 ? [
1385
- [
1386
- "GitHub status incidents:",
1387
- ...incidents.map(
1388
- (incident) => `- ${oneLineLabel(incident.name, 160)} (${incident.status}; ${incident.components.join(", ") || "no components"}; started ${incident.startedAt}${incident.resolvedAt ? `, resolved ${incident.resolvedAt}` : ""}): ${incident.url}`
1389
- )
1390
- ].join("\n")
1391
- ] : []
1392
- ];
1393
- const untrustedText = untrustedSections.length > 0 ? untrustedSections.join("\n\n") : void 0;
1394
- return {
1395
- eventKey: gitHubEventKey(
1396
- args.deliveryId,
1397
- pullRequestNumber === void 0 ? args.eventType : `${args.eventType}:${pullRequestNumber}`
1398
- ),
1399
- eventType: args.eventType,
1400
- occurredAtMs: Date.now(),
1401
- identifier: resource.identifier,
1402
- trustedSummary,
1403
- data,
1404
- ...untrustedText ? { untrustedText } : void 0
1405
- };
1406
- }
1407
- function selectFailingChecks(checkRuns, options) {
1408
- if (!Array.isArray(checkRuns)) return [];
1409
- const failing = [];
1410
- for (const run of checkRuns) {
1411
- if (!run || typeof run !== "object" || Array.isArray(run)) continue;
1412
- const record2 = run;
1413
- if (options?.checkSuiteId !== void 0) {
1414
- const suite = record2.check_suite;
1415
- const suiteId = suite && typeof suite === "object" && !Array.isArray(suite) && typeof suite.id === "number" ? suite.id : void 0;
1416
- if (suiteId !== void 0 && suiteId !== options.checkSuiteId) continue;
1417
- }
1418
- const conclusion = typeof record2.conclusion === "string" ? record2.conclusion : void 0;
1419
- const name = typeof record2.name === "string" ? record2.name.trim() : "";
1420
- const checkRunId = typeof record2.id === "number" && Number.isSafeInteger(record2.id) ? record2.id : void 0;
1421
- if (!conclusion || !FAILING_CHECK_CONCLUSIONS.has(conclusion)) continue;
1422
- if (!name || checkRunId === void 0) continue;
1423
- const htmlUrl = typeof record2.html_url === "string" && record2.html_url.length > 0 ? record2.html_url : void 0;
1424
- failing.push({
1425
- checkRunId,
1426
- conclusion,
1427
- ...htmlUrl ? { htmlUrl } : void 0,
1428
- name
1429
- });
1430
- }
1431
- return failing.slice(0, 12);
1432
- }
1433
- function normalizeCheckSuiteEvents(deliveryId, body, options) {
1434
- const parsed = checkSuiteWebhookSchema.safeParse(body);
1435
- if (!parsed.success || parsed.data.action !== "completed") return [];
1436
- const conclusion = parsed.data.check_suite.conclusion;
1437
- const eventType = checkSuiteEventType(conclusion);
1438
- if (!eventType || typeof conclusion !== "string") return [];
1439
- const suite = parsed.data.check_suite;
1440
- const appName = suite.app?.name?.trim() || suite.app?.slug?.trim() || void 0;
1441
- const headBranch = checkSuiteHeadBranch(suite.head_branch);
1442
- const headSha = typeof suite.head_sha === "string" && /^[0-9a-f]{7,40}$/i.test(suite.head_sha) ? suite.head_sha : void 0;
1443
- const repository = parsed.data.repository;
1444
- const repo = repository.full_name;
1445
- const shared = {
1446
- appName,
1447
- checkSuiteId: suite.id,
1448
- deliveryId,
1449
- eventType,
1450
- failingChecks: eventType === "pull_request.checks.failed" ? options?.failingChecks : void 0,
1451
- githubIncidents: eventType === "pull_request.checks.failed" ? options?.githubIncidents : void 0,
1452
- headSha,
1453
- latestCheckRunsCount: typeof suite.latest_check_runs_count === "number" ? suite.latest_check_runs_count : void 0,
1454
- repo,
1455
- suiteConclusion: conclusion
1456
- };
1457
- const sameRepoPullRequests = suite.pull_requests.filter(
1458
- (pullRequest) => isCheckSuiteRepositoryPullRequest(pullRequest, repository.id)
1459
- );
1460
- if (sameRepoPullRequests.length === 0) {
1461
- return [
1462
- buildCheckSuiteEvent({
1463
- ...shared,
1464
- ...headBranch ? { headBranch } : void 0
1465
- })
1466
- ];
1467
- }
1468
- return sameRepoPullRequests.flatMap((pullRequest) => {
1469
- const facts = options?.pullRequestFactsByNumber?.[pullRequest.number];
1470
- const pullRequestHeadBranch = checkSuiteHeadBranch(pullRequest.head?.ref) ?? headBranch;
1471
- return pullRequestTargets(
1472
- buildCheckSuiteEvent({
1473
- ...shared,
1474
- ...facts?.openerEmail ? { openerEmail: facts.openerEmail } : void 0,
1475
- ...facts?.openerUsername ? { openerUsername: facts.openerUsername } : void 0,
1476
- ...pullRequestHeadBranch ? { headBranch: pullRequestHeadBranch } : void 0,
1477
- ...typeof facts?.isDraft === "boolean" ? { isDraft: facts.isDraft } : void 0,
1478
- pullRequestNumber: pullRequest.number
1479
- }),
1480
- repo
1481
- );
1482
- });
1483
- }
1484
- function checkSuitePullRequests(body) {
1485
- const parsed = checkSuiteWebhookSchema.safeParse(body);
1486
- if (!parsed.success || parsed.data.action !== "completed") return [];
1487
- const repository = parsed.data.repository;
1488
- return parsed.data.check_suite.pull_requests.filter(
1489
- (pullRequest) => isCheckSuiteRepositoryPullRequest(pullRequest, repository.id)
1490
- ).map((pullRequest) => ({
1491
- number: pullRequest.number,
1492
- repositoryFullName: repository.full_name
1493
- }));
1494
- }
1495
- function parseCheckSuitePublishTargets(body) {
1496
- const parsed = checkSuiteWebhookSchema.safeParse(body);
1497
- if (!parsed.success || parsed.data.action !== "completed") return void 0;
1498
- const eventType = checkSuiteEventType(parsed.data.check_suite.conclusion);
1499
- if (!eventType) return void 0;
1500
- const repository = parsed.data.repository;
1501
- const repo = repository.full_name;
1502
- const identifiers = /* @__PURE__ */ new Set([
1503
- gitHubRepositoryResource({ repo }).identifier
1504
- ]);
1505
- for (const pullRequest of parsed.data.check_suite.pull_requests) {
1506
- if (!isCheckSuiteRepositoryPullRequest(pullRequest, repository.id))
1507
- continue;
1508
- identifiers.add(
1509
- gitHubPullRequestResource({ number: pullRequest.number, repo }).identifier
1510
- );
1511
- }
1512
- return {
1513
- // Every copy sets this repo, so a broad trigger for another repo adds
1514
- // no lazy keys.
1515
- data: { repo: gitHubRepoDataSchema.parse(repo) },
1516
- eventTypes: [eventType],
1517
- identifiers: [...identifiers]
1518
- };
1519
- }
1520
- function parseCheckSuiteFactsTarget(body, options) {
1521
- const parsed = checkSuiteWebhookSchema.safeParse(body);
1522
- if (!parsed.success || parsed.data.action !== "completed") return void 0;
1523
- const conclusion = parsed.data.check_suite.conclusion;
1524
- if (conclusion !== "failure" && conclusion !== "timed_out" && conclusion !== "success") {
1525
- return void 0;
1526
- }
1527
- const headSha = parsed.data.check_suite.head_sha;
1528
- const checkSuiteId = parsed.data.check_suite.id;
1529
- if (typeof headSha !== "string" || !/^[0-9a-f]{7,40}$/i.test(headSha) || typeof checkSuiteId !== "number") {
1530
- return void 0;
1531
- }
1532
- const repository = parsed.data.repository;
1533
- const pullRequestNumbers = [
1534
- ...new Set(
1535
- parsed.data.check_suite.pull_requests.filter(
1536
- (pullRequest) => isCheckSuiteRepositoryPullRequest(pullRequest, repository.id)
1537
- ).map((pullRequest) => pullRequest.number)
1538
- )
1539
- ];
1540
- const loadFailingChecks = conclusion === "failure" || conclusion === "timed_out";
1541
- const loadPullRequestFacts = Boolean(
1542
- options?.loadPullRequestFacts && pullRequestNumbers.length > 0
1543
- );
1544
- if (!loadFailingChecks && !loadPullRequestFacts) {
1545
- return void 0;
1546
- }
1547
- return {
1548
- checkSuiteId,
1549
- headSha,
1550
- loadFailingChecks,
1551
- loadPullRequestFacts,
1552
- owner: repository.owner.login,
1553
- pullRequestNumbers,
1554
- repoName: repository.name
1555
- };
1556
- }
1557
- function checkRunsFromResponse(value) {
1558
- const parsed = checkRunsListResponseSchema.safeParse(value);
1559
- if (!parsed.success) return [];
1560
- return parsed.data.check_runs ?? [];
1561
- }
1562
- function pullRequestFactsFromResponse(value) {
1563
- if (!isRecord(value)) return void 0;
1564
- const facts = {};
1565
- if (typeof value.draft === "boolean") facts.isDraft = value.draft;
1566
- const user = value.user;
1567
- if (isRecord(user)) {
1568
- const username = typeof user.login === "string" ? user.login.trim() : void 0;
1569
- if (username) facts.openerUsername = username;
1570
- const email = typeof user.email === "string" ? user.email.trim() : void 0;
1571
- if (email) facts.openerEmail = email;
1572
- }
1573
- return Object.keys(facts).length > 0 ? facts : void 0;
1574
- }
1575
- function needsCheckSuitePullRequestFacts(matchKeys) {
1576
- for (const key of matchKeys) {
1577
- if (CHECK_SUITE_PULL_REQUEST_MATCH_KEYS.has(key)) return true;
1578
- }
1579
- return false;
1580
- }
1581
- async function loadCheckSuiteFacts(args) {
1582
- const target = parseCheckSuiteFactsTarget(args.body, {
1583
- loadPullRequestFacts: args.loadPullRequestFacts
1584
- });
1585
- if (!target) return void 0;
1586
- const facts = {};
1587
- if (target.loadFailingChecks) {
1588
- try {
1589
- const token = await issueInstallationToken({
1590
- appIdEnv: args.appIdEnv,
1591
- installationIdEnv: args.installationIdEnv,
1592
- permissions: { checks: "read" },
1593
- privateKeyEnv: args.privateKeyEnv,
1594
- repositories: [target.repoName]
1595
- });
1596
- const response = await githubRequest(
1597
- "https://api.github.com",
1598
- `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/check-suites/${target.checkSuiteId}/check-runs?filter=latest&per_page=100`,
1599
- { token: token.token }
1600
- );
1601
- const failing = selectFailingChecks(checkRunsFromResponse(response), {
1602
- checkSuiteId: target.checkSuiteId
1603
- });
1604
- if (failing.length > 0) facts.failingChecks = failing;
1605
- } catch (error) {
1606
- logFailOpenFailure(args.log, "GitHub check suite load failed", error, {
1607
- checkSuiteId: target.checkSuiteId,
1608
- repository: `${target.owner}/${target.repoName}`
1609
- });
1610
- }
1611
- }
1612
- if (target.loadFailingChecks && args.loadGitHubIncidents) {
1613
- try {
1614
- const incidents = await args.loadGitHubIncidents();
1615
- if (incidents.length > 0) facts.githubIncidents = incidents;
1616
- } catch (error) {
1617
- logFailOpenFailure(args.log, "GitHub status load failed", error, {});
1618
- }
1619
- }
1620
- if (target.loadPullRequestFacts) {
1621
- try {
1622
- const token = await issueInstallationToken({
1623
- appIdEnv: args.appIdEnv,
1624
- installationIdEnv: args.installationIdEnv,
1625
- permissions: { pull_requests: "read" },
1626
- privateKeyEnv: args.privateKeyEnv,
1627
- repositories: [target.repoName]
1628
- });
1629
- const loaded = await Promise.all(
1630
- target.pullRequestNumbers.map(async (number5) => {
1631
- try {
1632
- const response = await githubRequest(
1633
- "https://api.github.com",
1634
- `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/pulls/${number5}`,
1635
- { token: token.token }
1636
- );
1637
- const loadedFacts = pullRequestFactsFromResponse(response);
1638
- return loadedFacts ? [number5, loadedFacts] : void 0;
1639
- } catch (error) {
1640
- if (!isGitHubNotFoundError(error)) {
1641
- logFailOpenFailure(
1642
- args.log,
1643
- "GitHub pull request data load failed",
1644
- error,
1645
- {
1646
- pullRequest: number5,
1647
- repository: `${target.owner}/${target.repoName}`
1648
- }
1649
- );
1650
- }
1651
- return void 0;
1652
- }
1653
- })
1654
- );
1655
- const pullRequestFactsByNumber = {};
1656
- for (const entry of loaded) {
1657
- if (!entry) continue;
1658
- pullRequestFactsByNumber[entry[0]] = entry[1];
1659
- }
1660
- if (Object.keys(pullRequestFactsByNumber).length > 0) {
1661
- facts.pullRequestFactsByNumber = pullRequestFactsByNumber;
1662
- }
1663
- } catch (error) {
1664
- logFailOpenFailure(
1665
- args.log,
1666
- "GitHub check suite pull request data load failed",
1667
- error,
1668
- {
1669
- checkSuiteId: target.checkSuiteId,
1670
- repository: `${target.owner}/${target.repoName}`
1671
- }
1672
- );
1673
- }
1674
- }
1675
- return facts.failingChecks || facts.pullRequestFactsByNumber ? facts : void 0;
1676
- }
1677
-
1678
- // src/webhooks/issue-update.ts
1679
- import * as z5 from "zod";
1680
-
1681
- // src/webhooks/ownership.ts
1682
- import { lexer } from "marked";
1683
- var GITHUB_BOT_NOREPLY_EMAIL = /^(?<userId>[1-9]\d*)\+(?<login>[^@]+\[bot\])@users\.noreply\.github\.com$/i;
1684
- function parseGitHubBotIdentity(value) {
1685
- const match = GITHUB_BOT_NOREPLY_EMAIL.exec(value?.trim() ?? "");
1686
- const login = match?.groups?.login;
1687
- const userId = match?.groups?.userId;
1688
- if (!login || !userId) return void 0;
1689
- return {
1690
- login,
1691
- userId: Number(userId)
1692
- };
1693
- }
1694
- function botLoginFromEmail(value) {
1695
- return parseGitHubBotIdentity(value)?.login;
1696
- }
1697
- function isBotLogin(login, botEmail) {
1698
- const botLogin = botLoginFromEmail(botEmail)?.toLowerCase();
1699
- return Boolean(botLogin && login?.trim().toLowerCase() === botLogin);
1700
- }
1701
- function botUserIdFromEmail(value) {
1702
- return parseGitHubBotIdentity(value)?.userId;
1703
- }
1704
- var SKIPPED_TOKEN_TYPES = /* @__PURE__ */ new Set(["blockquote", "code", "codespan", "html"]);
1705
- function ownTokenText(tokens, separator = "") {
1706
- return tokens.map((token) => {
1707
- if (SKIPPED_TOKEN_TYPES.has(token.type)) return " ";
1708
- if (token.type === "list") {
1709
- return token.items.map((item) => ownTokenText(item.tokens, "\n")).join("\n");
1710
- }
1711
- if (token.type === "table") {
1712
- const table = token;
1713
- return [table.header, ...table.rows].flat().map((cell) => ownTokenText(cell.tokens)).join(" ");
1714
- }
1715
- if ("tokens" in token && token.tokens) return ownTokenText(token.tokens);
1716
- return "text" in token ? token.text : token.raw;
1717
- }).join(separator);
1718
- }
1719
- function ownCommentText(text) {
1720
- return ownTokenText(lexer(text, { gfm: true }), "\n");
1721
- }
1722
- function mentionsBotLogin(text, botEmail) {
1723
- const slug = botLoginFromEmail(botEmail)?.replace(/\[bot\]$/i, "");
1724
- if (!slug) return false;
1725
- const escaped = slug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1726
- return new RegExp(`(?:^|[^\\w-])@${escaped}(?![\\w-])`, "i").test(
1727
- ownCommentText(text)
1728
- );
1729
- }
1730
-
1731
- // src/webhooks/issue-update.ts
1732
- var issueUpdateWebhookSchema = z5.object({
1733
- action: z5.enum(GITHUB_ISSUE_UPDATE_CHANGES),
1734
- assignee: z5.object({ login: z5.string().nullish() }).nullish(),
1735
- changes: z5.record(z5.string(), z5.unknown()).optional(),
1736
- issue: z5.object({
1737
- body: z5.string().optional().nullable(),
1738
- number: z5.number(),
1739
- title: z5.string().optional(),
1740
- updated_at: z5.string().optional()
1741
- }),
1742
- label: z5.object({ name: z5.string() }).nullish(),
1743
- milestone: z5.object({ title: z5.string() }).nullish(),
1744
- repository: z5.object({ full_name: z5.string().min(1) }),
1745
- sender: gitHubSenderSchema.optional()
1746
- });
1747
- function describeIssueUpdate(delivery) {
1748
- const assignee = nonBlank(delivery.assignee?.login);
1749
- switch (delivery.action) {
1750
- case "edited": {
1751
- const fields = ["title", "body"].filter(
1752
- (field) => field in (delivery.changes ?? {})
1753
- );
1754
- return {
1755
- change: fields.length ? `edited (${fields.join(", ")})` : "edited"
1756
- };
1757
- }
1758
- case "labeled":
1759
- case "unlabeled":
1760
- return {
1761
- change: delivery.action,
1762
- untrustedText: delivery.label ? `Label: ${delivery.label.name}` : void 0
1763
- };
1764
- case "assigned":
1765
- return { change: assignee ? `assigned to ${assignee}` : "assigned" };
1766
- case "unassigned":
1767
- return {
1768
- change: assignee ? `unassigned from ${assignee}` : "unassigned"
1769
- };
1770
- case "milestoned":
1771
- case "demilestoned":
1772
- return {
1773
- change: delivery.action,
1774
- untrustedText: delivery.milestone ? `Milestone: ${delivery.milestone.title}` : void 0
1775
- };
1776
- }
1777
- }
1778
- function normalizeIssueUpdateEvents(deliveryId, body, botEmail) {
1779
- const parsed = issueUpdateWebhookSchema.safeParse(body);
1780
- if (!parsed.success) return void 0;
1781
- const update = describeIssueUpdate(parsed.data);
1782
- const { action, label, sender } = parsed.data;
1783
- const doneBy = sender?.login;
1784
- if (isBotLogin(doneBy, botEmail)) return [];
1785
- const input = {
1786
- number: parsed.data.issue.number,
1787
- repo: parsed.data.repository.full_name
1788
- };
1789
- const issue = gitHubIssueResource(input);
1790
- const untrustedText = [
1791
- update.untrustedText,
1792
- titleAndBodyText(parsed.data.issue)
1793
- ].filter((part) => part !== void 0).join("\n\n");
1794
- return [issue, gitHubRepositoryResource(input)].map((resource) => ({
1795
- eventKey: gitHubEventKey(deliveryId, "issue.updated"),
1796
- eventType: "issue.updated",
1797
- occurredAtMs: providerTime(parsed.data.issue.updated_at) ?? Date.now(),
1798
- identifier: resource.identifier,
1799
- trustedSummary: `${issue.label} was ${update.change}${doneBy ? ` by ${doneBy}` : ""}.`,
1800
- ...gitHubDoneBy(doneBy),
1801
- // `change` and `label` let an automation select one label change in code,
1802
- // so the model does not decide from untrusted text.
1803
- data: definedValues({
1804
- repo: gitHubRepoDataSchema.parse(input.repo),
1805
- issue: input.number,
1806
- change: action,
1807
- label: label?.name.toLowerCase(),
1808
- ...gitHubSenderData(sender)
1809
- }),
1810
- ...untrustedText ? { untrustedText } : void 0
1811
- }));
1812
- }
1813
-
1814
- // src/webhooks/events.ts
1815
- var repositorySchema2 = z6.object({ full_name: z6.string().min(1) }).passthrough();
1816
- var deploymentSchema = z6.object({
1817
- created_at: z6.string().optional(),
1818
- environment: z6.string().trim().min(1),
1819
- id: z6.number(),
1820
- sha: z6.string().regex(/^[0-9a-f]{40}$/i)
1821
- }).passthrough();
1822
- var deploymentWorkflowSchema = {
1823
- workflow: z6.object({ id: z6.number(), path: z6.string().min(1) }).passthrough().nullish(),
1824
- workflow_run: z6.object({ id: z6.number() }).passthrough().nullish()
1825
- };
1826
- var deploymentWebhookSchema = z6.object({
1827
- action: z6.string(),
1828
- deployment: deploymentSchema,
1829
- repository: repositorySchema2,
1830
- ...deploymentWorkflowSchema
1831
- }).passthrough();
1832
- var canonicalDeploymentEventSchema = z6.object({
1833
- action: z6.string(),
1834
- commitSha: z6.string().regex(/^[0-9a-f]{40}$/i),
1835
- createdAt: z6.string().optional(),
1836
- deploymentId: z6.number(),
1837
- environment: z6.string().min(1),
1838
- repo: z6.string().min(1),
1839
- workflowId: z6.number().optional(),
1840
- workflowPath: z6.string().min(1).optional(),
1841
- workflowRunId: z6.number().optional()
1842
- }).strict();
1843
- function canonicalDeploymentFields(data) {
1844
- return {
1845
- action: data.action,
1846
- commitSha: data.deployment.sha,
1847
- createdAt: data.deployment.created_at,
1848
- deploymentId: data.deployment.id,
1849
- environment: data.deployment.environment,
1850
- repo: data.repository.full_name,
1851
- workflowId: data.workflow?.id,
1852
- workflowPath: data.workflow?.path,
1853
- workflowRunId: data.workflow_run?.id
1854
- };
1855
- }
1856
- function parseDeploymentEvent(body) {
1857
- const parsed = deploymentWebhookSchema.safeParse(body);
1858
- if (!parsed.success) return void 0;
1859
- return canonicalDeploymentEventSchema.parse(
1860
- canonicalDeploymentFields(parsed.data)
1861
- );
1862
- }
1863
- function normalizeDeploymentEvent(deliveryId, body) {
1864
- const parsed = parseDeploymentEvent(body);
1865
- if (!parsed || parsed.action !== "created") return [];
1866
- const eventType = "deployment.created";
1867
- const { label } = gitHubDeploymentSourceResource(parsed);
1868
- return deploymentTargets(parsed).map(({ identifier }) => ({
1869
- eventKey: gitHubEventKey(deliveryId, eventType),
1870
- eventType,
1871
- occurredAtMs: providerTime(parsed.createdAt) ?? Date.now(),
1872
- identifier,
1873
- trustedSummary: `${label} was created (deployment ${parsed.deploymentId}).`,
1874
- data: deploymentEventData(parsed)
1875
- }));
1876
- }
1877
- var deploymentStatusWebhookSchema = deploymentWebhookSchema.extend({
1878
- deployment_status: z6.object({
1879
- created_at: z6.string().optional(),
1880
- description: z6.string().optional().nullable(),
1881
- state: z6.string()
1882
- }).passthrough()
1883
- });
1884
- var canonicalDeploymentStatusEventSchema = canonicalDeploymentEventSchema.extend({
1885
- description: z6.string().optional().nullable(),
1886
- state: z6.string(),
1887
- statusCreatedAt: z6.string().optional()
1888
- }).strict();
1889
- function parseDeploymentStatusEvent(body) {
1890
- const parsed = deploymentStatusWebhookSchema.safeParse(body);
1891
- if (!parsed.success) return void 0;
1892
- return canonicalDeploymentStatusEventSchema.parse({
1893
- ...canonicalDeploymentFields(parsed.data),
1894
- description: parsed.data.deployment_status.description,
1895
- state: parsed.data.deployment_status.state,
1896
- statusCreatedAt: parsed.data.deployment_status.created_at
1897
- });
1898
- }
1899
- function deploymentStatusEventType(state) {
1900
- switch (state) {
1901
- case "queued":
1902
- case "pending":
1903
- case "in_progress":
1904
- return `deployment.${state}`;
1905
- case "success":
1906
- return "deployment.succeeded";
1907
- case "failure":
1908
- return "deployment.failed";
1909
- case "error":
1910
- return "deployment.error";
1911
- default:
1912
- return void 0;
1913
- }
1914
- }
1915
- function normalizeDeploymentStatusEvent(deliveryId, body) {
1916
- const parsed = parseDeploymentStatusEvent(body);
1917
- if (!parsed || parsed.action !== "created") return [];
1918
- const eventType = deploymentStatusEventType(parsed.state);
1919
- if (!eventType) return [];
1920
- const outcome = eventType === "deployment.succeeded" ? "succeeded" : eventType === "deployment.failed" ? "failed" : eventType === "deployment.error" ? "reported an error" : eventType === "deployment.in_progress" ? "started" : `is ${parsed.state}`;
1921
- const terminal = eventType === "deployment.succeeded" || eventType === "deployment.failed" || eventType === "deployment.error";
1922
- const { label } = gitHubDeploymentSourceResource(parsed);
1923
- return deploymentTargets(parsed).map(
1924
- ({ completeOnTerminalEvent, identifier }) => ({
1925
- eventKey: gitHubEventKey(deliveryId, eventType),
1926
- eventType,
1927
- occurredAtMs: providerTime(parsed.statusCreatedAt) ?? Date.now(),
1928
- identifier,
1929
- ...terminal && completeOnTerminalEvent ? { terminal: true } : void 0,
1930
- trustedSummary: `${label} ${outcome} (deployment ${parsed.deploymentId}).`,
1931
- data: deploymentEventData(parsed),
1932
- untrustedText: parsed.description ?? void 0
1933
- })
1934
- );
1935
- }
1936
- var deploymentEventDataSchema = z6.object({
1937
- repo: gitHubRepoDataSchema,
1938
- commitSha: gitHubCommitShaDataSchema,
1939
- deploymentId: z6.number(),
1940
- // Trimmed and lowercase, the same as in the identifier.
1941
- environment: z6.string().trim().min(1).toLowerCase(),
1942
- workflowId: z6.number().optional(),
1943
- workflowPath: z6.string().min(1).optional(),
1944
- workflowRunId: z6.number().optional()
1945
- }).strict();
1946
- function deploymentEventData(input) {
1947
- return deploymentEventDataSchema.parse(
1948
- definedValues({
1949
- repo: input.repo,
1950
- commitSha: input.commitSha,
1951
- deploymentId: input.deploymentId,
1952
- environment: input.environment,
1953
- workflowId: input.workflowId,
1954
- workflowPath: input.workflowPath,
1955
- workflowRunId: input.workflowRunId
1956
- })
1957
- );
1958
- }
1959
- function deploymentTargets(input) {
1960
- return [
1961
- {
1962
- completeOnTerminalEvent: true,
1963
- identifier: gitHubDeploymentSourceResource(input).identifier
1964
- },
1965
- {
1966
- completeOnTerminalEvent: false,
1967
- identifier: gitHubDeploymentSourceResource({
1968
- commitSha: input.commitSha,
1969
- repo: input.repo
1970
- }).identifier
1971
- },
1972
- {
1973
- completeOnTerminalEvent: false,
1974
- identifier: gitHubRepositoryResource({ repo: input.repo }).identifier
1975
- }
1976
- ];
1977
- }
1978
- var gitHubUserSchema = z6.object({
1979
- email: z6.string().nullish(),
1980
- login: z6.string().nullish()
1981
- });
1982
- var commentSchema = z6.object({
1983
- body: z6.string(),
1984
- id: z6.number(),
1985
- user: z6.object({ login: z6.string().optional() }).optional()
1986
- });
1987
- var commentAuthorDataSchema = z6.object({
1988
- mentionsBot: z6.boolean().optional(),
1989
- senderId: z6.number().optional(),
1990
- senderLogin: z6.string().min(1).optional()
1991
- });
1992
- function commentAuthorData(input) {
1993
- return {
1994
- mentionsBot: input.botEmail ? mentionsBotLogin(input.text ?? "", input.botEmail) : void 0,
1995
- ...gitHubSenderData(input.sender)
1996
- };
1997
- }
1998
- var pullRequestSchema = z6.object({
1999
- draft: z6.boolean().optional(),
2000
- head: z6.object({ ref: z6.string().nullish() }).nullish(),
2001
- number: z6.number(),
2002
- user: gitHubUserSchema.nullish()
2003
- });
2004
- var pullRequestEventDataSchema = commentAuthorDataSchema.extend({
2005
- repo: gitHubRepoDataSchema,
2006
- pullRequest: z6.number(),
2007
- headBranch: z6.string().min(1).optional(),
2008
- isDraft: z6.boolean().optional(),
2009
- openerEmail: z6.string().min(1).optional(),
2010
- openerUsername: z6.string().min(1).optional(),
2011
- commentId: z6.number().optional(),
2012
- commentKind: z6.enum(["conversation", "review", "review_body"]).optional()
2013
- }).strict();
2014
- function pullRequestEventData(input) {
2015
- const { pullRequest } = input;
2016
- return pullRequestEventDataSchema.parse(
2017
- definedValues({
2018
- repo: input.repo,
2019
- pullRequest: pullRequest.number,
2020
- headBranch: nonBlank(pullRequest.head?.ref),
2021
- isDraft: pullRequest.draft,
2022
- openerEmail: nonBlank(pullRequest.user?.email),
2023
- openerUsername: nonBlank(pullRequest.user?.login),
2024
- ...input.comment
2025
- })
2026
- );
2027
- }
2028
- var issueEventDataSchema = commentAuthorDataSchema.extend({
2029
- repo: gitHubRepoDataSchema,
2030
- issue: z6.number(),
2031
- commentId: z6.number().optional()
2032
- }).strict();
2033
- function issueEventData(input) {
2034
- return issueEventDataSchema.parse(definedValues(input));
2035
- }
2036
- var issueCommentWebhookSchema = z6.object({
2037
- action: z6.string(),
2038
- comment: commentSchema,
2039
- issue: z6.object({
2040
- draft: z6.boolean().optional(),
2041
- number: z6.number(),
2042
- pull_request: z6.object({ url: z6.string().min(1) }).optional(),
2043
- user: gitHubUserSchema.nullish()
2044
- }),
2045
- repository: repositorySchema2,
2046
- sender: gitHubSenderSchema.optional()
2047
- });
2048
- function normalizeIssueCommentEvents(deliveryId, body, botEmail) {
2049
- const parsed = issueCommentWebhookSchema.safeParse(body);
2050
- if (!parsed.success || parsed.data.action !== "created") return [];
2051
- const { comment, issue, sender } = parsed.data;
2052
- const author = comment.user?.login;
2053
- if (isBotLogin(author, botEmail)) return [];
2054
- const input = {
2055
- number: issue.number,
2056
- repo: parsed.data.repository.full_name
2057
- };
2058
- const writtenBy = commentAuthorData({ botEmail, sender, text: comment.body });
2059
- if (issue.pull_request) {
2060
- const eventType = "pull_request.comment.created";
2061
- const resource = gitHubPullRequestResource(input);
2062
- return pullRequestTargets(
2063
- {
2064
- eventKey: gitHubEventKey(deliveryId, eventType),
2065
- eventType,
2066
- occurredAtMs: Date.now(),
2067
- identifier: resource.identifier,
2068
- trustedSummary: `${resource.label} received a comment${author ? ` from ${author}` : ""}.`,
2069
- ...gitHubDoneBy(author),
2070
- data: pullRequestEventData({
2071
- comment: {
2072
- commentId: comment.id,
2073
- commentKind: "conversation",
2074
- ...writtenBy
2075
- },
2076
- pullRequest: issue,
2077
- repo: input.repo
2078
- }),
2079
- untrustedText: comment.body
2080
- },
2081
- input.repo
2082
- );
2083
- }
2084
- const issueResource = gitHubIssueResource(input);
2085
- const repository = gitHubRepositoryResource(input);
2086
- const data = issueEventData({
2087
- repo: input.repo,
2088
- issue: input.number,
2089
- commentId: comment.id,
2090
- ...writtenBy
2091
- });
2092
- return [issueResource, repository].map((resource) => ({
2093
- eventKey: gitHubEventKey(deliveryId, "issue.comment.created"),
2094
- eventType: "issue.comment.created",
2095
- occurredAtMs: Date.now(),
2096
- identifier: resource.identifier,
2097
- trustedSummary: `${issueResource.label} received a comment${author ? ` from ${author}` : ""}.`,
2098
- ...gitHubDoneBy(author),
2099
- data,
2100
- untrustedText: comment.body
2101
- }));
2102
- }
2103
- var issueWebhookSchema = z6.object({
2104
- action: z6.string(),
2105
- issue: z6.object({
2106
- body: z6.string().optional().nullable(),
2107
- closed_at: z6.string().optional().nullable(),
2108
- created_at: z6.string().optional(),
2109
- number: z6.number(),
2110
- title: z6.string().optional(),
2111
- updated_at: z6.string().optional()
2112
- }),
2113
- repository: repositorySchema2
2114
- });
2115
- function normalizeIssueEvents(deliveryId, body, botEmail) {
2116
- const updates = normalizeIssueUpdateEvents(deliveryId, body, botEmail);
2117
- if (updates) return updates;
2118
- const parsed = issueWebhookSchema.safeParse(body);
2119
- if (!parsed.success) return [];
2120
- const state = parsed.data.action === "opened" ? "opened" : parsed.data.action === "closed" ? "closed" : parsed.data.action === "reopened" ? "reopened" : void 0;
2121
- if (!state) return [];
2122
- const input = {
2123
- number: parsed.data.issue.number,
2124
- repo: parsed.data.repository.full_name
2125
- };
2126
- const issue = gitHubIssueResource(input);
2127
- const repository = gitHubRepositoryResource(input);
2128
- const occurredAtMs = providerTime(
2129
- state === "opened" ? parsed.data.issue.created_at : state === "closed" ? parsed.data.issue.closed_at : parsed.data.issue.updated_at
2130
- ) ?? Date.now();
2131
- const data = issueEventData({ repo: input.repo, issue: input.number });
2132
- const untrustedText = titleAndBodyText(parsed.data.issue);
2133
- return [issue, repository].map((resource) => ({
2134
- eventKey: gitHubEventKey(deliveryId, `issue.${state}`),
2135
- eventType: `issue.${state}`,
2136
- occurredAtMs,
2137
- identifier: resource.identifier,
2138
- trustedSummary: `${issue.label} was ${state}.`,
2139
- data,
2140
- ...untrustedText ? { untrustedText } : void 0
2141
- }));
2142
- }
2143
- var pullRequestReviewCommentWebhookSchema = z6.object({
2144
- action: z6.string(),
2145
- comment: commentSchema,
2146
- pull_request: pullRequestSchema,
2147
- repository: repositorySchema2,
2148
- sender: gitHubSenderSchema.optional()
2149
- });
2150
- function normalizePullRequestReviewCommentEvent(deliveryId, body, botEmail) {
2151
- const parsed = pullRequestReviewCommentWebhookSchema.safeParse(body);
2152
- if (!parsed.success || parsed.data.action !== "created") return [];
2153
- const { comment, pull_request: pullRequest, sender } = parsed.data;
2154
- const author = comment.user?.login;
2155
- if (isBotLogin(author, botEmail)) return [];
2156
- const eventType = "pull_request.review_comment.created";
2157
- const repo = parsed.data.repository.full_name;
2158
- const resource = gitHubPullRequestResource({
2159
- number: pullRequest.number,
2160
- repo
2161
- });
2162
- return pullRequestTargets(
2163
- {
2164
- eventKey: gitHubEventKey(deliveryId, eventType),
2165
- eventType,
2166
- occurredAtMs: Date.now(),
2167
- identifier: resource.identifier,
2168
- trustedSummary: `${resource.label} received an inline review comment${author ? ` from ${author}` : ""}.`,
2169
- ...gitHubDoneBy(author),
2170
- data: pullRequestEventData({
2171
- comment: {
2172
- commentId: comment.id,
2173
- commentKind: "review",
2174
- ...commentAuthorData({ botEmail, sender, text: comment.body })
2175
- },
2176
- pullRequest,
2177
- repo
2178
- }),
2179
- untrustedText: comment.body
2180
- },
2181
- repo
2182
- );
2183
- }
2184
- var pullRequestReviewWebhookSchema = z6.object({
2185
- action: z6.string(),
2186
- pull_request: pullRequestSchema,
2187
- repository: repositorySchema2,
2188
- review: z6.object({
2189
- body: z6.string().optional().nullable(),
2190
- // Only the feedback reaction needs the id, so a review without one is
2191
- // still delivered.
2192
- id: z6.number().optional(),
2193
- state: z6.string(),
2194
- user: z6.object({ login: z6.string().optional() }).optional()
2195
- }),
2196
- sender: gitHubSenderSchema.optional()
2197
- });
2198
- function normalizePullRequestReviewEvent(deliveryId, body, botEmail) {
2199
- const parsed = pullRequestReviewWebhookSchema.safeParse(body);
2200
- if (!parsed.success || parsed.data.action !== "submitted") return [];
2201
- const { pull_request: pullRequest, review, sender } = parsed.data;
2202
- if (isBotLogin(review.user?.login, botEmail)) return [];
2203
- const reviewState = review.state.toUpperCase();
2204
- const eventType = reviewState === "APPROVED" ? "pull_request.review.approved" : reviewState === "CHANGES_REQUESTED" ? "pull_request.review.changes_requested" : reviewState === "COMMENTED" ? "pull_request.review.commented" : void 0;
2205
- if (!eventType) return [];
2206
- const repo = parsed.data.repository.full_name;
2207
- const resource = gitHubPullRequestResource({
2208
- number: pullRequest.number,
2209
- repo
2210
- });
2211
- const reviewer = review.user?.login;
2212
- const event = {
2213
- eventKey: gitHubEventKey(deliveryId, eventType),
2214
- eventType,
2215
- occurredAtMs: Date.now(),
2216
- identifier: resource.identifier,
2217
- trustedSummary: eventType === "pull_request.review.approved" ? `${resource.label} was approved${reviewer ? ` by ${reviewer}` : ""}.` : eventType === "pull_request.review.changes_requested" ? `${resource.label} received requested changes${reviewer ? ` from ${reviewer}` : ""}.` : `${resource.label} received a review comment${reviewer ? ` from ${reviewer}` : ""}.`,
2218
- ...gitHubDoneBy(reviewer),
2219
- data: pullRequestEventData({
2220
- comment: {
2221
- ...review.id !== void 0 && nonBlank(review.body) ? { commentId: review.id, commentKind: "review_body" } : void 0,
2222
- ...commentAuthorData({ botEmail, sender, text: review.body })
2223
- },
2224
- pullRequest,
2225
- repo
2226
- }),
2227
- untrustedText: review.body ?? void 0
2228
- };
2229
- const events = pullRequestTargets(event, repo);
2230
- if (eventType !== "pull_request.review.approved" || !nonBlank(review.body)) {
2231
- return events;
2232
- }
2233
- return [
2234
- ...events,
2235
- ...pullRequestTargets(
2236
- {
2237
- ...event,
2238
- eventKey: gitHubEventKey(deliveryId, "pull_request.review.commented"),
2239
- eventType: "pull_request.review.commented"
2240
- },
2241
- repo
2242
- )
2243
- ];
2244
- }
2245
- var pullRequestWebhookSchema = z6.object({
2246
- action: z6.string(),
2247
- pull_request: pullRequestSchema.extend({
2248
- body: z6.string().optional().nullable(),
2249
- closed_at: z6.string().optional().nullable(),
2250
- created_at: z6.string().optional(),
2251
- merged: z6.boolean().optional(),
2252
- merged_at: z6.string().optional().nullable(),
2253
- title: z6.string().optional(),
2254
- updated_at: z6.string().optional()
2255
- }),
2256
- repository: repositorySchema2
2257
- });
2258
- function normalizePullRequestEvent(deliveryId, body) {
2259
- const parsed = pullRequestWebhookSchema.safeParse(body);
2260
- if (!parsed.success) return [];
2261
- const { pull_request: pullRequest } = parsed.data;
2262
- const repo = parsed.data.repository.full_name;
2263
- const resource = gitHubPullRequestResource({
2264
- number: pullRequest.number,
2265
- repo
2266
- });
2267
- const data = pullRequestEventData({ pullRequest, repo });
2268
- const readyData = pullRequestEventData({
2269
- pullRequest: { ...pullRequest, draft: false },
2270
- repo
2271
- });
2272
- const untrustedText = titleAndBodyText(pullRequest);
2273
- const lifecycleEvents = (event) => pullRequestTargets(
2274
- {
2275
- eventKey: gitHubEventKey(deliveryId, event.eventType),
2276
- eventType: event.eventType,
2277
- occurredAtMs: event.occurredAtMs,
2278
- identifier: resource.identifier,
2279
- trustedSummary: event.trustedSummary,
2280
- data: event.isDraft === false ? readyData : data,
2281
- ...event.untrustedText ? { untrustedText: event.untrustedText } : void 0
2282
- },
2283
- repo
2284
- );
2285
- if (parsed.data.action === "opened") {
2286
- const openedAtMs = providerTime(pullRequest.created_at) ?? Date.now();
2287
- const events = lifecycleEvents({
2288
- eventType: "pull_request.opened",
2289
- occurredAtMs: openedAtMs,
2290
- trustedSummary: `${resource.label} was opened.`,
2291
- untrustedText
2292
- });
2293
- if (pullRequest.draft !== true) {
2294
- events.push(
2295
- ...lifecycleEvents({
2296
- eventType: "pull_request.ready_for_review",
2297
- isDraft: false,
2298
- occurredAtMs: openedAtMs,
2299
- trustedSummary: `${resource.label} is ready for review.`,
2300
- untrustedText
2301
- })
2302
- );
2303
- }
2304
- return events;
2305
- }
2306
- if (parsed.data.action === "ready_for_review") {
2307
- return lifecycleEvents({
2308
- eventType: "pull_request.ready_for_review",
2309
- isDraft: false,
2310
- occurredAtMs: providerTime(pullRequest.updated_at) ?? Date.now(),
2311
- trustedSummary: `${resource.label} is ready for review.`,
2312
- untrustedText
2313
- });
2314
- }
2315
- return gitHubPullRequestTerminalEvents(body);
2316
- }
2317
- function gitHubPullRequestTerminalEvents(body) {
2318
- const parsed = pullRequestWebhookSchema.safeParse(body);
2319
- if (!parsed.success || parsed.data.action !== "closed") return [];
2320
- const { pull_request: pullRequest } = parsed.data;
2321
- const repo = parsed.data.repository.full_name;
2322
- const resource = gitHubPullRequestResource({
2323
- number: pullRequest.number,
2324
- repo
2325
- });
2326
- const merged = pullRequest.merged === true;
2327
- const eventType = merged ? "pull_request.merged" : "pull_request.closed_unmerged";
2328
- const occurredAtMs = providerTime(merged ? pullRequest.merged_at : pullRequest.closed_at) ?? providerTime(pullRequest.updated_at) ?? Date.now();
2329
- return pullRequestTargets(
2330
- {
2331
- // A pull request merges once. It can close, reopen, and close again,
2332
- // so the key of a close also has its time.
2333
- eventKey: merged ? `github:${resource.identifier}:${eventType}` : `github:${resource.identifier}:${eventType}:${occurredAtMs}`,
2334
- eventType,
2335
- occurredAtMs,
2336
- identifier: resource.identifier,
2337
- terminal: true,
2338
- trustedSummary: merged ? `${resource.label} was merged.` : `${resource.label} was closed without being merged.`,
2339
- data: pullRequestEventData({ pullRequest, repo })
2340
- },
2341
- repo
2342
- );
2343
- }
2344
- var releaseWebhookSchema = z6.object({
2345
- action: z6.string(),
2346
- release: z6.object({
2347
- body: z6.string().optional().nullable(),
2348
- draft: z6.boolean().optional(),
2349
- id: z6.number(),
2350
- name: z6.string().optional().nullable(),
2351
- prerelease: z6.boolean().optional(),
2352
- published_at: z6.string().optional().nullable(),
2353
- tag_name: z6.string().min(1)
2354
- }).passthrough(),
2355
- repository: repositorySchema2
2356
- }).passthrough();
2357
- var releaseEventDataSchema = z6.object({
2358
- repo: gitHubRepoDataSchema,
2359
- tag: gitHubReleaseTagDataSchema
2360
- }).strict();
2361
- function releaseSourceTargets(input) {
2362
- return [
2363
- {
2364
- completeOnTerminalEvent: true,
2365
- resource: gitHubReleaseSourceResource(input)
2366
- },
2367
- {
2368
- completeOnTerminalEvent: false,
2369
- resource: gitHubReleaseSourceResource({ repo: input.repo })
2370
- }
2371
- ];
2372
- }
2373
- function normalizeReleaseEvent(deliveryId, body) {
2374
- const parsed = releaseWebhookSchema.safeParse(body);
2375
- if (!parsed.success || parsed.data.action !== "published") return [];
2376
- if (parsed.data.release.draft) return [];
2377
- const eventType = "release.published";
2378
- const repo = parsed.data.repository.full_name;
2379
- const tag = parsed.data.release.tag_name.trim();
2380
- if (!tag) return [];
2381
- const untrustedParts = [
2382
- `Tag: ${tag}`,
2383
- parsed.data.release.name?.trim() ? `Name: ${parsed.data.release.name.trim()}` : void 0,
2384
- parsed.data.release.body?.trim() || void 0
2385
- ].filter((part) => part !== void 0);
2386
- const untrustedText = untrustedParts.length > 0 ? untrustedParts.join("\n\n") : void 0;
2387
- const data = releaseEventDataSchema.parse({ repo, tag });
2388
- return releaseSourceTargets({ repo, tag }).map(
2389
- ({ completeOnTerminalEvent, resource }) => ({
2390
- eventKey: gitHubEventKey(deliveryId, eventType),
2391
- eventType,
2392
- occurredAtMs: providerTime(parsed.data.release.published_at) ?? Date.now(),
2393
- identifier: resource.identifier,
2394
- ...completeOnTerminalEvent ? { terminal: true } : void 0,
2395
- trustedSummary: `${resource.label} was published (release ${parsed.data.release.id}).`,
2396
- data,
2397
- ...untrustedText ? { untrustedText } : void 0
2398
- })
2399
- );
2400
- }
2401
- function normalizeGitHubEvents(args) {
2402
- switch (args.eventName) {
2403
- case "deployment":
2404
- return normalizeDeploymentEvent(args.deliveryId, args.body);
2405
- case "deployment_status":
2406
- return normalizeDeploymentStatusEvent(args.deliveryId, args.body);
2407
- case "pull_request":
2408
- return normalizePullRequestEvent(args.deliveryId, args.body);
2409
- case "issues":
2410
- return normalizeIssueEvents(args.deliveryId, args.body, args.botEmail);
2411
- case "pull_request_review":
2412
- return normalizePullRequestReviewEvent(
2413
- args.deliveryId,
2414
- args.body,
2415
- args.botEmail
2416
- );
2417
- case "issue_comment":
2418
- return normalizeIssueCommentEvents(
2419
- args.deliveryId,
2420
- args.body,
2421
- args.botEmail
2422
- );
2423
- case "pull_request_review_comment":
2424
- return normalizePullRequestReviewCommentEvent(
2425
- args.deliveryId,
2426
- args.body,
2427
- args.botEmail
2428
- );
2429
- case "check_suite":
2430
- return normalizeCheckSuiteEvents(
2431
- args.deliveryId,
2432
- args.body,
2433
- args.checkSuiteFacts
2434
- );
2435
- case "release":
2436
- return normalizeReleaseEvent(args.deliveryId, args.body);
2437
- default:
2438
- return [];
2439
- }
2440
- }
2441
-
2442
- export {
2443
- normalizePermissions,
2444
- readGrantPermissions,
2445
- gitHubRepoDataSchema,
2446
- GITHUB_ISSUE_EVENTS,
2447
- GITHUB_ISSUE_SUGGESTED_EVENTS,
2448
- GITHUB_ISSUE_MATCH_FIELDS,
2449
- GITHUB_ISSUE_IDENTIFIER,
2450
- gitHubIssueSubscribable,
2451
- GITHUB_DEPLOYMENT_EVENTS,
2452
- GITHUB_DEPLOYMENT_SUGGESTED_EVENTS,
2453
- GITHUB_DEPLOYMENT_MATCH_FIELDS,
2454
- GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER,
2455
- gitHubDeploymentSourceSubscribable,
2456
- GITHUB_PULL_REQUEST_EVENTS,
2457
- gitHubPullRequestEventGuidance,
2458
- gitHubPullRequestSubscription,
2459
- gitHubPullRequestCreateWatch,
2460
- GITHUB_PULL_REQUEST_SUGGESTED_EVENTS,
2461
- GITHUB_PULL_REQUEST_MATCH_FIELDS,
2462
- GITHUB_PULL_REQUEST_IDENTIFIER,
2463
- gitHubPullRequestResource,
2464
- gitHubPullRequestSubscribable,
2465
- GITHUB_RELEASE_EVENTS,
2466
- GITHUB_RELEASE_MATCH_FIELDS,
2467
- GITHUB_RELEASE_SUGGESTED_EVENTS,
2468
- GITHUB_RELEASE_SOURCE_IDENTIFIER,
2469
- gitHubReleaseSourceSubscribable,
2470
- GITHUB_REPOSITORY_IDENTIFIER,
2471
- GITHUB_REPOSITORY_EVENTS,
2472
- GITHUB_REPOSITORY_SUGGESTED_EVENTS,
2473
- gitHubRepositorySubscribable,
2474
- botLoginFromEmail,
2475
- isBotLogin,
2476
- botUserIdFromEmail,
2477
- GITHUB_APP_ID_ENV,
2478
- GITHUB_APP_PRIVATE_KEY_ENV,
2479
- GITHUB_INSTALLATION_ID_ENV,
2480
- GITHUB_AUTH_TOKEN_ENV,
2481
- GITHUB_AUTH_TOKEN_PLACEHOLDER,
2482
- GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES,
2483
- HTTP_READ_METHODS,
2484
- CREATE_TOOL_ROUTING_GUIDANCE,
2485
- USER_WRITE_REQUIREMENTS,
2486
- GitHubRequestError,
2487
- isRecord,
2488
- readEnv,
2489
- requireEnv,
2490
- normalizeScopeList,
2491
- githubRequest,
2492
- githubRepositoryFromUrl,
2493
- resolveUserAccount,
2494
- listVerifiedUserEmails,
2495
- issueInstallationToken,
2496
- issueGitHubCredential,
2497
- createPermissionCache,
2498
- definedValues,
2499
- pullRequestTargets,
2500
- logFailOpenFailure,
2501
- checkSuitePullRequests,
2502
- parseCheckSuitePublishTargets,
2503
- needsCheckSuitePullRequestFacts,
2504
- loadCheckSuiteFacts,
2505
- gitHubPullRequestTerminalEvents,
2506
- normalizeGitHubEvents
2507
- };