@sentry/junior-github 0.300.0 → 0.301.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.
@@ -0,0 +1,8 @@
1
+ import type { PluginObjectLinkDefinition } from "@sentry/junior-plugin-api";
2
+ /**
3
+ * GitHub profile links, such as `https://github.com/octocat`. A login that
4
+ * links to a known person shows their Junior person card. Any other login
5
+ * shows a GitHub account card. Both come from the link alone, so the card
6
+ * needs no GitHub request.
7
+ */
8
+ export declare const githubAccountLinks: PluginObjectLinkDefinition;
@@ -0,0 +1,10 @@
1
+ /** A GitHub repository, by owner and name. */
2
+ export interface Repository {
3
+ name: string;
4
+ owner: string;
5
+ }
6
+ /**
7
+ * Read the `repo` config value as `owner/name`, or as `name` with the `org`
8
+ * config value. Return undefined when neither form is complete.
9
+ */
10
+ export declare function configuredRepository(config: Record<string, string>): Repository | undefined;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Description images of GitHub objects, served through the Junior image
3
+ * route. Each read checks that the viewer's linked GitHub account can see
4
+ * the repository. Only then does Junior fetch the image with the App.
5
+ */
6
+ import { type PluginImageSource } from "@sentry/junior-plugin-api";
7
+ /** Serve the description images of GitHub objects to viewers who can see the repository. */
8
+ export declare const githubImageSource: PluginImageSource;
package/dist/index.js CHANGED
@@ -65,6 +65,64 @@ import {
65
65
  resolveUserAccount
66
66
  } from "./chunk-YUF5P5I7.js";
67
67
 
68
+ // src/account-links.ts
69
+ var GITHUB_LOGIN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,38}$/;
70
+ var NON_ACCOUNT_PATHS = /* @__PURE__ */ new Set([
71
+ "about",
72
+ "apps",
73
+ "codespaces",
74
+ "collections",
75
+ "contact",
76
+ "copilot",
77
+ "dashboard",
78
+ "enterprise",
79
+ "events",
80
+ "explore",
81
+ "features",
82
+ "issues",
83
+ "login",
84
+ "logout",
85
+ "marketplace",
86
+ "new",
87
+ "notifications",
88
+ "organizations",
89
+ "pricing",
90
+ "pulls",
91
+ "search",
92
+ "security",
93
+ "settings",
94
+ "signup",
95
+ "sponsors",
96
+ "stars",
97
+ "topics",
98
+ "trending"
99
+ ]);
100
+ function githubAccountCard(login2) {
101
+ return {
102
+ kind: "object",
103
+ objectType: "person",
104
+ key: `github:${login2.toLowerCase()}`,
105
+ label: `@${login2}`,
106
+ title: login2,
107
+ url: `https://github.com/${login2}`,
108
+ displayType: "GitHub account",
109
+ facts: { type: "person", githubHandle: login2 }
110
+ };
111
+ }
112
+ var githubAccountLinks = {
113
+ filters: [{ host: "github.com", pathPattern: "/*" }],
114
+ // A GitHub profile is public, and the card holds only the login.
115
+ canView: async () => true,
116
+ objectType: "person",
117
+ async resolve(ctx, url) {
118
+ const login2 = url.pathname.split("/")[1] ?? "";
119
+ if (!GITHUB_LOGIN_PATTERN.test(login2) || NON_ACCOUNT_PATHS.has(login2.toLowerCase())) {
120
+ return void 0;
121
+ }
122
+ return await ctx.findPerson({ provider: "github", handle: login2 }) ?? githubAccountCard(login2);
123
+ }
124
+ };
125
+
68
126
  // src/tool-support/attribution.ts
69
127
  import * as z from "zod";
70
128
 
@@ -114,6 +172,16 @@ function redirectTarget(response, from) {
114
172
  const target = new URL(location, from);
115
173
  return target.origin === GITHUB_API_BASE ? target.href : void 0;
116
174
  }
175
+ async function githubAttachmentLocation(egress, url) {
176
+ const response = await egress.fetch({
177
+ provider: "github",
178
+ operation: "github.attachment.get",
179
+ request: new Request(url, { redirect: "manual" })
180
+ });
181
+ await response.body?.cancel();
182
+ const location = REDIRECT_STATUSES.has(response.status) ? response.headers.get("location") : null;
183
+ return location ? new URL(location, url).href : void 0;
184
+ }
117
185
  async function readBody(response) {
118
186
  const text2 = await response.text();
119
187
  if (!text2) return void 0;
@@ -158,10 +226,10 @@ function isRecord2(value) {
158
226
  var GITHUB_REQUEST_ATTRIBUTION_START = "<!-- junior-request-attribution:start -->";
159
227
  var GITHUB_REQUEST_ATTRIBUTION_END = "<!-- junior-request-attribution:end -->";
160
228
  var SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
161
- var GITHUB_LOGIN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/;
229
+ var GITHUB_LOGIN_PATTERN2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/;
162
230
  function parseGitHubLogin(value) {
163
231
  const login2 = value?.trim().replace(/^@/, "");
164
- return login2 && GITHUB_LOGIN_PATTERN.test(login2) ? login2 : void 0;
232
+ return login2 && GITHUB_LOGIN_PATTERN2.test(login2) ? login2 : void 0;
165
233
  }
166
234
  function linkedGitHubLogin(user) {
167
235
  return parseGitHubLogin(
@@ -754,18 +822,23 @@ function htmlImageSources(html) {
754
822
  visit2(parseFragment(html));
755
823
  return sources;
756
824
  }
757
- function publicArtifactUrl(value) {
825
+ var GITHUB_ATTACHMENT_PATH = /^\/user-attachments\/assets\/[0-9a-f-]{36}$/i;
826
+ function githubImageKind(url) {
827
+ if (url.username || url.password || url.href.length > 512) return void 0;
828
+ if (url.origin === "https://github.com" && !url.search && GITHUB_ATTACHMENT_PATH.test(url.pathname)) {
829
+ return "attachment";
830
+ }
758
831
  const baseUrl = process.env.JUNIOR_BASE_URL?.trim().replace(/\/+$/, "");
759
- if (!baseUrl) return void 0;
760
- let url;
761
- let prefix;
762
- try {
763
- url = new URL(value);
764
- prefix = new URL(`${baseUrl}/public/artifacts/`);
765
- } catch {
832
+ if (!baseUrl || !URL.canParse(`${baseUrl}/public/artifacts/`)) {
766
833
  return void 0;
767
834
  }
768
- return (url.protocol === "https:" || url.protocol === "http:") && url.origin === prefix.origin && url.pathname.length > prefix.pathname.length && url.pathname.startsWith(prefix.pathname) && !url.username && !url.password && url.href.length <= 512 ? url.href : void 0;
835
+ const prefix = new URL(`${baseUrl}/public/artifacts/`);
836
+ return (url.protocol === "https:" || url.protocol === "http:") && url.origin === prefix.origin && url.pathname.length > prefix.pathname.length && url.pathname.startsWith(prefix.pathname) ? "artifact" : void 0;
837
+ }
838
+ function previewImageUrl(value) {
839
+ if (!URL.canParse(value)) return void 0;
840
+ const url = new URL(value);
841
+ return githubImageKind(url) ? url.href : void 0;
769
842
  }
770
843
  function githubPreviewImageUrls(body) {
771
844
  const sources = [];
@@ -775,7 +848,7 @@ function githubPreviewImageUrls(body) {
775
848
  });
776
849
  return [
777
850
  ...new Set(
778
- sources.map(publicArtifactUrl).filter((url) => url !== void 0)
851
+ sources.map(previewImageUrl).filter((url) => url !== void 0)
779
852
  )
780
853
  ];
781
854
  }
@@ -4120,44 +4193,64 @@ function createGitHubSubmitPullRequestReviewTool(egress) {
4120
4193
  });
4121
4194
  }
4122
4195
 
4196
+ // src/tool-support/github-text.ts
4197
+ function withGitHubText(tools, users) {
4198
+ return Object.fromEntries(
4199
+ Object.entries(tools).map(([name, tool]) => {
4200
+ const execute = tool.execute;
4201
+ if (!execute) return [name, tool];
4202
+ const wrapped = Object.create(tool);
4203
+ wrapped.execute = async (input, options) => await execute.call(
4204
+ tool,
4205
+ await users.replaceSlackMentions(input, "github"),
4206
+ options
4207
+ );
4208
+ return [name, wrapped];
4209
+ })
4210
+ );
4211
+ }
4212
+
4123
4213
  // src/tools.ts
4124
4214
  function createGitHubTools(ctx, botEmail, pullRequestSubscription, experimental = {}) {
4125
4215
  const descriptionDecider = experimental.pullRequestDescriptionChecks ? ctx.decider : void 0;
4126
- return {
4127
- reactToIssue: createGitHubReactToIssueTool(ctx.egress),
4128
- cloneRepository: createGitHubCloneRepositoryTool(ctx),
4129
- commentOnIssue: createGitHubCommentOnIssueTool(ctx.egress),
4130
- commentOnPullRequest: createGitHubCommentOnPullRequestTool(ctx.egress),
4131
- createIssue: createGitHubIssueTool(ctx),
4132
- createPullRequest: createGitHubPullRequestTool(
4133
- ctx,
4134
- pullRequestSubscription,
4135
- descriptionDecider
4136
- ),
4137
- getDeployment: createGitHubGetDeploymentTool(ctx),
4138
- getIssue: createGitHubGetIssueTool(ctx),
4139
- getPullRequest: createGitHubGetPullRequestTool(ctx),
4140
- getRelease: createGitHubGetReleaseTool(ctx),
4141
- getRepository: createGitHubGetRepositoryTool(ctx),
4142
- getStatus: createGitHubGetStatusTool(ctx),
4143
- resolvePullRequestReviewThread: createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail),
4144
- submitPullRequestReview: createGitHubSubmitPullRequestReviewTool(
4145
- ctx.egress
4146
- ),
4147
- updateIssue: createGitHubUpdateIssueTool(ctx),
4148
- updateIssueComment: createGitHubUpdateIssueCommentTool(
4149
- ctx.egress,
4150
- botEmail
4151
- ),
4152
- updatePullRequest: createGitHubUpdatePullRequestTool(
4153
- ctx,
4154
- descriptionDecider
4155
- ),
4156
- updatePullRequestFeedback: createGitHubUpdatePullRequestFeedbackTool(
4157
- ctx,
4158
- botEmail
4159
- )
4160
- };
4216
+ return withGitHubText(
4217
+ {
4218
+ reactToIssue: createGitHubReactToIssueTool(ctx.egress),
4219
+ cloneRepository: createGitHubCloneRepositoryTool(ctx),
4220
+ commentOnIssue: createGitHubCommentOnIssueTool(ctx.egress),
4221
+ commentOnPullRequest: createGitHubCommentOnPullRequestTool(ctx.egress),
4222
+ createIssue: createGitHubIssueTool(ctx),
4223
+ createPullRequest: createGitHubPullRequestTool(
4224
+ ctx,
4225
+ pullRequestSubscription,
4226
+ descriptionDecider
4227
+ ),
4228
+ getDeployment: createGitHubGetDeploymentTool(ctx),
4229
+ getIssue: createGitHubGetIssueTool(ctx),
4230
+ getPullRequest: createGitHubGetPullRequestTool(ctx),
4231
+ getRelease: createGitHubGetReleaseTool(ctx),
4232
+ getRepository: createGitHubGetRepositoryTool(ctx),
4233
+ getStatus: createGitHubGetStatusTool(ctx),
4234
+ resolvePullRequestReviewThread: createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail),
4235
+ submitPullRequestReview: createGitHubSubmitPullRequestReviewTool(
4236
+ ctx.egress
4237
+ ),
4238
+ updateIssue: createGitHubUpdateIssueTool(ctx),
4239
+ updateIssueComment: createGitHubUpdateIssueCommentTool(
4240
+ ctx.egress,
4241
+ botEmail
4242
+ ),
4243
+ updatePullRequest: createGitHubUpdatePullRequestTool(
4244
+ ctx,
4245
+ descriptionDecider
4246
+ ),
4247
+ updatePullRequestFeedback: createGitHubUpdatePullRequestFeedbackTool(
4248
+ ctx,
4249
+ botEmail
4250
+ )
4251
+ },
4252
+ ctx.users
4253
+ );
4161
4254
  }
4162
4255
 
4163
4256
  // src/webhooks/handler.ts
@@ -6721,6 +6814,68 @@ async function classifyGitHubPullRequestCommitComposition(args) {
6721
6814
  return foundCommit ? "junior_only" : void 0;
6722
6815
  }
6723
6816
 
6817
+ // src/images.ts
6818
+ import {
6819
+ decodeObjectImageRef
6820
+ } from "@sentry/junior-plugin-api";
6821
+ import * as z44 from "zod";
6822
+ var OBJECT_KEY = /^([\w.-]+)\/([\w.-]+)#\d+$/;
6823
+ var ACCESS_TTL_MS = 10 * 60 * 1e3;
6824
+ var permissionSchema = z44.object({ permission: z44.string().min(1) });
6825
+ var AccessReadFailed = class extends Error {
6826
+ status;
6827
+ constructor(status) {
6828
+ super(`GitHub repository permission read failed with HTTP ${status}`);
6829
+ this.status = status;
6830
+ }
6831
+ };
6832
+ async function canSeeRepository(ctx, repository2, login2) {
6833
+ try {
6834
+ return await readRepositoryAccess(ctx, repository2, login2);
6835
+ } catch (error) {
6836
+ if (!(error instanceof AccessReadFailed)) throw error;
6837
+ ctx.log.warn("github.image_access.read_failed", {
6838
+ "http.response.status_code": error.status
6839
+ });
6840
+ return false;
6841
+ }
6842
+ }
6843
+ async function readRepositoryAccess(ctx, repository2, login2) {
6844
+ return await ctx.cache.getOrLoad(
6845
+ `image-access:${repository2.owner}/${repository2.name}:${login2}`.toLowerCase(),
6846
+ async () => {
6847
+ const response = await githubApi(ctx.egress, {
6848
+ operation: "github.repository.collaborator-permission.get",
6849
+ path: `${repoPath(repository2)}/collaborators/${encodeURIComponent(login2)}/permission`
6850
+ });
6851
+ if (!response.ok && response.status !== 404) {
6852
+ throw new AccessReadFailed(response.status);
6853
+ }
6854
+ const parsed = response.ok ? permissionSchema.safeParse(response.body) : void 0;
6855
+ return {
6856
+ value: parsed?.success === true && parsed.data.permission !== "none",
6857
+ ttlMs: ACCESS_TTL_MS
6858
+ };
6859
+ }
6860
+ );
6861
+ }
6862
+ var githubImageSource = {
6863
+ async resolve(ctx, ref) {
6864
+ const image = decodeObjectImageRef(ref);
6865
+ const key = image && OBJECT_KEY.exec(image.key);
6866
+ if (!image || !key || !URL.canParse(image.url)) return void 0;
6867
+ const kind = githubImageKind(new URL(image.url));
6868
+ const login2 = linkedGitHubLogin(ctx.viewer);
6869
+ if (!kind || !login2) return void 0;
6870
+ const repository2 = { name: key[2], owner: key[1] };
6871
+ if (!await canSeeRepository(ctx, repository2, login2)) return void 0;
6872
+ return kind === "artifact" ? { url: image.url } : {
6873
+ url: image.url,
6874
+ location: () => githubAttachmentLocation(ctx.egress, image.url)
6875
+ };
6876
+ }
6877
+ };
6878
+
6724
6879
  // src/git-config.ts
6725
6880
  function cleanIdentityPart(value) {
6726
6881
  return String(value ?? "").replaceAll("\n", " ").replaceAll("\r", " ").replace(/[<>]/g, "").trim();
@@ -7102,134 +7257,162 @@ async function prepareSandboxGit(ctx) {
7102
7257
  }
7103
7258
 
7104
7259
  // src/reply-markdown.ts
7105
- var GITHUB_OWNER_PATTERN = "[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?";
7106
- var GITHUB_REPOSITORY_PATTERN = "[A-Za-z0-9._-]+";
7107
- var GITHUB_ISSUE_REFERENCE_PATTERN = new RegExp(
7108
- `^(${GITHUB_OWNER_PATTERN})\\/(${GITHUB_REPOSITORY_PATTERN})#(\\d+)\\b`
7109
- );
7110
- function isReferenceBoundary(char) {
7111
- return char === void 0 || !/[A-Za-z0-9._-]/.test(char);
7112
- }
7113
- function readInlineCode(text2, start) {
7114
- if (text2[start] !== "`") {
7115
- return void 0;
7116
- }
7117
- let markerLength = 1;
7118
- while (text2[start + markerLength] === "`") {
7119
- markerLength++;
7120
- }
7121
- const marker = "`".repeat(markerLength);
7122
- const end = text2.indexOf(marker, start + markerLength);
7123
- return end === -1 ? void 0 : end + markerLength;
7260
+ import { fromMarkdown } from "mdast-util-from-markdown";
7261
+ import { gfmFromMarkdown } from "mdast-util-gfm";
7262
+ import { gfm } from "micromark-extension-gfm";
7263
+
7264
+ // src/configured-repository.ts
7265
+ function configuredRepository(config) {
7266
+ const [first, second, ...extra] = (config.repo ?? "").trim().split("/");
7267
+ if (extra.length > 0) return void 0;
7268
+ const owner = second ? first : config.org?.trim();
7269
+ const name = second || first;
7270
+ return owner && name ? { owner, name } : void 0;
7124
7271
  }
7125
- function readFenceLength(line) {
7126
- const trimmed = line.trimStart();
7127
- if (!trimmed.startsWith("```")) {
7128
- return void 0;
7129
- }
7130
- let length = 0;
7131
- while (trimmed[length] === "`") {
7132
- length++;
7133
- }
7134
- return length >= 3 ? length : void 0;
7272
+
7273
+ // src/reply-markdown.ts
7274
+ var OWNER = "[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?";
7275
+ var LOGIN = `${OWNER}(?:_[A-Za-z0-9]+)?`;
7276
+ var REPO = "[A-Za-z0-9._-]+";
7277
+ var SHA = "[0-9a-f]{7,40}";
7278
+ var START = "(?<![\\w.\\-/@&<\\\\])";
7279
+ var END = "(?![\\w-])";
7280
+ var TEXT_REFERENCE_PATTERN = new RegExp(
7281
+ [
7282
+ `${START}(?<issueOwner>${LOGIN})\\/(?<issueRepo>${REPO})#(?<issue>\\d+)${END}`,
7283
+ `${START}(?<commitOwner>${LOGIN})\\/(?<commitRepo>${REPO})@(?<commit>${SHA})${END}`,
7284
+ `${START}(?<user>${LOGIN})@(?<userCommit>[0-9a-f]{40})${END}`,
7285
+ `${START}(?:#|GH-)(?<bareIssue>\\d+)${END}`,
7286
+ // Not `@scope/name`, which is an npm package more often than a team.
7287
+ `${START}@(?<mention>${LOGIN})(?![\\w/-]|\\.\\w)`,
7288
+ // Only full SHAs: shorter hex runs are often other IDs, such as event IDs.
7289
+ `${START}(?<bareCommit>[0-9a-f]{40})${END}`
7290
+ ].join("|"),
7291
+ "g"
7292
+ );
7293
+ var GITHUB_URL_BODY = `https?:\\/\\/(?:www\\.)?github\\.com\\/(?!(?:orgs|enterprises)\\/)(?<owner>${LOGIN})\\/(?<repo>${REPO})\\/(?:(?:issues|pull|discussions)\\/(?<issue>\\d+)|commit\\/(?<commit>${SHA}))`;
7294
+ var GITHUB_URL_PATTERN = new RegExp(`^${GITHUB_URL_BODY}$`, "i");
7295
+ var GITHUB_LINKED_URL_PATTERN = new RegExp(GITHUB_URL_BODY, "gi");
7296
+ var NON_ACCOUNT_MENTIONS = /* @__PURE__ */ new Set(["channel", "everyone", "here"]);
7297
+ function readSpans(text2) {
7298
+ const spans = [];
7299
+ const visit2 = (node) => {
7300
+ const start = node.position?.start.offset;
7301
+ const end = node.position?.end.offset;
7302
+ if (start === void 0 || end === void 0) return;
7303
+ if (node.type === "text") {
7304
+ spans.push({ kind: "text", start, end });
7305
+ } else if (node.type === "link" || node.type === "definition") {
7306
+ const bare = node.type === "link" && text2.slice(start, end) === node.url;
7307
+ spans.push({ kind: bare ? "url" : "link", start, end, url: node.url });
7308
+ } else if (node.type !== "linkReference" && "children" in node) {
7309
+ for (const child of node.children) visit2(child);
7310
+ }
7311
+ };
7312
+ visit2(
7313
+ fromMarkdown(text2, {
7314
+ extensions: [gfm()],
7315
+ mdastExtensions: [gfmFromMarkdown()]
7316
+ })
7317
+ );
7318
+ return spans;
7135
7319
  }
7136
- function readMarkdownLink(text2, start) {
7137
- if (text2[start] !== "[") {
7138
- return void 0;
7139
- }
7140
- const labelEnd = text2.indexOf("](", start + 1);
7141
- if (labelEnd === -1) {
7142
- return void 0;
7143
- }
7144
- const label = text2.slice(start + 1, labelEnd);
7145
- if (label.includes("[") || label.includes("]") || label.includes("\n")) {
7146
- return void 0;
7320
+ function namedRepositories(text2, spans) {
7321
+ const repositories = /* @__PURE__ */ new Map();
7322
+ const add = (owner, name) => {
7323
+ if (owner && name) {
7324
+ repositories.set(`${owner}/${name}`.toLowerCase(), { owner, name });
7325
+ }
7326
+ };
7327
+ for (const span of spans) {
7328
+ if (span.url) {
7329
+ for (const { groups } of span.url.matchAll(GITHUB_LINKED_URL_PATTERN)) {
7330
+ add(groups?.owner, groups?.repo);
7331
+ }
7332
+ } else {
7333
+ const source = text2.slice(span.start, span.end);
7334
+ for (const { groups } of source.matchAll(TEXT_REFERENCE_PATTERN)) {
7335
+ add(groups?.issueOwner, groups?.issueRepo);
7336
+ add(groups?.commitOwner, groups?.commitRepo);
7337
+ }
7338
+ }
7147
7339
  }
7148
- const destStart = labelEnd + 2;
7149
- const closeParens = text2.indexOf(")", destStart);
7150
- return closeParens === -1 ? void 0 : closeParens + 1;
7340
+ return [...repositories.values()];
7151
7341
  }
7152
- function readAngleToken(text2, start) {
7153
- if (text2[start] !== "<") {
7154
- return void 0;
7342
+ var issueUrl = (owner, name, issue) => `https://github.com/${owner}/${name}/issues/${issue}`;
7343
+ var commitUrl = (owner, name, sha) => `https://github.com/${owner}/${name}/commit/${sha}`;
7344
+ function linkifyUrl(url) {
7345
+ const groups = GITHUB_URL_PATTERN.exec(url)?.groups;
7346
+ if (!groups?.owner || !groups.repo) {
7347
+ return url;
7155
7348
  }
7156
- const end = text2.indexOf(">", start + 1);
7157
- return end === -1 ? void 0 : end + 1;
7349
+ const label = groups.issue ? `${groups.owner}/${groups.repo}#${groups.issue}` : `${groups.owner}/${groups.repo}@${groups.commit.slice(0, 7)}`;
7350
+ return `[${label}](${url})`;
7158
7351
  }
7159
- function linkifyLine(line) {
7160
- let output = "";
7161
- let index2 = 0;
7162
- while (index2 < line.length) {
7163
- const codeEnd = readInlineCode(line, index2);
7164
- if (codeEnd !== void 0) {
7165
- output += line.slice(index2, codeEnd);
7166
- index2 = codeEnd;
7167
- continue;
7352
+ function linkifyTextReferences(text2, context) {
7353
+ const { repository: repository2 } = context;
7354
+ return text2.replace(TEXT_REFERENCE_PATTERN, (reference, ...args) => {
7355
+ const groups = args.at(-1);
7356
+ if (groups.issue) {
7357
+ return `[${reference}](${issueUrl(groups.issueOwner, groups.issueRepo, groups.issue)})`;
7168
7358
  }
7169
- const markdownLinkEnd = readMarkdownLink(line, index2);
7170
- if (markdownLinkEnd !== void 0) {
7171
- output += line.slice(index2, markdownLinkEnd);
7172
- index2 = markdownLinkEnd;
7173
- continue;
7359
+ if (groups.commit) {
7360
+ const label = `${groups.commitOwner}/${groups.commitRepo}@${groups.commit.slice(0, 7)}`;
7361
+ return `[${label}](${commitUrl(groups.commitOwner, groups.commitRepo, groups.commit)})`;
7174
7362
  }
7175
- const angleTokenEnd = readAngleToken(line, index2);
7176
- if (angleTokenEnd !== void 0) {
7177
- output += line.slice(index2, angleTokenEnd);
7178
- index2 = angleTokenEnd;
7179
- continue;
7363
+ if (groups.mention) {
7364
+ const login2 = groups.mention;
7365
+ if (NON_ACCOUNT_MENTIONS.has(login2.toLowerCase())) return reference;
7366
+ const known = context.mention(login2);
7367
+ if (known) return known;
7368
+ return context.linkProfiles ? `[${reference}](https://github.com/${login2})` : reference;
7180
7369
  }
7181
- if (line.startsWith("https://", index2) || line.startsWith("http://", index2)) {
7182
- const url = /^\S+/.exec(line.slice(index2))[0];
7183
- const scheme = line.startsWith("https://", index2) ? 8 : 7;
7184
- if (url.length > scheme) {
7185
- output += url;
7186
- index2 += url.length;
7187
- continue;
7188
- }
7370
+ if (!repository2) {
7371
+ return reference;
7189
7372
  }
7190
- if (isReferenceBoundary(index2 === 0 ? void 0 : line[index2 - 1])) {
7191
- const match = GITHUB_ISSUE_REFERENCE_PATTERN.exec(line.slice(index2));
7192
- if (match) {
7193
- const [reference, owner, repository2, number33] = match;
7194
- output += `[${reference}](https://github.com/${owner}/${repository2}/issues/${number33})`;
7195
- index2 += reference.length;
7196
- continue;
7197
- }
7373
+ if (groups.bareIssue) {
7374
+ return `[${reference}](${issueUrl(repository2.owner, repository2.name, groups.bareIssue)})`;
7198
7375
  }
7199
- output += line[index2];
7200
- index2++;
7201
- }
7202
- return output;
7203
- }
7204
- function linkifyGitHubReferences(text2) {
7205
- let openFenceLength = 0;
7206
- return text2.split("\n").map((line) => {
7207
- const fenceLength = readFenceLength(line);
7208
- if (fenceLength !== void 0) {
7209
- if (openFenceLength === 0) {
7210
- openFenceLength = fenceLength;
7211
- } else if (fenceLength >= openFenceLength) {
7212
- openFenceLength = 0;
7213
- }
7214
- return line;
7376
+ if (groups.userCommit) {
7377
+ const label = `${groups.user}@${groups.userCommit.slice(0, 7)}`;
7378
+ return `[${label}](${commitUrl(groups.user, repository2.name, groups.userCommit)})`;
7215
7379
  }
7216
- return openFenceLength > 0 ? line : linkifyLine(line);
7217
- }).join("\n");
7380
+ const sha = groups.bareCommit;
7381
+ return `[${sha.slice(0, 7)}](${commitUrl(repository2.owner, repository2.name, sha)})`;
7382
+ });
7383
+ }
7384
+ function linkifyGitHubReferences(text2, options = {}) {
7385
+ const spans = readSpans(text2);
7386
+ const named = namedRepositories(text2, spans);
7387
+ const context = {
7388
+ linkProfiles: options.githubText === true || named.length > 0,
7389
+ mention: options.mention ?? (() => void 0),
7390
+ repository: named.length === 0 ? configuredRepository(options.config ?? {}) : named.length === 1 ? named[0] : void 0
7391
+ };
7392
+ let result = "";
7393
+ let cursor = 0;
7394
+ for (const span of spans) {
7395
+ const source = text2.slice(span.start, span.end);
7396
+ result += text2.slice(cursor, span.start);
7397
+ result += span.kind === "text" ? linkifyTextReferences(source, context) : span.kind === "url" && !options.bareUrls ? linkifyUrl(source) : source;
7398
+ cursor = span.end;
7399
+ }
7400
+ return result + text2.slice(cursor);
7218
7401
  }
7219
7402
 
7220
7403
  // src/conversation-title-context.ts
7221
7404
  var MAX_REFERENCES = 3;
7222
7405
  var TITLE_MAX_LENGTH = 160;
7223
- var OWNER = String.raw`([A-Za-z0-9][A-Za-z0-9-]*)`;
7224
- var REPO = String.raw`([\w.-]*\w)`;
7225
- var SHA = String.raw`([0-9a-f]{7,40})`;
7406
+ var OWNER2 = String.raw`([A-Za-z0-9][A-Za-z0-9-]*)`;
7407
+ var REPO2 = String.raw`([\w.-]*\w)`;
7408
+ var SHA2 = String.raw`([0-9a-f]{7,40})`;
7226
7409
  var NOT_AFTER_PATH = String.raw`(?<![\w/.-])`;
7227
- var REPO_IN_PROSE = String.raw`(?:on|in|from|of|at)\s+${OWNER}\/${REPO}`;
7410
+ var REPO_IN_PROSE = String.raw`(?:on|in|from|of|at)\s+${OWNER2}\/${REPO2}`;
7228
7411
  var repository = (owner, name) => owner && name ? { owner, name } : void 0;
7229
7412
  var REFERENCE_PATTERNS = [
7230
7413
  {
7231
7414
  pattern: new RegExp(
7232
- String.raw`https?:\/\/(?:www\.)?github\.com\/${OWNER}\/${REPO}\/(issues|pull)\/(\d+)`,
7415
+ String.raw`https?:\/\/(?:www\.)?github\.com\/${OWNER2}\/${REPO2}\/(issues|pull)\/(\d+)`,
7233
7416
  "gi"
7234
7417
  ),
7235
7418
  read: ([, owner, name, path, id]) => ({
@@ -7240,7 +7423,7 @@ var REFERENCE_PATTERNS = [
7240
7423
  },
7241
7424
  {
7242
7425
  pattern: new RegExp(
7243
- String.raw`https?:\/\/(?:www\.)?github\.com\/${OWNER}\/${REPO}\/commit\/${SHA}`,
7426
+ String.raw`https?:\/\/(?:www\.)?github\.com\/${OWNER2}\/${REPO2}\/commit\/${SHA2}`,
7244
7427
  "gi"
7245
7428
  ),
7246
7429
  read: ([, owner, name, id]) => ({
@@ -7251,7 +7434,7 @@ var REFERENCE_PATTERNS = [
7251
7434
  },
7252
7435
  {
7253
7436
  pattern: new RegExp(
7254
- String.raw`${NOT_AFTER_PATH}${OWNER}\/${REPO}#(\d+)\b`,
7437
+ String.raw`${NOT_AFTER_PATH}${OWNER2}\/${REPO2}#(\d+)\b`,
7255
7438
  "g"
7256
7439
  ),
7257
7440
  read: ([, owner, name, id]) => ({
@@ -7262,7 +7445,7 @@ var REFERENCE_PATTERNS = [
7262
7445
  },
7263
7446
  {
7264
7447
  pattern: new RegExp(
7265
- String.raw`${NOT_AFTER_PATH}${OWNER}\/${REPO}@${SHA}\b`,
7448
+ String.raw`${NOT_AFTER_PATH}${OWNER2}\/${REPO2}@${SHA2}\b`,
7266
7449
  "g"
7267
7450
  ),
7268
7451
  read: ([, owner, name, id]) => ({
@@ -7287,11 +7470,6 @@ var REFERENCE_PATTERNS = [
7287
7470
  read: ([, id]) => ({ id, kind: "issue" })
7288
7471
  }
7289
7472
  ];
7290
- function configuredRepository(config) {
7291
- const [first, second, ...extra] = (config.repo ?? "").trim().split("/");
7292
- if (extra.length > 0) return void 0;
7293
- return second ? repository(first, second) : repository(config.org?.trim(), first);
7294
- }
7295
7473
  function parseGitHubReferences(text2, config) {
7296
7474
  const matches = REFERENCE_PATTERNS.flatMap(
7297
7475
  ({ pattern, read }) => [...text2.matchAll(pattern)].map((match) => ({
@@ -7305,23 +7483,23 @@ function parseGitHubReferences(text2, config) {
7305
7483
  const previous = accepted.at(-1);
7306
7484
  if (!previous || match.start >= previous.end) accepted.push(match);
7307
7485
  }
7308
- const namedRepositories = /* @__PURE__ */ new Map();
7486
+ const namedRepositories2 = /* @__PURE__ */ new Map();
7309
7487
  for (const match of accepted) {
7310
7488
  if (match.repository) {
7311
7489
  const key = `${match.repository.owner}/${match.repository.name}`;
7312
- namedRepositories.set(key.toLowerCase(), match.repository);
7490
+ namedRepositories2.set(key.toLowerCase(), match.repository);
7313
7491
  }
7314
7492
  }
7315
7493
  for (const match of text2.matchAll(new RegExp(REPO_IN_PROSE, "gi"))) {
7316
7494
  const named = repository(match[1], match[2]);
7317
7495
  if (named) {
7318
- namedRepositories.set(
7496
+ namedRepositories2.set(
7319
7497
  `${named.owner}/${named.name}`.toLowerCase(),
7320
7498
  named
7321
7499
  );
7322
7500
  }
7323
7501
  }
7324
- const fallback = namedRepositories.size === 1 ? [...namedRepositories.values()][0] : configuredRepository(config);
7502
+ const fallback = namedRepositories2.size === 1 ? [...namedRepositories2.values()][0] : configuredRepository(config);
7325
7503
  const references = /* @__PURE__ */ new Map();
7326
7504
  for (const match of accepted) {
7327
7505
  const target = match.repository ?? fallback;
@@ -7333,9 +7511,9 @@ function parseGitHubReferences(text2, config) {
7333
7511
  }
7334
7512
  return [...references.values()];
7335
7513
  }
7336
- function objectTitle(kind, object43) {
7337
- if (!isRecord(object43)) return void 0;
7338
- const raw = kind === "commit" ? isRecord(object43.commit) && typeof object43.commit.message === "string" ? object43.commit.message.split("\n")[0] : void 0 : typeof object43.title === "string" ? object43.title : void 0;
7514
+ function objectTitle(kind, object44) {
7515
+ if (!isRecord(object44)) return void 0;
7516
+ const raw = kind === "commit" ? isRecord(object44.commit) && typeof object44.commit.message === "string" ? object44.commit.message.split("\n")[0] : void 0 : typeof object44.title === "string" ? object44.title : void 0;
7339
7517
  return raw?.replace(/\s+/g, " ").trim() || void 0;
7340
7518
  }
7341
7519
  async function loadGitHubConversationTitleContext(args) {
@@ -7614,9 +7792,9 @@ import {
7614
7792
  } from "@sentry/junior-plugin-api";
7615
7793
 
7616
7794
  // src/default-branch.ts
7617
- import * as z44 from "zod";
7795
+ import * as z45 from "zod";
7618
7796
  var DEFAULT_BRANCH_TTL_MS = 10 * 60 * 1e3;
7619
- var repositorySchema3 = z44.object({ default_branch: z44.string().min(1) });
7797
+ var repositorySchema3 = z45.object({ default_branch: z45.string().min(1) });
7620
7798
  async function loadDefaultBranch(env, cache, repository2) {
7621
7799
  const { owner, name } = repository2;
7622
7800
  return await cache.getOrLoad(
@@ -8200,6 +8378,8 @@ function githubPlugin(options = {}) {
8200
8378
  const userScope = userScopes.length ? userScopes.join(" ") : void 0;
8201
8379
  return defineJuniorPlugin({
8202
8380
  packageName: "@sentry/junior-github",
8381
+ images: githubImageSource,
8382
+ objectLinks: [githubAccountLinks],
8203
8383
  events: {
8204
8384
  resourceTypes: [
8205
8385
  {
@@ -8339,8 +8519,21 @@ function githubPlugin(options = {}) {
8339
8519
  )
8340
8520
  };
8341
8521
  },
8342
- formatMarkdown({ text: text2 }) {
8343
- return linkifyGitHubReferences(text2);
8522
+ formatMarkdown({ config, mention, platform, provider, text: text2 }) {
8523
+ return linkifyGitHubReferences(text2, {
8524
+ // The dashboard shows a bare GitHub link as a card.
8525
+ bareUrls: platform === "web",
8526
+ config,
8527
+ githubText: provider === "github",
8528
+ mention: (login2) => mention({ provider: "github", handle: login2 })
8529
+ });
8530
+ },
8531
+ systemPrompt() {
8532
+ return [
8533
+ {
8534
+ text: "Write each GitHub issue, pull request, or commit reference with its repository, such as owner/repo#123 or owner/repo@abc1234, and not in code formatting. A bare #123, GH-123, or SHA is ambiguous when a conversation spans several repositories."
8535
+ }
8536
+ ];
8344
8537
  },
8345
8538
  async heartbeat(ctx) {
8346
8539
  const db = ctx.db;
@@ -1,8 +1,19 @@
1
1
  import { type ObjectAnnotation, type ObjectFacts } from "@sentry/junior-plugin-api";
2
2
  /**
3
- * Return the public images in a pull request body, in body order, for card
4
- * previews. Screenshots often come as a before and after pair, so the
5
- * dashboard chooses which one to show.
3
+ * Return where a description image is stored, or nothing when Junior does
4
+ * not serve it. The dashboard loads each one through the Junior image route:
5
+ * - `artifact`: Junior's own public artifacts, under `JUNIOR_BASE_URL`.
6
+ * - `attachment`: `github.com/user-attachments/assets/<id>` images. They
7
+ * need the GitHub App credential on private repositories, and GitHub
8
+ * redirects them to a short-lived signed URL. Junior never saves the
9
+ * signed `private-user-images.githubusercontent.com` URL, because it
10
+ * expires in minutes.
11
+ */
12
+ export declare function githubImageKind(url: URL): "artifact" | "attachment" | undefined;
13
+ /**
14
+ * Return the images in a pull request body that Junior serves, in body
15
+ * order, for card previews. Screenshots often come as a before and after
16
+ * pair, so the dashboard chooses which one to show.
6
17
  */
7
18
  export declare function githubPreviewImageUrls(body: string | null | undefined): string[];
8
19
  type CodeChangeFacts = Extract<ObjectFacts, {
@@ -1,2 +1,18 @@
1
- /** Linkify GitHub issue and pull request shorthand outside Markdown code. */
2
- export declare function linkifyGitHubReferences(text: string): string;
1
+ /**
2
+ * Linkify GitHub autolinked references outside Markdown code and links.
3
+ *
4
+ * `owner/repo#123`, `owner/repo@sha`, and GitHub issue, pull request,
5
+ * discussion, and commit URLs always become links. `#123`, `GH-123`,
6
+ * `user@sha`, and full SHAs need a repository: the one that the text names,
7
+ * else the `repo` config value when the text names none. `@login` becomes the
8
+ * `mention` of the known person with that GitHub login. Other logins become
9
+ * GitHub profile links when the text is GitHub text, or names a repository.
10
+ * Chat `@name` words are often people who are not GitHub accounts. Set
11
+ * `bareUrls` to keep bare URLs, where the place shows them as cards.
12
+ */
13
+ export declare function linkifyGitHubReferences(text: string, options?: {
14
+ bareUrls?: boolean;
15
+ config?: Record<string, string>;
16
+ githubText?: boolean;
17
+ mention?: (login: string) => string | undefined;
18
+ }): string;
@@ -24,6 +24,13 @@ export declare function githubApi(egress: PluginEgress, input: {
24
24
  path: string;
25
25
  signal?: AbortSignal;
26
26
  }): Promise<GitHubApiResponse>;
27
+ /**
28
+ * Return where a `github.com` attachment URL redirects, through host
29
+ * egress. GitHub signs that address for a short time, so it needs no
30
+ * credential. Egress does not follow the redirect, so the credential never
31
+ * reaches the image host.
32
+ */
33
+ export declare function githubAttachmentLocation(egress: PluginEgress, url: string): Promise<string | undefined>;
27
34
  /** Return the `/repos/{owner}/{name}` API path prefix for a parsed repo. */
28
35
  export declare function repoPath(repo: {
29
36
  name: string;
@@ -0,0 +1,8 @@
1
+ import type { PluginToolDefinition, ToolRegistrationHookContext } from "@sentry/junior-plugin-api";
2
+ /**
3
+ * Make every GitHub tool send GitHub text. The model reads Slack threads, so
4
+ * it can copy Slack mention syntax into a title, body, or comment. GitHub
5
+ * shows that syntax as literal text, so core rewrites it before the tool
6
+ * runs: a Slack user becomes their linked GitHub `@login`, or their name.
7
+ */
8
+ export declare function withGitHubText(tools: Record<string, PluginToolDefinition>, users: ToolRegistrationHookContext["users"]): Record<string, PluginToolDefinition>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentry/junior-github",
3
- "version": "0.300.0",
3
+ "version": "0.301.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -32,12 +32,16 @@
32
32
  "@sinclair/typebox": "^0.34.49",
33
33
  "drizzle-orm": "^0.45.4",
34
34
  "marked": "^18.1.2",
35
+ "mdast-util-from-markdown": "^2.0.3",
36
+ "mdast-util-gfm": "^3.1.0",
37
+ "micromark-extension-gfm": "^3.0.0",
35
38
  "parse5": "^7.3.0",
36
39
  "zod": "^4.6.7",
37
- "@sentry/junior-plugin-api": "0.300.0"
40
+ "@sentry/junior-plugin-api": "0.301.0"
38
41
  },
39
42
  "devDependencies": {
40
43
  "@oxlint/plugins": "1.79.0",
44
+ "@types/mdast": "^4.0.4",
41
45
  "@types/node": "^25.9.1",
42
46
  "@types/pg": "^8.15.6",
43
47
  "drizzle-kit": "^0.31.8",