import { WorkflowEntrypoint } from "cloudflare:workers";
import type { WorkflowEvent, WorkflowStep } from "cloudflare:workers";
import { first, run } from "../db";
import { loadRepoById } from "../repos";
import { PAGES_LIMITS } from "./config";
import { activateDeployment, failDeployment, loadDeployment, loadSite } from "./deploy";
import { DeployError, extractArtifact, planGitFiles, totalBytes, uploadGitBatch } from "./collect";
import type { CollectedFiles, PlannedFile } from "./collect";
export type PagesDeployParams = { deploymentId: string };
type Plan =
| { kind: "branch"; artifactsName: string; sha: string; folder: string }
| { kind: "artifact"; r2Key: string; folder: string }
| { kind: "skip"; error: string | null };
type Outcome<T> = { ok: true; value: T } | { ok: false; error: string };
async function attempt<T>(work: () => Promise<T>): Promise<Outcome<T>> {
try {
return { ok: true, value: await work() };
} catch (error) {
if (error instanceof DeployError) return { ok: false, error: error.message };
throw error;
}
}
async function start(deploymentId: string): Promise<Plan> {
const deployment = await loadDeployment(deploymentId);
if (!deployment || deployment.status !== "queued") return { kind: "skip", error: null };
const [repo, site] = await Promise.all([loadRepoById(deployment.repo_id), loadSite(deployment.repo_id)]);
if (!repo || !site) return { kind: "skip", error: "Pages is not enabled for this repository" };
await run("UPDATE pages_deployments SET status = 'building' WHERE id = ?", deploymentId);
if (!deployment.artifact_id) {
return { kind: "branch", artifactsName: repo.artifacts_name, sha: deployment.sha, folder: site.folder };
}
const artifact = await first<{ r2_key: string }>(
"SELECT a.r2_key FROM job_artifacts a JOIN workflow_runs r ON r.id = a.run_id WHERE a.id = ? AND r.repo_id = ?",
deployment.artifact_id,
repo.id,