import fs from "fs/promises";
import path from "path";
import type { Octokits } from "../api/client";
export type FsOps = {
mkdir: typeof fs.mkdir;
writeFile: typeof fs.writeFile;
};
const defaultFsOps: FsOps = {
mkdir: fs.mkdir.bind(fs),
writeFile: fs.writeFile.bind(fs),
};
// Build regexes at call time, reading GITHUB_SERVER_URL from process.env
// directly. The config.ts export freezes the value at module load time,
// which can be wrong when the Forgejo CI runner injects its own
// GITHUB_SERVER_URL that the shell export cannot override.
function buildImageRegexes(): { imageRegex: RegExp; htmlImgRegex: RegExp } {
const serverUrl = process.env.GITHUB_SERVER_URL || "https://github.com";
const escapedUrl = serverUrl.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const imageRegex = new RegExp(
`!\\[[^\\]]*\\]\\((${escapedUrl}\\/user-attachments\\/assets\\/[^)]+)\\)`,
"g",
);
const htmlImgRegex = new RegExp(
`
]+src=["']([^"']*${escapedUrl}\\/user-attachments\\/assets\\/[^"']+)["'][^>]*>`,
"gi",
);
return { imageRegex, htmlImgRegex };
}
type IssueComment = {
type: "issue_comment";
id: string;
body: string;
};
type ReviewComment = {
type: "review_comment";
id: string;
body: string;
};
type ReviewBody = {
type: "review_body";
id: string;
pullNumber: string;
body: string;
};
type IssueBody = {
type: "issue_body";
issueNumber: string;
body: string;
};
type PullRequestBody = {
type: "pr_body";
pullNumber: string;
body: string;
};
export type CommentWithImages =
| IssueComment
| ReviewComment
| ReviewBody
| IssueBody
| PullRequestBody;
export async function downloadCommentImages(
octokits: Octokits,
owner: string,
repo: string,
comments: CommentWithImages[],
fsOps: FsOps = defaultFsOps,
): Promise