@sentry/junior-github 0.310.0 → 0.312.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.
@@ -2,7 +2,7 @@ import * as z from "zod";
2
2
  import pLimit from "p-limit";
3
3
  import { PluginToolInputError, eventMatchFieldsSchema, mergeEventMatchFields } from "@sentry/junior-plugin-api";
4
4
  import { lexer } from "marked";
5
- import { createPrivateKey, createSign } from "node:crypto";
5
+ import { createHash, createPrivateKey, createSign } from "node:crypto";
6
6
  // src/tool-support/github-api.ts
7
7
  const GITHUB_API_BASE = "https://api.github.com";
8
8
  const MAX_REDIRECTS = 3;
@@ -100,23 +100,39 @@ function parseRepo(value) {
100
100
  ref: `${parts[0]}/${parts[1]}`
101
101
  };
102
102
  }
103
+ const githubErrorBodySchema = z.object({
104
+ errors: z.unknown().optional(),
105
+ message: z.unknown().optional()
106
+ });
107
+ const githubErrorEntrySchema = z.object({
108
+ code: z.unknown().optional(),
109
+ field: z.unknown().optional(),
110
+ message: z.unknown().optional(),
111
+ resource: z.unknown().optional()
112
+ });
113
+ const GITHUB_ERROR_DETAIL_FIELDS = [
114
+ "resource",
115
+ "field",
116
+ "code",
117
+ "message"
118
+ ];
103
119
  /**
104
120
  * Return a readable error from a GitHub REST or GraphQL error body.
105
121
  *
106
122
  * REST validation errors list the failed fields in `errors`, and GraphQL puts
107
123
  * every message in `errors`. Both details help the model fix its input.
108
124
  */
109
- function githubErrorMessage(body) {
110
- if (typeof body === "string" && body.trim()) return body.trim();
111
- if (!isRecord$1(body)) return "GitHub request failed";
112
- const errors = Array.isArray(body["errors"]) ? body["errors"].filter(isRecord$1) : [];
125
+ function githubErrorMessage(value) {
126
+ if (typeof value === "string" && value.trim()) return value.trim();
127
+ const parsed = githubErrorBodySchema.safeParse(value);
128
+ if (!parsed.success) return "GitHub request failed";
129
+ const body = parsed.data;
130
+ const errors = Array.isArray(body["errors"]) ? body["errors"].flatMap((entry) => {
131
+ const error = githubErrorEntrySchema.safeParse(entry);
132
+ return error.success ? [error.data] : [];
133
+ }) : [];
113
134
  if (typeof body["message"] === "string" && body["message"].trim()) {
114
- const details = errors.map((error) => [
115
- "resource",
116
- "field",
117
- "code",
118
- "message"
119
- ].map((name) => {
135
+ const details = errors.map((error) => GITHUB_ERROR_DETAIL_FIELDS.map((name) => {
120
136
  const value = error[name];
121
137
  return typeof value === "string" && value.trim() ? `${name}=${value.trim()}` : void 0;
122
138
  }).filter(Boolean).join(" ")).filter(Boolean).join("; ");
@@ -126,9 +142,6 @@ function githubErrorMessage(body) {
126
142
  const graphqlMessages = errors.map((error) => error["message"]).filter((message) => typeof message === "string" && message.trim());
127
143
  return graphqlMessages.length ? graphqlMessages.join("; ") : "GitHub request failed";
128
144
  }
129
- function isRecord$1(value) {
130
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
131
- }
132
145
  // src/tool-support/attribution.ts
133
146
  const GITHUB_REQUEST_ATTRIBUTION_START = "<!-- junior-request-attribution:start -->";
134
147
  const GITHUB_REQUEST_ATTRIBUTION_END = "<!-- junior-request-attribution:end -->";
@@ -638,7 +651,7 @@ function gitHubPullRequestEventGuidance(guidance) {
638
651
  * Junior maintains the pull requests it creates. The pull request is its own
639
652
  * work, so it answers and fixes review feedback without asking first.
640
653
  * GitHub already tells people about reviews, approvals, merges, and closes,
641
- * and the review desk shows the next action. So the Watch gets approvals,
654
+ * and the Inbox shows the next action. So the Watch gets approvals,
642
655
  * merges, and closes only as Quiet Events, and posts in the thread only when
643
656
  * a person must act.
644
657
  */
@@ -666,7 +679,7 @@ function gitHubPullRequestSubscription(config) {
666
679
  * Each passing suite wakes the Watch, so a suite that leaves the required
667
680
  * checks unfinished must stay silent, or every suite posts.
668
681
  */
669
- const DRAFT_CHECKS_RECOVERED_GUIDANCE = "If the pull request is still a draft, call github_getPullRequest and read its `checks`, `code_owners`, and `agents_md`. 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, when the person who asked for it said to mark it ready, or when `code_owners` is empty and `agents_md` does not ask for draft pull requests or say that a person marks them ready. Otherwise keep it a draft: marking it ready would ask the code owners to review, or break the AGENTS.md rule. Tell the person who asked for it in the originating thread that the checks pass and the draft waits for their review, and name why: the code owners that marking it ready asks, or the AGENTS.md rule. If you already told them for this head commit, stay silent. 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.";
682
+ const DRAFT_CHECKS_RECOVERED_GUIDANCE = "If the pull request is still a draft, call github_getPullRequest and read its `checks`, `code_owners`, and `agents_md`. When `checks.required` is `passing` and no decision is open, in the pull request body or in an open inbox item that waits on the person who asked for it: mark it ready with github_updatePullRequest and draft false, when the person who asked for it said to mark it ready, or when `code_owners` is empty and `agents_md` does not ask for draft pull requests or say that a person marks them ready. Otherwise keep it a draft: marking it ready would ask the code owners to review, or break the AGENTS.md rule. Tell the person who asked for it in the originating thread that the checks pass and the draft waits for their review, and name why: the code owners that marking it ready asks, or the AGENTS.md rule. If you already told them for this head commit, stay silent. 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.";
670
683
  /**
671
684
  * State changes that need no action but that a later Turn must know, so that
672
685
  * it does not call an approved pull request unreviewed, or a merged or
@@ -1007,6 +1020,124 @@ function mentionsBotLogin(text, botEmail) {
1007
1020
  const escaped = slug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1008
1021
  return new RegExp(`(?:^|[^\\w-])@${escaped}(?![\\w-])`, "i").test(splitCommentText(text, { withoutCode: true }).own ?? "");
1009
1022
  }
1023
+ // src/conditional-requests.ts
1024
+ /**
1025
+ * Conditional GitHub reads. GitHub does not count a `304 Not Modified`
1026
+ * answer against the rate limit, so a repeat read of an unchanged resource,
1027
+ * such as a pull request that every check suite webhook reads, is free.
1028
+ *
1029
+ * Saved bodies are plaintext in plugin state. A breach of that store exposes
1030
+ * up to 6 hours of webhook reads: pull requests, their commits with author
1031
+ * names and emails, and collaborator roles. It exposes no token.
1032
+ */
1033
+ /**
1034
+ * How long a saved response stays. Webhooks for one pull request come in
1035
+ * bursts, such as one for each check suite, so most repeat reads are minutes
1036
+ * apart.
1037
+ */
1038
+ const SAVED_RESPONSE_TTL_MS = 216e5;
1039
+ /** Larger bodies, such as long commit lists, are not saved. */
1040
+ const MAX_SAVED_BODY_LENGTH = 262144;
1041
+ const savedResponseSchema = z.object({
1042
+ body: z.string(),
1043
+ etag: z.string().min(1)
1044
+ });
1045
+ /**
1046
+ * The state key of a saved response. It has no token: GitHub answers 304
1047
+ * only to a request that it authorized, and only when the response to that
1048
+ * request did not change, so a saved body never reaches a token that cannot
1049
+ * read it.
1050
+ */
1051
+ function savedResponseKey(url) {
1052
+ return `github-response:${createHash("sha256").update(url).digest("hex")}`;
1053
+ }
1054
+ /**
1055
+ * Send one GitHub GET with the ETag of its saved response. On 304, return
1056
+ * the saved body as a 200 response. On a 200 with an ETag, save the body.
1057
+ * Without `responses`, send the request as it is.
1058
+ *
1059
+ * Saved responses only save rate limit. A read or write failure of plugin
1060
+ * state is a cache miss, so it never fails the GitHub read.
1061
+ */
1062
+ async function sendConditionalRequest(responses, url, send) {
1063
+ if (!responses) return await send({});
1064
+ const key = savedResponseKey(url);
1065
+ const saved = savedResponseSchema.safeParse(await responses.get(key).catch(() => void 0));
1066
+ const response = await send(saved.success ? { "If-None-Match": saved.data.etag } : {});
1067
+ if (response.status === 304 && saved.success) {
1068
+ await response.body?.cancel();
1069
+ return new Response(saved.data.body, {
1070
+ headers: { etag: saved.data.etag },
1071
+ status: 200
1072
+ });
1073
+ }
1074
+ const etag = response.headers.get("etag");
1075
+ if (!response.ok || !etag) return response;
1076
+ const body = await response.text();
1077
+ if (body.length <= MAX_SAVED_BODY_LENGTH) await responses.set(key, {
1078
+ body,
1079
+ etag
1080
+ }, SAVED_RESPONSE_TTL_MS).catch(() => void 0);
1081
+ return new Response(body, {
1082
+ headers: response.headers,
1083
+ status: response.status,
1084
+ statusText: response.statusText
1085
+ });
1086
+ }
1087
+ // src/installation-responses.ts
1088
+ /** Parsers for GitHub App installation API responses. */
1089
+ const installationTokenResponseSchema = z.object({
1090
+ expires_at: z.unknown().optional(),
1091
+ token: z.unknown().optional()
1092
+ });
1093
+ const installationPermissionsSchema = z.object({ permissions: z.record(z.string(), z.unknown()) });
1094
+ /** Read the token and its expiry from an installation token response. */
1095
+ function parseInstallationTokenResponse(value) {
1096
+ const parsed = installationTokenResponseSchema.safeParse(value);
1097
+ if (!parsed.success) throw new Error("GitHub installation token response is invalid");
1098
+ const data = parsed.data;
1099
+ const token = data["token"];
1100
+ if (typeof token !== "string" || !token.trim()) throw new Error("GitHub installation token response missing token");
1101
+ const expiresAt = data["expires_at"];
1102
+ const expiresAtMs = typeof expiresAt === "string" ? Date.parse(expiresAt) : NaN;
1103
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) throw new Error("GitHub installation token response returned invalid expires_at");
1104
+ return {
1105
+ token,
1106
+ expiresAtMs
1107
+ };
1108
+ }
1109
+ /** Read the read permissions that an installation was granted. */
1110
+ function readInstallationPermissions(installation) {
1111
+ const parsed = installationPermissionsSchema.safeParse(installation);
1112
+ if (!parsed.success) throw new Error("GitHub installation response missing permissions");
1113
+ return readGrantPermissions(parsed.data.permissions);
1114
+ }
1115
+ // src/installation-tokens.ts
1116
+ /** A token this close to its expiry is minted again. */
1117
+ const REUSE_BUFFER_MS = 3e5;
1118
+ /**
1119
+ * Return the token of the same permissions and repositories while it has
1120
+ * time left, or mint one. Concurrent callers share one mint. A failed mint
1121
+ * is not kept.
1122
+ */
1123
+ async function reuseInstallationToken(tokens, scope, mint) {
1124
+ const key = JSON.stringify([
1125
+ scope.permissions ?? null,
1126
+ scope.repositories ?? null,
1127
+ scope.repositoryIds ?? null
1128
+ ]);
1129
+ const pending = tokens.get(key);
1130
+ const reused = pending && await pending.catch(() => void 0);
1131
+ if (reused && reused.expiresAtMs - REUSE_BUFFER_MS > Date.now()) return reused;
1132
+ const minted = mint();
1133
+ tokens.set(key, minted);
1134
+ try {
1135
+ return await minted;
1136
+ } catch (error) {
1137
+ if (tokens.get(key) === minted) tokens.delete(key);
1138
+ throw error;
1139
+ }
1140
+ }
1010
1141
  // src/credential-support.ts
1011
1142
  /**
1012
1143
  * GitHub credential issuance and provider request support.
@@ -1054,10 +1185,25 @@ var GitHubPluginSetupError = class extends Error {
1054
1185
  this.name = "GitHubPluginSetupError";
1055
1186
  }
1056
1187
  };
1057
- /** Return whether a provider value is a JSON object. */
1058
- function isRecord(value) {
1059
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
1060
- }
1188
+ /** GitHub REST error body with a `message`. */
1189
+ const githubMessageSchema = z.object({ message: z.string() });
1190
+ const oauthErrorSchema = z.object({ error: z.string() });
1191
+ const oauthTokenResponseSchema = z.object({
1192
+ access_token: z.unknown().optional(),
1193
+ expires_in: z.unknown().optional(),
1194
+ refresh_token: z.unknown().optional(),
1195
+ refresh_token_expires_in: z.unknown().optional(),
1196
+ scope: z.unknown().optional()
1197
+ });
1198
+ const userAccountSchema = z.object({
1199
+ html_url: z.unknown().optional(),
1200
+ id: z.unknown().optional(),
1201
+ login: z.unknown().optional()
1202
+ });
1203
+ const verifiedEmailSchema = z.object({
1204
+ email: z.string(),
1205
+ verified: z.literal(true)
1206
+ });
1061
1207
  /** Read a non-empty GitHub plugin environment value. */
1062
1208
  function readEnv(name) {
1063
1209
  const value = process.env[name];
@@ -1125,16 +1271,19 @@ function createAppJwt(appId, privateKeyEnv) {
1125
1271
  }
1126
1272
  /** Send an authenticated request to the GitHub API. */
1127
1273
  async function githubRequest(apiBase, path, params) {
1128
- const response = await fetch(`${apiBase}${path}`, {
1129
- method: params.method ?? "GET",
1274
+ const method = params.method ?? "GET";
1275
+ const url = `${apiBase}${path}`;
1276
+ const response = await sendConditionalRequest(method === "GET" ? params.responses : void 0, url, (headers) => fetch(url, {
1277
+ method,
1130
1278
  headers: {
1279
+ ...headers,
1131
1280
  Accept: "application/vnd.github+json",
1132
1281
  Authorization: `Bearer ${params.token}`,
1133
1282
  "X-GitHub-Api-Version": "2022-11-28",
1134
1283
  ...params.body ? { "Content-Type": "application/json" } : void 0
1135
1284
  },
1136
1285
  ...params.body ? { body: JSON.stringify(params.body) } : void 0
1137
- });
1286
+ }));
1138
1287
  const text = await response.text();
1139
1288
  let parsed;
1140
1289
  if (text) try {
@@ -1142,7 +1291,10 @@ async function githubRequest(apiBase, path, params) {
1142
1291
  } catch {
1143
1292
  parsed = void 0;
1144
1293
  }
1145
- if (!response.ok) throw new GitHubRequestError(isRecord(parsed) && typeof parsed["message"] === "string" ? parsed["message"] : `GitHub API error ${response.status}`, response.status);
1294
+ if (!response.ok) {
1295
+ const error = githubMessageSchema.safeParse(parsed);
1296
+ throw new GitHubRequestError(error.success ? error.data.message : `GitHub API error ${response.status}`, response.status);
1297
+ }
1146
1298
  return parsed;
1147
1299
  }
1148
1300
  function buildOAuthTokenRequest(input) {
@@ -1168,13 +1320,16 @@ function parseOAuthResponseJson(responseText) {
1168
1320
  }
1169
1321
  }
1170
1322
  function oauthErrorCode(data) {
1171
- return isRecord(data) && typeof data["error"] === "string" ? data["error"] : void 0;
1323
+ const parsed = oauthErrorSchema.safeParse(data);
1324
+ return parsed.success ? parsed.data.error : void 0;
1172
1325
  }
1173
1326
  function isRejectedRefreshError(errorCode) {
1174
1327
  return errorCode === "bad_refresh_token" || errorCode === "invalid_grant";
1175
1328
  }
1176
- function parseOAuthTokenResponse(data, requestedScope) {
1177
- if (!isRecord(data)) throw new Error("OAuth token response is invalid");
1329
+ function parseOAuthTokenResponse(value, requestedScope) {
1330
+ const parsed = oauthTokenResponseSchema.safeParse(value);
1331
+ if (!parsed.success) throw new Error("OAuth token response is invalid");
1332
+ const data = parsed.data;
1178
1333
  if (typeof data["access_token"] !== "string" || !data["access_token"].trim()) throw new Error("OAuth token response missing access_token");
1179
1334
  if (typeof data["refresh_token"] !== "string" || !data["refresh_token"].trim()) throw new Error("OAuth token response missing refresh_token");
1180
1335
  let scope = normalizeOAuthScope(requestedScope);
@@ -1268,22 +1423,6 @@ function credentialUnavailable(message) {
1268
1423
  message
1269
1424
  };
1270
1425
  }
1271
- function parseInstallationTokenResponse(data) {
1272
- if (!isRecord(data)) throw new Error("GitHub installation token response is invalid");
1273
- const token = data["token"];
1274
- if (typeof token !== "string" || !token.trim()) throw new Error("GitHub installation token response missing token");
1275
- const expiresAt = data["expires_at"];
1276
- const expiresAtMs = typeof expiresAt === "string" ? Date.parse(expiresAt) : NaN;
1277
- if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) throw new Error("GitHub installation token response returned invalid expires_at");
1278
- return {
1279
- token,
1280
- expiresAtMs
1281
- };
1282
- }
1283
- function readInstallationPermissions(installation) {
1284
- if (!isRecord(installation) || !isRecord(installation["permissions"])) throw new Error("GitHub installation response missing permissions");
1285
- return readGrantPermissions(installation["permissions"]);
1286
- }
1287
1426
  function decodeGitHubPathSegment(value) {
1288
1427
  try {
1289
1428
  const decoded = decodeURIComponent(value).trim();
@@ -1314,8 +1453,9 @@ function githubRepositoryFromUrl(upstreamUrl) {
1314
1453
  }
1315
1454
  /** Resolve the GitHub account associated with stored user tokens. */
1316
1455
  async function resolveUserAccount(tokens) {
1317
- const account = await githubRequest("https://api.github.com", "/user", { token: tokens.accessToken });
1318
- if (!isRecord(account)) throw new Error("GitHub user response is invalid");
1456
+ const parsed = userAccountSchema.safeParse(await githubRequest("https://api.github.com", "/user", { token: tokens.accessToken }));
1457
+ if (!parsed.success) throw new Error("GitHub user response is invalid");
1458
+ const account = parsed.data;
1319
1459
  const id = account["id"];
1320
1460
  const login = account["login"];
1321
1461
  if (typeof id !== "number" && typeof id !== "string" || typeof login !== "string" || !login.trim()) throw new Error("GitHub user response missing id or login");
@@ -1342,7 +1482,11 @@ async function listVerifiedUserEmails(tokens) {
1342
1482
  throw error;
1343
1483
  }
1344
1484
  if (!Array.isArray(emails)) throw new Error("GitHub user emails response is invalid");
1345
- return emails.flatMap((entry) => isRecord(entry) && entry["verified"] === true && typeof entry["email"] === "string" && entry["email"].trim() ? [entry["email"].trim()] : []);
1485
+ return emails.flatMap((entry) => {
1486
+ const parsed = verifiedEmailSchema.safeParse(entry);
1487
+ const email = parsed.success ? parsed.data.email.trim() : "";
1488
+ return email ? [email] : [];
1489
+ });
1346
1490
  }
1347
1491
  async function tokensWithAccount(tokenSlot, stored, scope) {
1348
1492
  if (stored.account) return {
@@ -1455,8 +1599,15 @@ async function issueUserCredential(ctx, options) {
1455
1599
  }
1456
1600
  return credentialNeeded("Your GitHub authorization has expired.", scope);
1457
1601
  }
1458
- /** Issue a bounded raw token for plugin-owned GitHub API calls. */
1602
+ /**
1603
+ * Issue a bounded raw token for plugin-owned GitHub API calls. With
1604
+ * `tokens`, reuse a token of the same scope.
1605
+ */
1459
1606
  async function issueInstallationToken(options) {
1607
+ if (!options.tokens || options.loadPermissions) return await mintInstallationToken(options);
1608
+ return await reuseInstallationToken(options.tokens, options, () => mintInstallationToken(options));
1609
+ }
1610
+ async function mintInstallationToken(options) {
1460
1611
  const appId = requireEnv(options.appIdEnv);
1461
1612
  const installationIdRaw = requireEnv(options.installationIdEnv);
1462
1613
  const installationId = Number(installationIdRaw);
@@ -1534,6 +1685,26 @@ function createPermissionCache() {
1534
1685
  return await pending;
1535
1686
  };
1536
1687
  }
1688
+ // src/webhooks/fail-open-log.ts
1689
+ /**
1690
+ * Log a failure of optional webhook work. A GitHub 5xx is a GitHub outage,
1691
+ * not a Junior bug, so it is a warning with the HTTP status. Other failures
1692
+ * stay errors.
1693
+ */
1694
+ function logFailOpenFailure(log, message, error, metadata) {
1695
+ const attributes = {
1696
+ ...metadata,
1697
+ errorType: error instanceof Error ? error.name : "UnknownError"
1698
+ };
1699
+ if (error instanceof GitHubRequestError && error.status >= 500) {
1700
+ log?.warn(message, {
1701
+ ...attributes,
1702
+ "http.response.status_code": error.status
1703
+ });
1704
+ return;
1705
+ }
1706
+ log?.error(message, attributes);
1707
+ }
1537
1708
  // src/webhooks/event-targets.ts
1538
1709
  /**
1539
1710
  * The user who sent a webhook. GitHub authenticates this user, so on a comment
@@ -1626,26 +1797,6 @@ function pullRequestTargets(event, repo) {
1626
1797
  identifier: gitHubRepositoryResource({ repo }).identifier
1627
1798
  }];
1628
1799
  }
1629
- // src/webhooks/fail-open-log.ts
1630
- /**
1631
- * Log a failure of optional webhook work. A GitHub 5xx is a GitHub outage,
1632
- * not a Junior bug, so it is a warning with the HTTP status. Other failures
1633
- * stay errors.
1634
- */
1635
- function logFailOpenFailure(log, message, error, metadata) {
1636
- const attributes = {
1637
- ...metadata,
1638
- errorType: error instanceof Error ? error.name : "UnknownError"
1639
- };
1640
- if (error instanceof GitHubRequestError && error.status >= 500) {
1641
- log?.warn(message, {
1642
- ...attributes,
1643
- "http.response.status_code": error.status
1644
- });
1645
- return;
1646
- }
1647
- log?.error(message, attributes);
1648
- }
1649
1800
  // src/webhooks/check-suite.ts
1650
1801
  /**
1651
1802
  * GitHub check suite events.
@@ -2010,17 +2161,23 @@ function checkRunsFromResponse(value) {
2010
2161
  if (!parsed.success) return [];
2011
2162
  return parsed.data.check_runs ?? [];
2012
2163
  }
2164
+ const pullRequestFactsResponseSchema = z.object({
2165
+ draft: z.boolean().optional().catch(void 0),
2166
+ user: z.object({
2167
+ email: z.string().optional().catch(void 0),
2168
+ login: z.string().optional().catch(void 0)
2169
+ }).optional().catch(void 0)
2170
+ });
2013
2171
  function pullRequestFactsFromResponse(value) {
2014
- if (!isRecord(value)) return void 0;
2172
+ const parsed = pullRequestFactsResponseSchema.safeParse(value);
2173
+ if (!parsed.success) return void 0;
2174
+ const { draft, user } = parsed.data;
2015
2175
  const facts = {};
2016
- if (typeof value["draft"] === "boolean") facts.isDraft = value["draft"];
2017
- const user = value["user"];
2018
- if (isRecord(user)) {
2019
- const username = typeof user["login"] === "string" ? user["login"].trim() : void 0;
2020
- if (username) facts.openerUsername = username;
2021
- const email = typeof user["email"] === "string" ? user["email"].trim() : void 0;
2022
- if (email) facts.openerEmail = email;
2023
- }
2176
+ if (draft !== void 0) facts.isDraft = draft;
2177
+ const username = user?.login?.trim();
2178
+ if (username) facts.openerUsername = username;
2179
+ const email = user?.email?.trim();
2180
+ if (email) facts.openerEmail = email;
2024
2181
  return Object.keys(facts).length > 0 ? facts : void 0;
2025
2182
  }
2026
2183
  /** True when active match filters need pull request fields from the API. */
@@ -2066,7 +2223,8 @@ async function loadCheckSuiteFacts(args) {
2066
2223
  installationIdEnv: args.installationIdEnv,
2067
2224
  permissions: { checks: "read" },
2068
2225
  privateKeyEnv: args.privateKeyEnv,
2069
- repositories: [target.repoName]
2226
+ repositories: [target.repoName],
2227
+ tokens: args.tokens
2070
2228
  });
2071
2229
  const failing = selectFailingChecks(checkRunsFromResponse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/check-suites/${target.checkSuiteId}/check-runs?filter=latest&per_page=100`, { token: token.token })), { checkSuiteId: target.checkSuiteId });
2072
2230
  if (failing.length > 0) facts.failingChecks = failing;
@@ -2082,7 +2240,8 @@ async function loadCheckSuiteFacts(args) {
2082
2240
  installationIdEnv: args.installationIdEnv,
2083
2241
  permissions: { checks: "read" },
2084
2242
  privateKeyEnv: args.privateKeyEnv,
2085
- repositories: [target.repoName]
2243
+ repositories: [target.repoName],
2244
+ tokens: args.tokens
2086
2245
  });
2087
2246
  if (await loadAllCheckSuitesPassed({
2088
2247
  checkSuiteId: target.checkSuiteId,
@@ -2109,11 +2268,15 @@ async function loadCheckSuiteFacts(args) {
2109
2268
  installationIdEnv: args.installationIdEnv,
2110
2269
  permissions: { pull_requests: "read" },
2111
2270
  privateKeyEnv: args.privateKeyEnv,
2112
- repositories: [target.repoName]
2271
+ repositories: [target.repoName],
2272
+ tokens: args.tokens
2113
2273
  });
2114
2274
  const loaded = await pLimit(PULL_REQUEST_LOAD_CONCURRENCY).map(target.pullRequestNumbers, async (number) => {
2115
2275
  try {
2116
- const loadedFacts = pullRequestFactsFromResponse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/pulls/${number}`, { token: token.token }));
2276
+ const loadedFacts = pullRequestFactsFromResponse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/pulls/${number}`, {
2277
+ responses: args.responses,
2278
+ token: token.token
2279
+ }));
2117
2280
  return loadedFacts ? [number, loadedFacts] : void 0;
2118
2281
  } catch (error) {
2119
2282
  if (!isGitHubNotFoundError(error)) logFailOpenFailure(args.log, "GitHub pull request data load failed", error, {
@@ -2852,4 +3015,4 @@ function normalizeGitHubEvents(args) {
2852
3015
  default: return [];
2853
3016
  }
2854
3017
  }
2855
- export { GITHUB_DEPLOYMENT_EVENTS as $, requireEnv as A, GITHUB_RELEASE_MATCH_FIELDS as B, githubRequest as C, githubErrorMessage as Ct, listVerifiedUserEmails as D, issueInstallationToken as E, GITHUB_REPOSITORY_EVENTS as F, GITHUB_PULL_REQUEST_IDENTIFIER as G, GITHUB_RELEASE_SUGGESTED_EVENTS as H, GITHUB_REPOSITORY_IDENTIFIER as I, gitHubPullRequestCreateWatch as J, GITHUB_PULL_REQUEST_MATCH_FIELDS as K, GITHUB_REPOSITORY_SUGGESTED_EVENTS as L, botLoginFromEmail as M, botUserIdFromEmail as N, normalizeScopeList as O, isBotLogin as P, gitHubPullRequestSubscription as Q, gitHubRepositorySubscribable as R, githubRepositoryFromUrl as S, githubAttachmentLocation as St, issueGitHubCredential as T, repoPath as Tt, gitHubReleaseSourceSubscribable as U, GITHUB_RELEASE_SOURCE_IDENTIFIER as V, GITHUB_PULL_REQUEST_EVENTS as W, gitHubPullRequestResource as X, gitHubPullRequestEventGuidance as Y, gitHubPullRequestSubscribable as Z, GITHUB_INSTALLATION_ID_ENV as _, readGitHubBody as _t, needsCheckSuitePullRequestFacts as a, GITHUB_ISSUE_IDENTIFIER as at, USER_WRITE_REQUIREMENTS as b, startedByPerson as bt, logFailOpenFailure as c, gitHubIssueSubscribable as ct, CREATE_TOOL_ROUTING_GUIDANCE as d, normalizePermissions as dt, GITHUB_DEPLOYMENT_MATCH_FIELDS as et, GITHUB_APP_ID_ENV as f, readGrantPermissions as ft, GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES as g, parseGitHubLogin as gt, GITHUB_AUTH_TOKEN_PLACEHOLDER as h, linkedGitHubLogin as ht, loadCheckSuiteFacts as i, GITHUB_ISSUE_EVENTS as it, resolveUserAccount as j, readEnv as k, definedValues as l, watchGitHubIssue as lt, GITHUB_AUTH_TOKEN_ENV as m, assertGitHubPullRequestRequester as mt, normalizeGitHubEvents as n, GITHUB_DEPLOYMENT_SUGGESTED_EVENTS as nt, parseCheckSuitePublishTargets as o, GITHUB_ISSUE_MATCH_FIELDS as ot, GITHUB_APP_PRIVATE_KEY_ENV as p, appendGitHubRequesterAttribution as pt, GITHUB_PULL_REQUEST_SUGGESTED_EVENTS as q, checkSuitePullRequests as r, gitHubDeploymentSourceSubscribable as rt, wantsCheckSuitePassed as s, GITHUB_ISSUE_SUGGESTED_EVENTS as st, gitHubPullRequestTerminalEvents as t, GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER as tt, pullRequestTargets as u, gitHubRepoDataSchema as ut, GitHubRequestError as v, requesterPerson as vt, isRecord as w, parseRepo as wt, createPermissionCache as x, githubApi as xt, HTTP_READ_METHODS as y, resolveGitHubRequester as yt, GITHUB_RELEASE_EVENTS as z };
3018
+ export { GITHUB_DEPLOYMENT_EVENTS as $, requireEnv as A, GITHUB_RELEASE_MATCH_FIELDS as B, githubRepositoryFromUrl as C, githubErrorMessage as Ct, listVerifiedUserEmails as D, issueInstallationToken as E, GITHUB_REPOSITORY_EVENTS as F, GITHUB_PULL_REQUEST_IDENTIFIER as G, GITHUB_RELEASE_SUGGESTED_EVENTS as H, GITHUB_REPOSITORY_IDENTIFIER as I, gitHubPullRequestCreateWatch as J, GITHUB_PULL_REQUEST_MATCH_FIELDS as K, GITHUB_REPOSITORY_SUGGESTED_EVENTS as L, botLoginFromEmail as M, botUserIdFromEmail as N, normalizeScopeList as O, isBotLogin as P, gitHubPullRequestSubscription as Q, gitHubRepositorySubscribable as R, githubMessageSchema as S, githubAttachmentLocation as St, issueGitHubCredential as T, repoPath as Tt, gitHubReleaseSourceSubscribable as U, GITHUB_RELEASE_SOURCE_IDENTIFIER as V, GITHUB_PULL_REQUEST_EVENTS as W, gitHubPullRequestResource as X, gitHubPullRequestEventGuidance as Y, gitHubPullRequestSubscribable as Z, GITHUB_INSTALLATION_ID_ENV as _, readGitHubBody as _t, needsCheckSuitePullRequestFacts as a, GITHUB_ISSUE_IDENTIFIER as at, USER_WRITE_REQUIREMENTS as b, startedByPerson as bt, definedValues as c, gitHubIssueSubscribable as ct, CREATE_TOOL_ROUTING_GUIDANCE as d, normalizePermissions as dt, GITHUB_DEPLOYMENT_MATCH_FIELDS as et, GITHUB_APP_ID_ENV as f, readGrantPermissions as ft, GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES as g, parseGitHubLogin as gt, GITHUB_AUTH_TOKEN_PLACEHOLDER as h, linkedGitHubLogin as ht, loadCheckSuiteFacts as i, GITHUB_ISSUE_EVENTS as it, resolveUserAccount as j, readEnv as k, pullRequestTargets as l, watchGitHubIssue as lt, GITHUB_AUTH_TOKEN_ENV as m, assertGitHubPullRequestRequester as mt, normalizeGitHubEvents as n, GITHUB_DEPLOYMENT_SUGGESTED_EVENTS as nt, parseCheckSuitePublishTargets as o, GITHUB_ISSUE_MATCH_FIELDS as ot, GITHUB_APP_PRIVATE_KEY_ENV as p, appendGitHubRequesterAttribution as pt, GITHUB_PULL_REQUEST_SUGGESTED_EVENTS as q, checkSuitePullRequests as r, gitHubDeploymentSourceSubscribable as rt, wantsCheckSuitePassed as s, GITHUB_ISSUE_SUGGESTED_EVENTS as st, gitHubPullRequestTerminalEvents as t, GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER as tt, logFailOpenFailure as u, gitHubRepoDataSchema as ut, GitHubRequestError as v, requesterPerson as vt, githubRequest as w, parseRepo as wt, createPermissionCache as x, githubApi as xt, HTTP_READ_METHODS as y, resolveGitHubRequester as yt, GITHUB_RELEASE_EVENTS as z };