// THE SITE FORM'S FIELDS, BUILT WITHOUT A BROWSER — for `pnpm ops create-site`. // // The site form posts a FormData that saveSiteAction rebuilds the whole Site // from (a key it does not post is dropped on save). So an ops caller goes // through the same action with the same FormData: `siteToFormData` is the form // a site would post if nothing in it were touched (what SiteForm seeds from), // and `applySiteFields` lays the caller's keys over it. A create starts from a // blank site, an update from the stored one — "update" is the site page's Save // with those fields changed, and every key not named stays as it was. // // Pure: no fs, no server. The round trip (stored site -> FormData -> action -> // the same site.json) is pinned in app/api/ops/create-site/route.test.ts. import { isAccentId } from "yt-dlp-transcript-common/lib/brand"; import { parseChannelGroup } from "yt-dlp-transcript-common/lib/channelGroups"; import type { Site } from "yt-dlp-transcript-common/lib/site"; import { CITED_CHANNELS_FIELD } from "./citedChannelsFromForm"; const MB = 1024 * 1024; const on = (fd: FormData, key: string, value: boolean) => { if (value) fd.set(key, "on"); else fd.delete(key); }; export function siteToFormData(site: Site): FormData { const fd = new FormData(); fd.set("siteId", site.siteId); fd.set("siteTitle", site.siteTitle); fd.set("headerTitle", site.headerTitle); fd.set("wordmarkLead", site.wordmarkLead ?? ""); fd.set("siteDescription", site.siteDescription); fd.set("homeTagline", site.homeTagline); setAccent(fd, site.accent); fd.set("cloudflareProject", site.cloudflareProject ?? ""); fd.set("siteUrl", site.siteUrl ?? ""); fd.set("audience", site.audience === "private" ? "private" : "public"); fd.set("publishAuto", site.publish?.auto ?? "off"); // The opt-out checkboxes: absent / true = ticked. on(fd, "search", site.search !== false); on(fd, "listed", site.listed !== false); on(fd, "archives", site.archives !== false); on(fd, "duplicates", site.duplicates !== false); on(fd, "transcriptDownloads", site.transcriptDownloads !== false); on(fd, "pwa", site.pwa === true); fd.set("hubUrl", site.hubUrl ?? ""); // bytes / 2^20 is exact in binary and String() round-trips, so the action's // floor(MB * 2^20) gives the stored bytes back. fd.set("archiveMaxMB", site.archiveMaxBytes !== undefined ? String(site.archiveMaxBytes / MB) : ""); setSocialLinks(fd, site.socialLinks); fd.set("groupsJson", JSON.stringify(site.groups)); fd.set("defaultGroupId", site.defaultGroupId); fd.set("channelsJson", JSON.stringify(site.channels)); fd.set(CITED_CHANNELS_FIELD, JSON.stringify((site.citedChannels ?? []).map((c) => c.slug))); fd.set("relatedSitesJson", JSON.stringify(site.relatedSites ?? [])); return fd; } function setAccent(fd: FormData, accent: string | undefined) { // Absent = the default accent (the radio group's first choice reads the same). if (!accent || isAccentId(accent)) { fd.set("accent", accent ?? ""); fd.delete("accentCustom"); return; } fd.set("accent", "custom"); fd.set("accentCustom", accent); } function setSocialLinks(fd: FormData, links: unknown[] | undefined | null) { if (links === undefined || links === null) { fd.set("inheritSocialLinks", "on"); fd.delete("socialLinksJson"); return; } fd.delete("inheritSocialLinks"); fd.set("socialLinksJson", JSON.stringify(links)); } // The keys `create-site` takes beyond `siteId` and `update`, each the form // field of the same meaning. export const SITE_OPS_FIELDS = [ "siteTitle", "headerTitle", "siteDescription", "homeTagline", "wordmarkLead", "accent", "cloudflareProject", "siteUrl", "hubUrl", "audience", "publishAuto", "listed", "search", "archives", "duplicates", "transcriptDownloads", "pwa", "archiveMaxMB", "groups", "defaultGroupId", "channels", "citedChannels", "socialLinks", "relatedSites", ] as const; const STRING_FIELDS = new Set([ "siteTitle", "headerTitle", "siteDescription", "homeTagline", "wordmarkLead", "cloudflareProject", "siteUrl", "hubUrl", "audience", "publishAuto", "defaultGroupId", ]); const BOOL_FIELDS = new Set(["listed", "search", "archives", "duplicates", "transcriptDownloads", "pwa"]); // A key of the wrong shape, in the caller's words. The VALUES are the action's // to judge (its sentences: an unknown audience, a bad URL, a group list with // none) — only what cannot be turned into a form field is refused here. export class SiteFieldError extends Error {} export function applySiteFields(fd: FormData, fields: Record): void { for (const [key, v] of Object.entries(fields)) { if (v === undefined) continue; if (STRING_FIELDS.has(key)) { if (typeof v !== "string") throw new SiteFieldError(`"${key}" must be a string`); fd.set(key, v); } else if (BOOL_FIELDS.has(key)) { if (typeof v !== "boolean") throw new SiteFieldError(`"${key}" must be a boolean`); on(fd, key, v); } else if (key === "accent") { if (typeof v !== "string") throw new SiteFieldError(`"accent" must be a string (an accent id or "#rrggbb")`); // A hex is the form's "custom"; anything else is the radio's id, for the // action to accept or refuse by name. const a = v.trim(); if (/^#?[0-9a-f]{6}$/i.test(a)) setAccent(fd, a); else { fd.set("accent", a); fd.delete("accentCustom"); } } else if (key === "archiveMaxMB") { if (v !== null && (typeof v !== "number" || !Number.isFinite(v))) { throw new SiteFieldError(`"archiveMaxMB" must be a number of MB, or null for the global default`); } fd.set("archiveMaxMB", v === null ? "" : String(v)); } else if (key === "groups") { if (!Array.isArray(v)) throw new SiteFieldError(`"groups" must be an array of {id, name, …}`); // The parser drops a group it cannot read, which on a form is a row the // operator can see; over ops it would vanish without a word. const bad = v.findIndex((g) => parseChannelGroup(g) === null); if (bad >= 0) { throw new SiteFieldError( `"groups"[${bad}] is not a channel group: it needs an "id" (lowercase letters, digits, hyphens) and a "name"`, ); } fd.set("groupsJson", JSON.stringify(v.map((g, order) => (isObject(g) ? { order, ...g } : g)))); } else if (key === "channels") { fd.set("channelsJson", JSON.stringify(readChannels(v))); } else if (key === "citedChannels") { if (!Array.isArray(v) || v.some((s) => typeof s !== "string")) { throw new SiteFieldError(`"citedChannels" must be an array of channel slugs`); } fd.set(CITED_CHANNELS_FIELD, JSON.stringify(v)); } else if (key === "socialLinks") { if (v !== null && !Array.isArray(v)) { throw new SiteFieldError(`"socialLinks" must be an array of {label, url, svg}, or null to inherit the global default`); } setSocialLinks(fd, v as unknown[] | null); } else if (key === "relatedSites") { if (!Array.isArray(v)) throw new SiteFieldError(`"relatedSites" must be an array of {label?, siteIds}`); fd.set("relatedSitesJson", JSON.stringify(v)); } else { throw new SiteFieldError(`unknown site field "${key}"`); } } } // `channels`: slugs, or {slug, groupId?} — the pool, in the order given. export function readChannels(v: unknown): { slug: string; groupId?: string; order: number }[] { if (!Array.isArray(v)) { throw new SiteFieldError(`"channels" must be an array of channel slugs or {slug, groupId?}`); } return v.map((entry, order) => { if (typeof entry === "string") return { slug: entry.trim(), order }; if (isObject(entry) && typeof entry.slug === "string") { if (entry.groupId !== undefined && typeof entry.groupId !== "string") { throw new SiteFieldError(`"channels": the groupId of "${entry.slug}" must be a string`); } return { slug: entry.slug.trim(), ...(typeof entry.groupId === "string" && entry.groupId.trim() ? { groupId: entry.groupId.trim() } : {}), order, }; } throw new SiteFieldError(`"channels" must be an array of channel slugs or {slug, groupId?}`); }); } function isObject(v: unknown): v is Record { return typeof v === "object" && v !== null && !Array.isArray(v); }