commit b7d0f3bc866a2d82e0801afd0d324f2ba067ea49
parent cee2bb4c92f9bc007241935de052027406ab449f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 21:51:54 -0400
editor: pnpm ops delete-site — a site's delete, plan first
controller/siteDelete.ts: planSiteDelete lists what goes (sites/<id>/, its
publish state and last bundle under export/.export-builds/<id>/, compose's
staging under export/.export-index/sites/<id>/), what is kept (every
channel's data, the Pages project and what was deployed, a deployed hub,
export/out when it links into the bundle) and what refuses — forceable: a
cloudflareProject, a deploy in deployed.json, reports of its own; never: no
such site, a linked site dir, a publish stage running. deleteSiteByPlan
re-plans under the site.json lock and the publish lock (taken without
waiting), parks each directory aside, and removes the bulk after the locks.
POST /api/ops/delete-site {id, force?, dryRun?} (409 with the plan when
refused, 404 for no site), the ACTIONS row and help, COMMANDS.md. The
editor's Danger -> Delete is unchanged.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
5 files changed, 470 insertions(+), 0 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -94,6 +94,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `articles-config` | articles-config sets an article's audience and its place in the published list (transcripts/reports/index.json), through the article registry: {"id"} and any of "audience" ("public" \| "private"; absent in report.json = private), "published" (true = listed, false = a draft) and "position" (its place in the list, 0 = first; publishing with none keeps a listed article where it is, else puts it last). Refused before anything is written: an unknown article, a position on a draft or out of range, publishing an article whose report.json has problems (listed). Answers the article as saved. | `pnpm ops articles-config --json '{"id":"demo-article","published":true}'`<br>`pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}'` |
| `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` |
| `delete-iteration` | delete-iteration deletes one iteration and its video project: {"id", "n"}, "dryRun"?. Its number is never given again. Refused with the plan (409), no override: the current article, the iteration its report.json came from, the current video, a queued or running one, one another revises or copies. | `pnpm ops delete-iteration --json '{"id":"demo-article","n":3}'` |
+| `delete-site` | delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? It removes sites/<id>/ (site.json, its pool and pages, tags, charts, its reports), its publish state and last bundle (export/.export-builds/<id>/) and compose's staging for it (export/.export-index/sites/<id>/). Channel data is never touched; the Pages project, what was deployed and a deployed hub are kept (a delete does not undeploy). Refused with the plan (409) unless "force": a deploy target (cloudflareProject), a deploy in its publish state, reports of its own. Refused, force or not: no such site (404), a site dir that is a link, a publish stage running. | `pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}'` |
| `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'` |
| `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` |
| `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` |
diff --git a/common/controller/siteDelete.test.ts b/common/controller/siteDelete.test.ts
@@ -0,0 +1,152 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, symlink, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { acquirePublishLock } from "../publish/stageLock";
+import { deleteSiteByPlan, formatSiteDeletePlan, planSiteDelete, siteDeleteBlocked, SiteDeleteRefusedError } from "./siteDelete";
+
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/siteDelete.test.ts
+//
+// Release 28 H5: a site's delete over a temp transcripts/ and export/ — never
+// the real ones.
+
+async function tree() {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "site-delete-"));
+ const paths = {
+ sitesDir: path.join(dir, "transcripts", "sites"),
+ channelsDir: path.join(dir, "transcripts", "channels"),
+ exportDir: path.join(dir, "export"),
+ exportBuildsDir: path.join(dir, "export", ".export-builds"),
+ exportSitesIndexDir: path.join(dir, "export", ".export-index", "sites"),
+ };
+ const site = async (id: string, json: Record<string, unknown> = {}, o: { reports?: string[]; builds?: boolean; deployed?: unknown } = {}) => {
+ const d = path.join(paths.sitesDir, id);
+ await mkdir(d, { recursive: true });
+ await writeFile(path.join(d, "site.json"), JSON.stringify({ siteId: id, siteTitle: id, channels: ["demo-channel"], audience: "private", ...json }));
+ await writeFile(path.join(d, "tags.json"), "{}");
+ for (const r of o.reports ?? []) {
+ await mkdir(path.join(d, "reports", r), { recursive: true });
+ await writeFile(path.join(d, "reports", r, "report.json"), "{}");
+ }
+ if (o.builds !== false) {
+ const b = path.join(paths.exportBuildsDir, id);
+ await mkdir(path.join(b, "out"), { recursive: true });
+ await writeFile(path.join(b, "built.json"), "{}");
+ await writeFile(path.join(b, "out", "index.html"), "<html></html>");
+ if (o.deployed) await writeFile(path.join(b, "deployed.json"), JSON.stringify(o.deployed));
+ await mkdir(path.join(paths.exportSitesIndexDir, id, "report-media"), { recursive: true });
+ await writeFile(path.join(paths.exportSitesIndexDir, id, "summary.json"), "{}");
+ }
+ };
+ // A channel the site's pool names: never touched.
+ await mkdir(path.join(paths.channelsDir, "demo-channel", "data", "v1"), { recursive: true });
+ await writeFile(path.join(paths.channelsDir, "demo-channel", "config.json"), "{}");
+ await writeFile(path.join(paths.channelsDir, "demo-channel", "data", "v1", "transcript.json"), "{}");
+ return { dir, paths, site, done: () => rm(dir, { recursive: true, force: true }) };
+}
+
+test("a private site with nothing deployed: the plan, then its three directories go, and nothing else", async () => {
+ const t = await tree();
+ try {
+ await t.site("doomed");
+ await t.site("keeper");
+ const plan = await planSiteDelete("doomed", t.paths);
+ assert.equal(plan.exists, true);
+ assert.deepEqual(plan.refusals, []);
+ assert.deepEqual(plan.remove.map((e) => e.label), ["sites/doomed/", "export/.export-builds/doomed/", "export/.export-index/sites/doomed/"]);
+ assert.equal(plan.files, 5);
+ assert.ok(plan.kept.some((k) => k.what === "every channel's data"));
+ assert.match(formatSiteDeletePlan(plan)[0]!, /^delete site "doomed": 3 path\(s\)/);
+ const r = await deleteSiteByPlan("doomed", t.paths);
+ assert.equal(r.removed.length, 3);
+ assert.deepEqual(r.failed, []);
+ for (const e of plan.remove) assert.equal(existsSync(e.path), false, e.label);
+ // No park left behind; the other site and the channel untouched.
+ assert.deepEqual(await readdir(t.paths.sitesDir), ["keeper"]);
+ assert.deepEqual((await readdir(t.paths.exportBuildsDir)).filter((n) => !n.startsWith(".publish")), ["keeper"]);
+ assert.ok(existsSync(path.join(t.paths.exportSitesIndexDir, "keeper", "summary.json")));
+ assert.equal(await readFile(path.join(t.paths.channelsDir, "demo-channel", "data", "v1", "transcript.json"), "utf8"), "{}");
+ // Gone means gone: a second delete has no site to delete.
+ await assert.rejects(deleteSiteByPlan("doomed", t.paths), (e: unknown) => e instanceof SiteDeleteRefusedError && /no site "doomed"/.test(e.message));
+ } finally {
+ await t.done();
+ }
+});
+
+test("a deploy target, a recorded deploy or reports of its own refuse unless force; force deletes and keeps the remote", async () => {
+ const t = await tree();
+ try {
+ await t.site("public-one", { audience: "public", cloudflareProject: "demo-pages", siteUrl: "https://demo.example" }, {
+ reports: ["a-report"],
+ deployed: { v: 1, target: "public-one", previews: {}, production: { builtStampId: "x", builtAt: 1, kind: "production", url: "https://demo.example", at: 2, liveCheck: null } },
+ });
+ const plan = await planSiteDelete("public-one", t.paths);
+ assert.deepEqual(
+ plan.refusals.map((r) => [r.reason, r.forceable]),
+ [
+ ['it deploys to the Cloudflare Pages project "demo-pages"', true],
+ ["it holds 1 report (a-report), which go with it", true],
+ ["the publish state records a deploy: production (https://demo.example)", true],
+ ],
+ );
+ assert.equal(siteDeleteBlocked(plan), true);
+ assert.equal(siteDeleteBlocked(plan, true), false);
+ await assert.rejects(deleteSiteByPlan("public-one", t.paths), SiteDeleteRefusedError);
+ assert.ok(existsSync(path.join(t.paths.sitesDir, "public-one", "site.json")), "a refusal writes nothing");
+ assert.ok(plan.kept.some((k) => k.what === 'the Pages project "demo-pages"'));
+ const r = await deleteSiteByPlan("public-one", t.paths, { force: true });
+ assert.equal(r.removed.length, 3);
+ assert.equal(existsSync(path.join(t.paths.sitesDir, "public-one")), false);
+ } finally {
+ await t.done();
+ }
+});
+
+test("never forceable: no such site, a site dir that is a link, a publish stage running", async () => {
+ const t = await tree();
+ try {
+ const none = await planSiteDelete("ghost", t.paths);
+ assert.equal(none.exists, false);
+ assert.deepEqual(none.refusals, [{ reason: 'no site "ghost" (sites/ghost/site.json)', forceable: false }]);
+ // A link: refused, never followed.
+ await t.site("real", {}, { builds: false });
+ await symlink(path.join(t.paths.sitesDir, "real"), path.join(t.paths.sitesDir, "alias"));
+ const link = await planSiteDelete("alias", t.paths);
+ assert.equal(siteDeleteBlocked(link, true), true);
+ assert.match(link.refusals[0]!.reason, /sites\/alias is a link/);
+ // A publish stage holds the lock (this process, alive): refused, force or not.
+ await t.site("busy");
+ const lock = await acquirePublishLock(t.paths, { kind: "build-site", target: "other" });
+ try {
+ const busy = await planSiteDelete("busy", t.paths);
+ assert.deepEqual(busy.refusals.map((r) => r.forceable), [false]);
+ assert.match(busy.refusals[0]!.reason, /a publish stage is running: build-site other/);
+ await assert.rejects(deleteSiteByPlan("busy", t.paths, { force: true }), SiteDeleteRefusedError);
+ } finally {
+ await lock.release();
+ }
+ assert.ok(existsSync(path.join(t.paths.sitesDir, "busy", "site.json")));
+ assert.equal((await deleteSiteByPlan("busy", t.paths)).removed.length, 3);
+ assert.ok((await lstat(path.join(t.paths.sitesDir, "real"))).isDirectory(), "the link's target is kept");
+ } finally {
+ await t.done();
+ }
+});
+
+test("export/out linking into the site's bundle is named and kept", async () => {
+ const t = await tree();
+ try {
+ await t.site("linked");
+ await mkdir(t.paths.exportDir, { recursive: true });
+ const out = path.join(t.paths.exportDir, "out");
+ await symlink(path.join(t.paths.exportBuildsDir, "linked", "out"), out);
+ const plan = await planSiteDelete("linked", t.paths);
+ assert.ok(plan.kept.some((k) => k.what === "export/out" && /next build makes it again/.test(k.why)));
+ await deleteSiteByPlan("linked", t.paths);
+ assert.equal(await readlink(out), path.join(t.paths.exportBuildsDir, "linked", "out"));
+ } finally {
+ await t.done();
+ }
+});
diff --git a/common/controller/siteDelete.ts b/common/controller/siteDelete.ts
@@ -0,0 +1,250 @@
+// DELETE A SITE — a plan, then the delete (release 28 H5; `pnpm ops
+// delete-site`). The editor's Danger → Delete (`deleteSiteAction` →
+// lib/site.ts `deleteSite`) removes `sites/<id>/` and nothing else; this is
+// the scripted path, and it says first what goes, what stays and what refuses.
+//
+// WHAT A SITE IS ON DISK (the survey, 2026-10-13):
+// sites/<id>/ site.json (the pool: `channels`,
+// `citedChannels`), tags.json, charts,
+// its reports/ (each with history-git/)
+// export/.export-builds/<id>/ built.json, deployed.json (the publish
+// state), out/ (the last bundle),
+// public/ and .r2-staging/ (docker builds)
+// export/.export-index/sites/<id>/ compose's staging: report-media/,
+// report-exports/, summaries, stats
+// Nothing else names a site by id on disk: channel membership is site.json's
+// own pool (a channel's config holds no site list), the hub lists the sites
+// that are on disk with a siteUrl (its next build drops this one), and curated
+// tags' site scoping is read against the sites that exist.
+//
+// REMOVED: the three directories. KEPT, always: every channel's data (never
+// touched), the Cloudflare Pages project and anything already deployed to it
+// or to R2 (remote: a deploy, not a delete, takes a site off the edge), a
+// deployed hub until it is rebuilt, `export/out` when it links into this
+// site's bundle (the next build makes it again).
+//
+// REFUSED — forceable: a deploy target (`cloudflareProject`), a deploy the
+// publish state records (production, preview or local), a site that holds
+// reports (they go with it). Never forceable: no such site; its directory is a
+// link; a publish stage running (the publish lock held by a live holder).
+//
+// THE DELETE: under the site.json lock and the publish lock (taken without
+// waiting: a stage running refuses), the plan is made again, then each
+// directory is renamed aside to `.deleting-<id>-<stamp>` (not a site id, so no
+// reader lists it); the bulk is removed after the locks are let go.
+
+import type { Dirent } from "node:fs";
+import { lstat, readdir, readlink, rename, rm } from "node:fs/promises";
+import path from "node:path";
+import { withJsonFileLock } from "../lib/jsonFile-server";
+import type { Paths } from "../lib/paths";
+import { getSite, siteConfigFile, siteDir } from "../lib/site";
+import { isValidSiteId } from "../lib/siteSchema";
+import { exportOutPath } from "../publish/build";
+import { holderIsGone, LockWaitCancelled, acquirePublishLock, describeHolder, readLockHolder, type LockHolder } from "../publish/stageLock";
+import { readDeployedFile, targetDir } from "../publish/stamps";
+
+export type SiteDeletePaths = Pick<Paths, "sitesDir" | "exportBuildsDir" | "exportSitesIndexDir" | "exportDir">;
+
+export type SiteDeleteEntry = { path: string; label: string; what: string; kind: "dir" | "link" | "file"; bytes: number; files: number };
+export type SiteDeleteKept = { what: string; why: string };
+export type SiteDeleteRefusal = { reason: string; forceable: boolean };
+
+export type SiteDeletePlan = {
+ siteId: string;
+ exists: boolean;
+ refusals: SiteDeleteRefusal[];
+ remove: SiteDeleteEntry[];
+ kept: SiteDeleteKept[];
+ bytes: number;
+ files: number;
+};
+
+export type SiteDeleteResult = { plan: SiteDeletePlan; removed: string[]; failed: { path: string; error: string }[] };
+
+export class SiteDeleteRefusedError extends Error {
+ constructor(
+ message: string,
+ readonly plan: SiteDeletePlan,
+ ) {
+ super(message);
+ this.name = "SiteDeleteRefusedError";
+ }
+}
+
+export function siteDeleteBlocked(plan: Pick<SiteDeletePlan, "refusals">, force = false): boolean {
+ return plan.refusals.some((r) => !force || !r.forceable);
+}
+
+async function measure(p: string): Promise<{ bytes: number; files: number }> {
+ let bytes = 0;
+ let files = 0;
+ const walk = async (dir: string) => {
+ let entries: Dirent[];
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const e of entries) {
+ const child = path.join(dir, e.name);
+ if (e.isDirectory()) await walk(child);
+ else {
+ const s = await lstat(child).catch(() => null);
+ if (s) {
+ bytes += s.isSymbolicLink() ? 0 : s.size;
+ files += 1;
+ }
+ }
+ }
+ };
+ await walk(p);
+ return { bytes, files };
+}
+
+async function lstatOrNull(p: string) {
+ return lstat(p).catch(() => null);
+}
+
+export async function planSiteDelete(
+ siteId: string,
+ paths: SiteDeletePaths,
+ o: { measure?: boolean; ownLock?: LockHolder } = {},
+): Promise<SiteDeletePlan> {
+ if (!isValidSiteId(siteId)) throw new Error(`Invalid site id: ${String(siteId)}`);
+ const sizes = o.measure !== false;
+ const refusals: SiteDeleteRefusal[] = [];
+ const remove: SiteDeleteEntry[] = [];
+ const kept: SiteDeleteKept[] = [{ what: "every channel's data", why: "a site's delete never touches a channel" }];
+ const dir = siteDir(paths as Paths, siteId);
+ const st = await lstatOrNull(dir);
+ const exists = !!st && (st.isSymbolicLink() || (st.isDirectory() && !!(await lstatOrNull(siteConfigFile(paths as Paths, siteId)))));
+ if (!exists) refusals.push({ reason: `no site "${siteId}" (sites/${siteId}/site.json)`, forceable: false });
+ else if (st!.isSymbolicLink()) refusals.push({ reason: `sites/${siteId} is a link (to ${await readlink(dir).catch(() => "?")}): refused, never followed`, forceable: false });
+
+ const add = async (p: string, label: string, what: string) => {
+ const s = await lstatOrNull(p);
+ if (!s) return;
+ if (s.isSymbolicLink()) {
+ remove.push({ path: p, label, what, kind: "link", bytes: 0, files: 0 });
+ return;
+ }
+ const m = sizes && s.isDirectory() ? await measure(p) : { bytes: s.isDirectory() ? 0 : s.size, files: s.isDirectory() ? 0 : 1 };
+ remove.push({ path: p, label, what, kind: s.isDirectory() ? "dir" : "file", ...m });
+ };
+
+ if (exists && !st!.isSymbolicLink()) {
+ const site = getSite(siteId, paths as Paths);
+ await add(dir, `sites/${siteId}/`, "the site: site.json, its pool and pages, tags, charts, reports");
+ if (site.cloudflareProject?.trim()) {
+ refusals.push({ reason: `it deploys to the Cloudflare Pages project "${site.cloudflareProject.trim()}"`, forceable: true });
+ kept.push({ what: `the Pages project "${site.cloudflareProject.trim()}"`, why: "remote: what it serves stays until the project is changed there" });
+ }
+ const reports = (await readdir(path.join(dir, "reports"), { withFileTypes: true }).catch(() => [] as Dirent[])).filter((e) => e.isDirectory()).map((e) => e.name);
+ if (reports.length) {
+ refusals.push({ reason: `it holds ${reports.length} report${reports.length === 1 ? "" : "s"} (${reports.slice(0, 5).join(", ")}${reports.length > 5 ? ", …" : ""}), which go with it`, forceable: true });
+ }
+ }
+ // The publish state and the last bundle.
+ const builds = targetDir(paths, siteId);
+ const deployed = await readDeployedFile(paths, siteId).catch(() => null);
+ if (deployed) {
+ const kinds = [
+ ...(deployed.production ? [`production (${deployed.production.url ?? "no url"})`] : []),
+ ...Object.keys(deployed.previews ?? {}).map((b) => `preview ${b}`),
+ ...(deployed.local ? ["local"] : []),
+ ];
+ if (kinds.length) {
+ refusals.push({ reason: `the publish state records a deploy: ${kinds.join(", ")}`, forceable: true });
+ kept.push({ what: "what was deployed", why: "remote (or the local site volume): a delete does not undeploy" });
+ }
+ }
+ await add(builds, `export/.export-builds/${siteId}/`, "its publish state (built.json, deployed.json) and last bundle");
+ await add(path.join(paths.exportSitesIndexDir, siteId), `export/.export-index/sites/${siteId}/`, "compose's staging for it (report media and exports, summaries, stats)");
+ // export/out linking into this site's bundle: named, kept.
+ const out = exportOutPath(paths);
+ const outLink = await readlink(out).catch(() => null);
+ if (outLink) {
+ const target = path.resolve(path.dirname(out), outLink);
+ if (target === builds || target.startsWith(builds + path.sep)) {
+ kept.push({ what: "export/out", why: `it links to this site's bundle (${target}); the next build makes it again` });
+ }
+ }
+ kept.push({ what: "a deployed hub", why: "it lists the site until it is rebuilt (the next hub build drops it)" });
+ // A publish stage running: never forceable.
+ const holder = await readLockHolder(paths);
+ const mine = o.ownLock && holder && holder.pid === o.ownLock.pid && holder.since === o.ownLock.since && holder.host === o.ownLock.host;
+ if (holder && !mine && !holderIsGone(holder)) refusals.push({ reason: `a publish stage is running: ${describeHolder(holder)}`, forceable: false });
+
+ return {
+ siteId,
+ exists,
+ refusals,
+ remove,
+ kept,
+ bytes: remove.reduce((s, e) => s + e.bytes, 0),
+ files: remove.reduce((s, e) => s + e.files, 0),
+ };
+}
+
+export async function deleteSiteByPlan(siteId: string, paths: SiteDeletePaths, o: { force?: boolean; now?: Date } = {}): Promise<SiteDeleteResult> {
+ const first = await planSiteDelete(siteId, paths);
+ if (siteDeleteBlocked(first, o.force)) {
+ throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: ${first.refusals.map((r) => r.reason).join("; ")}`, first);
+ }
+ const stamp = (o.now ?? new Date()).toISOString().replace(/[-:.]/g, "");
+ const parked: string[] = [];
+ // The publish lock, without waiting: a stage that started since the plan refuses.
+ let lock: Awaited<ReturnType<typeof acquirePublishLock>>;
+ try {
+ lock = await acquirePublishLock(paths, { kind: "delete-site", target: siteId }, { signal: AbortSignal.timeout(1500), pollMs: 250 });
+ } catch (e) {
+ if (e instanceof LockWaitCancelled) {
+ const again = await planSiteDelete(siteId, paths, { measure: false });
+ throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: a publish stage is running`, again);
+ }
+ throw e;
+ }
+ try {
+ await withJsonFileLock(siteConfigFile(paths as Paths, siteId), async () => {
+ const plan = await planSiteDelete(siteId, paths, { measure: false, ownLock: lock.holder });
+ if (siteDeleteBlocked(plan, o.force)) {
+ throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: ${plan.refusals.map((r) => r.reason).join("; ")}`, plan);
+ }
+ for (const e of plan.remove) {
+ if (e.kind === "link") {
+ await rm(e.path, { force: true });
+ parked.push(e.path);
+ continue;
+ }
+ const aside = path.join(path.dirname(e.path), `.deleting-${siteId}-${stamp}`);
+ await rename(e.path, aside);
+ parked.push(aside);
+ }
+ });
+ } finally {
+ await lock.release();
+ }
+ const removed: string[] = [];
+ const failed: { path: string; error: string }[] = [];
+ for (const p of parked) {
+ try {
+ await rm(p, { recursive: true, force: true });
+ removed.push(p);
+ } catch (e) {
+ failed.push({ path: p, error: (e as Error).message });
+ }
+ }
+ return { plan: first, removed, failed };
+}
+
+const fmt = (n: number) => (n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KiB` : n < 1024 ** 3 ? `${(n / 1024 ** 2).toFixed(1)} MiB` : `${(n / 1024 ** 3).toFixed(1)} GiB`);
+
+export function formatSiteDeletePlan(plan: SiteDeletePlan, o: { force?: boolean } = {}): string[] {
+ const blocked = siteDeleteBlocked(plan, o.force);
+ const out = [`delete site "${plan.siteId}": ${plan.remove.length} path(s), ${fmt(plan.bytes)} in ${plan.files} file(s)${blocked ? " — REFUSED" : ""}`];
+ for (const r of plan.refusals) out.push(` refused${r.forceable ? (o.force ? " (force answers it)" : " (unless force)") : ""}: ${r.reason}`);
+ for (const e of plan.remove) out.push(` remove ${e.label} ${e.what}, ${e.kind === "link" ? "a link" : `${fmt(e.bytes)} in ${e.files} file(s)`}`);
+ for (const k of plan.kept) out.push(` keep ${k.what}: ${k.why}`);
+ return out;
+}
diff --git a/editor/app/api/ops/delete-site/route.ts b/editor/app/api/ops/delete-site/route.ts
@@ -0,0 +1,51 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { isValidSiteId } from "yt-dlp-transcript-common/lib/siteSchema";
+import {
+ SiteDeleteRefusedError,
+ deleteSiteByPlan,
+ planSiteDelete,
+ siteDeleteBlocked,
+} from "yt-dlp-transcript-common/controller/siteDelete";
+import { OpsInputError, ops, opsFail, optBool, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { id: string, force?: boolean, dryRun?: boolean }
+// -> { ok, applied, plan, removed?, failed? }
+//
+// DELETE A SITE (release 28 H5), plan first: `sites/<id>/` (site.json, its
+// pool and pages, tags, charts, reports), its publish state and last bundle
+// (`export/.export-builds/<id>/`) and compose's staging for it
+// (`export/.export-index/sites/<id>/`) — through controller/siteDelete.ts,
+// under the site.json lock and the publish lock. Channel data is never
+// touched; the Pages project, what was deployed and a deployed hub are kept
+// (remote: a delete does not undeploy). `dryRun` answers the plan and writes
+// nothing. Refused (409, with the plan): a site with a deploy target
+// (`cloudflareProject`), a deploy in its publish state, or reports of its own
+// — unless `force`; no such site, a site dir that is a link, or a publish
+// stage running — force or not.
+//
+// There is no undo, and transcripts/ is its own git repo — the only way back
+// for sites/<id>/ is a commit there.
+export async function POST(request: Request) {
+ return ops(request, ["id", "force", "dryRun"], async (body) => {
+ const id = reqString(body, "id");
+ if (!isValidSiteId(id)) throw new OpsInputError(`"${id}" is not a site id`);
+ const force = optBool(body, "force") === true;
+ const paths = getPaths();
+ try {
+ const plan = await planSiteDelete(id, paths);
+ if (siteDeleteBlocked(plan, force)) {
+ const why = plan.refusals.filter((r) => !force || !r.forceable).map((r) => r.reason);
+ return opsFail(`refused: ${why.join("; ")}`, plan.exists ? 409 : 404, { plan });
+ }
+ if (optBool(body, "dryRun") === true) return NextResponse.json({ ok: true, applied: false, plan });
+ const r = await deleteSiteByPlan(id, paths, { force });
+ return NextResponse.json({ ok: r.failed.length === 0, applied: true, plan: r.plan, removed: r.removed, failed: r.failed });
+ } catch (err) {
+ if (err instanceof SiteDeleteRefusedError) return opsFail(err.message, 409, { plan: err.plan });
+ throw err;
+ }
+ });
+}
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -58,6 +58,7 @@
// pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'
// pnpm ops delete-article --json '{"id":"demo-article","force":true}'
// pnpm ops delete-iteration --json '{"id":"demo-article","n":3}'
+// pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}'
// pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'
// pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'
// pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'
@@ -271,6 +272,9 @@ const ACTIONS = [
// Synchronous; no job.
"delete-article",
"delete-iteration",
+ // Delete a site ({id, force?, dryRun?}): the plan, then sites/<id>/, its
+ // publish state and its staging. Channel data is never touched. Synchronous.
+ "delete-site",
// The channel's lifecycle: the New channel form, and the channel page's
// Danger → Rename and Danger → Delete. Synchronous; no job.
"create-channel",
@@ -989,6 +993,18 @@ export function usage() {
' from, the current video, a queued or running one, one another revises',
' or copies.',
"",
+ 'delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan',
+ " — every path with its size, what is kept and why — and write nothing),",
+ ' "force"? It removes sites/<id>/ (site.json, its pool and pages, tags,',
+ " charts, its reports), its publish state and last bundle",
+ " (export/.export-builds/<id>/) and compose's staging for it",
+ " (export/.export-index/sites/<id>/). Channel data is never touched; the",
+ " Pages project, what was deployed and a deployed hub are kept (a delete",
+ ' does not undeploy). Refused with the plan (409) unless "force": a deploy',
+ " target (cloudflareProject), a deploy in its publish state, reports of its",
+ " own. Refused, force or not: no such site (404), a site dir that is a link,",
+ " a publish stage running.",
+ "",
'create-channel is the New channel form: {"fields": {"name", "handling":',
' "youtube"|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?,',
' "socialHandle"?, …}} with channel-config\'s patch keys; "slug"? (else',