commit 6a3434f6b1bf0d1345bc937e5f6140130c0abf3c
parent edff34a513de01eda113390970028d806d2730e0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 20:52:29 -0500
sites: the site save, create-site and a channel delete's membership patch run under the site's lock
Review of lane/editor-gaps. dropChannelFromSites read getSite then wrote
writeSite with no lock, and the site form's save (now what create-site's
update calls) read the stored pages and social links outside one too: a
concurrent edit of the site, a Reports-tab pages patch, could be written over.
lib/site.ts withSiteLock is patchSite's lock, exported; the delete's edit is a
patchSite; the save's core moves to sites/lib/saveSiteForm.ts and
saveSiteAction runs it under the lock; create-site takes the lock around its
existence check, its read of the stored site and the save. create-site also
refuses a channel's groupId that names none of the site's groups (the parser
dropped it without a word).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
9 files changed, 457 insertions(+), 345 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -125,7 +125,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `channel-priority` | channel-priority sets channels' priority, as the /channels deck's tier control does: {"slugs", "tier": "normal" \| "low" \| "paused"} sets the base tier; with "operation" (sync, transcription, download, digest, backfill) it pins that operation's tier, "tier": null clearing it back to the base; "preset": "sync-only" \| "clear" is the deck's two shortcuts and takes no tier. A manual change clears an automatic pause. {"focus": {"kind": "site", "siteId"} \| {"kind": "channels", "slugs"} \| {"kind": "none"}} alone is the deck's focus bar: those channels lead every lane (a site focus follows its membership); "none" ends it. | `pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'`<br>`pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}'` |
| `channel-rank` | channel-rank places one channel in the order every lane and the sync scheduler follow inside a tier (one rank per channel, 0 first; unranked channels come after every ranked one, by slug): {"slug"} and exactly one of "rank": <n> (before any channel holding it) or null (unranked), "top": true, "bottom": true, "before": "<slug>", "after": "<slug>" (a ranked channel; immediately next to it, a tie on its rank included). The channels after it move down only as far as they must. Only the rank moves — no tier, override or lane changes, unlike /channels' "Add to top". Refused: an unknown channel, an unranked anchor, a channel paused for every operation. Answers {slug, rank, order: \[{slug, rank}, …\]}. | `pnpm ops channel-rank --json '{"slug":"x","top":true}'`<br>`pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}'`<br>`pnpm ops channel-rank --json '{"slug":"x","rank":null}'` |
| `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "<regex with named groups year, month, day>"} (CHANNEL.md, recordedDate). A mirror's creator channels: "patch": {"mirrorOf": "<slug>, <slug>"} (CHANNEL.md, mirror; then mirror-scan). Caption languages and the live chat: "patch": {"subLangs": "en.\*", "chat": "with-download" \| "later" \| "never"} (CHANNEL.md, subLangs and chat). Manual downloads: "patch": {"downloadMode": "manual"} — only videos you add (import-video, the video page) are downloaded; the download lane, a sync's new uploads and download-missing leave the channel alone; "" (or "auto") is automatic (CHANNEL.md, downloadMode). | `pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` |
-| `create-site` | create-site is the New site form: {"siteId", "siteTitle"} and any of its fields — "headerTitle" (default the title), "siteDescription", "homeTagline", "wordmarkLead", "accent" (an id or "#rrggbb"), "siteUrl", "cloudflareProject", "hubUrl", "audience" ("private" \| "public"; default PRIVATE), "listed" (default FALSE), "publishAuto", "search", "archives", "duplicates", "transcriptDownloads", "pwa", "archiveMaxMB" (null = the global default), "groups" (\[{"id", "name", "selectedByDefault"?, "description"?, "inline"?}\]), "defaultGroupId", "channels" (slugs, or {"slug", "groupId"?}: the pool), "citedChannels" (slugs), "socialLinks" (\[{"label", "url", "svg"}\], null = inherit), "relatedSites". Saved by the form's action (its validation, its sentences). An existing id is refused (409) unless "update": true — the site page's Save with the keys given changed, every other key kept. An unknown channel is refused. Answers {siteId, created, site}. | `pnpm ops create-site --json '{"siteId":"demo-site","siteTitle":"Demoalyzer","channels":["demo-yt"]}'`<br>`pnpm ops create-site --json '{"siteId":"demo-site","update":true,"homeTagline":"Every stream, searchable"}'` |
+| `create-site` | create-site is the New site form: {"siteId", "siteTitle"} and any of its fields — "headerTitle" (default the title), "siteDescription", "homeTagline", "wordmarkLead", "accent" (an id or "#rrggbb"), "siteUrl", "cloudflareProject", "hubUrl", "audience" ("private" \| "public"; default PRIVATE), "listed" (default FALSE), "publishAuto", "search", "archives", "duplicates", "transcriptDownloads", "pwa", "archiveMaxMB" (null = the global default), "groups" (\[{"id", "name", "selectedByDefault"?, "description"?, "inline"?}\]), "defaultGroupId", "channels" (slugs, or {"slug", "groupId"?}: the pool), "citedChannels" (slugs), "socialLinks" (\[{"label", "url", "svg"}\], null = inherit), "relatedSites". Saved by the form's action (its validation, its sentences). An existing id is refused (409) unless "update": true — the site page's Save with the keys given changed, every other key kept — one read-modify-write under the site's lock. An unknown channel, or a channel's groupId naming no group of the site, is refused. Answers {siteId, created, site}. | `pnpm ops create-site --json '{"siteId":"demo-site","siteTitle":"Demoalyzer","channels":["demo-yt"]}'`<br>`pnpm ops create-site --json '{"siteId":"demo-site","update":true,"homeTagline":"Every stream, searchable"}'` |
| `site-config` | site-config sets two keys of a site as its form does: {"siteId"} and any of "citedChannels" (the WHOLE cited scope, channel slugs: what the site's reports may cite without publishing the channel; \[\] clears it; a slug the pool holds is dropped) and "publishAuto" ("off" \| "build" \| "preview" \| "production", the publish lane's policy; a deploying one needs a Pages project, a private site is clamped to "build"). Only those two keys; an unknown site or channel is refused before anything is written. Answers the saved values. | `pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'`<br>`pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'` |
| `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}'` |
diff --git a/common/controller/siteMemberships.ts b/common/controller/siteMemberships.ts
@@ -1,11 +1,12 @@
import type { Paths } from "../lib/paths";
-import { getSite, listSiteIds, writeSite } from "../lib/site";
+import { getSite, listSiteIds, patchSite, type Site } from "../lib/site";
// A DELETED CHANNEL LEAVES NO SITE NAMING IT (lane editor-gaps; 9 Nov:
// deleting `mooler` left it in efapalyzer's site.json, fixed by hand). Every
// site's pool (`channels`) and cited scope (`citedChannels`) drop the slug,
// through the one site writer (writeSite), the way a rename re-points them
-// (renameChannel.ts, step 5). A site that does not name it is not written.
+// (renameChannel.ts, step 5), each as a patchSite under the site's lock. A
+// site that does not name it is not written.
//
// Best-effort per site, because the channel is already gone: a site whose
// write is refused (its own file no longer valid) is named in `failed` with
@@ -19,23 +20,29 @@ export async function dropChannelFromSites(paths: Paths, slug: string): Promise<
const result: SiteDropResult = { updated: [], failed: [] };
for (const siteId of [...listSiteIds(paths)].sort()) {
try {
- const site = getSite(siteId, paths);
- const cited = site.citedChannels ?? [];
- const inPool = site.channels.some((c) => c.slug === slug);
- const inCited = cited.some((c) => c.slug === slug);
- if (!inPool && !inCited) continue;
- await writeSite(
- {
- ...site,
- channels: site.channels.filter((c) => c.slug !== slug),
- citedChannels: cited.filter((c) => c.slug !== slug),
- },
+ // A cheap look first, so a site that does not name it is not written;
+ // the edit itself is a patch, read again INSIDE the site's lock, so a
+ // concurrent edit of the site (a Reports-tab pages patch) is not
+ // written over with this copy.
+ if (!namesChannel(getSite(siteId, paths), slug)) continue;
+ const saved = await patchSite(
+ siteId,
+ (current) => ({
+ channels: current.channels.filter((c) => c.slug !== slug),
+ citedChannels: (current.citedChannels ?? []).filter((c) => c.slug !== slug),
+ }),
paths,
);
- result.updated.push(siteId);
+ if (saved) result.updated.push(siteId);
} catch (err) {
result.failed.push({ siteId, error: (err as Error).message });
}
}
return result;
}
+
+function namesChannel(site: Site, slug: string): boolean {
+ return (
+ site.channels.some((c) => c.slug === slug) || (site.citedChannels ?? []).some((c) => c.slug === slug)
+ );
+}
diff --git a/common/lib/site.ts b/common/lib/site.ts
@@ -307,6 +307,20 @@ export async function writeSite(
// interleave. A function patch is given the site as it is now (to reorder a
// list it did not read itself). Validated and written by writeSite. Null when
// the site has no site.json: a patch never creates a site.
+// THE SITE FILE'S LOCK: a read-modify-write of one site.json that must not
+// interleave with another (patchSite, the site form's save). Per process; NOT
+// re-entrant — never patchSite from inside it. writeSite does not take it.
+export function withSiteLock<T>(
+ siteId: string,
+ fn: () => Promise<T>,
+ paths: Paths = getPaths(),
+): Promise<T> {
+ if (!isValidSiteId(siteId)) {
+ throw new Error(`Invalid site id: ${String(siteId)}`);
+ }
+ return withJsonFileLock(siteConfigFile(paths, siteId), fn);
+}
+
export async function patchSite(
siteId: string,
patch:
@@ -318,7 +332,7 @@ export async function patchSite(
throw new Error(`Invalid site id: ${String(siteId)}`);
}
const file = siteConfigFile(paths, siteId);
- return withJsonFileLock(file, async () => {
+ return withSiteLock(siteId, async () => {
if (!fs.existsSync(file)) return null;
const current = getSite(siteId, paths);
const changes = typeof patch === "function" ? patch(current) : patch;
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,8 +1,8 @@
# Changelog
## [Unreleased]
-- **Deleting a channel takes it off every site.** On 9 Nov, deleting `mooler` left it in efapalyzer's `site.json`, and the site had to be fixed by hand. Danger → Delete and `pnpm ops delete-channel` now rewrite every site whose pool (`channels`) or cited scope (`citedChannels`) names the deleted channel, through the one site writer (`writeSite`), as a rename already re-points them. The ops answer names those sites in `sitesUpdated`. A site whose write is refused shows up as a `warnings` line, and the delete still stands. Sites that never named the channel are not written (`common/controller/siteMemberships.ts`).
-- **`pnpm ops create-site` is the New site form, without a browser.** On 9 Nov an agent had to call `writeSite` from a tsx script to make `efapalyzer`. `create-site` takes `{"siteId", "siteTitle"}` and any of the form's fields: header title (default the title), description, tagline, wordmark lead, accent, public URL, Pages project, hub URL, audience, listed, publish policy, search, archives, duplicates, transcript downloads, PWA, archive cap, groups, default group, channels, cited channels, social links and related sites. It builds the FormData the form posts and saves it through the form's own action (`saveSiteAction` → `writeSite`), so you get the same validation and the same sentences. A new site is **private and unlisted** unless the body says `"audience": "public"` / `"listed": true`. An existing id is refused (409) unless `"update": true`, which is the site page's Save with only the given keys changed; every other key, and the published page list, is kept. Unknown channels, unknown keys and keys of the wrong type are refused before anything is written. It answers the saved site.
+- **Deleting a channel takes it off every site.** On 9 Nov, deleting `mooler` left it in efapalyzer's `site.json`, and the site had to be fixed by hand. Danger → Delete and `pnpm ops delete-channel` now rewrite every site whose pool (`channels`) or cited scope (`citedChannels`) names the deleted channel, each as a `patchSite` under that site's lock, so a concurrent edit of the site is not written over (a rename already re-points them through the same writer). The ops answer names those sites in `sitesUpdated`. A site whose write is refused shows up as a `warnings` line, and the delete still stands. Sites that never named the channel are not written (`common/controller/siteMemberships.ts`).
+- **`pnpm ops create-site` is the New site form, without a browser.** On 9 Nov an agent had to call `writeSite` from a tsx script to make `efapalyzer`. `create-site` takes `{"siteId", "siteTitle"}` and any of the form's fields: header title (default the title), description, tagline, wordmark lead, accent, public URL, Pages project, hub URL, audience, listed, publish policy, search, archives, duplicates, transcript downloads, PWA, archive cap, groups, default group, channels, cited channels, social links and related sites. It builds the FormData the form posts and saves it through the form's own action (`saveSiteAction` → `writeSite`), so you get the same validation and the same sentences. A new site is **private and unlisted** unless the body says `"audience": "public"` / `"listed": true`. An existing id is refused (409) unless `"update": true`, which is the site page's Save with only the given keys changed; every other key, and the published page list, is kept. Unknown channels, a channel's `groupId` that names none of the site's groups, unknown keys and keys of the wrong type are refused before anything is written. The existence check, the read of the stored site and the save are one read-modify-write under the site's lock (`withSiteLock`). The site form's own Save now takes the same lock, so neither it nor an update is written over a concurrent edit such as a Reports-tab pages patch. It answers the saved site.
- **`pnpm ops channel-rank` places one channel in the order the lanes follow.** Before this, only /channels' "Add to top" moved a channel, and it also sets the tier to normal and turns the download lane on. `channel-rank` moves the rank alone: `{"slug"}` plus exactly one of `"rank": <n>` (or `null` to unrank), `"top": true`, `"bottom": true`, `"before": "<slug>"` or `"after": "<slug>"`. Every other channel keeps its order: channels after it move down only as far as they must, ties stay tied, and `after` lands immediately after its anchor even when the anchor's rank is tied. It goes through the deck's one writer, so the four lane roots are recompiled in the same write. That writer now does its read-modify-write inside a settings lock, which every `saveSettings` takes too, so a concurrent deck save or a parallel `channel-rank` is never written over. Refused before any write: an unknown channel or anchor, an anchor with no rank, a rank that is not a whole number ≥ 0, and a channel paused for every operation (its rank would not be kept). It answers the saved rank and the whole ranked order (`common/lib/channelPriority.ts` `placeChannelRank`).
- **Configure's Caption languages field (`subLangs`) is checked when you save.** Before, any text was saved, and a value yt-dlp's `--sub-langs` cannot use failed every caption download on the channel at the moment it ran. Configure and `pnpm ops channel-config` (`patch.subLangs`) now refuse it, in the field's words, with what you typed kept. Refused: an empty entry (two commas, or one at an end), a space inside an entry, a bare `-`, an entry that is not a regular expression, or a value over 200 characters. Spaces around an entry are dropped (`en.* , es` saves as `en.*,es`). A value saved before this check and submitted unchanged is kept, with a warning in the server log, so Configure is never locked on it. `all` and `-<lang>` exclusions are accepted as before (`common/lib/channelConfig.ts` `subLangsProblem`).
- **Transcribe refuses a video that is live.** On 4 Nov a transcribe-one on a live YouTube video downloaded the stream at 1x and held `platform:youtube` for the stream's whole length. Now the video page's Transcribe and `pnpm ops transcribe-one` refuse a video whose `metadata.info.json` says it is live (`is_live`), scheduled (`is_upcoming`) or still processing its VOD (`post_live`), before anything is queued. The refusal names `pnpm ops record-live` for the stream (not for `post_live`), says to wait for the VOD otherwise, and names `refresh-metadata` to re-read the record once the stream has ended. The job checks again just before its download, in case the record was re-read while it waited. Only the audio download is refused: a video whose audio or container is already on disk still transcribes, and a youtube-handling video with English captions listed still has its captions fetched instead. A finished stream (`was_live`) downloads as before (`common/lib/liveNow.ts`).
diff --git a/editor/app/api/ops/create-site/route.test.ts b/editor/app/api/ops/create-site/route.test.ts
@@ -18,7 +18,7 @@ for (const slug of ["pooled", "critic", "other"]) {
}
await corpus.writeSite("neighbour", {});
const { POST } = await import("./route");
-const { getSite, writeSite } = await import("yt-dlp-transcript-common/lib/site");
+const { getSite, writeSite, withSiteLock } = await import("yt-dlp-transcript-common/lib/site");
const { getPaths } = await import("yt-dlp-transcript-common/lib/paths");
const { siteToFormData } = await import("../../../sites/lib/siteFormData");
const { saveSiteAction } = await import("../../../sites/actions");
@@ -113,6 +113,11 @@ test("the form's refusals, and the door's, before anything is written", async ()
[{ siteId: "typ", siteTitle: "T", listed: "yes" }, 400, /"listed" must be a boolean/],
[{ siteId: "typ2", siteTitle: "T", archiveMaxMB: "12" }, 400, /"archiveMaxMB" must be a number/],
[{ siteId: "unk", siteTitle: "U", pages: ["a"] }, 400, /pages/],
+ [
+ { siteId: "grptypo", siteTitle: "G", channels: [{ slug: "pooled", groupId: "typo" }] },
+ 400,
+ /"channels": "pooled" names group "typo", which is not one of the site's groups \("default"\)/,
+ ],
] as const) {
const r = await callPost(POST, body);
assert.equal(r.status, status, JSON.stringify(body) + " " + JSON.stringify(r.body));
@@ -187,3 +192,30 @@ test("siteToFormData -> saveSiteAction gives a full site back unchanged", async
assert.equal((await saveSiteAction(undefined, siteToFormData(getSite("plain", paths)))).ok, true);
assert.deepEqual(await siteFile("plain"), plain);
});
+
+// An update is ONE read-modify-write under the site's lock: an edit of the
+// site that holds the lock when the update arrives (a Reports-tab patch, say)
+// is read by the update, not written over by a copy taken before it landed.
+test("an update waits for a held edit of the site and keeps it", async () => {
+ const paths = getPaths();
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const held = withSiteLock(
+ "shown",
+ async () => {
+ const current = getSite("shown", paths);
+ await gate;
+ await writeSite({ ...current, homeTagline: "written while the update waited" }, paths);
+ },
+ paths,
+ );
+ const up = callPost(POST, { siteId: "shown", update: true, siteDescription: "after the held edit" });
+ await new Promise((r) => setTimeout(r, 20));
+ release();
+ await held;
+ const r = await up;
+ assert.equal(r.status, 200, JSON.stringify(r.body));
+ const file = await siteFile("shown");
+ assert.equal(file.homeTagline, "written while the update waited");
+ assert.equal(file.siteDescription, "after the held edit");
+});
diff --git a/editor/app/api/ops/create-site/route.ts b/editor/app/api/ops/create-site/route.ts
@@ -5,14 +5,16 @@ import {
getSite,
isValidSiteId,
siteConfigFile,
+ withSiteLock,
type Site,
} from "yt-dlp-transcript-common/lib/site";
import {
DEFAULT_GROUP_FALLBACK_ID,
FALLBACK_GROUP,
+ parseChannelGroups,
} from "yt-dlp-transcript-common/lib/channelGroups";
import { channelExists, isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
-import { saveSiteAction } from "../../../sites/actions";
+import { saveSiteFromForm } from "../../../sites/lib/saveSiteForm";
import {
SITE_OPS_FIELDS,
SiteFieldError,
@@ -60,38 +62,69 @@ export async function POST(request: Request) {
}
const update = optBool(body, "update") === true;
const paths = getPaths();
- const exists = existsSync(siteConfigFile(paths, siteId));
- if (exists && !update) {
- return opsFail(
- `Site "${siteId}" already exists. "update": true saves the keys given over it, as its form's Save does ` +
- `(site-config sets its cited channels and publish policy alone).`,
- 409,
- );
- }
- if (!exists && update) {
- return opsFail(`Site "${siteId}" not found — leave out "update" to create it`, 404);
- }
if (!update && typeof body.siteTitle !== "string") {
throw new OpsInputError('a new site needs a "siteTitle"');
}
await refuseUnknownChannels(body);
-
const fields: Record<string, unknown> = {};
for (const key of SITE_OPS_FIELDS) if (body[key] !== undefined) fields[key] = body[key];
if (!update && fields.headerTitle === undefined) fields.headerTitle = fields.siteTitle;
- const fd = siteToFormData(update ? getSite(siteId, paths) : blankSite(siteId));
- try {
- applySiteFields(fd, fields);
- } catch (e) {
- if (e instanceof SiteFieldError) throw new OpsInputError(e.message);
- throw e;
- }
- const saved = await saveSiteAction(undefined, fd);
- if (!saved.ok) return opsFail(saved.error);
- return NextResponse.json({ ok: true, siteId, created: !update, site: getSite(siteId, paths) });
+ // ONE READ-MODIFY-WRITE, under the site's lock (lib/site.ts withSiteLock):
+ // whether the site exists, the stored site an update starts from, and the
+ // form's save — so a concurrent edit of the site (a Reports-tab pages
+ // patch, a channel delete's membership patch) is never written over with
+ // the copy read here, and two creates of one id cannot both pass.
+ return withSiteLock(siteId, () => createOrUpdate(siteId, update, fields), paths);
});
}
+async function createOrUpdate(
+ siteId: string,
+ update: boolean,
+ fields: Record<string, unknown>,
+): Promise<NextResponse> {
+ const paths = getPaths();
+ const exists = existsSync(siteConfigFile(paths, siteId));
+ if (exists && !update) {
+ return opsFail(
+ `Site "${siteId}" already exists. "update": true saves the keys given over it, as its form's Save does ` +
+ `(site-config sets its cited channels and publish policy alone).`,
+ 409,
+ );
+ }
+ if (!exists && update) {
+ return opsFail(`Site "${siteId}" not found — leave out "update" to create it`, 404);
+ }
+ const fd = siteToFormData(update ? getSite(siteId, paths) : blankSite(siteId));
+ try {
+ applySiteFields(fd, fields);
+ refuseUnknownGroups(fd);
+ } catch (e) {
+ if (e instanceof SiteFieldError) return opsFail(e.message);
+ throw e;
+ }
+ const saved = await saveSiteFromForm(fd);
+ if (!saved.ok) return opsFail(saved.error);
+ return NextResponse.json({ ok: true, siteId, created: !update, site: getSite(siteId, paths) });
+}
+
+// A channel's groupId that names no group of the site: the parser would drop
+// it without a word (the channel falls into the default group). The form only
+// offers the site's groups; over ops it is said.
+function refuseUnknownGroups(fd: FormData): void {
+ const groups = parseChannelGroups(JSON.parse(String(fd.get("groupsJson") ?? "[]")));
+ const ids = new Set(groups.map((g) => g.id));
+ const channels = JSON.parse(String(fd.get("channelsJson") ?? "[]")) as { slug?: unknown; groupId?: unknown }[];
+ for (const c of channels) {
+ if (typeof c.groupId === "string" && c.groupId && !ids.has(c.groupId)) {
+ throw new SiteFieldError(
+ `"channels": "${String(c.slug)}" names group "${c.groupId}", which is not one of the site's groups ` +
+ `(${[...ids].map((id) => `"${id}"`).join(", ") || "none"})`,
+ );
+ }
+ }
+}
+
// What /sites/new starts from, private and unlisted.
function blankSite(siteId: string): Site {
return {
diff --git a/editor/app/sites/actions.ts b/editor/app/sites/actions.ts
@@ -1,33 +1,7 @@
"use server";
-import { PUBLISH_POLICIES, type PublishPolicy } from "yt-dlp-transcript-common/lib/settingsSchema";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
-import {
- parseAccent,
- parseAccentSetting,
-} from "yt-dlp-transcript-common/lib/accent";
-import {
- DEFAULT_ACCENT,
- wordmarkLeadFor,
-} from "yt-dlp-transcript-common/lib/brand";
-import {
- getSite,
- writeSite,
- isValidSiteId,
- reservedSiteIdProblem,
- parseRelatedSites,
- parseSiteChannels,
- parseSiteUrl,
- type Site,
-} from "yt-dlp-transcript-common/lib/site";
-import {
- parseSocialLinks,
- type SocialLink,
-} from "yt-dlp-transcript-common/lib/settings";
-import {
- parseChannelGroups,
- resolveDefaultGroupId,
-} from "yt-dlp-transcript-common/lib/channelGroups";
+import { isValidSiteId, withSiteLock } from "yt-dlp-transcript-common/lib/site";
import { migrateToSites } from "yt-dlp-transcript-common/controller/migrateToSites";
import {
SiteDeleteRefusedError,
@@ -36,288 +10,21 @@ import {
siteDeleteBlocked,
type SiteDeletePlan,
} from "yt-dlp-transcript-common/publish/siteDelete";
-import { socialLinksForSave } from "yt-dlp-transcript-common/lib/socialLinks";
-import { formValues, type FormState, type FormValues } from "../lib/formState";
-import { reportSiteKeysFromForm } from "./lib/reportSiteKeys";
-import { citedChannelsFromForm } from "./lib/citedChannelsFromForm";
+import { saveSiteFromForm, type SaveResult } from "./lib/saveSiteForm";
-// A failure carries what was submitted, so SiteForm keeps what was typed
-// (lib/formState.ts).
-export type SaveResult = FormState<{ siteId: string; values: FormValues }>;
+export type { SaveResult } from "./lib/saveSiteForm";
+// The site form's Save: the save under the site's lock (lib/site.ts
+// withSiteLock), so it and a concurrent patch of the same site (the Reports
+// tab's pages, a channel delete's membership patch) never interleave. An
+// invalid id has no file to lock; the save refuses it in its own words.
export async function saveSiteAction(
_prev: SaveResult | undefined,
formData: FormData,
): Promise<SaveResult> {
- const values = formValues(formData);
const siteId = String(formData.get("siteId") ?? "").trim();
- if (!isValidSiteId(siteId)) {
- return {
- ok: false,
- error: "Site ID must be lowercase letters, numbers, and hyphens.",
- values,
- };
- }
- // `articles` and `new` are the editor's own /sites/ routes (writeSite refuses
- // them too): said here, before anything else is read.
- const reserved = reservedSiteIdProblem(siteId);
- if (reserved) return { ok: false, error: reserved, values };
- const siteTitle = String(formData.get("siteTitle") ?? "").trim();
- const headerTitle = String(formData.get("headerTitle") ?? "").trim();
- if (!siteTitle) {
- return { ok: false, error: "Site title is required", values };
- }
- if (!headerTitle) {
- return { ok: false, error: "Header title is required", values };
- }
- const siteDescription = String(formData.get("siteDescription") ?? "").trim();
- const homeTagline = String(formData.get("homeTagline") ?? "").trim();
- // The wordmark's heavy lead must be a proper prefix of the header title;
- // lib/siteSchema.ts would silently drop anything else, so say so here.
- const wordmarkLead = String(formData.get("wordmarkLead") ?? "").trim();
- if (wordmarkLead && !wordmarkLeadFor(headerTitle, wordmarkLead)) {
- return {
- ok: false,
- error: `Wordmark lead must be how the header title starts, same case, and shorter than it (e.g. "Jer" for "Jeralyzer") — or left blank.`,
- values,
- };
- }
- // Brand accent: a named id from the radio group, or "custom" + its hex
- // field. The default (Signal) is stored as absent — the two read the same.
- // A bare hex in `accent` (a form from before the radio group) is taken as
- // a custom colour.
- const accentChoice = String(formData.get("accent") ?? "").trim();
- const accentCustomRaw = String(formData.get("accentCustom") ?? "").trim();
- let accent: string | undefined;
- if (accentChoice === "custom") {
- accent = parseAccent(accentCustomRaw);
- if (!accent) {
- return {
- ok: false,
- error: "Custom accent must be a hex color like #cc3366.",
- values,
- };
- }
- } else if (accentChoice) {
- accent = parseAccentSetting(accentChoice);
- if (!accent) {
- return {
- ok: false,
- error: `Unknown brand accent "${accentChoice}".`,
- values,
- };
- }
- if (accent === DEFAULT_ACCENT) accent = undefined;
- }
- const cloudflareProject = String(
- formData.get("cloudflareProject") ?? "",
- ).trim();
- const siteUrlRaw = String(formData.get("siteUrl") ?? "").trim();
- if (siteUrlRaw && !parseSiteUrl(siteUrlRaw)) {
- return {
- ok: false,
- error: "Public URL must be an absolute http(s):// URL, or left blank.",
- values,
- };
- }
- const siteUrl = parseSiteUrl(siteUrlRaw);
- // Listed on the homepage and hub by default: the same opt-out idiom as
- // archives below (an unchecked box sends no key → persisted as false).
- const listed = formData.get("listed") === "on";
- // Who the site is built for (release 17 slice XP): only "private" is kept.
- const audienceRaw = String(formData.get("audience") ?? "public");
- if (audienceRaw !== "public" && audienceRaw !== "private") {
- return { ok: false, error: `Unknown audience "${audienceRaw}".`, values };
- }
- const isPrivate = audienceRaw === "private";
- // The publish lane's policy for this site (release 18). writeSite refuses a
- // deploying policy with no Pages project (sitePublishProblem) and stores a
- // private site's as "build".
- const publishAutoRaw = String(formData.get("publishAuto") ?? "off");
- if (!(PUBLISH_POLICIES as readonly string[]).includes(publishAutoRaw)) {
- return { ok: false, error: `Unknown publish policy "${publishAutoRaw}".`, values };
- }
- const publishAuto = publishAutoRaw as PublishPolicy;
- // Search (opt-out; off = pages only) and the page list, which is not on
- // this form: the stored one is carried over.
- let storedReports: Pick<Site, "pages"> | undefined;
- try {
- storedReports = getSite(siteId, getPaths());
- } catch {
- storedReports = undefined;
- }
- const reportKeys = reportSiteKeysFromForm(formData, storedReports);
-
- // Hub parent (per-site override of the family default) + PWA opt-in.
- const hubUrlRaw = String(formData.get("hubUrl") ?? "").trim();
- if (hubUrlRaw && !parseSiteUrl(hubUrlRaw)) {
- return {
- ok: false,
- error: "Hub URL must be an absolute http(s):// URL, or left blank.",
- values,
- };
- }
- const hubUrl = parseSiteUrl(hubUrlRaw);
- const pwa = formData.get("pwa") === "on";
- // Archives default on: an unchecked (default-on) box yields no "archives" key
- // → false → persisted as the explicit opt-out.
- const archives = formData.get("archives") === "on";
- // Duplicates default on, same opt-out idiom as archives.
- const duplicates = formData.get("duplicates") === "on";
- // Per-video transcript downloads default on, same opt-out idiom.
- const transcriptDownloads = formData.get("transcriptDownloads") === "on";
- const archiveMaxMBRaw = String(formData.get("archiveMaxMB") ?? "").trim();
- let archiveMaxBytes: number | undefined;
- if (archiveMaxMBRaw) {
- const mb = Number(archiveMaxMBRaw);
- if (!Number.isFinite(mb) || mb < 0) {
- return {
- ok: false,
- error: "Archive size cap must be a non-negative number of MB, or blank.",
- values,
- };
- }
- archiveMaxBytes = Math.floor(mb * 1024 * 1024);
- }
-
- let relatedSitesInput: unknown;
- try {
- relatedSitesInput = JSON.parse(
- String(formData.get("relatedSitesJson") ?? "[]"),
- );
- } catch {
- return { ok: false, error: "Related sites payload is malformed", values };
- }
- const relatedSites = parseRelatedSites(relatedSitesInput);
-
- let groupsInput: unknown;
- try {
- groupsInput = JSON.parse(String(formData.get("groupsJson") ?? "[]"));
- } catch {
- return { ok: false, error: "Channel groups payload is malformed", values };
- }
- const groups = parseChannelGroups(groupsInput);
- if (groups.length === 0) {
- return {
- ok: false,
- error: "At least one channel group is required (check ID/name fields)",
- values,
- };
- }
- const defaultGroupIdRaw = String(formData.get("defaultGroupId") ?? "").trim();
- const defaultGroupId = resolveDefaultGroupId(defaultGroupIdRaw, groups);
- if (defaultGroupIdRaw && defaultGroupIdRaw !== defaultGroupId) {
- return {
- ok: false,
- error: `Default group "${defaultGroupIdRaw}" is not among the configured group IDs`,
- values,
- };
- }
-
- // When inheriting, leave socialLinks undefined so writeSite omits the key and
- // the site falls back to the global default at render time.
- const inheritSocialLinks = formData.get("inheritSocialLinks") === "on";
- let socialLinks: SocialLink[] | undefined;
- if (!inheritSocialLinks) {
- let socialInput: unknown;
- try {
- socialInput = JSON.parse(String(formData.get("socialLinksJson") ?? "[]"));
- } catch {
- return { ok: false, error: "Social links payload is malformed", values };
- }
- const socialParsed = parseSocialLinks(socialInput);
- if (
- Array.isArray(socialInput) &&
- socialParsed.length !== socialInput.length
- ) {
- return {
- ok: false,
- error:
- "Each social link needs a label, URL (http(s)://, mailto:, or /), and SVG.",
- values,
- };
- }
- // A link whose SVG is unchanged from the site's file is kept as it is; a
- // new or edited one is checked (lib/socialLinks.ts socialLinksForSave).
- let stored: SocialLink[] = [];
- try {
- stored = getSite(siteId, getPaths()).socialLinks ?? [];
- } catch {
- stored = [];
- }
- const checked = socialLinksForSave(socialParsed, stored);
- if ("refused" in checked) {
- return {
- ok: false,
- error: `Social link "${checked.refused.label}" has an invalid SVG: ${checked.refused.problem}.`,
- values,
- };
- }
- socialLinks = checked.links;
- }
-
- let channelsInput: unknown;
- try {
- channelsInput = JSON.parse(String(formData.get("channelsJson") ?? "[]"));
- } catch {
- return {
- ok: false,
- error: "Channel membership payload is malformed",
- values,
- };
- }
- const channels = parseSiteChannels(channelsInput);
- // The cited scope: channels outside the pool this site's reports may cite
- // without publishing them (lib/citedChannelsFromForm.ts).
- const citedChannels = citedChannelsFromForm(formData, channels);
- if (citedChannels === null) {
- return { ok: false, error: "Cited channels payload is malformed", values };
- }
-
- const site: Site = {
- siteId,
- siteTitle,
- siteDescription,
- headerTitle,
- ...(wordmarkLead ? { wordmarkLead } : {}),
- homeTagline,
- ...(socialLinks !== undefined ? { socialLinks } : {}),
- groups,
- defaultGroupId,
- channels,
- ...(citedChannels.length > 0 ? { citedChannels } : {}),
- ...(accent ? { accent } : {}),
- ...(cloudflareProject ? { cloudflareProject } : {}),
- ...(siteUrl ? { siteUrl } : {}),
- // The Site is rebuilt from the form: a key missing here is dropped on save.
- ...(listed ? {} : { listed: false }),
- ...(isPrivate ? { audience: "private" as const } : {}),
- ...(publishAuto !== "off" ? { publish: { auto: publishAuto } } : {}),
- ...reportKeys,
- ...(hubUrl ? { hubUrl } : {}),
- ...(pwa ? { pwa: true } : {}),
- ...(archives ? {} : { archives: false }),
- ...(duplicates ? {} : { duplicates: false }),
- ...(transcriptDownloads ? {} : { transcriptDownloads: false }),
- ...(archiveMaxBytes !== undefined ? { archiveMaxBytes } : {}),
- ...(relatedSites.length > 0 ? { relatedSites } : {}),
- };
- try {
- await writeSite(site, getPaths());
- } catch (err) {
- return {
- ok: false,
- error: err instanceof Error ? err.message : String(err),
- values,
- };
- }
- // NO revalidatePath (release 24 H5): React commits a revalidating action's
- // state with the router's refresh of the page, which now and then did not
- // settle until the next AutoRefresh tick, so "Saved." came up to ~6 s late.
- // SiteForm seeds from `values` and refreshes the page itself once "Saved." is
- // in (lib/formState.ts seedAfterSave, lib/useRefreshAfterSave.ts) — the h1
- // above the tabs and /sites's list follow with that refresh.
- return { ok: true, siteId, values };
+ if (!isValidSiteId(siteId)) return saveSiteFromForm(formData);
+ return withSiteLock(siteId, () => saveSiteFromForm(formData));
}
export type DeleteResult = { ok: true } | { ok: false; error: string };
diff --git a/editor/app/sites/lib/saveSiteForm.ts b/editor/app/sites/lib/saveSiteForm.ts
@@ -0,0 +1,317 @@
+// The site form's save (moved out of sites/actions.ts, review of lane
+// editor-gaps, so a caller can hold the site's lock around it). NOT a "use
+// server" module: saveSiteAction is the action a client may call.
+
+import { PUBLISH_POLICIES, type PublishPolicy } from "yt-dlp-transcript-common/lib/settingsSchema";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import {
+ parseAccent,
+ parseAccentSetting,
+} from "yt-dlp-transcript-common/lib/accent";
+import {
+ DEFAULT_ACCENT,
+ wordmarkLeadFor,
+} from "yt-dlp-transcript-common/lib/brand";
+import {
+ getSite,
+ writeSite,
+ isValidSiteId,
+ reservedSiteIdProblem,
+ parseRelatedSites,
+ parseSiteChannels,
+ parseSiteUrl,
+ type Site,
+} from "yt-dlp-transcript-common/lib/site";
+import {
+ parseSocialLinks,
+ type SocialLink,
+} from "yt-dlp-transcript-common/lib/settings";
+import {
+ parseChannelGroups,
+ resolveDefaultGroupId,
+} from "yt-dlp-transcript-common/lib/channelGroups";
+import { socialLinksForSave } from "yt-dlp-transcript-common/lib/socialLinks";
+import { formValues, type FormState, type FormValues } from "../../lib/formState";
+import { reportSiteKeysFromForm } from "./reportSiteKeys";
+import { citedChannelsFromForm } from "./citedChannelsFromForm";
+
+// A failure carries what was submitted, so SiteForm keeps what was typed
+// (lib/formState.ts).
+export type SaveResult = FormState<{ siteId: string; values: FormValues }>;
+
+// THE SITE FORM'S SAVE, without its lock: the caller holds the site's lock
+// (withSiteLock) around it, so the stored keys it carries over (the page
+// list, unchanged social link SVGs) and the write are one read-modify-write.
+// saveSiteAction is the form's; `pnpm ops create-site` takes the lock around
+// its own read of the stored site as well.
+export async function saveSiteFromForm(formData: FormData): Promise<SaveResult> {
+ const values = formValues(formData);
+ const siteId = String(formData.get("siteId") ?? "").trim();
+ if (!isValidSiteId(siteId)) {
+ return {
+ ok: false,
+ error: "Site ID must be lowercase letters, numbers, and hyphens.",
+ values,
+ };
+ }
+ // `articles` and `new` are the editor's own /sites/ routes (writeSite refuses
+ // them too): said here, before anything else is read.
+ const reserved = reservedSiteIdProblem(siteId);
+ if (reserved) return { ok: false, error: reserved, values };
+ const siteTitle = String(formData.get("siteTitle") ?? "").trim();
+ const headerTitle = String(formData.get("headerTitle") ?? "").trim();
+ if (!siteTitle) {
+ return { ok: false, error: "Site title is required", values };
+ }
+ if (!headerTitle) {
+ return { ok: false, error: "Header title is required", values };
+ }
+ const siteDescription = String(formData.get("siteDescription") ?? "").trim();
+ const homeTagline = String(formData.get("homeTagline") ?? "").trim();
+ // The wordmark's heavy lead must be a proper prefix of the header title;
+ // lib/siteSchema.ts would silently drop anything else, so say so here.
+ const wordmarkLead = String(formData.get("wordmarkLead") ?? "").trim();
+ if (wordmarkLead && !wordmarkLeadFor(headerTitle, wordmarkLead)) {
+ return {
+ ok: false,
+ error: `Wordmark lead must be how the header title starts, same case, and shorter than it (e.g. "Jer" for "Jeralyzer") — or left blank.`,
+ values,
+ };
+ }
+ // Brand accent: a named id from the radio group, or "custom" + its hex
+ // field. The default (Signal) is stored as absent — the two read the same.
+ // A bare hex in `accent` (a form from before the radio group) is taken as
+ // a custom colour.
+ const accentChoice = String(formData.get("accent") ?? "").trim();
+ const accentCustomRaw = String(formData.get("accentCustom") ?? "").trim();
+ let accent: string | undefined;
+ if (accentChoice === "custom") {
+ accent = parseAccent(accentCustomRaw);
+ if (!accent) {
+ return {
+ ok: false,
+ error: "Custom accent must be a hex color like #cc3366.",
+ values,
+ };
+ }
+ } else if (accentChoice) {
+ accent = parseAccentSetting(accentChoice);
+ if (!accent) {
+ return {
+ ok: false,
+ error: `Unknown brand accent "${accentChoice}".`,
+ values,
+ };
+ }
+ if (accent === DEFAULT_ACCENT) accent = undefined;
+ }
+ const cloudflareProject = String(
+ formData.get("cloudflareProject") ?? "",
+ ).trim();
+ const siteUrlRaw = String(formData.get("siteUrl") ?? "").trim();
+ if (siteUrlRaw && !parseSiteUrl(siteUrlRaw)) {
+ return {
+ ok: false,
+ error: "Public URL must be an absolute http(s):// URL, or left blank.",
+ values,
+ };
+ }
+ const siteUrl = parseSiteUrl(siteUrlRaw);
+ // Listed on the homepage and hub by default: the same opt-out idiom as
+ // archives below (an unchecked box sends no key → persisted as false).
+ const listed = formData.get("listed") === "on";
+ // Who the site is built for (release 17 slice XP): only "private" is kept.
+ const audienceRaw = String(formData.get("audience") ?? "public");
+ if (audienceRaw !== "public" && audienceRaw !== "private") {
+ return { ok: false, error: `Unknown audience "${audienceRaw}".`, values };
+ }
+ const isPrivate = audienceRaw === "private";
+ // The publish lane's policy for this site (release 18). writeSite refuses a
+ // deploying policy with no Pages project (sitePublishProblem) and stores a
+ // private site's as "build".
+ const publishAutoRaw = String(formData.get("publishAuto") ?? "off");
+ if (!(PUBLISH_POLICIES as readonly string[]).includes(publishAutoRaw)) {
+ return { ok: false, error: `Unknown publish policy "${publishAutoRaw}".`, values };
+ }
+ const publishAuto = publishAutoRaw as PublishPolicy;
+ // Search (opt-out; off = pages only) and the page list, which is not on
+ // this form: the stored one is carried over.
+ let storedReports: Pick<Site, "pages"> | undefined;
+ try {
+ storedReports = getSite(siteId, getPaths());
+ } catch {
+ storedReports = undefined;
+ }
+ const reportKeys = reportSiteKeysFromForm(formData, storedReports);
+
+ // Hub parent (per-site override of the family default) + PWA opt-in.
+ const hubUrlRaw = String(formData.get("hubUrl") ?? "").trim();
+ if (hubUrlRaw && !parseSiteUrl(hubUrlRaw)) {
+ return {
+ ok: false,
+ error: "Hub URL must be an absolute http(s):// URL, or left blank.",
+ values,
+ };
+ }
+ const hubUrl = parseSiteUrl(hubUrlRaw);
+ const pwa = formData.get("pwa") === "on";
+ // Archives default on: an unchecked (default-on) box yields no "archives" key
+ // → false → persisted as the explicit opt-out.
+ const archives = formData.get("archives") === "on";
+ // Duplicates default on, same opt-out idiom as archives.
+ const duplicates = formData.get("duplicates") === "on";
+ // Per-video transcript downloads default on, same opt-out idiom.
+ const transcriptDownloads = formData.get("transcriptDownloads") === "on";
+ const archiveMaxMBRaw = String(formData.get("archiveMaxMB") ?? "").trim();
+ let archiveMaxBytes: number | undefined;
+ if (archiveMaxMBRaw) {
+ const mb = Number(archiveMaxMBRaw);
+ if (!Number.isFinite(mb) || mb < 0) {
+ return {
+ ok: false,
+ error: "Archive size cap must be a non-negative number of MB, or blank.",
+ values,
+ };
+ }
+ archiveMaxBytes = Math.floor(mb * 1024 * 1024);
+ }
+
+ let relatedSitesInput: unknown;
+ try {
+ relatedSitesInput = JSON.parse(
+ String(formData.get("relatedSitesJson") ?? "[]"),
+ );
+ } catch {
+ return { ok: false, error: "Related sites payload is malformed", values };
+ }
+ const relatedSites = parseRelatedSites(relatedSitesInput);
+
+ let groupsInput: unknown;
+ try {
+ groupsInput = JSON.parse(String(formData.get("groupsJson") ?? "[]"));
+ } catch {
+ return { ok: false, error: "Channel groups payload is malformed", values };
+ }
+ const groups = parseChannelGroups(groupsInput);
+ if (groups.length === 0) {
+ return {
+ ok: false,
+ error: "At least one channel group is required (check ID/name fields)",
+ values,
+ };
+ }
+ const defaultGroupIdRaw = String(formData.get("defaultGroupId") ?? "").trim();
+ const defaultGroupId = resolveDefaultGroupId(defaultGroupIdRaw, groups);
+ if (defaultGroupIdRaw && defaultGroupIdRaw !== defaultGroupId) {
+ return {
+ ok: false,
+ error: `Default group "${defaultGroupIdRaw}" is not among the configured group IDs`,
+ values,
+ };
+ }
+
+ // When inheriting, leave socialLinks undefined so writeSite omits the key and
+ // the site falls back to the global default at render time.
+ const inheritSocialLinks = formData.get("inheritSocialLinks") === "on";
+ let socialLinks: SocialLink[] | undefined;
+ if (!inheritSocialLinks) {
+ let socialInput: unknown;
+ try {
+ socialInput = JSON.parse(String(formData.get("socialLinksJson") ?? "[]"));
+ } catch {
+ return { ok: false, error: "Social links payload is malformed", values };
+ }
+ const socialParsed = parseSocialLinks(socialInput);
+ if (
+ Array.isArray(socialInput) &&
+ socialParsed.length !== socialInput.length
+ ) {
+ return {
+ ok: false,
+ error:
+ "Each social link needs a label, URL (http(s)://, mailto:, or /), and SVG.",
+ values,
+ };
+ }
+ // A link whose SVG is unchanged from the site's file is kept as it is; a
+ // new or edited one is checked (lib/socialLinks.ts socialLinksForSave).
+ let stored: SocialLink[] = [];
+ try {
+ stored = getSite(siteId, getPaths()).socialLinks ?? [];
+ } catch {
+ stored = [];
+ }
+ const checked = socialLinksForSave(socialParsed, stored);
+ if ("refused" in checked) {
+ return {
+ ok: false,
+ error: `Social link "${checked.refused.label}" has an invalid SVG: ${checked.refused.problem}.`,
+ values,
+ };
+ }
+ socialLinks = checked.links;
+ }
+
+ let channelsInput: unknown;
+ try {
+ channelsInput = JSON.parse(String(formData.get("channelsJson") ?? "[]"));
+ } catch {
+ return {
+ ok: false,
+ error: "Channel membership payload is malformed",
+ values,
+ };
+ }
+ const channels = parseSiteChannels(channelsInput);
+ // The cited scope: channels outside the pool this site's reports may cite
+ // without publishing them (lib/citedChannelsFromForm.ts).
+ const citedChannels = citedChannelsFromForm(formData, channels);
+ if (citedChannels === null) {
+ return { ok: false, error: "Cited channels payload is malformed", values };
+ }
+
+ const site: Site = {
+ siteId,
+ siteTitle,
+ siteDescription,
+ headerTitle,
+ ...(wordmarkLead ? { wordmarkLead } : {}),
+ homeTagline,
+ ...(socialLinks !== undefined ? { socialLinks } : {}),
+ groups,
+ defaultGroupId,
+ channels,
+ ...(citedChannels.length > 0 ? { citedChannels } : {}),
+ ...(accent ? { accent } : {}),
+ ...(cloudflareProject ? { cloudflareProject } : {}),
+ ...(siteUrl ? { siteUrl } : {}),
+ // The Site is rebuilt from the form: a key missing here is dropped on save.
+ ...(listed ? {} : { listed: false }),
+ ...(isPrivate ? { audience: "private" as const } : {}),
+ ...(publishAuto !== "off" ? { publish: { auto: publishAuto } } : {}),
+ ...reportKeys,
+ ...(hubUrl ? { hubUrl } : {}),
+ ...(pwa ? { pwa: true } : {}),
+ ...(archives ? {} : { archives: false }),
+ ...(duplicates ? {} : { duplicates: false }),
+ ...(transcriptDownloads ? {} : { transcriptDownloads: false }),
+ ...(archiveMaxBytes !== undefined ? { archiveMaxBytes } : {}),
+ ...(relatedSites.length > 0 ? { relatedSites } : {}),
+ };
+ try {
+ await writeSite(site, getPaths());
+ } catch (err) {
+ return {
+ ok: false,
+ error: err instanceof Error ? err.message : String(err),
+ values,
+ };
+ }
+ // NO revalidatePath (release 24 H5): React commits a revalidating action's
+ // state with the router's refresh of the page, which now and then did not
+ // settle until the next AutoRefresh tick, so "Saved." came up to ~6 s late.
+ // SiteForm seeds from `values` and refreshes the page itself once "Saved." is
+ // in (lib/formState.ts seedAfterSave, lib/useRefreshAfterSave.ts) — the h1
+ // above the tabs and /sites's list follow with that refresh.
+ return { ok: true, siteId, values };
+}
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -1446,7 +1446,9 @@ export function usage() {
' ([{"label", "url", "svg"}], null = inherit), "relatedSites". Saved by',
' the form\'s action (its validation, its sentences). An existing id is',
' refused (409) unless "update": true — the site page\'s Save with the',
- ' keys given changed, every other key kept. An unknown channel is refused.',
+ ' keys given changed, every other key kept — one read-modify-write under',
+ ' the site\'s lock. An unknown channel, or a channel\'s groupId naming no',
+ ' group of the site, is refused.',
' Answers {siteId, created, site}.',
"",
'site-config sets two keys of a site as its form does: {"siteId"} and any of',