import { all, first } from "../db";
import { HttpError } from "../errors";
import { loadRepoById } from "../repos";
import { ZERO_SHA } from "../git/store";
import { createDeployment, loadSite } from "./deploy";
import type { DeployRequest } from "./deploy";
const MAX_PREVIEWS_PER_PUSH = 5;
async function tryDeploy(input: DeployRequest): Promise<string | null> {
try {
return (await createDeployment(input)).id;
} catch (error) {
if (error instanceof HttpError) {
console.warn("Pages deploy skipped", input.repo.id, error.message);
return null;
}
throw error;
}
}
/** Push hook: deploys the site branch to production and open pull request heads to previews. */
export async function deployPagesForPush(
repoId: string,
branch: string | null,
sha: string,
pusherId: string | null,
): Promise<number> {
if (!branch || sha === ZERO_SHA) return 0;
const [repo, site] = await Promise.all([loadRepoById(repoId), loadSite(repoId)]);
if (!repo || !site || site.source !== "branch" || repo.visibility !== "public") return 0;
const base = { repo, site, ref: `refs/heads/${branch}`, sha, artifactId: null, creatorId: pusherId };
if (branch === site.branch) {
return (await tryDeploy({ ...base, environment: "production", prNumber: null })) ? 1 : 0;
}
if (site.previews !== 1) return 0;
const pulls = await all<{ number: number }>(
`SELECT i.number FROM pull_requests p JOIN issues i ON i.id = p.issue_id
WHERE p.repo_id = ? AND p.head_repo_id = ? AND p.head_ref = ? AND i.state = 'open' LIMIT ?`,
repo.id,