From b7a9bc882b56e1c61d7d91b9e7cf73bf86c8c7bd Mon Sep 17 00:00:00 2001 From: shimentosh Date: Thu, 3 Sep 2026 20:44:11 +0600 Subject: [PATCH 1/8] Audit fixes: auth on every data route, tests, hooks, template transfer, researcher Security - requireUser() on all 15 data routes that only checked for a cookie's presence (packs, runs, series, topics, workspaces, tools). A forged contentos_session read and wrote the whole workspace; now 401. - proxy.ts comment and docs corrected to say so (middleware.ts -> proxy.ts). Correctness - Failed status derived from sections; a dead run no longer reads Writing forever, a never-started run is an Idea again; Retry requeues failures. - Run pages render the polled copy, not the store's snapshot (live updates without a refresh); WRITING NOW strip links to /runs/, not a 404. - deleteSource removes the download directory with the row. - One slug rule (lib/slug.ts) replaces five copies. Features - Template import/export as a file (lib/packs-transfer.ts). - Tools as rows with per-workspace assignment; /tools/manage. - Content Researcher: upload or link, pick frames, read them with Claude, save ideas as topics. Vision on the API path; opt-in Read for the CLI. - Per-template builder URLs (/builder/); status in builder step 1. - Holding shelf renamed Misc. Structure - lib/use-run-document.ts, lib/use-run-watch.ts, lib/use-content-list.ts and components/tools/FramePicker.tsx lifted out of the two largest views. - projectsLoaded guards writes until the server's workspace list arrives. Tooling - vitest with 34 unit tests; npm run check; GitHub Actions workflow. - sourcedata volume in docker-compose.prod.yml; env template un-ignored. Co-Authored-By: Claude Fable 5.1 --- .env.production.example | 23 + .github/workflows/check.yml | 26 + .gitignore | 3 + app/api/packs/[slug]/route.ts | 5 + app/api/packs/route.ts | 3 + app/api/runs/[id]/route.ts | 4 + .../runs/[id]/sections/[sectionId]/route.ts | 3 + app/api/runs/[id]/start/route.ts | 3 + app/api/runs/route.ts | 3 + app/api/series/[id]/merge/route.ts | 2 + app/api/series/[id]/route.ts | 5 + app/api/series/[id]/source/route.ts | 3 + app/api/series/route.ts | 3 + app/api/sources/[id]/route.ts | 5 +- app/api/tools/[slug]/route.ts | 3 + app/api/tools/route.ts | 2 + app/api/topics/[id]/route.ts | 3 + app/api/workspaces/[id]/route.ts | 4 + app/api/workspaces/route.ts | 3 + components/overlays/RunSetupSheet.tsx | 21 + components/tools/FramePicker.tsx | 334 ++++++ components/views/ContentGroupsView.tsx | 465 +------- components/views/ContentResearcherView.tsx | 320 +----- components/views/DocumentView.tsx | 232 +--- docker-compose.prod.yml | 8 + docs/ARCHITECTURE.md | 9 +- docs/BROWSER.md | 3 +- docs/DECISIONS.md | 67 ++ docs/DEPLOYING.md | 4 +- docs/DEVELOPING.md | 19 +- lib/content-docs.ts | 10 +- lib/packs-transfer.ts | 8 +- lib/run-doc.ts | 15 +- lib/server/repos/packs.ts | 10 +- lib/server/services/ingest.ts | 33 + lib/server/services/researcher.ts | 11 +- lib/slug.ts | 22 + lib/store.tsx | 14 + lib/topics.ts | 7 +- lib/use-content-list.ts | 428 ++++++++ lib/use-run-document.ts | 173 +++ lib/use-run-watch.ts | 77 ++ package-lock.json | 992 +++++++++++++++++- package.json | 6 +- proxy.ts | 8 +- tests/prompt.test.ts | 64 ++ tests/researcher.test.ts | 44 + tests/status.test.ts | 79 ++ tests/transfer.test.ts | 126 +++ vitest.config.mts | 22 + 50 files changed, 2763 insertions(+), 974 deletions(-) create mode 100644 .env.production.example create mode 100644 .github/workflows/check.yml create mode 100644 components/tools/FramePicker.tsx create mode 100644 lib/slug.ts create mode 100644 lib/use-content-list.ts create mode 100644 lib/use-run-document.ts create mode 100644 lib/use-run-watch.ts create mode 100644 tests/prompt.test.ts create mode 100644 tests/researcher.test.ts create mode 100644 tests/status.test.ts create mode 100644 tests/transfer.test.ts create mode 100644 vitest.config.mts diff --git a/.env.production.example b/.env.production.example new file mode 100644 index 0000000..daa52fe --- /dev/null +++ b/.env.production.example @@ -0,0 +1,23 @@ +# Copy to .env.production on the server and fill in. Never commit the real one. + +# The database password. Anything long and random. +POSTGRES_PASSWORD= + +# The domain the console answers on, and the address Let's Encrypt writes to. +APP_HOST=content.yourcompany.com +ACME_EMAIL=you@yourcompany.com + +# Encrypts the API keys stored in the settings table. +# +# MOVE THE EXISTING VALUE from your local .env. A different secret does not +# fail loudly — it makes every key already saved unreadable, which reads as +# "the key vanished". +CONTENTOS_SECRET= + +# How the model is reached on a server. +# +# Your laptop runs the `claude` CLI and bills your subscription. A server has +# no CLI and no login, so it needs a key; the app falls back to the API path +# when the command is missing. Set the brain to the matching model in +# Settings → Generation after the first sign-in. +ANTHROPIC_API_KEY= diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..3f8f88a --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,26 @@ +# Typecheck, lint, tests, and a production build — the same four things +# `npm run check` and `npm run build:check` do on a laptop. +# +# No database and no model: nothing here talks to Postgres or spends a credit. +# The tests are the pure ones in tests/, and the build only has to compile. +name: check + +on: + push: + branches: ["**"] + pull_request: + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + - run: npm ci + - run: npm run check + # Into .next-check, so it can never be confused with a dev server's + # output — see next.config.ts. + - run: npm run build:check diff --git a/.gitignore b/.gitignore index 5ce0008..60f3b54 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,9 @@ yarn-error.log* # env files (can opt-in for committing if needed) .env* +# …except the template a fresh clone copies from — DEPLOYING.md tells you to +# `cp` it, which needs it to be in the repo. +!.env.production.example # vercel .vercel diff --git a/app/api/packs/[slug]/route.ts b/app/api/packs/[slug]/route.ts index 1598810..fc799ed 100644 --- a/app/api/packs/[slug]/route.ts +++ b/app/api/packs/[slug]/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { deletePack, getPack, @@ -12,6 +13,7 @@ export async function GET( ) { try { await ready(); + await requireUser(); const { slug } = await params; const pack = await getPack(slug); return pack ? ok(pack) : fail("No such pack", 404); @@ -35,6 +37,7 @@ export async function PATCH( ) { try { await ready(); + await requireUser(); const { slug } = await params; const pack = await updatePack(slug, await request.json().catch(() => ({}))); return pack ? ok(pack) : fail("No such pack", 404); @@ -50,6 +53,7 @@ export async function POST( ) { try { await ready(); + await requireUser(); const { slug } = await params; const pack = await restorePack(slug); return pack @@ -66,6 +70,7 @@ export async function DELETE( ) { try { await ready(); + await requireUser(); const { slug } = await params; return ok({ ok: await deletePack(slug) }); } catch (e) { diff --git a/app/api/packs/route.ts b/app/api/packs/route.ts index 5829287..07a0790 100644 --- a/app/api/packs/route.ts +++ b/app/api/packs/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { createPack, listPacks } from "@/lib/server/repos/packs"; import { caught, fail, ok, ready } from "@/lib/server/http"; @@ -11,6 +12,7 @@ import { caught, fail, ok, ready } from "@/lib/server/http"; export async function GET() { try { await ready(); + await requireUser(); return ok(await listPacks()); } catch (e) { return caught(e); @@ -20,6 +22,7 @@ export async function GET() { export async function POST(request: Request) { try { await ready(); + await requireUser(); const body = await request.json().catch(() => ({})); if (!body?.name?.trim()) return fail("A pack needs a name"); return ok(await createPack(body), 201); diff --git a/app/api/runs/[id]/route.ts b/app/api/runs/[id]/route.ts index d66d7a4..05d24f4 100644 --- a/app/api/runs/[id]/route.ts +++ b/app/api/runs/[id]/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { deleteRun, getRun, setRunDecision } from "@/lib/server/repos/runs"; import { caught, fail, ok, ready } from "@/lib/server/http"; @@ -7,6 +8,7 @@ export async function GET( ) { try { await ready(); + await requireUser(); const { id } = await params; const run = await getRun(id); return run ? ok(run) : fail("No such run", 404); @@ -28,6 +30,7 @@ export async function PATCH( ) { try { await ready(); + await requireUser(); const { id } = await params; const body = (await request.json().catch(() => ({}))) as { decision?: string; @@ -53,6 +56,7 @@ export async function DELETE( ) { try { await ready(); + await requireUser(); const { id } = await params; return ok({ ok: await deleteRun(id) }); } catch (e) { diff --git a/app/api/runs/[id]/sections/[sectionId]/route.ts b/app/api/runs/[id]/sections/[sectionId]/route.ts index 9e3be15..6c4e13f 100644 --- a/app/api/runs/[id]/sections/[sectionId]/route.ts +++ b/app/api/runs/[id]/sections/[sectionId]/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { editSection, writeSection } from "@/lib/server/services/runs"; import { caught, fail, ok, ready } from "@/lib/server/http"; @@ -10,6 +11,7 @@ export async function POST( ) { try { await ready(); + await requireUser(); const { id, sectionId } = await params; return ok(await writeSection(id, sectionId)); } catch (e) { @@ -30,6 +32,7 @@ export async function PATCH( ) { try { await ready(); + await requireUser(); const { id, sectionId } = await params; const body = (await request.json().catch(() => ({}))) as { content?: unknown; diff --git a/app/api/runs/[id]/start/route.ts b/app/api/runs/[id]/start/route.ts index 4c29684..f57400c 100644 --- a/app/api/runs/[id]/start/route.ts +++ b/app/api/runs/[id]/start/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { driveRun, isDriving } from "@/lib/server/services/runs"; import { getRun, requeueFailed } from "@/lib/server/repos/runs"; import { caught, fail, ok, ready } from "@/lib/server/http"; @@ -21,6 +22,7 @@ export async function POST( ) { try { await ready(); + await requireUser(); const { id } = await params; const run = await getRun(id); if (!run) return fail("No such run", 404); @@ -38,6 +40,7 @@ export async function GET( ) { try { await ready(); + await requireUser(); const { id } = await params; return ok({ running: isDriving(id) }); } catch (e) { diff --git a/app/api/runs/route.ts b/app/api/runs/route.ts index dc14cfc..76ea1f3 100644 --- a/app/api/runs/route.ts +++ b/app/api/runs/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { listRuns } from "@/lib/server/repos/runs"; import { startRun } from "@/lib/server/services/runs"; import { caught, ok, ready } from "@/lib/server/http"; @@ -5,6 +6,7 @@ import { caught, ok, ready } from "@/lib/server/http"; export async function GET(request: Request) { try { await ready(); + await requireUser(); const workspaceId = new URL(request.url).searchParams.get("workspaceId"); return ok(await listRuns(workspaceId ?? undefined)); } catch (e) { @@ -22,6 +24,7 @@ export async function GET(request: Request) { export async function POST(request: Request) { try { await ready(); + await requireUser(); const body = (await request.json().catch(() => ({}))) as { workspaceId?: string; topicId?: string | null; diff --git a/app/api/series/[id]/merge/route.ts b/app/api/series/[id]/merge/route.ts index b5e1e8d..d540978 100644 --- a/app/api/series/[id]/merge/route.ts +++ b/app/api/series/[id]/merge/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { mergeSeries } from "@/lib/server/repos/series"; import { caught, fail, ok, ready } from "@/lib/server/http"; @@ -14,6 +15,7 @@ export async function POST( ) { try { await ready(); + await requireUser(); const { id } = await params; const body = (await request.json().catch(() => ({}))) as { into?: string }; if (!body.into) return fail("Which series should it merge into?"); diff --git a/app/api/series/[id]/route.ts b/app/api/series/[id]/route.ts index 6e07c45..52d1671 100644 --- a/app/api/series/[id]/route.ts +++ b/app/api/series/[id]/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { DuplicateName, addTopics, @@ -13,6 +14,7 @@ export async function GET( ) { try { await ready(); + await requireUser(); const { id } = await params; const s = await getSeries(id); return s ? ok(s) : fail("No such series", 404); @@ -27,6 +29,7 @@ export async function PATCH( ) { try { await ready(); + await requireUser(); const { id } = await params; const s = await updateSeries(id, await request.json().catch(() => ({}))); return s ? ok(s) : fail("No such series", 404); @@ -55,6 +58,7 @@ export async function DELETE( ) { try { await ready(); + await requireUser(); const { id } = await params; const keepTopics = new URL(request.url).searchParams.get("keepTopics") === "1"; @@ -77,6 +81,7 @@ export async function POST( ) { try { await ready(); + await requireUser(); const { id } = await params; const body = (await request.json().catch(() => ({}))) as { topics?: { name: string; context?: string; status?: string }[]; diff --git a/app/api/series/[id]/source/route.ts b/app/api/series/[id]/source/route.ts index eb004c4..0edd321 100644 --- a/app/api/series/[id]/source/route.ts +++ b/app/api/series/[id]/source/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { getSeries, updateSeries } from "@/lib/server/repos/series"; import { FetchError, fetchSource } from "@/lib/server/services/webfetch"; import { caught, fail, ok, ready } from "@/lib/server/http"; @@ -18,6 +19,7 @@ export async function POST( ) { try { await ready(); + await requireUser(); const { id } = await params; if (!(await getSeries(id))) return fail("No such series", 404); @@ -48,6 +50,7 @@ export async function DELETE( ) { try { await ready(); + await requireUser(); const { id } = await params; const s = await updateSeries(id, { source: null, briefFrom: "typed" }); return s ? ok(s) : fail("No such series", 404); diff --git a/app/api/series/route.ts b/app/api/series/route.ts index 72ec8b8..0bf9a62 100644 --- a/app/api/series/route.ts +++ b/app/api/series/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { DuplicateName, createSeries, @@ -8,6 +9,7 @@ import { caught, fail, ok, ready } from "@/lib/server/http"; export async function GET(request: Request) { try { await ready(); + await requireUser(); const workspaceId = new URL(request.url).searchParams.get("workspaceId"); if (!workspaceId) return fail("workspaceId is required"); return ok(await listSeries(workspaceId)); @@ -19,6 +21,7 @@ export async function GET(request: Request) { export async function POST(request: Request) { try { await ready(); + await requireUser(); const body = (await request.json().catch(() => ({}))) as { workspaceId?: string; name?: string; diff --git a/app/api/sources/[id]/route.ts b/app/api/sources/[id]/route.ts index 2eec00e..3aa7a68 100644 --- a/app/api/sources/[id]/route.ts +++ b/app/api/sources/[id]/route.ts @@ -1,5 +1,6 @@ import { requireUser } from "@/lib/server/auth"; -import { deleteSource, getSource } from "@/lib/server/repos/sources"; +import { getSource } from "@/lib/server/repos/sources"; +import { removeSource } from "@/lib/server/services/ingest"; import { caught, fail, ok, ready } from "@/lib/server/http"; export async function GET( @@ -25,7 +26,7 @@ export async function DELETE( await ready(); await requireUser(); const { id } = await params; - return ok({ ok: await deleteSource(id) }); + return ok({ ok: await removeSource(id) }); } catch (e) { return caught(e); } diff --git a/app/api/tools/[slug]/route.ts b/app/api/tools/[slug]/route.ts index 874a8d5..0ee3f30 100644 --- a/app/api/tools/[slug]/route.ts +++ b/app/api/tools/[slug]/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { getTool, updateTool } from "@/lib/server/repos/tools"; import { caught, fail, ok, ready } from "@/lib/server/http"; @@ -7,6 +8,7 @@ export async function GET( ) { try { await ready(); + await requireUser(); const { slug } = await params; const tool = await getTool(slug); return tool ? ok(tool) : fail("No such tool", 404); @@ -22,6 +24,7 @@ export async function PATCH( ) { try { await ready(); + await requireUser(); const { slug } = await params; const tool = await updateTool(slug, await request.json().catch(() => ({}))); return tool ? ok(tool) : fail("No such tool", 404); diff --git a/app/api/tools/route.ts b/app/api/tools/route.ts index 37f8b3c..fecae74 100644 --- a/app/api/tools/route.ts +++ b/app/api/tools/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { listTools, toolsFor } from "@/lib/server/repos/tools"; import { caught, ok, ready } from "@/lib/server/http"; @@ -11,6 +12,7 @@ import { caught, ok, ready } from "@/lib/server/http"; export async function GET(request: Request) { try { await ready(); + await requireUser(); const workspace = new URL(request.url).searchParams.get("workspace"); return ok(workspace ? await toolsFor(workspace) : await listTools()); } catch (e) { diff --git a/app/api/topics/[id]/route.ts b/app/api/topics/[id]/route.ts index 663f76a..e9ecd42 100644 --- a/app/api/topics/[id]/route.ts +++ b/app/api/topics/[id]/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { deleteTopic, updateTopic } from "@/lib/server/repos/series"; import { caught, fail, ok, ready } from "@/lib/server/http"; @@ -7,6 +8,7 @@ export async function PATCH( ) { try { await ready(); + await requireUser(); const { id } = await params; const t = await updateTopic(id, await request.json().catch(() => ({}))); return t ? ok(t) : fail("No such topic", 404); @@ -21,6 +23,7 @@ export async function DELETE( ) { try { await ready(); + await requireUser(); const { id } = await params; return ok({ ok: await deleteTopic(id) }); } catch (e) { diff --git a/app/api/workspaces/[id]/route.ts b/app/api/workspaces/[id]/route.ts index ef59698..e16ab3c 100644 --- a/app/api/workspaces/[id]/route.ts +++ b/app/api/workspaces/[id]/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { deleteWorkspace, getWorkspace, @@ -13,6 +14,7 @@ export async function GET( ) { try { await ready(); + await requireUser(); const { id } = await params; const ws = await getWorkspace(id); return ws @@ -29,6 +31,7 @@ export async function PATCH( ) { try { await ready(); + await requireUser(); const { id } = await params; const ws = await updateWorkspace(id, await request.json().catch(() => ({}))); return ws @@ -45,6 +48,7 @@ export async function DELETE( ) { try { await ready(); + await requireUser(); const { id } = await params; // The last one cannot go: every screen reads the current workspace's packs, // series and voice, and an empty list is a shell with nothing to render. diff --git a/app/api/workspaces/route.ts b/app/api/workspaces/route.ts index 79acb9d..3da1010 100644 --- a/app/api/workspaces/route.ts +++ b/app/api/workspaces/route.ts @@ -1,3 +1,4 @@ +import { requireUser } from "@/lib/server/auth"; import { createWorkspace, listWorkspaces } from "@/lib/server/repos/workspaces"; import { listSeries } from "@/lib/server/repos/series"; import { caught, ok, ready } from "@/lib/server/http"; @@ -6,6 +7,7 @@ import { caught, ok, ready } from "@/lib/server/http"; export async function GET() { try { await ready(); + await requireUser(); const list = await listWorkspaces(); // Concurrently rather than in sequence: the queries are independent, and // four workspaces should cost one round trip of latency, not four. @@ -22,6 +24,7 @@ export async function GET() { export async function POST(request: Request) { try { await ready(); + await requireUser(); const body = await request.json().catch(() => ({})); return ok({ ...(await createWorkspace(body)), series: [] }, 201); } catch (e) { diff --git a/components/overlays/RunSetupSheet.tsx b/components/overlays/RunSetupSheet.tsx index 37f2c9f..3c3eed2 100644 --- a/components/overlays/RunSetupSheet.tsx +++ b/components/overlays/RunSetupSheet.tsx @@ -21,6 +21,7 @@ export function RunSetupSheet() { setQuality, go, project, + projectsLoaded, seriesList, runTopicName, setRunTopicName, @@ -129,9 +130,23 @@ export function RunSetupSheet() { const [fetching, setFetching] = useState(false); const [sourceError, setSourceError] = useState(""); + /* + * Nothing is written against a workspace the server has not confirmed. + * + * The store opens on sample workspaces with empty ids until the first + * request answers. A run or a download in that window would go out with + * workspaceId "" and come back as a foreign-key error — reported as + * "something went wrong", on a button that looked ready. + */ + const ready = projectsLoaded && Boolean(project.id); + const pullSource = async () => { const url = sourceUrl.trim(); if (!url || fetching) return; + if (!ready) { + setSourceError("Still loading the workspace — try again in a second."); + return; + } setFetching(true); setSourceError(""); try { @@ -155,6 +170,10 @@ export function RunSetupSheet() { */ const start = async () => { if (starting) return; + if (!ready) { + setStartError("Still loading the workspace — try again in a second."); + return; + } setStarting(true); setStartError(""); try { @@ -741,6 +760,7 @@ export function RunSetupSheet() { { + const m = Math.floor(seconds / 60); + const s = Math.floor(seconds % 60); + return `${m}:${String(s).padStart(2, "0")}`; +}; + +export function FramePicker({ + source, + picked, + setPicked, + chosen, + at, + setAt, + onCut, +}: { + source: Source; + /** The files ticked, by name. */ + picked: string[]; + setPicked: (next: string[] | ((list: string[]) => string[])) => void; + /** What will actually be sent — every frame when nothing is ticked. */ + chosen: string[]; + /** The "another moment" box, held by the screen so a cut can clear it. */ + at: string; + setAt: (value: string) => void; + onCut: () => void; +}) { + const frames = source.frames; + + const toggle = (file: string) => + setPicked((list) => + list.includes(file) ? list.filter((f) => f !== file) : [...list, file], + ); + + return ( + <> +

+ Pick the moments worth reading — the address bar, the result on + screen. Every picked frame is sent as a picture, so the right four + beat all eight. +

+ + {/* + The strip, and the toolbar that acts on it. + + The count comes first, because "how many am I sending" is the + question the price of this run turns on. All and None sit beside it + rather than under the grid: picking eight things one at a time is + the work this screen exists to save. + */} +
+ + {chosen.length} OF {frames.length} PICKED + + + + + + {/* + Adding a moment belongs here, not under the grid: it is the same + job as picking one — deciding what gets looked at — and it was + two rows away from the thing it adds to. + */} + + AT + setAt(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") onCut(); + }} + placeholder="1:12" + aria-label="Cut a frame at this time" + style={{ + width: 54, + height: 24, + border: "none", + outline: "none", + background: "transparent", + fontFamily: font.mono, + fontSize: 12, + color: "#f0f0f4", + }} + /> + + +
+ + {/* + The video as a line, with a node per frame. + + Eight thumbnails say what was captured; they do not say WHEN, and + "the bit where the address bar is up" is a question about time. The + track is the video, each node sits where it was taken, and clicking + one picks it — the same act as clicking its thumbnail, approached + from the other side. + */} + {frames.length && source.duration ? ( +
+ + {frames.map((frame) => { + const on = picked.includes(frame.file); + const left = Math.min( + 100, + Math.max(0, (frame.at / (source.duration || 1)) * 100), + ); + return ( + toggle(frame.file)} + style={{ + position: "absolute", + left: left + "%", + top: on ? 5 : 7, + width: on ? 13 : 9, + height: on ? 13 : 9, + marginLeft: on ? -6.5 : -4.5, + borderRadius: "50%", + cursor: "pointer", + background: on ? "#0057fc" : w(0.22), + boxShadow: on ? "0 0 10px rgba(0,87,252,0.55)" : "none", + transition: "all 180ms " + spring, + }} + hover={{ background: on ? "#3b7bff" : w(0.4) }} + /> + ); + })} +
+ ) : null} + + {frames.length ? ( +
+ {frames.map((frame) => { + const on = picked.includes(frame.file); + return ( + toggle(frame.file)} + style={{ + position: "relative", + aspectRatio: "16 / 10", + borderRadius: 13, + overflow: "hidden", + cursor: "pointer", + background: "#0b0d12", + border: "1px solid " + (on ? "transparent" : w(0.08)), + /* + * A ring rather than a fat border: a 2px border on a + * 148px card reflows the picture inside it every time one + * is picked, and the whole grid twitches under the cursor. + */ + boxShadow: on + ? "0 0 0 2px #0057fc, 0 10px 24px -12px rgba(0,87,252,0.8)" + : "0 1px 2px rgba(0,0,0,0.35)", + transition: + "transform 180ms " + spring + ", box-shadow 180ms " + spring, + }} + hover={{ transform: "translateY(-2px)" }} + > + {/* eslint-disable-next-line @next/next/no-img-element */} + {"Frame + + + + + {clock(frame.at)} + + + + {on ? : null} + + + ); + })} +
+ ) : ( +

+ No frames were cut — the video itself was not downloaded, or + ffmpeg is off in Integrations. It can still read the transcript. +

+ )} + + + ); +} diff --git a/components/views/ContentGroupsView.tsx b/components/views/ContentGroupsView.tsx index 1f36b93..fd1ec46 100644 --- a/components/views/ContentGroupsView.tsx +++ b/components/views/ContentGroupsView.tsx @@ -3,7 +3,6 @@ import { useCallback, useEffect, - useMemo, useRef, useState, type CSSProperties, @@ -11,39 +10,27 @@ import { import { USAGE, - USAGE_ORDER, STATE_STYLE, - docsByPack, outputsFor, type ContentDoc, type Decision, - type UsageStatus, } from "@/lib/content-docs"; -import { - isEditable, - setDecision, - statusOf, - useDecisions, -} from "@/lib/decisions"; +import { isEditable, setDecision, statusOf } from "@/lib/decisions"; import { useStore } from "@/lib/store"; -import { slugify } from "@/lib/content-docs"; -import { partName } from "@/lib/topics"; +import { deleteRun } from "@/lib/runs-client"; import { - deleteRun, - listRuns, - startWriting, - type Run, -} from "@/lib/runs-client"; -import { runToDoc } from "@/lib/run-doc"; + ALL, + SORTS, + hrefFor, + useContentList, + type FilterKey, + type SortKey, +} from "@/lib/use-content-list"; import { CONTENT_TABS } from "@/components/views/content-tabs"; - -/** Where a row opens: the run that made it, or the document it is. */ -const hrefFor = (doc: ContentDoc) => - doc.runId ? `/runs/${doc.runId}` : `/content/${doc.slug}`; import { useTopicAdmin } from "@/components/topics/TopicAdmin"; import { font, panel, primary, rise, t, w } from "@/lib/theme"; import { Hov } from "@/components/ui/Hov"; -import { FilterMenu, type FilterOption } from "@/components/ui/FilterMenu"; +import { FilterMenu } from "@/components/ui/FilterMenu"; import type { RailItem } from "@/components/ui"; import { Button, @@ -104,34 +91,6 @@ const GRID = "1fr 168px 132px 76px 96px"; /** The statuses you can pick — "Writing" is derived, so it is not offered. */ const DECISIONS: Decision[] = ["used", "ready", "ignored"]; -/** - * The status switcher: one status at a time, never a set. - * - * This was a checkbox menu, which asked a question nobody was answering. The - * list is one lifecycle — an idea, then the writing of it, then what came out - * — and you read it a stage at a time: what have I not started, what is in - * flight, what is done. Ticking two boxes interleaves two stages into one - * list, and the "0 selected means all" state that a checkbox menu needs made - * the default screen a pile of everything at once. - * - * So it is a switcher, opening on IDEA — the shelf of things not yet made, - * which is where the work starts. - * - * Used and Ignored are not tabs here: they are the end of the line, and a - * permanent tab for a status nothing has yet is a dead segment. They join the - * row the moment a topic carries one — see `statusTabs` — so nothing is ever - * filtered out of reach. - */ -/* - * Writing is not one of them. - * - * A run in flight is not a shelf you browse — it is a thing happening right - * now, and hiding it behind a filter meant the only way to see what the - * machine was doing was to remember to go and look. It has its own strip at - * the top of the page instead, always on, whichever status you are reading. - */ -const STATUS_TABS: UsageStatus[] = ["idea", "ready"]; - /** The status's colour, in the switcher. */ const StatusDot = ({ color }: { color: string }) => ( ( /> ); -type SortKey = "recent" | "topic" | "status"; - -const SORTS: { key: SortKey; label: string }[] = [ - { key: "recent", label: "Most recent" }, - { key: "topic", label: "Topic A–Z" }, - // "Least finished" went with the SECTIONS column: it ordered the list by a - // number that is no longer on screen, so the rows moved and nothing visible - // explained why. - // Content first, ideas last — the split "most recent" does not make. - { key: "status", label: "Finished first" }, -]; - const chipStyle: CSSProperties = { display: "flex", alignItems: "center", @@ -536,7 +483,6 @@ function ActiveChip({ ); } -type FilterKey = "status" | "template" | "series"; export function ContentGroupsView() { const { @@ -545,7 +491,6 @@ export function ContentGroupsView() { deleteTopic, reloadRuns, askConfirm, - seriesList, packs, runTopicNow, } = useStore(); @@ -553,42 +498,38 @@ export function ContentGroupsView() { /** The series strip, the two dialogs, and the state behind them. */ const admin = useTopicAdmin(); - /* - * What has actually been written. - * - * The rows above this are topics and the design's sample documents; these are - * real runs off the server, with real text behind every section. Fetched - * rather than seeded, and merged in below so a pack you ran ten minutes ago - * appears in the list you came here to read. - */ - const [runs, setRuns] = useState([]); - useEffect(() => { - void listRuns() - .then(setRuns) - // Silent: the list is still useful without them, and a failed fetch must - // not blank a page that has plenty else to show. - .catch(() => {}); - }, []); + /** Every row, filter, count and sort — see lib/use-content-list.ts. */ + const { + DOCS, + groups, + shown, + options, + active, + anyFilter, + statusTabs, + writingNow, + retry, + query, + setQuery, + sort, + setSort, + filters, + toggle, + clear, + clearAll, + status, + pickStatus, + seriesTab, + pickSeries, + templateTab, + pickTemplate, + } = useContentList(); - /** - * Start a failed run again. - * - * The server clears the failures and picks up where the drive stopped, so - * this is one press rather than a section-by-section repair. The list is - * re-read straight after: the row has to leave the Failed tab the moment it - * is writing again, or the button looks like it did nothing. - */ - const retry = useCallback(async (runId: string) => { - try { - await startWriting(runId); - } catch { - // The row keeps saying Failed, which is still true. Nothing else to say. - } - await listRuns() - .then(setRuns) - .catch(() => {}); - void reloadRuns(); - }, [reloadRuns]); + const [open, setOpen] = useState(null); + const [statusOpen, setStatusOpen] = useState(null); + + const activeSeries = + admin.seriesList.find((series) => series.id === seriesTab) ?? null; /** * The row that is being started, so its button can say so. @@ -654,323 +595,6 @@ export function ContentGroupsView() { if (doc.topicId) deleteTopic(doc.topicId); }; - // Re-renders this list whenever a status is changed anywhere. - const version = useDecisions(); - - const [query, setQuery] = useState(""); - const [sort, setSort] = useState("recent"); - const [open, setOpen] = useState(null); - const [statusOpen, setStatusOpen] = useState(null); - const [filters, setFilters] = useState>({ - status: ["idea"], - template: [], - series: [], - }); - - const toggle = (key: FilterKey, value: string) => - setFilters((prev) => ({ - ...prev, - [key]: prev[key].includes(value) - ? prev[key].filter((v) => v !== value) - : [...prev[key], value], - })); - - const clear = (key: FilterKey) => - setFilters((prev) => ({ ...prev, [key]: [] })); - - const clearAll = () => { - // The series is navigation now, not a filter — the tab survives a clear. - // Neither does the status: it is a switcher, and a switcher with nothing - // selected is not a state it has. Clearing returns it to Idea. - setFilters((prev) => ({ - status: ["idea"], - template: [], - series: prev.series, - })); - setQuery(""); - }; - - /** The switcher's current status, and how it moves. */ - const status = (filters.status[0] ?? "idea") as UsageStatus; - const pickStatus = (next: UsageStatus) => - setFilters((prev) => ({ ...prev, status: [next] })); - - /** - * The documents as this screen sees them: the data underneath, with the - * renames applied and the removed ones dropped. The documents themselves are - * left alone, so /content/ still opens what it always did. - */ - const DOCS = useMemo(() => { - /* - * Every topic in this workspace, plus what has actually been written. - * - * The sample documents are gone. They put twenty-four invented topics on - * this list under a template that does not exist, each opening a page of - * text nobody wrote — which made the screen look full and made it - * impossible to see what was really there. - * - * A topic with no run gets a row with no sections, which `statusOf` reads - * as "idea": the first step of the same lifecycle that ends in used or - * ignored. Real runs go in front, newest first, because the thing you just - * made is the thing you came to look at. - */ - const shelfOf = new Map( - seriesList.flatMap((series) => - series.topics.map((topic) => [topic.id, series.id] as const), - ), - ); - - const produced: ContentDoc[] = runs.map((r) => ({ - ...runToDoc( - r, - packs.find((x) => x.id === r.packSlug), - ), - // A run's shelf is its topic's shelf. `inputs.series` is the name that - // was typed into it, which is a label, not an identity. - seriesId: r.topicId ? shelfOf.get(r.topicId) : undefined, - })); - - const written = new Set(produced.map((d) => d.topic.toLowerCase())); - const rows: ContentDoc[] = []; - - for (const series of seriesList) { - for (const topic of series.topics) { - // A topic whose run is already in `produced` would otherwise appear - // twice: once as the content, once as the idea it started as. - if (written.has(topic.name.toLowerCase())) continue; - rows.push({ - slug: slugify(topic.name), - topicId: topic.id, - seriesId: series.id, - topic: topic.name, - series: series.name, - pack: series.pack || "No template", - // Zero-padded: the tiles are a monospace column, and "8" beside "24" - // reads as a stray digit where "08" reads as a part number. - part: - topic.part !== null - ? partName(series.partLabel, topic.part) - : "", - blurb: "", - decision: topic.decision, - created: topic.activity, - updated: topic.activity, - at: topic.updatedAt, - sections: [], - }); - } - } - - return [...produced, ...rows]; - }, [seriesList, runs, packs]); - - const { groups, shown, options, active } = useMemo(() => { - void version; - const q = query.trim().toLowerCase(); - - const passes = { - search: (d: ContentDoc) => - !q || - `${d.topic} ${d.pack} ${d.blurb} ${d.series}`.toLowerCase().includes(q), - status: (d: ContentDoc) => - !filters.status.length || filters.status.includes(statusOf(d)), - pack: (d: ContentDoc) => - !filters.template.length || filters.template.includes(d.pack), - series: (d: ContentDoc) => - !filters.series.length || filters.series.includes(d.seriesId ?? ""), - }; - - const matched = DOCS.filter( - (d) => - passes.search(d) && - passes.status(d) && - passes.pack(d) && - passes.series(d), - ); - - /** - * Counts for one dimension are taken with that dimension left open, so - * picking "Ignored" still shows how many Used topics there are. Values - * that would match nothing are dropped unless they are already picked. - */ - const facet = ( - pool: ContentDoc[], - pick: (d: ContentDoc) => string, - values: string[], - selected: string[], - label: (v: string) => string, - dot?: (v: string) => string, - ): FilterOption[] => - values - .map((value) => ({ - value, - label: label(value), - count: pool.filter((d) => pick(d) === value).length, - dot: dot?.(value), - })) - .filter((o) => o.count > 0 || selected.includes(o.value)); - - const forStatus = DOCS.filter( - (d) => passes.search(d) && passes.pack(d) && passes.series(d), - ); - const forPack = DOCS.filter( - (d) => passes.search(d) && passes.status(d) && passes.series(d), - ); - const forSeries = DOCS.filter( - (d) => passes.search(d) && passes.status(d) && passes.pack(d), - ); - - const packs = [...new Set(DOCS.map((d) => d.pack))].sort(); - const series = [...new Set(DOCS.map((d) => d.seriesId ?? ""))]; - - /* - * Writing first, then what needs a person: a failed run is the one thing - * on the list that is waiting on you rather than on the model. - */ - const rank: Record = { - writing: 0, - failed: 1, - ready: 2, - used: 3, - idea: 4, - ignored: 5, - }; - - const sorted = [...matched].sort((a, b) => { - switch (sort) { - case "topic": - return a.topic.localeCompare(b.topic); - case "status": - /* - * Status first, then recency inside it. - * - * This is the view that separates finished content from ideas, which - * "most recent" deliberately does not — sorted by time, an idea from - * yesterday belongs between two runs from yesterday. Without the - * second key, rows sharing a status fell back to build order and - * moved for reasons nothing on screen explained. - */ - return ( - rank[statusOf(a)] - rank[statusOf(b)] || b.at.localeCompare(a.at) - ); - default: - /* - * Most recent, actually sorted. - * - * This used to return 0 and lean on the order DOCS builds — runs - * first, then topics shelf by shelf — so a topic you had just added - * appeared at the bottom of its shelf's block with nothing above it - * explaining why. `at` is an ISO instant and sorts as a string, so - * newest first is a plain descending compare. - * - * A tie falls back to the name, so equal timestamps give a stable - * order rather than one that reshuffles on every render. - */ - return b.at.localeCompare(a.at) || a.topic.localeCompare(b.topic); - } - }); - - return { - groups: docsByPack(sorted), - shown: sorted.length, - options: { - status: facet( - forStatus, - (d) => statusOf(d), - USAGE_ORDER, - filters.status, - (v) => USAGE[v as UsageStatus].label, - (v) => USAGE[v as UsageStatus].dot, - ), - template: facet( - forPack, - (d) => d.pack, - packs, - filters.template, - (v) => v, - ), - series: facet( - forSeries, - (d) => d.seriesId ?? "", - series, - filters.series, - // The facet is keyed by id but read by people: anything rendering it - // needs the shelf's name, not `ser_mtbuo7f4e59wg`. - (id) => seriesList.find((x) => x.id === id)?.name ?? "No series", - ), - }, - // Series and status are left out on purpose: both are controls that - // always read their own state — the rail says which shelf, the switcher - // says which status — and a chip that removes one would leave it with - // nothing selected, which is not a state either of them has. - active: filters.template.map((value) => ({ - key: "template" as FilterKey, - value, - label: value, - dot: undefined as string | undefined, - })), - }; - }, [DOCS, query, filters, sort, version, seriesList]); - - /** - * The switcher's segments: the three lifecycle stages, plus any end state a - * topic has actually reached. Mark one Used and a USED segment appears — - * which is the only way back to it, so it has to. - */ - const statusTabs = useMemo(() => { - const present = new Set(options.status.map((o) => o.value)); - return [ - ...STATUS_TABS, - ...USAGE_ORDER.filter( - (s) => - !STATUS_TABS.includes(s) && - present.has(s) && - // Writing has the strip; a segment for it would be a second place - // saying the same thing, and the worse of the two. It comes back - // only if it is the segment you are standing on, because otherwise - // there would be no way off it. - (s !== "writing" || status === "writing"), - ), - ]; - }, [options.status, status]); - - /** - * What the machine is doing right now. - * - * Off DOCS rather than off the filtered list on purpose: a run in flight is - * news whatever you happen to be reading, and a strip that empties because - * you switched to Ready would be a status light you cannot trust. - */ - const writingNow = useMemo( - () => - DOCS.filter((d) => statusOf(d) === "writing").map((d) => ({ - slug: d.slug, - topic: d.topic, - pack: d.pack, - // Where this row opens. Carried rather than rebuilt from the slug: a - // row that came from a run has the RUN's id as its slug, and - // `/content/run_…` is a 404 that reads as "your work is gone". - href: hrefFor(d), - written: d.sections.filter((x) => x.state === "written").length, - total: d.sections.length, - })), - [DOCS], - ); - - const anyFilter = active.length > 0 || query.trim().length > 0; - - /* - * The tabs run off the series filter rather than a second piece of state, so - * picking one narrows the list the same way the menu used to and the counts - * on the other filters stay honest. - */ - const ALL = ""; - const seriesTab = filters.series[0] ?? ALL; - const activeSeries = - admin.seriesList.find((series) => series.id === seriesTab) ?? null; - - const pickSeries = (id: string) => - setFilters((prev) => ({ ...prev, series: id === ALL ? [] : [id] })); /** * Counts come from the facet, so they already answer "how many are left in @@ -1058,13 +682,6 @@ export function ContentGroupsView() { ]; })(); - const templateTab = filters.template[0] ?? ALL; - const pickTemplate = (value: string) => - setFilters((prev) => ({ - ...prev, - template: value === ALL ? [] : [value], - })); - const railSeries: RailItem[] = [ { id: ALL, diff --git a/components/views/ContentResearcherView.tsx b/components/views/ContentResearcherView.tsx index bb42a32..37d7d1b 100644 --- a/components/views/ContentResearcherView.tsx +++ b/components/views/ContentResearcherView.tsx @@ -24,11 +24,11 @@ import { ghostHover, primary, rise, - spring, t, w, } from "@/lib/theme"; import { Hov } from "@/components/ui/Hov"; +import { FramePicker, clock } from "@/components/tools/FramePicker"; import { Button, Chip, @@ -39,12 +39,7 @@ import { TextInput, } from "@/components/ui"; import { BackGlyph, ClockGlyph } from "@/components/ui/DocIcons"; -import { - AlertIcon, - CheckIcon, - PlayIcon, - TrashIcon, -} from "@/components/ui/Icons"; +import { AlertIcon, PlayIcon, TrashIcon } from "@/components/ui/Icons"; /** * The researcher. @@ -78,12 +73,6 @@ function parseAt(text: string) { return seconds >= 0 ? seconds : null; } -const clock = (seconds: number) => { - const m = Math.floor(seconds / 60); - const s = Math.floor(seconds % 60); - return `${m}:${String(s).padStart(2, "0")}`; -}; - /** * The video this browser had open, remembered across reloads. * @@ -117,7 +106,8 @@ const nameOf = (row: Source) => row.title.trim() || row.filename.trim() || row.url.replace(/^https?:\/\//, ""); export function ContentResearcherView() { - const { go, project, seriesList, reloadSeries, askConfirm } = useStore(); + const { go, project, projectsLoaded, seriesList, reloadSeries, askConfirm } = + useStore(); const tool = findTool("content-researcher"); const [url, setUrl] = useState(""); @@ -238,8 +228,20 @@ export function ContentResearcherView() { }, }); + /* + * The same rule the run sheet keeps: nothing goes out against a workspace + * the server has not confirmed. Before the first request answers, `project` + * is a sample with an empty id, and an upload filed under "" is a + * foreign-key error wearing a generic message. + */ + const workspaceReady = projectsLoaded && Boolean(project?.id); + const fetchUrl = async () => { if (!url.trim() || fetching) return; + if (!workspaceReady) { + setError("Still loading the workspace — try again in a second."); + return; + } setFetching(true); setError(""); try { @@ -252,6 +254,10 @@ export function ContentResearcherView() { }; const upload = async (file: File) => { + if (!workspaceReady) { + setError("Still loading the workspace — try again in a second."); + return; + } setFetching(true); setError(""); try { @@ -488,283 +494,15 @@ export function ContentResearcherView() {
STEP 2 · WHAT IT LOOKS AT
-

- Pick the moments worth reading — the address bar, the result on - screen. Every picked frame is sent as a picture, so the right four - beat all eight. -

- - {/* - The strip, and the toolbar that acts on it. - - The count comes first, because "how many am I sending" is the - question the price of this run turns on. All and None sit beside it - rather than under the grid: picking eight things one at a time is - the work this screen exists to save. - */} -
- - {chosen.length} OF {frames.length} PICKED - - - - - - {/* - Adding a moment belongs here, not under the grid: it is the same - job as picking one — deciding what gets looked at — and it was - two rows away from the thing it adds to. - */} - - AT - setAt(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Enter") void cutFrame(); - }} - placeholder="1:12" - aria-label="Cut a frame at this time" - style={{ - width: 54, - height: 24, - border: "none", - outline: "none", - background: "transparent", - fontFamily: font.mono, - fontSize: 12, - color: "#f0f0f4", - }} - /> - - -
- - {/* - The video as a line, with a node per frame. - - Eight thumbnails say what was captured; they do not say WHEN, and - "the bit where the address bar is up" is a question about time. The - track is the video, each node sits where it was taken, and clicking - one picks it — the same act as clicking its thumbnail, approached - from the other side. - */} - {frames.length && source.duration ? ( -
- - {frames.map((frame) => { - const on = picked.includes(frame.file); - const left = Math.min( - 100, - Math.max(0, (frame.at / (source.duration || 1)) * 100), - ); - return ( - - setPicked((list) => - on - ? list.filter((f) => f !== frame.file) - : [...list, frame.file], - ) - } - style={{ - position: "absolute", - left: left + "%", - top: on ? 5 : 7, - width: on ? 13 : 9, - height: on ? 13 : 9, - marginLeft: on ? -6.5 : -4.5, - borderRadius: "50%", - cursor: "pointer", - background: on ? "#0057fc" : w(0.22), - boxShadow: on ? "0 0 10px rgba(0,87,252,0.55)" : "none", - transition: "all 180ms " + spring, - }} - hover={{ background: on ? "#3b7bff" : w(0.4) }} - /> - ); - })} -
- ) : null} - - {frames.length ? ( -
- {frames.map((frame) => { - const on = picked.includes(frame.file); - return ( - - setPicked((list) => - on - ? list.filter((f) => f !== frame.file) - : [...list, frame.file], - ) - } - style={{ - position: "relative", - aspectRatio: "16 / 10", - borderRadius: 13, - overflow: "hidden", - cursor: "pointer", - background: "#0b0d12", - border: "1px solid " + (on ? "transparent" : w(0.08)), - /* - * A ring rather than a fat border: a 2px border on a - * 148px card reflows the picture inside it every time one - * is picked, and the whole grid twitches under the cursor. - */ - boxShadow: on - ? "0 0 0 2px #0057fc, 0 10px 24px -12px rgba(0,87,252,0.8)" - : "0 1px 2px rgba(0,0,0,0.35)", - transition: - "transform 180ms " + spring + ", box-shadow 180ms " + spring, - }} - hover={{ transform: "translateY(-2px)" }} - > - {/* eslint-disable-next-line @next/next/no-img-element */} - {"Frame - - - - - {clock(frame.at)} - - - - {on ? : null} - - - ); - })} -
- ) : ( -

- No frames were cut — the video itself was not downloaded, or - ffmpeg is off in Integrations. It can still read the transcript. -

- )} + void cutFrame()} + /> {notice ? (
diff --git a/components/views/DocumentView.tsx b/components/views/DocumentView.tsx index 702333c..8743437 100644 --- a/components/views/DocumentView.tsx +++ b/components/views/DocumentView.tsx @@ -20,18 +20,11 @@ import { type SectionState, } from "@/lib/content-docs"; import { useStore } from "@/lib/store"; -import { latestRunFor, runToDoc, topicSlug } from "@/lib/run-doc"; -import { getPack, type ApiPack } from "@/lib/packs-client"; +import { latestRunFor, topicSlug } from "@/lib/run-doc"; import { packForSeries } from "@/lib/packs"; -import { - editSection, - getRun, - isWriting, - startWriting, - type Run, - writeSection, -} from "@/lib/runs-client"; -import { frameUrl, getSource, type Source } from "@/lib/sources-client"; +import { editSection, startWriting, writeSection } from "@/lib/runs-client"; +import { useRunDocument } from "@/lib/use-run-document"; +import { frameUrl, type Source } from "@/lib/sources-client"; import { font, panel, primary, rise, t, w } from "@/lib/theme"; import { Hov } from "@/components/ui/Hov"; import { Button, Rail, TextArea } from "@/components/ui"; @@ -217,124 +210,26 @@ export function DocumentView({ slug?: string; runId?: string; }) { - const { - go, - seriesList, - runs, - packs, - reloadRuns, - settings, - runTopicNow, - } = useStore(); - - /* - * The run this page is about. - * - * Fetched directly when the URL names one, because a run started seconds ago - * is not in the store's list yet and waiting for a reload to notice it is - * the difference between watching your run and watching an empty page. - */ - const [fetched, setFetched] = useState(null); - - useEffect(() => { - if (!runId) return; - let cancelled = false; - void getRun(runId) - .then((r) => { - if (!cancelled) setFetched(r); - }) - .catch(() => {}); - return () => { - cancelled = true; - }; - }, [runId]); - - const run = useMemo(() => { - /* - * The polled copy wins here too. - * - * This read the store's list first, and that list is loaded once and - * reloaded on navigation — never on a timer. So /runs/ rendered a - * snapshot taken when the page was opened, the poll below kept a fresh - * copy in `fetched` that nothing looked at, and the only way to see any - * progress was to reload the page. Which is exactly what it looked like: - * live updates that only arrive on a refresh. - */ - if (runId) { - return fetched?.id === runId - ? fetched - : (runs.find((r) => r.id === runId) ?? fetched); - } - const topic = seriesList - .flatMap((series) => series.topics) - .find((t) => topicSlug(t.name) === slug); - const latest = topic ? latestRunFor(runs, topic.id) : null; - /* - * The polled copy wins, when it is the same run. - * - * /content/ reads the store's list, which is reloaded on navigation - * and not on a timer — so a run started from this page wrote twelve - * sections while the page it was started from showed twelve queued ones. - * The poll below keeps `fetched` current for whichever run is on screen; - * this is where that gets used. - */ - return latest && fetched?.id === latest.id ? fetched : latest; - }, [runId, fetched, runs, seriesList, slug]); + const { go, seriesList, runs, packs, reloadRuns, settings, runTopicNow } = + useStore(); - /* - * The template as the engine runs it. - * - * The store's copy is the builder's shape and carries no dependency arrows, - * and those are what decide which section may go next. Fetched by slug so a - * template written in the builder works here too. + /** + * The run, its template, its topic, the document and the reel — resolved + * from whichever address this page was opened by. See + * lib/use-run-document.ts, which is also where the polled copy is made to + * win over the store's list. */ - const [runtime, setRuntime] = useState(null); - - useEffect(() => { - const packSlug = run?.packSlug; - if (!packSlug) return; - let cancelled = false; - void getPack(packSlug) - .then((p) => { - if (!cancelled) setRuntime(p); - }) - .catch(() => {}); - return () => { - cancelled = true; - }; - }, [run?.packSlug]); - - /** The topic behind it, for the rail and for the empty states. */ - const topic = useMemo( - () => - seriesList - .flatMap((series) => series.topics.map((t) => ({ ...t, series }))) - .find((t) => (runId ? t.id === run?.topicId : topicSlug(t.name) === slug)), - [seriesList, slug, runId, run], - ); - - const doc = useMemo( - () => - run ? runToDoc(run, packs.find((p) => p.id === run.packSlug)) : null, - [run, packs], - ); - - /** The reel this run was given, when it was given one. */ - const [source, setSource] = useState(null); - - useEffect(() => { - const sid = run?.sourceId; - if (!sid) return; - let cancelled = false; - void getSource(sid) - .then((x) => { - if (!cancelled) setSource(x); - }) - .catch(() => {}); - return () => { - cancelled = true; - }; - }, [run?.sourceId]); + const { + run, + topic, + doc, + source, + pending, + unwritten, + setFetched, + serverWriting, + setServerWriting, + } = useRunDocument({ slug, runId }); const [openSections, setOpenSections] = useState>( new Set(["03"]), @@ -368,36 +263,6 @@ export function DocumentView({ const groups = useMemo(() => (doc ? buildGroups(doc) : []), [doc]); const [reading, setReading] = useState(false); - /* - * Sections that have not been written yet, in the template's own order. - * - * A dependency is satisfied when the section it names is done, so this is - * recomputed from the run every time rather than held as a queue: a section - * rewritten by hand changes what is ready next, and a queue built once would - * not notice. - */ - const pending = useMemo(() => { - if (!run || !runtime) return []; - const done = new Set( - run.sections.filter((x) => x.state === "done").map((x) => x.id), - ); - return runtime.sections - .filter((def) => { - const row = run.sections.find((x) => x.id === def.id); - return ( - row && row.state !== "done" && def.dependsOn.every((d) => done.has(d)) - ); - }) - .map((def) => def.id); - }, [run, runtime]); - - const unwritten = run - ? run.sections.filter((x) => x.state !== "done").length - : 0; - - /** Set while the server is writing this run — see the polling effect. */ - const [serverWriting, setServerWriting] = useState(false); - /** * Is it writing, waiting, or stopped? * @@ -513,7 +378,7 @@ export function DocumentView({ }); } await reloadRuns(); - }, [run, doc, runId, reloadRuns]); + }, [run, doc, runId, reloadRuns, setFetched]); // The local driver, for "Write next" and for the auto-approve preference. // The whole-run case is the server's job now — see `serverWriting` below. @@ -524,55 +389,6 @@ export function DocumentView({ // eslint-disable-next-line react-hooks/exhaustive-deps }, [auto, run, pending, busy.size]); - /** - * Whether the server is writing this run, and following it while it does. - * - * The page used to BE the driver: a loop in the tab asking for one section - * at a time. A run therefore stopped when the tab did — on a navigation, a - * hot reload, or a closed window — mid-way, with no sign of why. The server - * drives now, so this only watches: poll the run while anything is moving, - * stop when it settles. - * - * Whichever way the page was addressed. It watched only /runs/, so a - * topic opened by name — which is how the list opens one — sat perfectly - * still while its run was being written, and only a refresh showed any of - * it. The run is the run either way. - */ - const watchId = runId ?? run?.id ?? null; - useEffect(() => { - if (!watchId) return; - let stop = false; - - const tick = async () => { - try { - const [state, fresh] = await Promise.all([ - isWriting(watchId), - getRun(watchId), - ]); - if (stop) return; - setServerWriting(state.running); - if (fresh) setFetched(fresh); - // Slower once nothing is in flight: the answer stops changing, and a - // page left open overnight should not be asking twice a second. - return state.running ? 1500 : 6000; - } catch { - return 6000; - } - }; - - let timer: ReturnType; - const loop = async () => { - const wait = (await tick()) ?? 6000; - if (!stop) timer = setTimeout(() => void loop(), wait); - }; - void loop(); - - return () => { - stop = true; - clearTimeout(timer); - }; - }, [watchId]); - /** Write the lot, on the server, and start watching straight away. */ const writeEverything = useCallback(async () => { if (!run) return; @@ -582,7 +398,7 @@ export function DocumentView({ } catch { setServerWriting(false); } - }, [run]); + }, [run, setServerWriting]); /* * Two ways to have nothing to show, and they are different problems. diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 320fe5a..b37a7cc 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -34,6 +34,11 @@ services: depends_on: postgres: condition: service_healthy + volumes: + # The downloads live here: every fetched video, and the stills cut out of + # it. Without this they are inside the container, so a redeploy loses + # them and every frame the researcher already read 404s. + - sourcedata:/app/.data # Migrations first, then the server — a deploy that adds a column must not # take traffic against a database that has not got it yet. command: > @@ -66,4 +71,7 @@ services: volumes: pgdata: + # Videos and frames. Big, and re-fetchable — worth keeping across a deploy, + # not worth putting in the nightly dump beside the database. + sourcedata: letsencrypt: diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index dd2c5b1..ea512aa 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -126,9 +126,12 @@ the reader shows an EDITED mark, and regenerating clears both. ## Auth -`middleware.ts` gates everything except `/login`, `/signup` and `/api/auth/*`. -It only checks that a session cookie is **present** — validity is checked by -`requireUser()` in every route handler. Sessions are rows in Postgres; signup +`proxy.ts` — Next 16 renamed the `middleware` convention — gates everything +except `/login`, `/signup` and `/api/auth/*`. It only checks that a session +cookie is **present**, so validity is `requireUser()`'s job, and every route +handler outside `/api/auth/*` calls it. That was a claim rather than a fact +until it was checked: fifteen routes did not, and `contentos_session=anything` +read and wrote the whole workspace. Sessions are rows in Postgres; signup is open only while `users` is empty (`signupOpen()`), so a second account can only be made by an existing one. diff --git a/docs/BROWSER.md b/docs/BROWSER.md index e1475c0..c4f30c3 100644 --- a/docs/BROWSER.md +++ b/docs/BROWSER.md @@ -25,7 +25,8 @@ see what a signed-out visitor gets). ## Signing in -The app is behind `middleware.ts`: a page load without a session cookie +The app is behind `proxy.ts` — Next 16's name for what used to be +`middleware.ts`: a page load without a session cookie redirects to `/login`, and every `/api/*` call answers `401 {"error":"Sign in first"}`. `browse.mjs` borrows the newest non-expired row from the `sessions` table and sets it as the `contentos_session` cookie, so there is no password to diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 1a98a73..6469c99 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -120,6 +120,73 @@ Runs are untouched; `runs.topic_id` outlives the topic and a moved topic keeps its id. The Series screen marks duplicate rows and offers the merge; which copy is the real one is the user's call. +## A screen's data logic lives in a hook beside it, not in the screen + +DocumentView and ContentGroupsView were each eighteen hundred lines: fetching, +derived state, and layout in one file, so the subtlest rule on the page — which +copy of a run to render, how facet counts are taken — sat between a tooltip and +a border radius. Two hooks now hold what can be reasoned about without a +screen: + +- `lib/use-run-document.ts` — the run, template, topic, document and reel a + document page is about, resolved from either address (`/runs/` or + `/content/`), with the polled copy winning over the store's list. + `lib/use-run-watch.ts` underneath it is the poll. +- `lib/use-content-list.ts` — every row on Content, the filters, the facet + counts taken with their own dimension left open, the sort, the writing strip. + +The views keep what only a view has: which menu is open, which row is being +edited, rails made of glyphs. `components/tools/FramePicker.tsx` is the same +cut on the researcher: the one part of that screen with real interaction, and +it holds no state of its own so a new video cannot leave a stale selection. + +The line is "could a test exercise it without rendering". If yes, it belongs +in the hook, and `tests/` is where its rules go. + +## Nothing writes against a workspace the server has not confirmed + +`projects` opens on the design's sample workspaces, whose ids are empty, so +that every screen has a name to draw before the first request answers. A run +or an upload in that second went out with `workspaceId: ""` and came back as a +foreign-key error dressed as "something went wrong". `projectsLoaded` on the +store says whether the list is the server's yet; the run sheet, the researcher +and the tools manager refuse to write until it is, and say so. + +## Every route that touches data calls `requireUser` + +`proxy.ts` checks only that a session cookie is PRESENT — it cannot do more, +because it runs before the database is reachable. Validity is the route's job, +and for fifteen routes it was nobody's: `contentos_session=anything` listed +every run, every template, every workspace, and could start runs that spend +model credit. The comment in `proxy.ts` asserting the opposite is how it +survived a year of reading that file. + +So: one `await requireUser()` under the `await ready()` in every handler except +`/api/auth/login|logout|me|signup`, which are what you reach before you have a +session. Adding a route means adding that line — the proxy will not save you, +and nothing in a type or a test will notice. + +## One slug rule, in lib/slug.ts + +The same three lines lived in five files. Copies of a rule are a tidiness +problem right up until two of them are load-bearing against each other, and two +of these were: `/content/` finds its topic by comparing `slug(name)` to +the address bar. A stray edit to one copy would not fail a build or a test — it +would 404 one topic, silently, forever. + +## Tests cover what a screenshot cannot + +`tests/*.test.ts`, run by vitest, and deliberately narrow: no components, no +database. They cover the pure functions the screens stand on — `statusOf` (the +logic that had a dead run reading "Writing" for five days), the template +import/export round trip, `interpolate`, `slug`, and the parse that has to +survive a model wrapping its JSON in prose. `npm run check` is typecheck, lint +and these together. + +Do not grow this into component tests. The screens are checked by opening them +(`docs/BROWSER.md`); what these are for is the logic that fails silently, on one +row, days later. + ## A template travels as a file, and arrives as a draft Export writes the whole brief — rules, purpose, every section and its prompt, diff --git a/docs/DEPLOYING.md b/docs/DEPLOYING.md index d8ea7be..dc7450d 100644 --- a/docs/DEPLOYING.md +++ b/docs/DEPLOYING.md @@ -75,7 +75,9 @@ read, that is a feature to build, not a setting to find. ## Keeping it -The whole workspace is the `pgdata` volume. +The workspace is the `pgdata` volume. Videos and the stills cut from them are +in `sourcedata` — big, and re-fetchable from the links they came from, which is +why it is a second volume rather than something in the dump below. ```bash docker compose -f docker-compose.prod.yml exec -T postgres \ diff --git a/docs/DEVELOPING.md b/docs/DEVELOPING.md index ae0cb81..e05072c 100644 --- a/docs/DEVELOPING.md +++ b/docs/DEVELOPING.md @@ -15,14 +15,23 @@ because `start.sh` puts it there. Assume 3333 unless told otherwise. ## Check it ```bash -npm run typecheck # tsc --noEmit -npx eslint components lib app scripts +npm run check # typecheck, then eslint, then the tests +npm run test # vitest, on its own +npm run test:watch # while you are in one of them npm run build:check # a production build that does NOT touch the dev server ``` -Run typecheck and eslint after any edit. They are fast, and they catch the class -of mistake that a screenshot never will — a renamed identifier, a filter key -that no longer matches its type. +Run `npm run check` after any edit. It is seconds, and it catches the class of +mistake a screenshot never will — a renamed identifier, a filter key that no +longer matches its type, a status that stops being derived the way the list +expects. + +The tests are `tests/*.test.ts` and deliberately narrow: no components, no +database. They cover the pure functions everything stands on — what status a +row shows, what slug a URL resolves by, what an imported template turns into, +what the researcher makes of a model's answer. Those are the ones that fail +silently on one row, days later. Add to them when you touch that kind of +logic; do not try to test the screens here. ## Never `next build` while the dev server is up diff --git a/lib/content-docs.ts b/lib/content-docs.ts index 6277921..a9869c7 100644 --- a/lib/content-docs.ts +++ b/lib/content-docs.ts @@ -18,6 +18,8 @@ * `queued`, because a queued section is one that has not run yet and a failed * one is work waiting to be tried again. */ +import { slug } from "./slug"; + export type SectionState = "written" | "writing" | "queued" | "failed"; export type OutputKey = "en" | "bn" | "social" | "seo" | "tags"; @@ -299,12 +301,8 @@ export function looseSections(doc: ContentDoc) { return doc.sections.filter((s) => s.output === null); } -/** The slug a name is reached by. */ -export const slugify = (name: string) => - name - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-|-$/g, ""); +/** The slug a name is reached by. The one rule, from lib/slug.ts. */ +export const slugify = slug; export function docsByPack(docs: ContentDoc[]) { const groups: { pack: string; docs: ContentDoc[] }[] = []; diff --git a/lib/packs-transfer.ts b/lib/packs-transfer.ts index d64d82f..9d77ca4 100644 --- a/lib/packs-transfer.ts +++ b/lib/packs-transfer.ts @@ -1,6 +1,7 @@ "use client"; import type { Pack } from "@/lib/packs"; +import { slug } from "@/lib/slug"; import { fromDraft } from "@/lib/packs-client"; /** @@ -79,12 +80,7 @@ export function toFile(pack: Pack): TemplateFile { /** `ENBN Website Content` → `enbn-website-content.template.json` */ export const fileNameFor = (name: string) => - `${ - name - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-|-$/g, "") || "template" - }.template.json`; + `${slug(name) || "template"}.template.json`; export class TransferError extends Error {} diff --git a/lib/run-doc.ts b/lib/run-doc.ts index 97439f8..1bb0e0a 100644 --- a/lib/run-doc.ts +++ b/lib/run-doc.ts @@ -1,5 +1,6 @@ "use client"; +import { slug } from "@/lib/slug"; import type { ContentDoc, DocSection, OutputKey } from "@/lib/content-docs"; import type { Pack } from "@/lib/packs"; import type { Run } from "@/lib/runs-client"; @@ -116,9 +117,11 @@ export function latestRunFor(runs: Run[], topicId: string) { ); } -/** The slug a topic is reached by. Matches how the list builds its rows. */ -export const topicSlug = (name: string) => - name - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-|-$/g, ""); +/** + * The slug a topic is reached by. + * + * Re-exported rather than reimplemented: `/content/` resolves by + * comparing this to the address bar, so it and `slugify` have to be the same + * function — see lib/slug.ts. + */ +export const topicSlug = slug; diff --git a/lib/server/repos/packs.ts b/lib/server/repos/packs.ts index 704e2e5..fe94903 100644 --- a/lib/server/repos/packs.ts +++ b/lib/server/repos/packs.ts @@ -1,4 +1,5 @@ import { id, iso, one, q } from "@/lib/server/db/client"; +import { slug } from "@/lib/slug"; import { getRaw, setRaw } from "@/lib/server/repos/settings"; import { PACKS as BUILTIN, @@ -132,12 +133,9 @@ export type PackPatch = Partial< /** A slug from a name, made unique by suffix rather than by rejection. */ async function freeSlug(name: string) { - const base = - name - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-|-$/g, "") - .slice(0, 48) || "pack"; + // The same rule every other slug uses, capped so a pasted paragraph does not + // become a 400-character primary key. + const base = slug(name).slice(0, 48) || "pack"; const taken = new Set([ ...BUILTIN.map((p) => p.slug), ...(await q<{ slug: string }>("SELECT slug FROM packs")).map((r) => r.slug), diff --git a/lib/server/services/ingest.ts b/lib/server/services/ingest.ts index 1a2b52e..8016527 100644 --- a/lib/server/services/ingest.ts +++ b/lib/server/services/ingest.ts @@ -5,8 +5,10 @@ import { requireTool, run, toolStatus } from "@/lib/server/tools"; import { getSettings } from "@/lib/server/repos/settings"; import { createSource, + deleteSource, findByUrl, getSource, + listSources, updateSource, type Frame, type Source, @@ -220,6 +222,37 @@ export async function addFrameAt(sourceId: string, at: number): Promise return (await updateSource(sourceId, { frames }))!; } +/** + * Delete a source, and the download that went with it. + * + * The row and the directory are one thing: `deleteSource` on its own left a + * video and eight JPEGs on disk with nothing in the database pointing at them, + * so the only way to find them was to go looking. A reel is tens of megabytes + * — a few deletes and the disk is carrying a folder nobody can reach. + */ +export async function removeSource(sourceId: string) { + const gone = await deleteSource(sourceId); + // The files go whether or not the row was there: a half-deleted source is + // exactly the state this is meant to clean up. + await fs.rm(dirFor(sourceId), { recursive: true, force: true }).catch(() => {}); + return gone; +} + +/** + * Directories under .data/sources with no row behind them. + * + * Left by every delete before `removeSource` existed, and by an ingest that + * died between writing the file and writing the row. Reported rather than + * removed on sight — this is somebody's downloaded footage, and the caller + * decides. + */ +export async function orphanSourceDirs() { + const dirs = await fs.readdir(DATA).catch(() => [] as string[]); + const rows = await listSources(); + const known = new Set(rows.map((r) => r.id)); + return dirs.filter((d) => d.startsWith("src_") && !known.has(d)); +} + /** The bytes of one frame, for a model that is going to look at it. */ export async function frameBytes(sourceId: string, file: string) { if (!FRAME_FILE.test(file)) return null; diff --git a/lib/server/services/researcher.ts b/lib/server/services/researcher.ts index 3b87c5d..24d54a6 100644 --- a/lib/server/services/researcher.ts +++ b/lib/server/services/researcher.ts @@ -90,8 +90,15 @@ ${SHAPE} Give between 4 and 8 ideas, each a DIFFERENT video rather than the same one reworded: a different benefit, a different audience, a different moment of the tool. Never name the site in an idea title — the channel withholds the link deliberately and the name gives away the answer the comment is meant to buy.`; -/** The JSON out of an answer that may be wrapped in prose or a code fence. */ -function parse(text: string) { +/** + * The JSON out of an answer that may be wrapped in prose or a code fence. + * + * Exported for the tests. Models are asked for bare JSON and hand back a code + * fence, a sentence before it, or both — and every one of those failures shows + * up as an empty result rather than an error, which is the hardest kind to + * notice. It is worth the export. + */ +export function parse(text: string) { const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(text)?.[1]; const body = (fenced ?? text).trim(); const start = body.indexOf("{"); diff --git a/lib/slug.ts b/lib/slug.ts new file mode 100644 index 0000000..cc617c7 --- /dev/null +++ b/lib/slug.ts @@ -0,0 +1,22 @@ +/** + * One slug rule, for every name that becomes part of a URL. + * + * There were five copies of this — in `lib/topics.ts`, `lib/run-doc.ts`, + * `lib/content-docs.ts`, `lib/packs-transfer.ts` and the packs repo — all + * spelling out the same three lines. Copies of a rule are only a tidiness + * problem until two of them disagree, and two of these are load-bearing + * against each other: `/content/` finds its topic by comparing + * `slug(topic.name)` to what is in the address bar. A stray change to one + * would not fail a build or a test; it would 404 a page that was working + * yesterday, for one topic, silently. + * + * Deliberately plain: lowercase, anything that is not a letter or a digit + * becomes a hyphen, no hyphens on the ends. It is not reversible and does not + * try to be — Bangla names collapse to an empty string, which is why callers + * that must have something (a pack's own id) supply a fallback. + */ +export const slug = (name: string) => + name + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-|-$/g, ""); diff --git a/lib/store.tsx b/lib/store.tsx index 764ad41..ef8e4ec 100644 --- a/lib/store.tsx +++ b/lib/store.tsx @@ -119,6 +119,16 @@ type Store = { * a project whose voice you have to restate in every brief instead. */ projects: Project[]; + /** + * Whether `projects` is the server's list yet. + * + * It opens on the design's sample workspaces, which carry an empty id, so + * that every screen has a name to show before the first request answers. + * Anything that WRITES with a workspace id has to wait for this — a run or + * an upload against `""` is a foreign-key error dressed as "something went + * wrong", and it is only reachable in the first second after a load. + */ + projectsLoaded: boolean; /** The one the switcher is pointed at. */ project: Project; updateProject: (i: number, patch: Partial) => void; @@ -520,6 +530,7 @@ export function AppProvider({ children }: { children: ReactNode }) { const [projectIdx, setProjectIdx] = useState(0); const [projects, setProjects] = useState(PROJECTS); + const [projectsLoaded, setProjectsLoaded] = useState(false); const [projectSheet, setProjectSheet] = useState(null); const [confirm, setConfirm] = useState(null); const [projectOpen, setProjectOpen] = useState(false); @@ -619,6 +630,7 @@ export function AppProvider({ children }: { children: ReactNode }) { if (rows?.length) { setProjects(rows.map(toProject)); + setProjectsLoaded(true); // The series shown are the current workspace's. Which one that is // comes from `projectIdx`, so this follows it below rather than here. setTopicSeries(rows[0].series.map(toSeries)); @@ -1632,6 +1644,7 @@ export function AppProvider({ children }: { children: ReactNode }) { }, projects: countedProjects, + projectsLoaded, // Clamped rather than indexed blindly: the switcher's index and the list // are separate pieces of state, and a stale index must not blank the // header while every screen reads `project.name` off it. @@ -1816,6 +1829,7 @@ export function AppProvider({ children }: { children: ReactNode }) { newPack, savePack, projectIdx, + projectsLoaded, projectOpen, addProject, confirm, diff --git a/lib/topics.ts b/lib/topics.ts index b1b25aa..ef014d4 100644 --- a/lib/topics.ts +++ b/lib/topics.ts @@ -14,6 +14,7 @@ import type { Decision } from "./content-docs"; import { TOPIC_GROUPS } from "./data"; import { normalizeName } from "@/lib/dedupe"; +import { slug } from "./slug"; export type TopicStatus = "idea" | "generating" | "done"; @@ -198,12 +199,6 @@ const SEED_PACK: Record = { Business: "ENBN Website Content", }; -const slug = (s: string) => - s - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-|-$/g, ""); - /** The series a fresh session starts with, lifted from the design data. */ /** * The part number each seeded topic carries. diff --git a/lib/use-content-list.ts b/lib/use-content-list.ts new file mode 100644 index 0000000..4239545 --- /dev/null +++ b/lib/use-content-list.ts @@ -0,0 +1,428 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useState } from "react"; + +import { + USAGE, + USAGE_ORDER, + docsByPack, + slugify, + type ContentDoc, + type UsageStatus, +} from "@/lib/content-docs"; +import { statusOf, useDecisions } from "@/lib/decisions"; +import { useStore } from "@/lib/store"; +import { partName } from "@/lib/topics"; +import { listRuns, startWriting, type Run } from "@/lib/runs-client"; +import { runToDoc } from "@/lib/run-doc"; + +/** + * Everything the Content list knows, minus how it looks. + * + * Lifted out of ContentGroupsView, which was eighteen hundred lines of data + * logic and layout in one file. The split is on what can be reasoned about + * without a screen: which rows exist, which are shown, in what order, what the + * facets count, what is being written right now. The view keeps what only a + * view has — which menu is open, which row is being edited, the rails made of + * glyphs. + * + * The rules in here are the ones that went wrong quietly: a topic and its run + * appearing twice, counts that lied when a filter was on, "most recent" that + * returned 0 and leaned on build order. Each is commented where it lives. + */ + +export type SortKey = "recent" | "topic" | "status"; + +export const SORTS: { key: SortKey; label: string }[] = [ + { key: "recent", label: "Most recent" }, + { key: "topic", label: "Topic A–Z" }, + // "Least finished" went with the SECTIONS column: it ordered the list by a + // number that is no longer on screen, so the rows moved and nothing visible + // explained why. Content first, ideas last — the split "most recent" does + // not make. + { key: "status", label: "Finished first" }, +]; + +export type FilterKey = "status" | "template" | "series"; + +/** One value a facet offers — the same shape the FilterMenu draws. */ +export type FacetOption = { + value: string; + label: string; + /** How many rows would still be here if this value were picked. */ + count: number; + /** Optional swatch, used by the status filter. */ + dot?: string; +}; + +/** + * The status switcher's fixed segments: the lifecycle stages a topic is + * always in one of. Used and Ignored join the row only once a topic carries + * one — a permanent tab for a status nothing has yet is a dead segment. + * + * Writing is not one of them. A run in flight is not a shelf you browse — it + * is a thing happening right now, and it has its own strip at the top of the + * page, always on, whichever status you are reading. + */ +export const STATUS_TABS: UsageStatus[] = ["idea", "ready"]; + +/** The "every one" value for the series and template tabs. */ +export const ALL = ""; + +/** Where a row opens: the run that made it, or the document it is. */ +export const hrefFor = (doc: ContentDoc) => + doc.runId ? `/runs/${doc.runId}` : `/content/${doc.slug}`; + +export function useContentList() { + const { seriesList, packs, reloadRuns } = useStore(); + + /* + * What has actually been written. + * + * Real runs off the server, with real text behind every section. Fetched + * rather than seeded, and merged in below so a pack you ran ten minutes ago + * appears in the list you came here to read. + */ + const [runs, setRuns] = useState([]); + useEffect(() => { + void listRuns() + .then(setRuns) + // Silent: the list is still useful without them, and a failed fetch must + // not blank a page that has plenty else to show. + .catch(() => {}); + }, []); + + /** + * Start a failed run again. + * + * The server clears the failures and picks up where the drive stopped, so + * this is one press rather than a section-by-section repair. The list is + * re-read straight after: the row has to leave the Failed tab the moment it + * is writing again, or the button looks like it did nothing. + */ + const retry = useCallback( + async (runId: string) => { + try { + await startWriting(runId); + } catch { + // The row keeps saying Failed, which is still true. Nothing else to say. + } + await listRuns() + .then(setRuns) + .catch(() => {}); + void reloadRuns(); + }, + [reloadRuns], + ); + + // Re-renders the list whenever a status is changed anywhere. + const version = useDecisions(); + + const [query, setQuery] = useState(""); + const [sort, setSort] = useState("recent"); + const [filters, setFilters] = useState>({ + status: ["idea"], + template: [], + series: [], + }); + + const toggle = (key: FilterKey, value: string) => + setFilters((prev) => ({ + ...prev, + [key]: prev[key].includes(value) + ? prev[key].filter((v) => v !== value) + : [...prev[key], value], + })); + + const clear = (key: FilterKey) => + setFilters((prev) => ({ ...prev, [key]: [] })); + + const clearAll = () => { + // The series is navigation now, not a filter — the tab survives a clear. + // Neither does the status: it is a switcher, and a switcher with nothing + // selected is not a state it has. Clearing returns it to Idea. + setFilters((prev) => ({ + status: ["idea"], + template: [], + series: prev.series, + })); + setQuery(""); + }; + + /** The switcher's current status, and how it moves. */ + const status = (filters.status[0] ?? "idea") as UsageStatus; + const pickStatus = (next: UsageStatus) => + setFilters((prev) => ({ ...prev, status: [next] })); + + /* + * The series and template tabs run off the filters rather than a second + * piece of state, so picking one narrows the list the same way the menu + * used to and the counts on the other facets stay honest. + */ + const seriesTab = filters.series[0] ?? ALL; + const pickSeries = (id: string) => + setFilters((prev) => ({ ...prev, series: id === ALL ? [] : [id] })); + + const templateTab = filters.template[0] ?? ALL; + const pickTemplate = (value: string) => + setFilters((prev) => ({ + ...prev, + template: value === ALL ? [] : [value], + })); + + /** + * Every topic in this workspace, plus what has actually been written. + * + * A topic with no run gets a row with no sections, which `statusOf` reads + * as "idea": the first step of the same lifecycle that ends in used or + * ignored. Real runs go in front, newest first, because the thing you just + * made is the thing you came to look at. + */ + const DOCS = useMemo(() => { + const shelfOf = new Map( + seriesList.flatMap((series) => + series.topics.map((topic) => [topic.id, series.id] as const), + ), + ); + + const produced: ContentDoc[] = runs.map((r) => ({ + ...runToDoc( + r, + packs.find((x) => x.id === r.packSlug), + ), + // A run's shelf is its topic's shelf. `inputs.series` is the name that + // was typed into it, which is a label, not an identity. + seriesId: r.topicId ? shelfOf.get(r.topicId) : undefined, + })); + + const written = new Set(produced.map((d) => d.topic.toLowerCase())); + const rows: ContentDoc[] = []; + + for (const series of seriesList) { + for (const topic of series.topics) { + // A topic whose run is already in `produced` would otherwise appear + // twice: once as the content, once as the idea it started as. + if (written.has(topic.name.toLowerCase())) continue; + rows.push({ + slug: slugify(topic.name), + topicId: topic.id, + seriesId: series.id, + topic: topic.name, + series: series.name, + pack: series.pack || "No template", + part: + topic.part !== null ? partName(series.partLabel, topic.part) : "", + blurb: "", + decision: topic.decision, + created: topic.activity, + updated: topic.activity, + at: topic.updatedAt, + sections: [], + }); + } + } + + return [...produced, ...rows]; + }, [seriesList, runs, packs]); + + const { groups, shown, options, active } = useMemo(() => { + void version; + const q = query.trim().toLowerCase(); + + const passes = { + search: (d: ContentDoc) => + !q || + `${d.topic} ${d.pack} ${d.blurb} ${d.series}`.toLowerCase().includes(q), + status: (d: ContentDoc) => + !filters.status.length || filters.status.includes(statusOf(d)), + pack: (d: ContentDoc) => + !filters.template.length || filters.template.includes(d.pack), + series: (d: ContentDoc) => + !filters.series.length || filters.series.includes(d.seriesId ?? ""), + }; + + const matched = DOCS.filter( + (d) => + passes.search(d) && + passes.status(d) && + passes.pack(d) && + passes.series(d), + ); + + /** + * Counts for one dimension are taken with that dimension left open, so + * picking "Ignored" still shows how many Used topics there are. Values + * that would match nothing are dropped unless they are already picked. + */ + const facet = ( + pool: ContentDoc[], + pick: (d: ContentDoc) => string, + values: string[], + selected: string[], + label: (v: string) => string, + dot?: (v: string) => string, + ): FacetOption[] => + values + .map((value) => ({ + value, + label: label(value), + count: pool.filter((d) => pick(d) === value).length, + dot: dot?.(value), + })) + .filter((o) => o.count > 0 || selected.includes(o.value)); + + const forStatus = DOCS.filter( + (d) => passes.search(d) && passes.pack(d) && passes.series(d), + ); + const forPack = DOCS.filter( + (d) => passes.search(d) && passes.status(d) && passes.series(d), + ); + const forSeries = DOCS.filter( + (d) => passes.search(d) && passes.status(d) && passes.pack(d), + ); + + const packNames = [...new Set(DOCS.map((d) => d.pack))].sort(); + const seriesIds = [...new Set(DOCS.map((d) => d.seriesId ?? ""))]; + + /* + * Writing first, then what needs a person: a failed run is the one thing + * on the list that is waiting on you rather than on the model. + */ + const rank: Record = { + writing: 0, + failed: 1, + ready: 2, + used: 3, + idea: 4, + ignored: 5, + }; + + const sorted = [...matched].sort((a, b) => { + switch (sort) { + case "topic": + return a.topic.localeCompare(b.topic); + case "status": + // Status first, then recency inside it. Without the second key, rows + // sharing a status fell back to build order and moved for reasons + // nothing on screen explained. + return ( + rank[statusOf(a)] - rank[statusOf(b)] || b.at.localeCompare(a.at) + ); + default: + // Most recent, actually sorted. This used to return 0 and lean on + // the order DOCS builds. `at` is an ISO instant and sorts as a + // string; a tie falls back to the name so equal timestamps give a + // stable order rather than one that reshuffles on every render. + return b.at.localeCompare(a.at) || a.topic.localeCompare(b.topic); + } + }); + + return { + groups: docsByPack(sorted), + shown: sorted.length, + options: { + status: facet( + forStatus, + (d) => statusOf(d), + USAGE_ORDER, + filters.status, + (v) => USAGE[v as UsageStatus].label, + (v) => USAGE[v as UsageStatus].dot, + ), + template: facet(forPack, (d) => d.pack, packNames, filters.template, (v) => v), + series: facet( + forSeries, + (d) => d.seriesId ?? "", + seriesIds, + filters.series, + // The facet is keyed by id but read by people: anything rendering it + // needs the shelf's name, not `ser_mtbuo7f4e59wg`. + (id) => seriesList.find((x) => x.id === id)?.name ?? "No series", + ), + }, + // Series and status are left out on purpose: both are controls that + // always read their own state — the rail says which shelf, the switcher + // says which status — and a chip that removes one would leave it with + // nothing selected, which is not a state either of them has. + active: filters.template.map((value) => ({ + key: "template" as FilterKey, + value, + label: value, + dot: undefined as string | undefined, + })), + }; + }, [DOCS, query, filters, sort, version, seriesList]); + + /** + * The switcher's segments: the fixed stages, plus any end state a topic has + * actually reached. Mark one Used and a USED segment appears — which is the + * only way back to it, so it has to. + */ + const statusTabs = useMemo(() => { + const present = new Set(options.status.map((o) => o.value)); + return [ + ...STATUS_TABS, + ...USAGE_ORDER.filter( + (s) => + !STATUS_TABS.includes(s) && + present.has(s) && + // Writing has the strip; a segment for it would be a second place + // saying the same thing. It comes back only if it is the segment you + // are standing on, because otherwise there would be no way off it. + (s !== "writing" || status === "writing"), + ), + ]; + }, [options.status, status]); + + /** + * What the machine is doing right now. + * + * Off DOCS rather than off the filtered list on purpose: a run in flight is + * news whatever you happen to be reading, and a strip that empties because + * you switched to Ready would be a status light you cannot trust. + */ + const writingNow = useMemo( + () => + DOCS.filter((d) => statusOf(d) === "writing").map((d) => ({ + slug: d.slug, + topic: d.topic, + pack: d.pack, + // Carried rather than rebuilt from the slug: a row that came from a + // run has the RUN's id as its slug, and `/content/run_…` is a 404. + href: hrefFor(d), + written: d.sections.filter((x) => x.state === "written").length, + total: d.sections.length, + })), + [DOCS], + ); + + const anyFilter = active.length > 0 || query.trim().length > 0; + + return { + DOCS, + groups, + shown, + options, + active, + anyFilter, + statusTabs, + writingNow, + retry, + + query, + setQuery, + sort, + setSort, + filters, + toggle, + clear, + clearAll, + + status, + pickStatus, + seriesTab, + pickSeries, + templateTab, + pickTemplate, + }; +} diff --git a/lib/use-run-document.ts b/lib/use-run-document.ts new file mode 100644 index 0000000..3efa815 --- /dev/null +++ b/lib/use-run-document.ts @@ -0,0 +1,173 @@ +"use client"; + +import { useEffect, useMemo, useState } from "react"; + +import { useStore } from "@/lib/store"; +import { latestRunFor, runToDoc, topicSlug } from "@/lib/run-doc"; +import { getPack, type ApiPack } from "@/lib/packs-client"; +import { getSource, type Source } from "@/lib/sources-client"; +import { useRunWatch } from "@/lib/use-run-watch"; + +/** + * The run a document page is about, resolved from either kind of address. + * + * `/runs/` names a run; `/content/` names a topic and means its + * latest run. Both end up here as the same five things — the run, the + * template as the engine executes it, the topic behind it, the document the + * page reads, and the reel the run was given — plus what is still to write. + * + * Lifted out of DocumentView, where it was the first hundred lines of a + * nineteen-hundred-line screen and where the page's one real bug lived: the + * store's once-loaded list was consulted before the polled copy, so the poll + * ran and nothing it fetched was ever drawn. That rule is now in one place, + * with the reason beside it. + */ +export function useRunDocument({ + slug, + runId, +}: { + slug?: string; + runId?: string; +}) { + const { seriesList, runs, packs } = useStore(); + + /* + * Which run to follow. + * + * The URL when it names one; otherwise the topic's latest, worked out from + * the store's list rather than from `run` below — `run` is built from what + * the watcher fetches, so asking it here would be circular. A topic opened + * by name has to be watched too: it sat perfectly still while its run was + * being written until somebody noticed. + */ + const watchId = useMemo(() => { + if (runId) return runId; + const mine = seriesList + .flatMap((series) => series.topics) + .find((x) => topicSlug(x.name) === slug); + return mine ? (latestRunFor(runs, mine.id)?.id ?? null) : null; + }, [runId, seriesList, slug, runs]); + + const { fetched, setFetched, serverWriting, setServerWriting } = + useRunWatch(watchId); + + const run = useMemo(() => { + /* + * The polled copy wins. + * + * The store's list is loaded once and reloaded on navigation — never on a + * timer. Reading it first rendered a snapshot taken when the page was + * opened, while the poll kept a fresh copy in `fetched` that nothing + * looked at: live updates that only arrived on a refresh. Whichever way + * the page was addressed, if the fetched run IS this run, it is the truth. + */ + if (runId) { + return fetched?.id === runId + ? fetched + : (runs.find((r) => r.id === runId) ?? fetched); + } + const topic = seriesList + .flatMap((series) => series.topics) + .find((t) => topicSlug(t.name) === slug); + const latest = topic ? latestRunFor(runs, topic.id) : null; + return latest && fetched?.id === latest.id ? fetched : latest; + }, [runId, fetched, runs, seriesList, slug]); + + /* + * The template as the engine runs it. + * + * The store's copy is the builder's shape and carries no dependency arrows, + * and those are what decide which section may go next. Fetched by slug so a + * template written in the builder works here too. + */ + const [runtime, setRuntime] = useState(null); + + useEffect(() => { + const packSlug = run?.packSlug; + if (!packSlug) return; + let cancelled = false; + void getPack(packSlug) + .then((p) => { + if (!cancelled) setRuntime(p); + }) + .catch(() => {}); + return () => { + cancelled = true; + }; + }, [run?.packSlug]); + + /** The topic behind it, for the rail and for the empty states. */ + const topic = useMemo( + () => + seriesList + .flatMap((series) => series.topics.map((t) => ({ ...t, series }))) + .find((t) => + runId ? t.id === run?.topicId : topicSlug(t.name) === slug, + ), + [seriesList, slug, runId, run], + ); + + const doc = useMemo( + () => + run ? runToDoc(run, packs.find((p) => p.id === run.packSlug)) : null, + [run, packs], + ); + + /** The reel this run was given, when it was given one. */ + const [source, setSource] = useState(null); + + useEffect(() => { + const sid = run?.sourceId; + if (!sid) return; + let cancelled = false; + void getSource(sid) + .then((x) => { + if (!cancelled) setSource(x); + }) + .catch(() => {}); + return () => { + cancelled = true; + }; + }, [run?.sourceId]); + + /* + * Sections that have not been written yet, in the template's own order. + * + * A dependency is satisfied when the section it names is done, so this is + * recomputed from the run every time rather than held as a queue: a section + * rewritten by hand changes what is ready next, and a queue built once would + * not notice. + */ + const pending = useMemo(() => { + if (!run || !runtime) return []; + const done = new Set( + run.sections.filter((x) => x.state === "done").map((x) => x.id), + ); + return runtime.sections + .filter((def) => { + const row = run.sections.find((x) => x.id === def.id); + return ( + row && row.state !== "done" && def.dependsOn.every((d) => done.has(d)) + ); + }) + .map((def) => def.id); + }, [run, runtime]); + + const unwritten = run + ? run.sections.filter((x) => x.state !== "done").length + : 0; + + return { + run, + runtime, + topic, + doc, + source, + pending, + unwritten, + fetched, + setFetched, + serverWriting, + setServerWriting, + }; +} diff --git a/lib/use-run-watch.ts b/lib/use-run-watch.ts new file mode 100644 index 0000000..b281d28 --- /dev/null +++ b/lib/use-run-watch.ts @@ -0,0 +1,77 @@ +"use client"; + +import { useEffect, useState } from "react"; + +import { getRun, isWriting, type Run } from "@/lib/runs-client"; + +/** + * The server's copy of one run, kept current while it moves. + * + * Lifted out of DocumentView, where it was sixty lines in the middle of a + * nineteen-hundred-line screen — and where the subtlest bug on the page lived: + * the poll worked, and what it fetched was never rendered, because the store's + * once-loaded list was consulted first. Whoever calls this has to prefer what + * it returns over any list copy of the same run. + * + * Two jobs, because they are the same fact: fetch the run the URL names (it may + * be seconds old and not in any list yet), then follow it — fast while + * something is being written, slowly once it settles, so a page left open + * overnight is not asking twice a second. + */ +export function useRunWatch(runId: string | null | undefined) { + const [fetched, setFetched] = useState(null); + const [serverWriting, setServerWriting] = useState(false); + + useEffect(() => { + if (!runId) return; + let cancelled = false; + void getRun(runId) + .then((r) => { + if (!cancelled) setFetched(r); + }) + .catch(() => {}); + return () => { + cancelled = true; + }; + }, [runId]); + + useEffect(() => { + if (!runId) return; + let stop = false; + + const tick = async () => { + try { + const [state, fresh] = await Promise.all([ + isWriting(runId), + getRun(runId), + ]); + if (stop) return; + setServerWriting(state.running); + if (fresh) setFetched(fresh); + return state.running ? 1500 : 6000; + } catch { + return 6000; + } + }; + + let timer: ReturnType; + const loop = async () => { + const wait = (await tick()) ?? 6000; + if (!stop) timer = setTimeout(() => void loop(), wait); + }; + void loop(); + + return () => { + stop = true; + clearTimeout(timer); + }; + }, [runId]); + + /** + * `setFetched` is handed back on purpose: writing a section returns the whole + * run, and the page that asked has the answer a poll would spend a second and + * a half getting to. `setServerWriting` likewise, so pressing "Write the + * rest" shows as busy before the first poll confirms it. + */ + return { fetched, setFetched, serverWriting, setServerWriting }; +} diff --git a/package-lock.json b/package-lock.json index 772888b..4735359 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,7 +21,8 @@ "@types/react-dom": "^19", "eslint": "^9", "eslint-config-next": "16.3.3", - "typescript": "^5" + "typescript": "^5", + "vitest": "^5.0.0" } }, "node_modules/@anthropic-ai/sdk": { @@ -1314,6 +1315,278 @@ "node": ">=12.4.0" } }, + "node_modules/@oxc-project/types": { + "version": "0.148.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.148.0.tgz", + "integrity": "sha512-Nm4s/jB+4FpFsPhWGEC4h7rzksesmtnMXomo6rCMcg/b8zLQuOziRgkCS1fxDCXOlJB/6Q8oABOZ/OP6RIPj9A==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.7.tgz", + "integrity": "sha512-EypzgnYCwyVY4NDHKzGmNJT5b+XaQEBniHxsMdeIQLB/tcCzZnhqrzHpZFbX9iaxx+5RiB8caATBtfvZP7zVxQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.7.tgz", + "integrity": "sha512-l17HE9EweWaqJZhuUuNBN/FzM62xw+DECVnJyvMsxn8vJFAGLy5QfLDoYAcronkAN8VxKZHezDpulHDPx95vFw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.7.tgz", + "integrity": "sha512-8ED8ELFvHXc6OCETIn4gXObPiaR6bckM/ipXtbzlPVDRMBfEGjCKgO90F9YtfdpDatVx/ZQw7aZ1vUMf/+T3Mw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.7.tgz", + "integrity": "sha512-/WPripjtiAIZ2tWY7ddijORT0Ujg87wxWW/qcoFVCKAWVDPhtY0xr7Dj0M3GyNGz60jGwTElhro/mkF9dT7dDQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.7.tgz", + "integrity": "sha512-14DI4NcqpvbICxSnGLx3PmtDaWqRP/KGSGb6C+JLLVPeZRl6dKdHba3pGsqT3vpdTqhEYIPG0MMQ8c0xYqoJxA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.7.tgz", + "integrity": "sha512-bxrWIRvHWQvbJwi+VIie/kDJmQxcNE6xxWwZdqF/ExVAigtHkv54WTLQPb+QsZdnFy18fg7JPfWGL0RH6vwIlQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.7.tgz", + "integrity": "sha512-toOY2BChBZyuxU7OYX6Tn389di4IzAqPTycVcci0O7FSfBqzRB3RZn+K5Is6ANf4tmgRd/K1yZTsNTXbkXsnLg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.7.tgz", + "integrity": "sha512-lAIXTH/aiLRLxsTgQvfhjo4K1ydWIp00+V0voOr9beb/9ZmkUFrSIb03dXNFRgMNvkE6oGsF10ioQ6UsI+vS5Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.7.tgz", + "integrity": "sha512-kdnwS28Pkenp/mZMRwjXXXwxQ7pIsm+bF919LUK93BOyhcLsrVKdP2p9fxpiPNPAbNuch8ypQt0pm2P2LYCAGg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.7.tgz", + "integrity": "sha512-516OdsyLdr5E65paF3yBF55t8mfm9+gmtCsK3xI7XKXIT7EfRlHhxL8K/NR6Hu8BWSgF5+1w74lTL0+nxcc8Qw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.7.tgz", + "integrity": "sha512-r8/z8n7GFaYRln3xmP1Cxy0HH/HLM0uBUPkEuSVEfKGDA89M0FsZRZJRSwe/tJjRx+fpH/gjorfhB8tmEbSFLA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.7.tgz", + "integrity": "sha512-pAsE8iiDxUg1xBqdhrTfg45AVDVpirjz00sblEYClGNNcMnDb+e8beQgqIAw6LvauX/APvgxUnwrgun/YYGBhw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.7.tgz", + "integrity": "sha512-lTcIYmmnQQA8Or/2DatS6oSqcdLHvendjS+zLu+FwgToynWMRSmQdpM65fTANJgIS4mjbMOo5KT2lnT9SAb96w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.7.tgz", + "integrity": "sha512-e3Gu3WxbNk/UqQhxqU7YIYO+9ZBvWNz3U+h/qRFosscMFzdRPbXYSaSWgSnklv2fz1TgzBTcti2z35c/7irsHw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.7.tgz", + "integrity": "sha512-W/jg5qoRSqjsEv0+dZi4e687mcHqmVuU0P4fK6qS/xjetW2Gmc1W8j//z5nAeNcC8Ttm0hV46IjcYeuVwYhuiw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, "node_modules/@rtsao/scc": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz", @@ -1347,6 +1620,24 @@ "tslib": "^2.4.0" } }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", @@ -2054,6 +2345,44 @@ "win32" ] }, + "node_modules/@vitest/mocker": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.0.tgz", + "integrity": "sha512-66PGTMIiVJP3t4a5yxU9qPtf7MdTBs8jmToMvy+HVflB3Yy13WJZTtPePdvU+wjRV02SKK5doLbSA6o9pwOmiA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.0", + "estree-walker": "^3.0.3", + "magic-string": "^1.2.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.0.tgz", + "integrity": "sha512-uy+luWBAPw9XfthoHi5AkfHUnuPYEESjl0p/r+meoBnU8bxg5GDQ3Ey8MjcJ6sqahkL4PFyrvfMJJBw7LbU06g==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/acorn": { "version": "8.18.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", @@ -2288,6 +2617,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/ast-types-flow": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.8.tgz", @@ -2499,6 +2838,16 @@ ], "license": "CC-BY-4.0" }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -2704,8 +3053,8 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "devOptional": true, "license": "Apache-2.0", - "optional": true, "engines": { "node": ">=8" } @@ -2888,6 +3237,13 @@ "node": ">= 0.4" } }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, "node_modules/es-object-atoms": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", @@ -3373,8 +3729,18 @@ "node": ">=4.0" } }, - "node_modules/esutils": { - "version": "2.0.3", + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", "dev": true, @@ -3383,6 +3749,16 @@ "node": ">=0.10.0" } }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -3530,6 +3906,21 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, "node_modules/function-bind": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", @@ -4496,6 +4887,267 @@ "node": ">= 0.8.0" } }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -4542,6 +5194,16 @@ "yallist": "^3.0.2" } }, + "node_modules/magic-string": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.2.3.tgz", + "integrity": "sha512-Bpb0W2TbLKOZ7vJnOUnVRGq3WL2p+ISV29M6hYPL1AFCpyKZpdr5ytiXoTSSxRVhg8YW7f65+6gbG8WG6PCa/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -4852,6 +5514,20 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/obug": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz", + "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -5329,6 +6005,40 @@ "node": ">=0.10.0" } }, + "node_modules/rolldown": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.7.tgz", + "integrity": "sha512-g0EtLvBjTUB7jhyV0S/TCup3v/XSVl45vUIGbOGU4QPiyjTenCe4mKuFvW9fEgYmS2Fo42AUssRmNuMziXdrig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.148.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.7", + "@rolldown/binding-android-arm64": "1.2.7", + "@rolldown/binding-darwin-arm64": "1.2.7", + "@rolldown/binding-darwin-x64": "1.2.7", + "@rolldown/binding-freebsd-x64": "1.2.7", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.7", + "@rolldown/binding-linux-arm64-gnu": "1.2.7", + "@rolldown/binding-linux-arm64-musl": "1.2.7", + "@rolldown/binding-linux-ppc64-gnu": "1.2.7", + "@rolldown/binding-linux-s390x-gnu": "1.2.7", + "@rolldown/binding-linux-x64-gnu": "1.2.7", + "@rolldown/binding-linux-x64-musl": "1.2.7", + "@rolldown/binding-openharmony-arm64": "1.2.7", + "@rolldown/binding-win32-arm64-msvc": "1.2.7", + "@rolldown/binding-win32-x64-msvc": "1.2.7" + } + }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -5635,6 +6345,13 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", @@ -5660,6 +6377,13 @@ "dev": true, "license": "MIT" }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, "node_modules/standardwebhooks": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.0.0.tgz", @@ -5670,6 +6394,13 @@ "fast-sha256": "^1.3.0" } }, + "node_modules/std-env": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz", + "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", + "dev": true, + "license": "MIT" + }, "node_modules/stop-iteration-iterator": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", @@ -5870,6 +6601,26 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/tinybench": { + "version": "6.1.4", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.1.4.tgz", + "integrity": "sha512-9APumHG7r4yOk4X4WlkmE71aZcv1gvin1czO3OQ1U9iJcFA5Ja/ygyb0vPOVHTthFozUYs8CLoLUlM8grb2lTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.0.tgz", + "integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", @@ -6218,6 +6969,222 @@ "punycode": "^2.1.0" } }, + "node_modules/vite": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.2.tgz", + "integrity": "sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.5", + "postcss": "^8.5.26", + "rolldown": "~1.2.4", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.4.0 || ^0.5.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/vite/node_modules/postcss": { + "version": "8.5.27", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.27.tgz", + "integrity": "sha512-79Iho8QeYyooJ8e9lCRyTVlyTAkS/kXBYKff6TMzS3kEWGQ8Ds5UEtXpGrSUDLUWok6QTvxeYy0GO8fopHnaSA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/vitest": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.0.tgz", + "integrity": "sha512-gpsMNoRhMjMktVxPtstOH4/PJuPyovVaMDr4oDilXaGH1EcqM2OE96SoHT2VIQ6fTGtTjqmHDrEu2X9RQiXf8Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.0", + "chai": "^6.2.2", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.2.3", + "obug": "^2.1.4", + "picomatch": "^4.0.7", + "std-env": "^4.2.0", + "tinybench": "6.1.4", + "tinyexec": "1.3.0", + "tinyglobby": "^0.2.17", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.0", + "@vitest/browser-preview": "5.0.0", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.0", + "@vitest/coverage-v8": "5.0.0", + "@vitest/ui": "5.0.0", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/vitest/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -6323,6 +7290,23 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", diff --git a/package.json b/package.json index c2883b9..fc9dd49 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,9 @@ "build": "next build", "build:check": "node scripts/build-check.mjs", "typecheck": "tsc --noEmit", + "test": "vitest run", + "test:watch": "vitest", + "check": "npm run typecheck && npm run lint && npm run test", "start": "next start", "lint": "eslint" }, @@ -30,6 +33,7 @@ "@types/react-dom": "^19", "eslint": "^9", "eslint-config-next": "16.3.3", - "typescript": "^5" + "typescript": "^5", + "vitest": "^5.0.0" } } diff --git a/proxy.ts b/proxy.ts index efc7b19..b7a2e6c 100644 --- a/proxy.ts +++ b/proxy.ts @@ -9,8 +9,12 @@ import { SESSION_COOKIE } from "@/lib/session"; * convention and renamed it. Same runtime, same matcher, same one job. * * It checks only that a session cookie is PRESENT, not that it is valid — - * this runs before the database is reachable, and a forged cookie gets - * no further than the first API call, every one of which calls `requireUser`. + * this runs before the database is reachable. A forged cookie therefore gets + * no further than the first API call, PROVIDED the route calls `requireUser`. + * Fifteen of them did not, and this comment asserting otherwise is how that + * survived: anything with a cookie header read and wrote everything. Adding a + * route without that call re-opens the hole, so it is the route's job and not + * this file's. * This exists so someone who is not signed in lands on the sign-in page * instead of an empty shell that 401s six times. */ diff --git a/tests/prompt.test.ts b/tests/prompt.test.ts new file mode 100644 index 0000000..438f27e --- /dev/null +++ b/tests/prompt.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from "vitest"; + +import { interpolate } from "@/lib/server/prompt"; +import { slug } from "@/lib/slug"; + +/** + * The two rules a prompt and a URL are built out of. + * + * `interpolate` decides what a section is actually sent — a placeholder that + * silently resolves to the empty string is how a script gets written for + * "Part " with no number. `slug` decides whether `/content/` finds its + * topic at all, and it is now one function precisely so that two copies cannot + * drift into 404ing a page that worked yesterday. + */ + +describe("interpolate", () => { + it("replaces what it was given", () => { + expect(interpolate("{{series}} — Part {{part_number}}.", { + series: "Powerful website you should know", + part_number: "18", + })).toBe("Powerful website you should know — Part 18."); + }); + + it("leaves a placeholder it has no value for alone", () => { + // Visible in the output, which is the point: a braced key that survives + // into a script is a missing input somebody can see and fix. Blanking it + // would produce "Part ." and look like the model's mistake. + expect(interpolate("Part {{part_number}}.", {})).toBe("Part {{part_number}}."); + }); + + it("blanks a key that exists and is empty, rather than printing braces", () => { + expect(interpolate("Part {{part_number}}.", { part_number: "" })).toBe("Part ."); + }); + + it("trims what it drops in", () => { + expect(interpolate("{{series}}!", { series: " Shelf " })).toBe("Shelf!"); + }); + + it("ignores anything that is not a plain key", () => { + expect(interpolate("{{ series }} {{a-b}}", { series: "x" })).toBe( + "{{ series }} {{a-b}}", + ); + }); +}); + +describe("slug", () => { + it("lowercases and hyphenates", () => { + expect(slug("ENBN Website Content")).toBe("enbn-website-content"); + }); + + it("survives a URL as a name — the common case on this console", () => { + expect(slug("https://www.swishy.ai/")).toBe("https-www-swishy-ai"); + }); + + it("has no hyphens on the ends", () => { + expect(slug(" ¿What now? ")).toBe("what-now"); + }); + + it("collapses to nothing for a name with no latin letters", () => { + // Callers that need something must supply a fallback — see `fileNameFor` + // and the packs repo's `freeSlug`. + expect(slug("বাংলা স্ক্রিপ্ট")).toBe(""); + }); +}); diff --git a/tests/researcher.test.ts b/tests/researcher.test.ts new file mode 100644 index 0000000..efd282a --- /dev/null +++ b/tests/researcher.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; + +import { parse } from "@/lib/server/services/researcher"; + +/** + * What the researcher can make of an answer. + * + * The model is asked for bare JSON and reliably sends back something else: a + * fenced block, a sentence of preamble, occasionally both. Every one of those + * failures reads as "the tool found nothing" rather than as an error, so this + * is the parse that has to be forgiving. + */ +describe("parse", () => { + it("reads plain JSON", () => { + expect(parse('{"site":{"name":"remove.bg"}}')).toEqual({ + site: { name: "remove.bg" }, + }); + }); + + it("reads it out of a code fence", () => { + const answer = 'Here you go:\n\n```json\n{"does":"removes backgrounds"}\n```'; + expect(parse(answer)).toEqual({ does: "removes backgrounds" }); + }); + + it("reads it out of an unlabelled fence", () => { + expect(parse('```\n{"a":1}\n```')).toEqual({ a: 1 }); + }); + + it("finds the object inside prose on both sides", () => { + const answer = 'I looked at the frames.\n{"a":1}\nHope that helps.'; + expect(parse(answer)).toEqual({ a: 1 }); + }); + + it("returns null rather than throwing on nonsense", () => { + expect(parse("I could not see the frames.")).toBeNull(); + expect(parse('{"a": ')).toBeNull(); + expect(parse("")).toBeNull(); + }); + + it("keeps nested objects whole", () => { + const answer = '{"ideas":[{"title":"one","angle":"a"},{"title":"two"}]}'; + expect((parse(answer) as { ideas: unknown[] }).ideas).toHaveLength(2); + }); +}); diff --git a/tests/status.test.ts b/tests/status.test.ts new file mode 100644 index 0000000..0a235f2 --- /dev/null +++ b/tests/status.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vitest"; + +import type { ContentDoc, DocSection, SectionState } from "@/lib/content-docs"; +import { usageOf } from "@/lib/content-docs"; +import { statusOf } from "@/lib/decisions"; + +/** + * What a row says about itself. + * + * This is the logic that had a run sitting in "Writing" for five days: the + * status was derived from a count of written sections and nothing else, so a + * run that died and a run that never started were both indistinguishable from + * one being written that second. The cases below are exactly those, and they + * are cheap to keep honest. + */ + +const section = (n: string, state: SectionState): DocSection => ({ + id: n, + n, + name: `Section ${n}`, + purpose: "", + kind: "script", + output: null, + lang: null, + state, + body: state === "written" ? ["some text"] : [], +}); + +const doc = (states: SectionState[]): ContentDoc => ({ + slug: "run_test", + topic: "A topic", + series: "A shelf", + pack: "A template", + part: "", + blurb: "", + decision: "ready", + created: "", + updated: "", + at: new Date().toISOString(), + sections: states.map((s, i) => section(String(i + 1).padStart(2, "0"), s)), +}); + +describe("statusOf", () => { + it("is an idea when nothing has been run", () => { + expect(statusOf(doc([]))).toBe("idea"); + }); + + it("is writing while a section is being written", () => { + expect(statusOf(doc(["written", "writing", "queued"]))).toBe("writing"); + }); + + it("is failed when a section gave up, even mid-run", () => { + expect(statusOf(doc(["written", "failed", "queued"]))).toBe("failed"); + }); + + it("prefers writing over failed — something is still moving", () => { + expect(statusOf(doc(["failed", "writing"]))).toBe("writing"); + }); + + it("is an idea again when a run was created and never got going", () => { + // The two Squoosh rows that read "Writing" for five days: twelve queued + // sections, nothing written, nothing failed, nothing in flight. + expect(statusOf(doc(["queued", "queued", "queued"]))).toBe("idea"); + }); + + it("is writing when it is part-way through", () => { + expect(statusOf(doc(["written", "queued"]))).toBe("writing"); + }); + + it("falls through to the decision once every section landed", () => { + expect(statusOf(doc(["written", "written"]))).toBe("ready"); + }); +}); + +describe("usageOf", () => { + it("agrees with statusOf about failure", () => { + expect(usageOf(doc(["written", "failed"]))).toBe("failed"); + }); +}); diff --git a/tests/transfer.test.ts b/tests/transfer.test.ts new file mode 100644 index 0000000..9567831 --- /dev/null +++ b/tests/transfer.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it } from "vitest"; + +import type { Pack } from "@/lib/packs"; +import { TransferError, fileNameFor, fromFile, toFile } from "@/lib/packs-transfer"; +import { slug } from "@/lib/slug"; + +/** + * A template leaving one console and arriving at another. + * + * The failure this has to make impossible is a half-imported template: a name + * and a description, no prompts, and no sign that anything was lost. So the + * round trip is checked field by field, and every way a file can be wrong is + * checked for a sentence rather than a silent success. + */ + +const pack = (): Pack => ({ + id: "enbn-website-package", + n: "01", + name: "ENBN Website Content", + desc: "A researched website becomes a short-form set", + sections: "2", + used: "never", + status: "ACTIVE", + inputs: [{ key: "series", label: "Series", required: true }], + outputs: [{ key: "en", label: "English script", sections: ["script-en"] }], + draft: { + name: "ENBN Website Content", + summary: "A researched website becomes a short-form set", + status: "ACTIVE", + purpose: "Earn a save and a comment", + rules: "Never name the website.", + sections: [ + { + id: "research", + name: "Website research", + type: "Research", + brief: "Read the landing page.", + }, + { + id: "script-en", + name: "English script", + type: "Script", + brief: "Write ONE script.", + }, + ], + }, +}); + +describe("toFile", () => { + it("carries the whole brief, and leaves the slug behind", () => { + const file = toFile(pack()); + expect(file.kind).toBe("contentos.template"); + expect(file.template.rules).toBe("Never name the website."); + expect(file.template.sections).toHaveLength(2); + expect(file.template.sections[1].instruction).toBe("Write ONE script."); + // The importing console mints its own — carrying it would collide. + expect(JSON.stringify(file)).not.toContain('"slug"'); + }); + + it("exports the inputs a run asks for, which the builder never edits", () => { + expect(toFile(pack()).template.inputs).toEqual([ + { key: "series", label: "Series", required: true }, + ]); + }); +}); + +describe("fromFile", () => { + it("round-trips every prompt", () => { + const body = fromFile(toFile(pack())); + expect(body.name).toBe("ENBN Website Content"); + expect(body.sections.map((s) => s.instruction)).toEqual([ + "Read the landing page.", + "Write ONE script.", + ]); + expect(body.inputs).toHaveLength(1); + expect(body.outputs).toHaveLength(1); + }); + + it("arrives as a draft whatever it was at home", () => { + expect(fromFile(toFile(pack())).status).toBe("DRAFT"); + }); + + it("refuses anything that is not a template file", () => { + expect(() => fromFile({ name: "looks like a pack" })).toThrow(TransferError); + expect(() => fromFile(null)).toThrow(TransferError); + }); + + it("refuses a file from a newer version rather than half-reading it", () => { + const file = { ...toFile(pack()), version: 99 }; + expect(() => fromFile(file)).toThrow(/newer version/); + }); + + it("refuses a template with no sections", () => { + const file = toFile(pack()); + file.template.sections = []; + expect(() => fromFile(file)).toThrow(/no sections/); + }); + + it("drops a dependency on a section that did not travel", () => { + const file = toFile(pack()); + file.template.sections[1].dependsOn = ["research", "a-section-left-behind"]; + expect(fromFile(file).sections[1].dependsOn).toEqual(["research"]); + }); + + it("keeps an output only while the sections it names are here", () => { + const file = toFile(pack()); + file.template.outputs = [ + { key: "en", label: "EN", sections: ["script-en"] }, + { key: "bn", label: "BN", sections: ["script-bn"] }, + ]; + expect(fromFile(file).outputs.map((o) => o.key)).toEqual(["en"]); + }); +}); + +describe("fileNameFor", () => { + it("is the slug rule plus a suffix", () => { + expect(fileNameFor("ENBN Website Content")).toBe( + "enbn-website-content.template.json", + ); + }); + + it("still gives a usable name when the title slugs to nothing", () => { + expect(slug("বাংলা")).toBe(""); + expect(fileNameFor("বাংলা")).toBe("template.template.json"); + }); +}); diff --git a/vitest.config.mts b/vitest.config.mts new file mode 100644 index 0000000..6cdb821 --- /dev/null +++ b/vitest.config.mts @@ -0,0 +1,22 @@ +import { defineConfig } from "vitest/config"; + +/** + * Unit tests, for the logic a screenshot cannot check. + * + * Deliberately narrow. No component tests and no database: what these cover is + * the pure functions everything else stands on — the status a row shows, the + * slug a URL resolves by, what an imported template turns into, what the + * researcher makes of a model's answer. Those are the things that fail + * silently, days later, on one row. + * + * `.mts` because the package is CommonJS and this file is ESM; `tsconfigPaths` + * is what makes `@/lib/...` resolve the way it does in the app, so a test + * imports the real module rather than a copy of it. + */ +export default defineConfig({ + resolve: { tsconfigPaths: true }, + test: { + environment: "node", + include: ["tests/**/*.test.ts"], + }, +}); From 6a9fc3c7d3a7e18f121db203d42d72421ebdcbc6 Mon Sep 17 00:00:00 2001 From: shimentosh Date: Thu, 3 Sep 2026 20:59:31 +0600 Subject: [PATCH 2/8] Stream uploads to disk with a 512MB cap; docs tree and README current - ingestFile takes the request's stream and pipes it into the source's directory through a byte counter; past MAX_UPLOAD_BYTES the pipeline is torn down and the partial file removed. The route rejects the declared size first. Previously the whole upload was buffered twice in memory. - Dead orphanSourceDirs helper removed. - ARCHITECTURE "Where things live" and README layout/routes list the hooks, tools/, slug.ts, tests/, the workflow, proxy.ts, and the new API routes. Co-Authored-By: Claude Fable 5.1 --- README.md | 24 +++++++++--- app/api/sources/upload/route.ts | 11 +++++- docs/ARCHITECTURE.md | 9 +++++ docs/DECISIONS.md | 10 +++++ lib/server/services/ingest.ts | 67 ++++++++++++++++++++++++++------- 5 files changed, 100 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index f452431..8b717ae 100644 --- a/README.md +++ b/README.md @@ -45,11 +45,15 @@ and Noto Sans Bengali for the Bangla script screens). | `/content/[topic]` | One document | | `/packs` | Pack library — the shipped pack and anything written here | | `/pack/[slug]` | One pack: its real sections, its rules, what it asks for | -| `/builder` | Writing a pack — saves to the database | +| `/builder` | Writing a new template — saving moves it to its own URL | +| `/builder/[slug]` | Editing that template | | `/runs/[id]` | A run as it happens, section by section | | `/login`, `/signup` | Sign in; claim the console (open only while it has no owner) | | `/integrations` | What this machine can actually reach, probed live | -| `/tools`, `/settings` | Tools; preferences, keys and the account | +| `/tools` | This workspace's bench, grouped by category | +| `/tools/manage` | Every tool: category, on/off, which workspaces it stands in | +| `/tools/[tool]` | One tool — Content Research, or the video researcher | +| `/settings` | Preferences, keys, team and the account | Three overlays render above any route: the **Run Pack** sheet, the **Add Section** sheet, and the **command palette** (`⌘K` / `Ctrl+K`, `Esc` to close). @@ -66,14 +70,20 @@ components/ views/ one component per screen overlays/ run-setup, add-section, command palette ui/ Hov (hover/press styles), Popover, Icons + tools/ the interactive pieces of a tool's screen (FramePicker) lib/ data.ts what is left of the design's strings and numbers store.tsx client state, hydrated from the API and written back + use-*.ts a screen's data logic as a hook (content list, run document) + slug.ts the one rule for turning a name into part of a URL packs-client.ts the pack API, and the brief <-> runtime translation + packs-transfer.ts a template as a file: export, import, validation runs-client.ts the run API + tools-client.ts the tool bench, uploads, and the researcher theme.ts fonts, colors, repeated style fragments config.ts advancedNav / runSpeed, the canvas's two props server/ everything that touches the database (see below) +tests/ vitest, pure functions only — `npm run check` design/ the imported source canvas, for reference ``` @@ -86,7 +96,7 @@ matters lives in React state any more. ``` docker-compose.yml Postgres 17 on 5437, one named volume -middleware.ts the lock on the front door +proxy.ts the lock on the front door (Next 16's middleware) lib/server/db/schema.ts the schema, as an ordered list of migrations lib/server/db/client.ts the pool, `q` / `one` / `tx`, and `ready()` lib/server/auth.ts scrypt passwords, session rows, `requireUser` @@ -94,12 +104,14 @@ lib/server/tools.ts what is installed, by running it lib/server/brains.ts the four models, each over a CLI or an API lib/server/repos/ rows in, objects out — workspaces, series, packs, runs, sources, settings -lib/server/services/ the rules that are not the database's job, - including the yt-dlp / ffmpeg / whisper ingest +lib/server/services/ the rules that are not the database's job: + runs, the yt-dlp / ffmpeg / whisper ingest, the + researcher that reads frames lib/packs/enbn-website.ts the shipped pack: rules, 12 sections, instructions lib/server/prompt.ts system = voice + rules, user = source + inputs + deps app/api/ auth, settings, integrations, sources, workspaces, - series, topics, packs, runs + series, topics, packs, runs, tools, research — + every route outside auth calls requireUser() ``` ### Signing in diff --git a/app/api/sources/upload/route.ts b/app/api/sources/upload/route.ts index a8d3196..bcbb858 100644 --- a/app/api/sources/upload/route.ts +++ b/app/api/sources/upload/route.ts @@ -1,5 +1,5 @@ import { requireUser } from "@/lib/server/auth"; -import { ingestFile } from "@/lib/server/services/ingest"; +import { MAX_UPLOAD_BYTES, ingestFile } from "@/lib/server/services/ingest"; import { caught, fail, ok, ready } from "@/lib/server/http"; /** Frames and a transcript off an uploaded file. Minutes. */ @@ -20,12 +20,19 @@ export async function POST(request: Request) { const file = form?.get("file"); if (!(file instanceof File)) return fail("Choose a video file"); if (!file.size) return fail("That file is empty"); + // The declared size, before a byte is read. The stream re-checks the truth. + if (file.size > MAX_UPLOAD_BYTES) { + return fail( + `That file is over ${Math.round(MAX_UPLOAD_BYTES / 1048576)}MB — trim it or export it smaller.`, + 413, + ); + } const workspaceId = form?.get("workspaceId"); return ok( await ingestFile({ filename: file.name, - bytes: Buffer.from(await file.arrayBuffer()), + stream: file.stream(), workspaceId: typeof workspaceId === "string" ? workspaceId : null, }), 201, diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ea512aa..9fb9726 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -49,13 +49,22 @@ components/views/ one file per screen components/overlays/ full-window things: sheets, dialogs, command palette, reading mode components/ui/ the kit — read components/ui/README.md before adding to it components/topics/ TopicAdmin: the topic controls, mounted inside Content +components/tools/ pieces of a tool's screen with real interaction (FramePicker) lib/*-client.ts browser-side fetch wrappers for the API +lib/use-*.ts a screen's data logic as a hook — what can be reasoned + about without rendering (use-content-list, use-run-document, + use-run-watch) lib/store.tsx client state, navigation (`go`), filters +lib/slug.ts the one rule for turning a name into part of a URL lib/theme.ts tokens: t(), w(), font, spring, panel(), layer lib/server/ server-only: auth, db, repos, services, prompt building lib/server/db/ Postgres pool + the schema as an ordered migration list lib/server/repos/ one module per table +lib/server/services/ the rules between a route and a repo: runs, ingest, + researcher, seed lib/packs/ the shipped template(s), as code +tests/ vitest, pure functions only — `npm run check` runs them +.github/workflows/ the same checks, on every push ``` ## How a change reaches the screen diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 6469c99..5d6d78e 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -120,6 +120,16 @@ Runs are untouched; `runs.topic_id` outlives the topic and a moved topic keeps its id. The Series screen marks duplicate rows and offers the merge; which copy is the real one is the user's call. +## An upload is streamed to disk and capped, never buffered + +`await file.arrayBuffer()` held the whole upload in memory, then `Buffer.from` +made a second copy — a 400MB recording was 800MB of heap in one route, and the +Node process was what fell over, not the request. The upload route now hands +`file.stream()` to the ingest, which pipes it to the source's directory through +a counter that tears the pipeline down past `MAX_UPLOAD_BYTES` (512MB) and +removes the partial file. The declared size is checked first, as a courtesy; +the bytes are checked as they pass, because the header is a claim. + ## A screen's data logic lives in a hook beside it, not in the screen DocumentView and ContentGroupsView were each eighteen hundred lines: fetching, diff --git a/lib/server/services/ingest.ts b/lib/server/services/ingest.ts index 8016527..b0506f1 100644 --- a/lib/server/services/ingest.ts +++ b/lib/server/services/ingest.ts @@ -1,5 +1,8 @@ import fs from "node:fs/promises"; +import { createWriteStream } from "node:fs"; import path from "node:path"; +import { Readable, Transform } from "node:stream"; +import { pipeline } from "node:stream/promises"; import { requireTool, run, toolStatus } from "@/lib/server/tools"; import { getSettings } from "@/lib/server/repos/settings"; @@ -8,7 +11,6 @@ import { deleteSource, findByUrl, getSource, - listSources, updateSource, type Frame, type Source, @@ -114,6 +116,17 @@ export async function ingest(input: { } } +/** + * The most an upload may be. + * + * A reel at 720p is tens of megabytes; a raw phone recording of one is a few + * hundred. Half a gigabyte is above anything this is for and below anything + * that would fill the disk by accident. Checked twice: on the declared size + * before a byte is read, and on the bytes as they arrive, because the first is + * a claim and the second is the truth. + */ +export const MAX_UPLOAD_BYTES = 512 * 1024 * 1024; + /** * A video somebody had on their machine. * @@ -122,10 +135,16 @@ export async function ingest(input: { * one is. Footage that was never posted anywhere is the ordinary case for * research — a screen recording, a client's export, a reel saved months ago — * and it had no way in at all while a URL was the only input. + * + * Streamed to disk, not buffered. `await file.arrayBuffer()` holds the whole + * upload in memory — a 400MB recording became 400MB of heap in the route, then + * a second copy in the Buffer — and Node's process was the thing that fell + * over, not the request. */ export async function ingestFile(input: { filename: string; - bytes: Buffer; + /** The upload's bytes, as the request hands them over. */ + stream: ReadableStream; workspaceId?: string | null; }): Promise { const name = input.filename.trim() || "video.mp4"; @@ -146,7 +165,7 @@ export async function ingestFile(input: { const dir = dirFor(source.id); await fs.mkdir(dir, { recursive: true }); const file = path.join(dir, `video${ext}`); - await fs.writeFile(file, input.bytes); + await writeCapped(input.stream, file); const seconds = await durationOf(file); const frames = await cutFrames(file, dir); @@ -239,18 +258,40 @@ export async function removeSource(sourceId: string) { } /** - * Directories under .data/sources with no row behind them. + * Stream an upload to disk, refusing it the moment it passes the cap. * - * Left by every delete before `removeSource` existed, and by an ingest that - * died between writing the file and writing the row. Reported rather than - * removed on sight — this is somebody's downloaded footage, and the caller - * decides. + * Counted as the bytes pass rather than trusted from the header: a client can + * say 10MB and send 10GB. Past the limit the pipeline is torn down, the + * partial file removed, and the caller gets a sentence with the number in it. */ -export async function orphanSourceDirs() { - const dirs = await fs.readdir(DATA).catch(() => [] as string[]); - const rows = await listSources(); - const known = new Set(rows.map((r) => r.id)); - return dirs.filter((d) => d.startsWith("src_") && !known.has(d)); +async function writeCapped(stream: ReadableStream, file: string) { + let seen = 0; + const cap = new Transform({ + transform(chunk: Buffer, _enc, done) { + seen += chunk.length; + if (seen > MAX_UPLOAD_BYTES) { + done( + new IngestError( + `That file is over ${Math.round(MAX_UPLOAD_BYTES / 1048576)}MB — trim it or export it smaller.`, + 413, + ), + ); + return; + } + done(null, chunk); + }, + }); + + try { + await pipeline( + Readable.fromWeb(stream as import("node:stream/web").ReadableStream), + cap, + createWriteStream(file), + ); + } catch (e) { + await fs.rm(file, { force: true }).catch(() => {}); + throw e; + } } /** The bytes of one frame, for a model that is going to look at it. */ From 4c9faa2d4546f8e795beb59ce1fd9bf9d6d74eaf Mon Sep 17 00:00:00 2001 From: shimentosh Date: Thu, 3 Sep 2026 21:33:15 +0600 Subject: [PATCH 3/8] Backend moves to NestJS: api/ service on :4000, browser calls it cross-origin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - api/: NestJS 12, one module, ten controllers over the shared lib/server (repos, services, run driver, ingest, researcher). A global SessionGuard closes every route by default; @Public() opens the four sign-in routes. ErrorsFilter answers exactly as caught() did ({error}, 503 offline, 409 + existing on DuplicateName). Streamed multipart upload via busboy. - app/api/** removed (35 handlers). proxy.ts guards pages only. - lib/server/auth.ts no longer reads Next's cookie jar; currentUser and requireUser take the session id. The only Next-bound line is gone. - lib/api-base.ts: NEXT_PUBLIC_API_URL + apiFetch (credentials: include); all 64 browser calls and the frame URL go through it. - One data root for both processes (CONTENTOS_DATA_DIR). - Deploy: api/Dockerfile (ffmpeg, yt-dlp move here), compose runs api + app on API_HOST / APP_HOST behind Traefik, cookie shared via COOKIE_DOMAIN, NEXT_PUBLIC_API_URL as a build arg. start.sh runs both. CI builds the API. - Docs: ARCHITECTURE, DEVELOPING, DEPLOYING, README, DECISIONS. Verified: guard/CORS probes, upload → frames → delete on the API, compiled dist run the way the image runs it, web app calling only :4000, production build of the web app, npm run check green. Co-Authored-By: Claude Fable 5.1 --- .env.production.example | 11 +- .github/workflows/check.yml | 3 + .gitignore | 4 + Dockerfile | 14 +- README.md | 19 +- api/Dockerfile | 48 + api/nest-cli.json | 5 + api/package-lock.json | 1868 +++++++++++++++++ api/package.json | 32 + api/src/app.module.ts | 49 + api/src/auth/auth.controller.ts | 164 ++ api/src/common/cookie.ts | 40 + api/src/common/errors.filter.ts | 70 + api/src/common/session.guard.ts | 52 + api/src/common/user.decorator.ts | 21 + .../integrations/integrations.controller.ts | 95 +- api/src/main.ts | 63 + api/src/packs/packs.controller.ts | 73 + api/src/research/research.controller.ts | 23 + api/src/runs/runs.controller.ts | 130 ++ api/src/series/series.controller.ts | 158 ++ api/src/settings/settings.controller.ts | 58 + api/src/sources/sources.controller.ts | 160 ++ api/src/tools/tools.controller.ts | 47 + api/src/workspaces/workspaces.controller.ts | 64 + api/tsconfig.json | 21 + app/api/auth/login/route.ts | 32 - app/api/auth/logout/route.ts | 21 - app/api/auth/me/route.ts | 12 - app/api/auth/password/route.ts | 34 - app/api/auth/sessions/route.ts | 30 - app/api/auth/signup/route.ts | 50 - app/api/integrations/route.ts | 72 - app/api/invites/[token]/route.ts | 18 - app/api/invites/route.ts | 43 - app/api/packs/[slug]/route.ts | 79 - app/api/packs/route.ts | 32 - app/api/research/route.ts | 28 - app/api/runs/[id]/route.ts | 65 - .../runs/[id]/sections/[sectionId]/route.ts | 47 - app/api/runs/[id]/start/route.ts | 49 - app/api/runs/route.ts | 50 - app/api/series/[id]/merge/route.ts | 26 - app/api/series/[id]/route.ts | 103 - app/api/series/[id]/source/route.ts | 60 - app/api/series/route.ts | 57 - app/api/settings/keys/route.ts | 53 - app/api/settings/route.ts | 23 - app/api/sources/[id]/frames/[file]/route.ts | 32 - app/api/sources/[id]/frames/route.ts | 24 - app/api/sources/[id]/route.ts | 33 - app/api/sources/route.ts | 48 - app/api/sources/upload/route.ts | 43 - app/api/tools/[slug]/route.ts | 34 - app/api/tools/route.ts | 21 - app/api/topics/[id]/route.ts | 32 - app/api/users/[id]/route.ts | 18 - app/api/users/route.ts | 13 - app/api/workspaces/[id]/route.ts | 62 - app/api/workspaces/route.ts | 33 - components/Header.tsx | 5 +- components/settings/TeamPanel.tsx | 11 +- components/views/AuthView.tsx | 5 +- components/views/SettingsView.tsx | 15 +- docker-compose.prod.yml | 38 +- docs/ARCHITECTURE.md | 36 +- docs/DECISIONS.md | 30 + docs/DEPLOYING.md | 22 +- docs/DEVELOPING.md | 13 +- eslint.config.mjs | 4 + lib/api-base.ts | 23 + lib/decisions.ts | 3 +- lib/integrations-client.ts | 17 +- lib/packs-client.ts | 13 +- lib/runs-client.ts | 19 +- lib/server/auth.ts | 23 +- lib/server/services/ingest.ts | 12 +- lib/server/services/seed.ts | 3 +- lib/sources-client.ts | 11 +- lib/store.tsx | 27 +- lib/tools-client.ts | 15 +- package.json | 5 +- proxy.ts | 36 +- start.sh | 25 +- tsconfig.json | 4 +- 85 files changed, 3519 insertions(+), 1565 deletions(-) create mode 100644 api/Dockerfile create mode 100644 api/nest-cli.json create mode 100644 api/package-lock.json create mode 100644 api/package.json create mode 100644 api/src/app.module.ts create mode 100644 api/src/auth/auth.controller.ts create mode 100644 api/src/common/cookie.ts create mode 100644 api/src/common/errors.filter.ts create mode 100644 api/src/common/session.guard.ts create mode 100644 api/src/common/user.decorator.ts rename app/api/integrations/test/route.ts => api/src/integrations/integrations.controller.ts (51%) create mode 100644 api/src/main.ts create mode 100644 api/src/packs/packs.controller.ts create mode 100644 api/src/research/research.controller.ts create mode 100644 api/src/runs/runs.controller.ts create mode 100644 api/src/series/series.controller.ts create mode 100644 api/src/settings/settings.controller.ts create mode 100644 api/src/sources/sources.controller.ts create mode 100644 api/src/tools/tools.controller.ts create mode 100644 api/src/workspaces/workspaces.controller.ts create mode 100644 api/tsconfig.json delete mode 100644 app/api/auth/login/route.ts delete mode 100644 app/api/auth/logout/route.ts delete mode 100644 app/api/auth/me/route.ts delete mode 100644 app/api/auth/password/route.ts delete mode 100644 app/api/auth/sessions/route.ts delete mode 100644 app/api/auth/signup/route.ts delete mode 100644 app/api/integrations/route.ts delete mode 100644 app/api/invites/[token]/route.ts delete mode 100644 app/api/invites/route.ts delete mode 100644 app/api/packs/[slug]/route.ts delete mode 100644 app/api/packs/route.ts delete mode 100644 app/api/research/route.ts delete mode 100644 app/api/runs/[id]/route.ts delete mode 100644 app/api/runs/[id]/sections/[sectionId]/route.ts delete mode 100644 app/api/runs/[id]/start/route.ts delete mode 100644 app/api/runs/route.ts delete mode 100644 app/api/series/[id]/merge/route.ts delete mode 100644 app/api/series/[id]/route.ts delete mode 100644 app/api/series/[id]/source/route.ts delete mode 100644 app/api/series/route.ts delete mode 100644 app/api/settings/keys/route.ts delete mode 100644 app/api/settings/route.ts delete mode 100644 app/api/sources/[id]/frames/[file]/route.ts delete mode 100644 app/api/sources/[id]/frames/route.ts delete mode 100644 app/api/sources/[id]/route.ts delete mode 100644 app/api/sources/route.ts delete mode 100644 app/api/sources/upload/route.ts delete mode 100644 app/api/tools/[slug]/route.ts delete mode 100644 app/api/tools/route.ts delete mode 100644 app/api/topics/[id]/route.ts delete mode 100644 app/api/users/[id]/route.ts delete mode 100644 app/api/users/route.ts delete mode 100644 app/api/workspaces/[id]/route.ts delete mode 100644 app/api/workspaces/route.ts create mode 100644 lib/api-base.ts diff --git a/.env.production.example b/.env.production.example index daa52fe..73055a4 100644 --- a/.env.production.example +++ b/.env.production.example @@ -3,10 +3,19 @@ # The database password. Anything long and random. POSTGRES_PASSWORD= -# The domain the console answers on, and the address Let's Encrypt writes to. +# The two hostnames: the web app, and the NestJS API the browser talks to. +# Both get their own certificate from Let's Encrypt at ACME_EMAIL. APP_HOST=content.yourcompany.com +API_HOST=api.content.yourcompany.com ACME_EMAIL=you@yourcompany.com +# The session cookie has to be readable on BOTH hosts: the API sets it, the +# web app's proxy checks for it. A shared parent domain does that. Leave +# COOKIE_SAMESITE at lax while the two hosts share a site; set it to none +# only if they do not (then Secure is forced, and the domain must be set). +COOKIE_DOMAIN=.content.yourcompany.com +COOKIE_SAMESITE=lax + # Encrypts the API keys stored in the settings table. # # MOVE THE EXISTING VALUE from your local .env. A different secret does not diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 3f8f88a..ce345f4 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -20,7 +20,10 @@ jobs: node-version: 24 cache: npm - run: npm ci + - run: npm ci --prefix api - run: npm run check # Into .next-check, so it can never be confused with a dev server's # output — see next.config.ts. - run: npm run build:check + # The API compiles on its own; the image is what a server runs. + - run: npm run build --prefix api diff --git a/.gitignore b/.gitignore index 60f3b54..2f0ba7c 100644 --- a/.gitignore +++ b/.gitignore @@ -57,3 +57,7 @@ next-env.d.ts # the real production secrets .env.production + +# the NestJS API has its own install and build output +api/node_modules +api/dist diff --git a/Dockerfile b/Dockerfile index 6bf366c..c29e1cb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,6 +12,9 @@ FROM node:24-bookworm-slim AS build WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY . . +# Read by the browser bundle, so it has to be known when the bundle is built. +ARG NEXT_PUBLIC_API_URL +ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL # `output: "standalone"` in next.config.ts is what makes .next/standalone a # server that can run without node_modules beside it. RUN npm run build @@ -21,20 +24,11 @@ WORKDIR /app ENV NODE_ENV=production ENV PORT=3333 -# The tools the Integrations page probes for. Without them the app still runs; -# source-video features report the binary as missing, which is the truth. -RUN apt-get update \ - && apt-get install -y --no-install-recommends ffmpeg python3 ca-certificates curl \ - && curl -fsSL https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp \ - && chmod a+rx /usr/local/bin/yt-dlp \ - && rm -rf /var/lib/apt/lists/* +# No ffmpeg or yt-dlp here any more: the ingest runs in the API's image. COPY --from=build /app/public ./public COPY --from=build /app/.next/standalone ./ COPY --from=build /app/.next/static ./.next/static -# Migrations run from the image on deploy, before the server takes traffic. -COPY --from=build /app/scripts ./scripts -COPY --from=build /app/lib/server/db ./lib/server/db EXPOSE 3333 CMD ["node", "server.js"] diff --git a/README.md b/README.md index 8b717ae..6bcabbe 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,9 @@ production dashboard where **topics** feed **packs**, packs run to produce ```bash npm run db:up # Postgres in Docker, on 5437 -./start.sh # dev server on http://localhost:3333 -./start.sh prod # production build, then serve it on 3333 -PORT=4000 ./start.sh # any other port +./start.sh # the NestJS API on :4000 and the Next dev server on :3333 +./start.sh prod # production builds of both, then serve both +PORT=3400 ./start.sh # any other web port (API_PORT for the API's) ``` `./start.sh` brings the database up itself and says so if it cannot — every @@ -29,7 +29,10 @@ which default to port 3000. ## Stack -Next.js 16 (App Router, Turbopack) · React 19 · TypeScript. No CSS framework: +**Frontend:** Next.js 16 (App Router, Turbopack) · React 19 · TypeScript. +**Backend:** NestJS 12 in `api/`, its own process on port 4000, sharing +`lib/server` (the repos, the run driver, the ingest) with the root. The +browser calls it directly at `NEXT_PUBLIC_API_URL`; there is no `app/api`. No CSS framework: the design is expressed in inline styles, matching the source canvas one declaration at a time, with shared fragments in [lib/theme.ts](lib/theme.ts). Fonts are self-hosted through `next/font` (Inter, Inter Tight, JetBrains Mono, @@ -96,7 +99,10 @@ matters lives in React state any more. ``` docker-compose.yml Postgres 17 on 5437, one named volume -proxy.ts the lock on the front door (Next 16's middleware) +proxy.ts the front door: pages need a session cookie +api/src/main.ts the NestJS service: CORS, cookies, migrate + seed +api/src/common/ SessionGuard (global, closed by default), errors +api/src// one controller per feature, over lib/server lib/server/db/schema.ts the schema, as an ordered list of migrations lib/server/db/client.ts the pool, `q` / `one` / `tx`, and `ready()` lib/server/auth.ts scrypt passwords, session rows, `requireUser` @@ -109,9 +115,6 @@ lib/server/services/ the rules that are not the database's job: researcher that reads frames lib/packs/enbn-website.ts the shipped pack: rules, 12 sections, instructions lib/server/prompt.ts system = voice + rules, user = source + inputs + deps -app/api/ auth, settings, integrations, sources, workspaces, - series, topics, packs, runs, tools, research — - every route outside auth calls requireUser() ``` ### Signing in diff --git a/api/Dockerfile b/api/Dockerfile new file mode 100644 index 0000000..5577c39 --- /dev/null +++ b/api/Dockerfile @@ -0,0 +1,48 @@ +# The API, as a server runs it. +# +# Built from the REPO ROOT as context (`docker build -f api/Dockerfile .`), +# because the service shares lib/server with the web app: the repos, the run +# driver, the ingest. The image carries only what a request actually reaches — +# the compiled TypeScript and the binaries the ingest shells out to. +FROM node:24-bookworm-slim AS deps +WORKDIR /app/api +COPY api/package.json api/package-lock.json* ./ +RUN npm ci + +FROM node:24-bookworm-slim AS build +WORKDIR /app +COPY --from=deps /app/api/node_modules ./api/node_modules +# The shared code, and the root packages it imports (pg, the Anthropic SDK). +COPY package.json package-lock.json* ./ +RUN npm ci --omit=dev +COPY lib ./lib +COPY api ./api +RUN cd api && npm run build + +FROM node:24-bookworm-slim AS runtime +WORKDIR /app +ENV NODE_ENV=production +ENV PORT=4000 +# `@/lib/...` inside the compiled output points at dist, not at the sources. +ENV TS_NODE_BASEURL=./dist +# Downloads and frames live here; mount a volume on it. +ENV CONTENTOS_DATA_DIR=/app/.data + +# The tools the ingest runs. Without them the API still starts; source-video +# features report the binary as missing, which is the truth. +RUN apt-get update \ + && apt-get install -y --no-install-recommends ffmpeg python3 ca-certificates curl \ + && curl -fsSL https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp \ + && chmod a+rx /usr/local/bin/yt-dlp \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=build /app/node_modules ./node_modules +COPY --from=build /app/api/node_modules ./api/node_modules +COPY --from=build /app/api/dist ./api/dist +COPY --from=build /app/api/package.json /app/api/tsconfig.json ./api/ + +WORKDIR /app/api +EXPOSE 4000 +# tsconfig-paths resolves the `@/` imports inside the compiled output, the +# same way ts-node does in development. +CMD ["node", "-r", "tsconfig-paths/register", "dist/api/src/main.js"] diff --git a/api/nest-cli.json b/api/nest-cli.json new file mode 100644 index 0000000..2566481 --- /dev/null +++ b/api/nest-cli.json @@ -0,0 +1,5 @@ +{ + "$schema": "https://json.schemastore.org/nest-cli", + "collection": "@nestjs/schematics", + "sourceRoot": "src" +} diff --git a/api/package-lock.json b/api/package-lock.json new file mode 100644 index 0000000..54eb391 --- /dev/null +++ b/api/package-lock.json @@ -0,0 +1,1868 @@ +{ + "name": "contentos-api", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "contentos-api", + "version": "0.1.0", + "dependencies": { + "@nestjs/common": "^12.0.1", + "@nestjs/core": "^12.0.1", + "@nestjs/platform-express": "^12.0.1", + "busboy": "^1.6.0", + "cookie-parser": "^1.4.7", + "reflect-metadata": "^0.2.2", + "rxjs": "^7.8.2", + "tsconfig-paths": "^4.2.0" + }, + "devDependencies": { + "@types/busboy": "^1.5.4", + "@types/cookie-parser": "^1.4.9", + "@types/express": "^5.0.3", + "@types/node": "^24.13.3", + "cross-env": "^7.0.3", + "ts-node": "^10.9.2", + "typescript": "^5" + } + }, + "node_modules/@borewit/text-codec": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.2.2.tgz", + "integrity": "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@lukeed/csprng": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz", + "integrity": "sha512-Z7C/xXCiGWsg0KuKsHTKJxbWhpI3Vs5GwLfOean7MGyVFGqdRgBbAjOCh6u4bbjPc/8MJ2pZmK/0DLdCbivLDA==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@nestjs/common": { + "version": "12.0.1", + "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-12.0.1.tgz", + "integrity": "sha512-v0zTaRCTV2K2xSnb3GnJoQKtaR6VxouJtm+P2gpr5w61dlXeWpXl1WVknCSzUqx2QwTV10tBkHETxvQvkf2Exg==", + "license": "MIT", + "peer": true, + "dependencies": { + "@standard-schema/spec": "1.1.0", + "file-type": "22.0.2", + "iterare": "1.2.1", + "load-esm": "1.0.3", + "tslib": "2.8.1", + "uid": "2.0.2" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "class-transformer": ">=0.4.1", + "class-validator": ">=0.13.2", + "reflect-metadata": "^0.1.12 || ^0.2.0", + "rxjs": "^7.1.0" + }, + "peerDependenciesMeta": { + "class-transformer": { + "optional": true + }, + "class-validator": { + "optional": true + } + } + }, + "node_modules/@nestjs/core": { + "version": "12.0.1", + "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-12.0.1.tgz", + "integrity": "sha512-rU6tAi8vDdyzHgN0iW0J4UJvziroOqzHqzlqL7phOSPizaXVEePfv+OUOsdJEOh0Qd14mslc3udOheLrAEcZow==", + "license": "MIT", + "peer": true, + "dependencies": { + "fast-safe-stringify": "2.1.1", + "iterare": "1.2.1", + "path-to-regexp": "8.4.2", + "tslib": "2.8.1", + "uid": "2.0.2" + }, + "engines": { + "node": ">= 20" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^12.0.0", + "@nestjs/microservices": "^12.0.0", + "@nestjs/platform-express": "^12.0.0", + "@nestjs/websockets": "^12.0.0", + "reflect-metadata": "^0.1.12 || ^0.2.0", + "rxjs": "^7.1.0" + }, + "peerDependenciesMeta": { + "@nestjs/microservices": { + "optional": true + }, + "@nestjs/platform-express": { + "optional": true + }, + "@nestjs/websockets": { + "optional": true + } + } + }, + "node_modules/@nestjs/platform-express": { + "version": "12.0.1", + "resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-12.0.1.tgz", + "integrity": "sha512-nF8bRgROptMyixYBfiJUAsjj2o9k13zxAjUKYaqHTPk8mTSd+gk7hXz6NykXNrfHWmMEYC9RttQlMUdMHNTbuA==", + "license": "MIT", + "peer": true, + "dependencies": { + "cors": "2.8.6", + "express": "5.2.1", + "multer": "2.2.0", + "path-to-regexp": "8.4.2", + "tslib": "2.8.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^12.0.0", + "@nestjs/core": "^12.0.0" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/@tokenizer/inflate": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.4.1.tgz", + "integrity": "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "token-types": "^6.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@tokenizer/token": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", + "license": "MIT" + }, + "node_modules/@tsconfig/node10": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.13.tgz", + "integrity": "sha512-gcLdvR9HO1ZJBypsOGqaP6TFEzb6vIta0KSTLt9NAQ6pXQO3cRgSVyCN6pzYqI9DlJgY71XKO0dpDhCf08b3pg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/busboy": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/@types/busboy/-/busboy-1.5.4.tgz", + "integrity": "sha512-kG7WrUuAKK0NoyxfQHsVE6j1m01s6kMma64E+OZenQABMQyTJop1DumUWcLwAQ2JzpefU7PDYoRDKl8uZosFjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/cookie-parser": { + "version": "1.4.10", + "resolved": "https://registry.npmjs.org/@types/cookie-parser/-/cookie-parser-1.4.10.tgz", + "integrity": "sha512-B4xqkqfZ8Wek+rCOeRxsjMS9OgvzebEzzLYw7NHYuvzb7IdxOkI0ZHGgeEBX4PUM7QGVvNSK60T3OvWj3YfBRg==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/express": "*" + } + }, + "node_modules/@types/express": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz", + "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^5.0.0", + "@types/serve-static": "^2" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.3.tgz", + "integrity": "sha512-dPfW8NFiOF4wOHc7+N/QSxlY9cfSsenewGbAz8C8U/MULPd/YZ27LvJUIlzaXie7e6Ove9YunJGgC9tbHD2cKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.13.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz", + "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "undici-types": "~7.18.0" + } + }, + "node_modules/@types/qs": { + "version": "6.15.1", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz", + "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", + "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", + "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true, + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "engines": [ + "node >= 6.0" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-parser": { + "version": "1.4.7", + "resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.7.tgz", + "integrity": "sha512-nGUvgXnotP3BsjiLX2ypbQnWoGUPIIfHQNZkkC668ntrzGWEZVW70HDEB1qnNGMicPje6EttlIgzo51YSwNQGw==", + "license": "MIT", + "dependencies": { + "cookie": "0.7.2", + "cookie-signature": "1.0.6" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "license": "MIT" + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-env": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz", + "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.1" + }, + "bin": { + "cross-env": "src/bin/cross-env.js", + "cross-env-shell": "src/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=10.14", + "npm": ">=6", + "yarn": ">=1" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/diff": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", + "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express/node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "license": "MIT" + }, + "node_modules/file-type": { + "version": "22.0.2", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-22.0.2.tgz", + "integrity": "sha512-0H8TsCUGBLx+V5adH3EY52hTAcyLKbV1D4gq5cIOJ6DnQAHeV9Z2Hhuc5CoBX4YmvB2oL+JIC84z0qO7JsCoNw==", + "license": "MIT", + "dependencies": { + "@tokenizer/inflate": "^0.4.1", + "strtok3": "^10.3.5", + "token-types": "^6.1.2", + "uint8array-extras": "^1.5.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/iterare": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/iterare/-/iterare-1.2.1.tgz", + "integrity": "sha512-RKYVTCjAnRthyJes037NX/IiqeidgN1xc3j1RjFfECFp28A1GVwK9nA+i0rJPaHqSZwygLzRnFlzUuHFoWWy+Q==", + "license": "ISC", + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/load-esm": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/load-esm/-/load-esm-1.0.3.tgz", + "integrity": "sha512-v5xlu8eHD1+6r8EHTg6hfmO97LN8ugKtiXcy5e6oN72iD2r6u0RPfLl6fxM+7Wnh2ZRq15o0russMst44WauPA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + { + "type": "buymeacoffee", + "url": "https://buymeacoffee.com/borewit" + } + ], + "license": "MIT", + "engines": { + "node": ">=13.2.0" + } + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true, + "license": "ISC" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/multer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.2.0.tgz", + "integrity": "sha512-6rdyFg2kLrMh9Jee7/BMPuV9lEAd7lLW2YUpF9/YxR7njyoUwwQ0ZPh3TaIY50Sw6vlyD2HW3wGOkTS4P79xrQ==", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "concat-stream": "^2.0.0", + "type-is": "^1.6.18" + }, + "engines": { + "node": ">= 10.16.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/multer/node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/negotiator/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.16.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", + "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "license": "Apache-2.0", + "peer": true + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/strtok3": { + "version": "10.3.5", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.5.tgz", + "integrity": "sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA==", + "license": "MIT", + "dependencies": { + "@tokenizer/token": "^0.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/token-types": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.2.tgz", + "integrity": "sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww==", + "license": "MIT", + "dependencies": { + "@borewit/text-codec": "^0.2.1", + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "node_modules/tsconfig-paths": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-4.2.0.tgz", + "integrity": "sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==", + "license": "MIT", + "dependencies": { + "json5": "^2.2.2", + "minimist": "^1.2.6", + "strip-bom": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/uid": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/uid/-/uid-2.0.2.tgz", + "integrity": "sha512-u3xV3X7uzvi5b1MncmZo3i2Aw222Zk1keqLA1YkHldREkAhAqi65wuPfe7lHx8H/Wzy+8CE7S7uS3jekIM5s8g==", + "license": "MIT", + "dependencies": { + "@lukeed/csprng": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/uint8array-extras": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.5.0.tgz", + "integrity": "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + } + } +} diff --git a/api/package.json b/api/package.json new file mode 100644 index 0000000..ce4f013 --- /dev/null +++ b/api/package.json @@ -0,0 +1,32 @@ +{ + "name": "contentos-api", + "version": "0.1.0", + "private": true, + "description": "The Content OS backend, as a NestJS service. Shares lib/server with the repo root.", + "scripts": { + "dev": "cross-env TS_NODE_TRANSPILE_ONLY=1 CONTENTOS_DATA_DIR=../.data ts-node -r tsconfig-paths/register src/main.ts", + "build": "tsc -p tsconfig.json", + "start": "cross-env TS_NODE_BASEURL=./dist node -r tsconfig-paths/register dist/api/src/main.js", + "start:local": "cross-env TS_NODE_BASEURL=./dist CONTENTOS_DATA_DIR=../.data node -r tsconfig-paths/register dist/api/src/main.js", + "typecheck": "tsc -p tsconfig.json --noEmit" + }, + "dependencies": { + "@nestjs/common": "^12.0.1", + "@nestjs/core": "^12.0.1", + "@nestjs/platform-express": "^12.0.1", + "busboy": "^1.6.0", + "cookie-parser": "^1.4.7", + "reflect-metadata": "^0.2.2", + "rxjs": "^7.8.2", + "tsconfig-paths": "^4.2.0" + }, + "devDependencies": { + "@types/busboy": "^1.5.4", + "@types/cookie-parser": "^1.4.9", + "@types/express": "^5.0.3", + "@types/node": "^24.13.3", + "cross-env": "^7.0.3", + "ts-node": "^10.9.2", + "typescript": "^5" + } +} diff --git a/api/src/app.module.ts b/api/src/app.module.ts new file mode 100644 index 0000000..e647f3f --- /dev/null +++ b/api/src/app.module.ts @@ -0,0 +1,49 @@ +import { Module } from "@nestjs/common"; +import { APP_GUARD } from "@nestjs/core"; + +import { SessionGuard } from "./common/session.guard"; +import { AuthController } from "./auth/auth.controller"; +import { WorkspacesController } from "./workspaces/workspaces.controller"; +import { + SeriesController, + TopicsController, +} from "./series/series.controller"; +import { PacksController } from "./packs/packs.controller"; +import { ToolsController } from "./tools/tools.controller"; +import { SettingsController } from "./settings/settings.controller"; +import { IntegrationsController } from "./integrations/integrations.controller"; +import { RunsController } from "./runs/runs.controller"; +import { SourcesController } from "./sources/sources.controller"; +import { ResearchController } from "./research/research.controller"; + +/** + * One module, because there is one database and one set of rules. + * + * Nest's usual shape is a module per feature, each with its own providers. + * Here the "providers" are the functions in `lib/server` — repos and services + * shared with the repo root — and a controller is a thin translation from HTTP + * to those. Ten controllers in one module is honest about that; ten modules + * each importing nothing would be ceremony. + * + * The session guard is global. Every route is behind it unless the handler + * says otherwise with `@Public()` — the auth gap that the audit found was + * fifteen routes that each had to remember a line, and a default that fails + * closed cannot be forgotten. + */ +@Module({ + controllers: [ + AuthController, + WorkspacesController, + SeriesController, + TopicsController, + PacksController, + ToolsController, + SettingsController, + IntegrationsController, + RunsController, + SourcesController, + ResearchController, + ], + providers: [{ provide: APP_GUARD, useClass: SessionGuard }], +}) +export class AppModule {} diff --git a/api/src/auth/auth.controller.ts b/api/src/auth/auth.controller.ts new file mode 100644 index 0000000..f94c1a7 --- /dev/null +++ b/api/src/auth/auth.controller.ts @@ -0,0 +1,164 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpCode, + NotFoundException, + Param, + Post, + Res, +} from "@nestjs/common"; +import type { Response } from "express"; + +import { + authenticate, + createInvite, + createUser, + endOtherSessions, + endSession, + listInvites, + listSessions, + listUsers, + removeUser, + revokeInvite, + signupOpen, + startSession, + sweepSessions, + updatePassword, + type User, +} from "@/lib/server/auth"; + +import { clearSession, setSession } from "../common/cookie"; +import { Public } from "../common/session.guard"; +import { CurrentUser, SessionId } from "../common/user.decorator"; + +/** + * Signing in, signing up, and the people who can. + * + * The four routes a visitor reaches before they have a session are `@Public()`; + * everything else is behind the global guard. The cookie is set by this + * process, on this origin — see common/cookie.ts for what that means when the + * web app is somewhere else. + */ +@Controller() +export class AuthController { + @Public() + @Post("auth/login") + @HttpCode(200) + async login( + @Body() body: { email?: string; password?: string }, + @Headers("user-agent") agent: string | undefined, + @Res({ passthrough: true }) res: Response, + ) { + const user = await authenticate(body.email ?? "", body.password ?? ""); + void sweepSessions(); + setSession(res, await startSession(user.id, agent ?? "")); + return user; + } + + @Public() + @Get("auth/signup") + async signupOpen() { + return { open: await signupOpen() }; + } + + @Public() + @Post("auth/signup") + async signup( + @Body() + body: { email?: string; password?: string; name?: string; invite?: string }, + @Headers("user-agent") agent: string | undefined, + @Res({ passthrough: true }) res: Response, + ) { + const user = await createUser({ + email: body.email ?? "", + password: body.password ?? "", + name: body.name, + invite: body.invite, + }); + setSession(res, await startSession(user.id, agent ?? "")); + return user; + } + + @Public() + @Post("auth/logout") + @HttpCode(200) + async logout( + @SessionId() sid: string, + @Res({ passthrough: true }) res: Response, + ) { + if (sid) await endSession(sid); + clearSession(res); + return { ok: true }; + } + + /** Who is signed in, and whether the console still has no owner. */ + @Public() + @Get("auth/me") + async me(@CurrentUser() user: User | null) { + return { user, signupOpen: await signupOpen() }; + } + + @Post("auth/password") + @HttpCode(200) + async password( + @CurrentUser() user: User, + @Body() body: { current?: string; next?: string }, + @Headers("user-agent") agent: string | undefined, + @Res({ passthrough: true }) res: Response, + ) { + await updatePassword(user.id, body.current ?? "", body.next ?? ""); + // A new session on a new password: whatever knew the old one is out. + setSession(res, await startSession(user.id, agent ?? "")); + return { ok: true }; + } + + @Get("auth/sessions") + sessions(@CurrentUser() user: User, @SessionId() sid: string) { + return listSessions(user.id, sid); + } + + @Delete("auth/sessions") + async endOthers(@CurrentUser() user: User, @SessionId() sid: string) { + return { ended: await endOtherSessions(user.id, sid) }; + } + + @Get("invites") + invites() { + return listInvites(); + } + + @Post("invites") + invite( + @CurrentUser() user: User, + @Body() body: { email?: string; note?: string; days?: number }, + ) { + return createInvite({ + createdBy: user.id, + email: body.email, + note: body.note, + days: body.days, + }); + } + + @Delete("invites/:token") + async revoke(@Param("token") token: string) { + const gone = await revokeInvite(token); + if (!gone) throw new NotFoundException("That invite is already used"); + return { ok: true }; + } + + @Get("users") + users() { + return listUsers(); + } + + @Delete("users/:id") + async remove(@CurrentUser() me: User, @Param("id") id: string) { + const gone = await removeUser(id, me.id); + if (!gone) throw new NotFoundException("No such account"); + return { ok: true }; + } +} diff --git a/api/src/common/cookie.ts b/api/src/common/cookie.ts new file mode 100644 index 0000000..e10b889 --- /dev/null +++ b/api/src/common/cookie.ts @@ -0,0 +1,40 @@ +import type { CookieOptions, Response } from "express"; + +import { SESSION_COOKIE } from "@/lib/server/auth"; + +const SESSION_DAYS = 30; + +/** + * How the session cookie is set, on an API that lives on its own origin. + * + * The Next handlers set it same-origin with SameSite=Lax. Here the browser + * may be on app.example.com and this on api.example.com — same *site*, so Lax + * still travels — or on two unrelated hosts, where only SameSite=None with + * Secure does. Which one is a deployment fact, not a code one, so it is env: + * + * COOKIE_SAMESITE lax (default) | none | strict + * COOKIE_DOMAIN ".example.com" to share the cookie across subdomains, + * which is also what lets the Next proxy see it and send + * a signed-out visitor to /login instead of a blank shell. + * + * Secure is on in production regardless — a session cookie over plain HTTP + * is a session handed to the network. + */ +export function cookieOptions(maxAgeDays = SESSION_DAYS): CookieOptions { + const sameSite = (process.env.COOKIE_SAMESITE ?? "lax").toLowerCase(); + return { + httpOnly: true, + sameSite: + sameSite === "none" ? "none" : sameSite === "strict" ? "strict" : "lax", + secure: process.env.NODE_ENV === "production" || sameSite === "none", + path: "/", + ...(process.env.COOKIE_DOMAIN ? { domain: process.env.COOKIE_DOMAIN } : {}), + maxAge: maxAgeDays * 24 * 60 * 60 * 1000, + }; +} + +export const setSession = (res: Response, sid: string) => + res.cookie(SESSION_COOKIE, sid, cookieOptions()); + +export const clearSession = (res: Response) => + res.clearCookie(SESSION_COOKIE, { ...cookieOptions(), maxAge: undefined }); diff --git a/api/src/common/errors.filter.ts b/api/src/common/errors.filter.ts new file mode 100644 index 0000000..279a35d --- /dev/null +++ b/api/src/common/errors.filter.ts @@ -0,0 +1,70 @@ +import { + ArgumentsHost, + Catch, + ExceptionFilter, + HttpException, +} from "@nestjs/common"; +import type { Response } from "express"; + +import { DuplicateName } from "@/lib/server/repos/series"; + +/** + * Every thrown thing, as the JSON the browser already understands. + * + * The same rules `caught()` in lib/server/http.ts applies for the Next + * handlers, so the API answers identically whichever process is behind it: + * `{ error }` with the status the service asked for, 503 with a sentence + * when Postgres is not there, and `existing` beside the error on a duplicate + * name so the screen can offer the merge. + */ + +const OFFLINE = + /ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT|Connection terminated|connect ECONN/i; + +const isOffline = (e: unknown) => { + const code = (e as { code?: string })?.code ?? ""; + const message = e instanceof Error ? e.message : String(e); + return OFFLINE.test(code) || OFFLINE.test(message); +}; + +@Catch() +export class ErrorsFilter implements ExceptionFilter { + catch(e: unknown, host: ArgumentsHost) { + const res = host.switchToHttp().getResponse(); + + if (e instanceof HttpException) { + const body = e.getResponse(); + const message = + typeof body === "string" + ? body + : ((body as { message?: string | string[] }).message ?? e.message); + res.status(e.getStatus()).json({ + error: Array.isArray(message) ? message.join(", ") : message, + }); + return; + } + + if (e instanceof DuplicateName) { + res.status(409).json({ error: e.message, existing: e.existing }); + return; + } + + if (isOffline(e)) { + res.status(503).json({ + error: + "The database is not running. Start Docker Desktop, then run: npm run db:up", + }); + return; + } + + // AuthError, RunError, IngestError, ResearchError, FetchError all carry + // the status they want; anything without one is a 500 with its message. + const status = + typeof e === "object" && e && "status" in e + ? Number((e as { status: number }).status) + : 500; + res + .status(Number.isFinite(status) && status >= 400 ? status : 500) + .json({ error: e instanceof Error ? e.message : "Something went wrong" }); + } +} diff --git a/api/src/common/session.guard.ts b/api/src/common/session.guard.ts new file mode 100644 index 0000000..eadda0b --- /dev/null +++ b/api/src/common/session.guard.ts @@ -0,0 +1,52 @@ +import { + CanActivate, + ExecutionContext, + Injectable, + SetMetadata, + UnauthorizedException, +} from "@nestjs/common"; +import { Reflector } from "@nestjs/core"; +import type { Request } from "express"; + +import { SESSION_COOKIE, sessionUser, type User } from "@/lib/server/auth"; + +/** Marks a handler reachable without a session — the sign-in routes. */ +export const PUBLIC = "contentos:public"; +export const Public = () => SetMetadata(PUBLIC, true); + +/** The request, once the guard has run: the user rides on it. */ +export type SessionRequest = Request & { user?: User; sessionId: string }; + +/** + * The lock on every route. + * + * Reads the session cookie off the request, looks the session up, and puts + * the user on the request for `@CurrentUser()`. Global, so a new controller + * is closed by default: the audit found fifteen Next route handlers that + * each had to remember to call `requireUser()`, and did not. + * + * A route that must be open — login, signup, the "is signup open" probe — + * says so with `@Public()`. The session id is put on the request either way, + * because logout needs it whether or not the session is still valid. + */ +@Injectable() +export class SessionGuard implements CanActivate { + constructor(private readonly reflector: Reflector) {} + + async canActivate(context: ExecutionContext) { + const req = context.switchToHttp().getRequest(); + req.sessionId = String(req.cookies?.[SESSION_COOKIE] ?? ""); + + const open = this.reflector.getAllAndOverride(PUBLIC, [ + context.getHandler(), + context.getClass(), + ]); + + const user = req.sessionId ? await sessionUser(req.sessionId) : null; + if (user) req.user = user; + if (open) return true; + + if (!user) throw new UnauthorizedException("Sign in first"); + return true; + } +} diff --git a/api/src/common/user.decorator.ts b/api/src/common/user.decorator.ts new file mode 100644 index 0000000..e6c639a --- /dev/null +++ b/api/src/common/user.decorator.ts @@ -0,0 +1,21 @@ +import { createParamDecorator, type ExecutionContext } from "@nestjs/common"; + +import type { SessionRequest } from "./session.guard"; + +/** + * The signed-in user, as a handler parameter. + * + * `@CurrentUser()` on a guarded route is never undefined — the guard has + * already refused the request otherwise. On a `@Public()` route it may be + * null, which is how /auth/me says "nobody" without failing. + */ +export const CurrentUser = createParamDecorator( + (_data: unknown, ctx: ExecutionContext) => + ctx.switchToHttp().getRequest().user ?? null, +); + +/** The session id off the cookie, valid or not — logout needs it either way. */ +export const SessionId = createParamDecorator( + (_data: unknown, ctx: ExecutionContext) => + ctx.switchToHttp().getRequest().sessionId, +); diff --git a/app/api/integrations/test/route.ts b/api/src/integrations/integrations.controller.ts similarity index 51% rename from app/api/integrations/test/route.ts rename to api/src/integrations/integrations.controller.ts index b67009c..1bc2a69 100644 --- a/app/api/integrations/test/route.ts +++ b/api/src/integrations/integrations.controller.ts @@ -1,31 +1,68 @@ -import { requireUser } from "@/lib/server/auth"; +import { + BadRequestException, + Body, + Controller, + ConflictException, + Get, + HttpCode, + Patch, + Post, + Query, +} from "@nestjs/common"; + import { brainStatuses, findBrain, write } from "@/lib/server/brains"; -import { caught, fail, ok, ready } from "@/lib/server/http"; +import { getSettings, listSecrets, setSettings } from "@/lib/server/repos/settings"; +import { toolStatuses } from "@/lib/server/tools"; -/** A cold CLI can take a while to answer its first prompt. */ -export const maxDuration = 200; +const MEDIA = ["yt-dlp", "ffmpeg", "ffprobe", "whisper"]; /** - * Ask a model to say one word, and report exactly what happened. + * What this machine can actually reach, probed by running it. * - * Installed is not the same as working, and the difference is invisible until - * something is actually sent: a CLI can be on PATH, report a version, even be - * logged in, and still fail — out of date, no auth method configured, a model - * name the account cannot reach. Every one of those looks identical to a - * `--version` probe, and the first time you would otherwise find out is six - * minutes into a twelve-section run. + * The models and the local binaries, each checked by invoking it rather than + * by reading a flag somebody set. `?recheck=1` runs the probes again instead + * of answering from the cache. */ -export async function POST(request: Request) { - try { - await ready(); - await requireUser(); - const body = (await request.json().catch(() => ({}))) as { id?: string }; +@Controller("integrations") +export class IntegrationsController { + @Get() + async wiring(@Query("recheck") recheck?: string) { + const again = recheck === "1"; + const [brains, tools, settings, keys] = await Promise.all([ + again ? toolStatuses(true).then(brainStatuses) : brainStatuses(), + toolStatuses(again), + getSettings(), + listSecrets(), + ]); + return { + brains, + tools: tools.filter((t) => MEDIA.includes(t.id)), + settings, + keys: Object.keys(keys), + }; + } + + /** Pick the brain, or switch local tools on and off. */ + @Patch() + async update(@Body() body: { brain?: string; enabled?: string[] }) { + if (body.brain) { + const status = (await brainStatuses()).find((b) => b.id === body.brain); + if (!status) throw new BadRequestException(`No model called "${body.brain}"`); + if (!status.available) throw new ConflictException(status.reason); + } + return setSettings(body); + } + + /** Ask a model for two words, and report what happened. */ + @Post("test") + @HttpCode(200) + async test(@Body() body: { id?: string }) { const def = findBrain(body.id ?? ""); - if (!def) return fail("No such model"); + if (!def) throw new BadRequestException("No such model"); const status = (await brainStatuses()).find((b) => b.id === def.id)!; if (!status.available) { - return ok({ ok: false, ms: 0, reply: "", error: status.reason, fix: "" }); + return { ok: false, ms: 0, reply: "", error: status.reason, fix: "" }; } const started = Date.now(); @@ -36,44 +73,32 @@ export async function POST(request: Request) { tier: "cheap", timeoutMs: 150_000, }); - return ok({ + return { ok: Boolean(reply.trim()), ms: Date.now() - started, reply: reply.slice(0, 200), error: reply.trim() ? "" : "It answered with nothing", fix: "", transport: status.transport, - }); + }; } catch (e) { - return ok({ + return { ok: false, ms: Date.now() - started, reply: "", - // The tool's own words, not a summary of them. "Please set an Auth - // method" is the whole fix; "could not reach Gemini" is not. error: e instanceof Error ? e.message.slice(0, 400) : "It did not answer", fix: e instanceof Error ? fixFor(def.id, e.message) : "", transport: status.transport, - }); + }; } - } catch (e) { - return caught(e); } } -/** - * The command that fixes the failure, when the failure names itself. - * - * A CLI's error is precise about what is wrong and silent about what to do — - * "unknown variant `max`" is a version mismatch, but only if you already know - * that. These map the handful of failures that have one obvious fix. - */ +/** The one-line remedy for the failures people actually hit. */ function fixFor(id: string, message: string) { const m = message.toLowerCase(); if (m.includes("unknown variant") || m.includes("failed to refresh available models")) { - // The CLI is older than the service it is talking to and cannot parse the - // reply any more. Nothing about the account or the prompt is wrong. return id === "codex-cli" ? "That CLI is out of date — run: npm i -g @openai/codex@latest" : "That CLI is out of date — reinstall it at the latest version"; diff --git a/api/src/main.ts b/api/src/main.ts new file mode 100644 index 0000000..bd7044f --- /dev/null +++ b/api/src/main.ts @@ -0,0 +1,63 @@ +import "reflect-metadata"; + +import { NestFactory } from "@nestjs/core"; +import type { NestExpressApplication } from "@nestjs/platform-express"; +import cookieParser from "cookie-parser"; + +import { ready } from "@/lib/server/http"; + +import { AppModule } from "./app.module"; +import { ErrorsFilter } from "./common/errors.filter"; + +/** + * The Content OS API, as its own process. + * + * Everything the Next.js route handlers used to do, on its own port, reached + * by the browser directly. It shares `lib/server` with the repo root — the + * repos, the services, the run driver — so what changed is who answers HTTP, + * not what happens underneath. + * + * Cross-origin on purpose: the web app is on one origin and this on another, + * so CORS is on for exactly the origins named in WEB_ORIGIN, with credentials, + * and the session cookie is what carries the session across. + */ +async function main() { + const app = await NestFactory.create(AppModule, { + // The seed and the migrations log through here; Nest's own startup lines + // are noise on a dev terminal that already has Next's. + logger: ["error", "warn"], + }); + + app.setGlobalPrefix("api"); + app.use(cookieParser()); + app.useGlobalFilters(new ErrorsFilter()); + + const origins = (process.env.WEB_ORIGIN ?? "http://localhost:3333") + .split(",") + .map((o) => o.trim()) + .filter(Boolean); + app.enableCors({ + origin: origins, + credentials: true, + methods: ["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"], + }); + + // Uploads are streamed by the sources controller; nothing else needs a body + // over a megabyte, and a JSON body that size is a bug being sent. + app.useBodyParser("json", { limit: "1mb" }); + + /* + * Migrations and the seed before the first request, not on it. + * + * `ready()` is the same memoised seed the route handlers call; running it + * here means a deploy that adds a column is never taking traffic against a + * database that has not got it yet. + */ + await ready(); + + const port = Number(process.env.PORT ?? 4000); + await app.listen(port); + console.log(`Content OS API on http://localhost:${port}/api`); +} + +void main(); diff --git a/api/src/packs/packs.controller.ts b/api/src/packs/packs.controller.ts new file mode 100644 index 0000000..12e3a2f --- /dev/null +++ b/api/src/packs/packs.controller.ts @@ -0,0 +1,73 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + HttpCode, + NotFoundException, + Param, + Patch, + Post, +} from "@nestjs/common"; + +import { + createPack, + deletePack, + getPack, + listPacks, + restorePack, + updatePack, + type PackPatch, +} from "@/lib/server/repos/packs"; + +/** + * The template library. + * + * Instructions come back with the list — the builder edits them, so it needs + * them. Any pack can be edited, the shipped ones included; POST on a slug puts + * a shipped one back the way it came. + */ +@Controller("packs") +export class PacksController { + @Get() + list() { + return listPacks(); + } + + @Post() + create(@Body() body: PackPatch) { + if (!body?.name?.trim()) throw new BadRequestException("A pack needs a name"); + return createPack(body); + } + + @Get(":slug") + async get(@Param("slug") slug: string) { + const pack = await getPack(slug); + if (!pack) throw new NotFoundException("No such pack"); + return pack; + } + + @Patch(":slug") + async update(@Param("slug") slug: string, @Body() body: PackPatch) { + const pack = await updatePack(slug, body ?? {}); + if (!pack) throw new NotFoundException("No such pack"); + return pack; + } + + /** Restore the shipped version, section by section. */ + @Post(":slug") + @HttpCode(200) + async restore(@Param("slug") slug: string) { + const pack = await restorePack(slug); + if (!pack) { + throw new NotFoundException("No version of that pack ships with the app"); + } + return pack; + } + + @Delete(":slug") + async remove(@Param("slug") slug: string) { + return { ok: await deletePack(slug) }; + } +} diff --git a/api/src/research/research.controller.ts b/api/src/research/research.controller.ts new file mode 100644 index 0000000..bd78455 --- /dev/null +++ b/api/src/research/research.controller.ts @@ -0,0 +1,23 @@ +import { BadRequestException, Body, Controller, HttpCode, Post } from "@nestjs/common"; + +import { research } from "@/lib/server/services/researcher"; + +/** + * Watch a reel and say what it is about. + * + * Minutes: eight stills go to the model as pictures. Nothing here times out + * on purpose — the service has its own ten-minute ceiling on the model call. + */ +@Controller("research") +export class ResearchController { + @Post() + @HttpCode(200) + run(@Body() body: { sourceId?: string; frames?: string[]; note?: string }) { + if (!body.sourceId) throw new BadRequestException("Fetch a video first"); + return research({ + sourceId: body.sourceId, + frames: body.frames, + note: body.note, + }); + } +} diff --git a/api/src/runs/runs.controller.ts b/api/src/runs/runs.controller.ts new file mode 100644 index 0000000..683162c --- /dev/null +++ b/api/src/runs/runs.controller.ts @@ -0,0 +1,130 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + HttpCode, + NotFoundException, + Param, + Patch, + Post, + Query, +} from "@nestjs/common"; + +import { + deleteRun, + getRun, + listRuns, + requeueFailed, + setRunDecision, +} from "@/lib/server/repos/runs"; +import { + driveRun, + editSection, + isDriving, + startRun, + writeSection, +} from "@/lib/server/services/runs"; + +/** + * Runs, and the sections written into them. + * + * The driver is `driveRun` in lib/server/services — a loop inside THIS + * process, one section at a time, carrying on whether or not anybody is + * watching. That is the reason the API is its own long-lived service and not + * a serverless function: a run takes minutes and shells out to a local + * model, and both need somewhere to stand. + */ +@Controller("runs") +export class RunsController { + @Get() + list(@Query("workspaceId") workspaceId?: string) { + return listRuns(workspaceId || undefined); + } + + /** Create a run with every section queued. It does not start writing. */ + @Post() + create( + @Body() + body: { + workspaceId?: string; + topicId?: string | null; + sourceId?: string | null; + packSlug?: string; + inputs?: Record; + title?: string; + }, + ) { + return startRun({ + workspaceId: body.workspaceId ?? "", + topicId: body.topicId ?? null, + sourceId: body.sourceId ?? null, + packSlug: body.packSlug ?? "enbn-website-package", + inputs: body.inputs ?? {}, + title: body.title, + }); + } + + @Get(":id") + async get(@Param("id") id: string) { + const run = await getRun(id); + if (!run) throw new NotFoundException("No such run"); + return run; + } + + @Patch(":id") + async decide(@Param("id") id: string, @Body() body: { decision?: string }) { + const d = body.decision; + if (d !== "used" && d !== "ready" && d !== "ignored") { + throw new BadRequestException("decision must be used, ready or ignored"); + } + if (!(await setRunDecision(id, d))) throw new NotFoundException("No such run"); + return { id, decision: d }; + } + + @Delete(":id") + async remove(@Param("id") id: string) { + return { ok: await deleteRun(id) }; + } + + /** + * Write everything that is left, on the server, and return at once. + * + * Pressing this on a run that failed is a retry: the failures go back in + * the queue first, so the loop tries them again rather than skipping them. + */ + @Post(":id/start") + @HttpCode(200) + async start(@Param("id") id: string) { + if (!(await getRun(id))) throw new NotFoundException("No such run"); + const retried = await requeueFailed(id); + return { ...driveRun(id), retried, running: true }; + } + + /** Is this run being written right now, by anyone? */ + @Get(":id/start") + running(@Param("id") id: string) { + return { running: isDriving(id) }; + } + + /** Write one section, now, and answer with the whole run. */ + @Post(":id/sections/:sectionId") + @HttpCode(200) + write(@Param("id") id: string, @Param("sectionId") sectionId: string) { + return writeSection(id, sectionId); + } + + /** Replace a section's text by hand. It counts as finished from then on. */ + @Patch(":id/sections/:sectionId") + edit( + @Param("id") id: string, + @Param("sectionId") sectionId: string, + @Body() body: { content?: unknown }, + ) { + if (typeof body.content !== "string") { + throw new BadRequestException("content must be text"); + } + return editSection(id, sectionId, body.content); + } +} diff --git a/api/src/series/series.controller.ts b/api/src/series/series.controller.ts new file mode 100644 index 0000000..e33e9b4 --- /dev/null +++ b/api/src/series/series.controller.ts @@ -0,0 +1,158 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + HttpCode, + NotFoundException, + Param, + Patch, + Post, + Query, + Res, +} from "@nestjs/common"; +import type { Response } from "express"; + +import { + addTopics, + createSeries, + deleteSeries, + deleteTopic, + getSeries, + listSeries, + mergeSeries, + updateSeries, + updateTopic, +} from "@/lib/server/repos/series"; +import { FetchError, fetchSource } from "@/lib/server/services/webfetch"; + +type SeriesPatch = Parameters[1]; +type TopicPatch = Parameters[1]; + +/** Shelves: the series under a workspace, and the topics that stand on them. */ +@Controller("series") +export class SeriesController { + @Get() + list(@Query("workspaceId") workspaceId?: string) { + if (!workspaceId) throw new BadRequestException("workspaceId is required"); + return listSeries(workspaceId); + } + + @Post() + create( + @Body() + body: { + workspaceId?: string; + name?: string; + context?: string; + pack?: string; + numbered?: boolean; + partLabel?: string; + }, + ) { + if (!body.workspaceId) throw new BadRequestException("workspaceId is required"); + if (!body.name?.trim()) throw new BadRequestException("A series needs a name"); + // DuplicateName is answered by the errors filter as a 409 with `existing`. + return createSeries({ + workspaceId: body.workspaceId, + name: body.name.trim(), + context: body.context, + pack: body.pack, + numbered: body.numbered, + partLabel: body.partLabel, + }); + } + + @Get(":id") + async get(@Param("id") id: string) { + const s = await getSeries(id); + if (!s) throw new NotFoundException("No such series"); + return s; + } + + @Patch(":id") + async update(@Param("id") id: string, @Body() body: SeriesPatch) { + const s = await updateSeries(id, body ?? {}); + if (!s) throw new NotFoundException("No such series"); + return s; + } + + /** `?keepTopics=1` moves the topics to the Misc shelf instead of deleting them. */ + @Delete(":id") + remove(@Param("id") id: string, @Query("keepTopics") keep?: string) { + return deleteSeries(id, { keepTopics: keep === "1" }); + } + + /** + * Add topics — one or fifty, same call. + * + * 201 when something was added, 200 when everything was already there: the + * body says which, and the status is what the screen reads first. + */ + @Post(":id") + async add( + @Param("id") id: string, + @Body() + body: { topics?: { name: string; context?: string; status?: string }[] }, + @Res({ passthrough: true }) res: Response, + ) { + const topics = (body.topics ?? []).filter((t) => t?.name?.trim()); + if (!topics.length) throw new BadRequestException("Nothing to add"); + const result = await addTopics(id, topics); + res.status(result.added.length ? 201 : 200); + return result; + } + + @Post(":id/merge") + @HttpCode(200) + merge(@Param("id") id: string, @Body() body: { into?: string }) { + if (!body.into) { + throw new BadRequestException("Which series should it merge into?"); + } + return mergeSeries(id, body.into); + } + + /** Read a link or a feed into the shelf's brief. */ + @Post(":id/source") + @HttpCode(200) + async source( + @Param("id") id: string, + @Body() body: { url?: string; kind?: string }, + ) { + if (!(await getSeries(id))) throw new NotFoundException("No such series"); + try { + const source = await fetchSource(String(body.url ?? "")); + const briefFrom = source.kind === "feed" ? "feed" : "link"; + return await updateSeries(id, { source, briefFrom }); + } catch (e) { + if (e instanceof FetchError) { + throw new BadRequestException(e.message); + } + throw e; + } + } + + @Delete(":id/source") + async clearSource(@Param("id") id: string) { + const s = await updateSeries(id, { source: null, briefFrom: "typed" }); + if (!s) throw new NotFoundException("No such series"); + return s; + } +} + +/** One topic: rename it, move it, decide about it, or take it off the shelf. */ +@Controller("topics") +export class TopicsController { + @Patch(":id") + async update(@Param("id") id: string, @Body() body: TopicPatch) { + const t = await updateTopic(id, body ?? {}); + if (!t) throw new NotFoundException("No such topic"); + return t; + } + + @Delete(":id") + async remove(@Param("id") id: string) { + return { ok: await deleteTopic(id) }; + } +} diff --git a/api/src/settings/settings.controller.ts b/api/src/settings/settings.controller.ts new file mode 100644 index 0000000..a3d3d16 --- /dev/null +++ b/api/src/settings/settings.controller.ts @@ -0,0 +1,58 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + Patch, + Post, + Query, +} from "@nestjs/common"; + +import { + clearSecret, + getSettings, + listSecrets, + setSecret, + setSettings, + type Settings, +} from "@/lib/server/repos/settings"; + +/** + * Preferences, and the API keys beside them. + * + * Keys go in and never come back out: `listSecrets` answers with which ids + * are stored, not their values. The settings table encrypts them with + * CONTENTOS_SECRET — see the repo for why a dump is not a list of live keys. + */ +@Controller("settings") +export class SettingsController { + @Get() + get() { + return getSettings(); + } + + @Patch() + update(@Body() body: Partial) { + return setSettings(body ?? {}); + } + + @Get("keys") + keys() { + return listSecrets(); + } + + @Post("keys") + async setKey(@Body() body: { id?: string; value?: string }) { + if (!body.id) throw new BadRequestException("Which key?"); + await setSecret(body.id, body.value ?? ""); + return listSecrets(); + } + + @Delete("keys") + async clearKey(@Query("id") id?: string) { + if (!id) throw new BadRequestException("Which key?"); + await clearSecret(id); + return listSecrets(); + } +} diff --git a/api/src/sources/sources.controller.ts b/api/src/sources/sources.controller.ts new file mode 100644 index 0000000..ed67a4f --- /dev/null +++ b/api/src/sources/sources.controller.ts @@ -0,0 +1,160 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + HttpCode, + NotFoundException, + Param, + PayloadTooLargeException, + Post, + Query, + Req, + Res, +} from "@nestjs/common"; +import busboy from "busboy"; +import type { Request, Response } from "express"; + +import { getSource, listSources } from "@/lib/server/repos/sources"; +import { + MAX_UPLOAD_BYTES, + addFrameAt, + frameFile, + ingest, + ingestFile, + removeSource, +} from "@/lib/server/services/ingest"; + +/** + * Source videos: fetched from a link, or uploaded from a machine. + * + * Slow on purpose. A fetch holds while yt-dlp downloads, ffmpeg cuts stills + * and a transcriber runs — minutes, not seconds — and the browser waits with + * a spinner on it. Express has no request timeout of its own, so there is + * nothing here to raise; the Next handlers needed `maxDuration` and this does + * not. + */ +@Controller("sources") +export class SourcesController { + @Get() + list(@Query("workspaceId") workspaceId?: string) { + return listSources(workspaceId || undefined); + } + + /** Fetch a reel by link, or hand back the one already fetched. */ + @Post() + fetch( + @Body() body: { url?: string; workspaceId?: string | null; refresh?: boolean }, + ) { + if (!body.url?.trim()) throw new BadRequestException("Paste a link first"); + return ingest({ + url: body.url, + workspaceId: body.workspaceId ?? null, + refresh: body.refresh, + }); + } + + /** + * A video off somebody's machine, streamed to disk as it arrives. + * + * Read straight off the request with busboy rather than through a body + * parser: a parser buffers, and the whole point of the ingest's streaming + * path is that a 400MB recording never sits in memory. The declared size is + * refused up front as a courtesy; the ingest counts the bytes itself. + */ + @Post("upload") + upload(@Req() req: Request) { + const declared = Number(req.headers["content-length"] ?? 0); + if (declared > MAX_UPLOAD_BYTES) { + throw new PayloadTooLargeException( + `That file is over ${Math.round(MAX_UPLOAD_BYTES / 1048576)}MB — trim it or export it smaller.`, + ); + } + + return new Promise((resolve, reject) => { + const bb = busboy({ headers: req.headers, limits: { files: 1 } }); + let workspaceId: string | null = null; + let handled = false; + + bb.on("field", (name, value) => { + if (name === "workspaceId" && value) workspaceId = value; + }); + + bb.on("file", (name, file, info) => { + if (name !== "file") { + file.resume(); + return; + } + handled = true; + // Node's Readable, as the Web stream the ingest takes: the ingest is + // shared with code that gets a fetch() body, so it speaks that shape. + const web = ReadableStreamFromNode(file); + ingestFile({ filename: info.filename, stream: web, workspaceId }) + .then(resolve) + .catch(reject); + }); + + bb.on("error", reject); + bb.on("finish", () => { + if (!handled) reject(new BadRequestException("Choose a video file")); + }); + + req.pipe(bb); + }); + } + + @Get(":id") + async get(@Param("id") id: string) { + const source = await getSource(id); + if (!source) throw new NotFoundException("No such source"); + return source; + } + + /** The row and the download go together. */ + @Delete(":id") + async remove(@Param("id") id: string) { + return { ok: await removeSource(id) }; + } + + /** One more still, at a moment somebody asked for. */ + @Post(":id/frames") + @HttpCode(201) + addFrame(@Param("id") id: string, @Body() body: { at?: number }) { + const at = Number(body.at); + if (!Number.isFinite(at) || at < 0) { + throw new BadRequestException("Give a time in seconds"); + } + return addFrameAt(id, at); + } + + /** The frame's bytes. Immutable: a frame at a second never changes. */ + @Get(":id/frames/:file") + async frame( + @Param("id") id: string, + @Param("file") file: string, + @Res() res: Response, + ) { + const bytes = await frameFile(id, file); + if (!bytes) throw new NotFoundException("No such frame"); + res + .set({ + "content-type": "image/jpeg", + "cache-control": "private, max-age=31536000, immutable", + }) + .send(bytes); + } +} + +/** A Node readable as a Web ReadableStream, without the whole of node:stream/web's types. */ +function ReadableStreamFromNode( + file: NodeJS.ReadableStream, +): ReadableStream { + return new ReadableStream({ + start(controller) { + file.on("data", (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk))); + file.on("end", () => controller.close()); + file.on("error", (e) => controller.error(e)); + }, + }); +} diff --git a/api/src/tools/tools.controller.ts b/api/src/tools/tools.controller.ts new file mode 100644 index 0000000..7b44bb7 --- /dev/null +++ b/api/src/tools/tools.controller.ts @@ -0,0 +1,47 @@ +import { + Body, + Controller, + Get, + NotFoundException, + Param, + Patch, + Query, +} from "@nestjs/common"; + +import { + getTool, + listTools, + toolsFor, + updateTool, + type ToolPatch, +} from "@/lib/server/repos/tools"; + +/** + * The tool bench. + * + * `?workspace=` is one workspace's bench — what it is allowed to see. + * Without it you get every tool and its assignment, which is what the screen + * that manages them needs and nothing else should be reading. + */ +@Controller("tools") +export class ToolsController { + @Get() + list(@Query("workspace") workspace?: string) { + return workspace ? toolsFor(workspace) : listTools(); + } + + @Get(":slug") + async get(@Param("slug") slug: string) { + const tool = await getTool(slug); + if (!tool) throw new NotFoundException("No such tool"); + return tool; + } + + /** Rename it, recategorise it, switch it off, or say where it appears. */ + @Patch(":slug") + async update(@Param("slug") slug: string, @Body() body: ToolPatch) { + const tool = await updateTool(slug, body ?? {}); + if (!tool) throw new NotFoundException("No such tool"); + return tool; + } +} diff --git a/api/src/workspaces/workspaces.controller.ts b/api/src/workspaces/workspaces.controller.ts new file mode 100644 index 0000000..37c57c9 --- /dev/null +++ b/api/src/workspaces/workspaces.controller.ts @@ -0,0 +1,64 @@ +import { + Body, + ConflictException, + Controller, + Delete, + Get, + NotFoundException, + Param, + Patch, + Post, +} from "@nestjs/common"; + +import { listSeries } from "@/lib/server/repos/series"; +import { + createWorkspace, + deleteWorkspace, + getWorkspace, + listWorkspaces, + updateWorkspace, +} from "@/lib/server/repos/workspaces"; + +type Patch = Parameters[1]; +type Create = Parameters[0]; + +/** Workspaces, each answered with its shelves — the shape the store hydrates from. */ +@Controller("workspaces") +export class WorkspacesController { + @Get() + async list() { + const list = await listWorkspaces(); + return Promise.all( + list.map(async (w) => ({ ...w, series: await listSeries(w.id) })), + ); + } + + @Post() + async create(@Body() body: Create) { + return { ...(await createWorkspace(body)), series: [] }; + } + + @Get(":id") + async get(@Param("id") id: string) { + const ws = await getWorkspace(id); + if (!ws) throw new NotFoundException("No such workspace"); + return { ...ws, series: await listSeries(id) }; + } + + @Patch(":id") + async update(@Param("id") id: string, @Body() body: Patch) { + const ws = await updateWorkspace(id, body ?? {}); + if (!ws) throw new NotFoundException("No such workspace"); + return { ...ws, series: await listSeries(id) }; + } + + @Delete(":id") + async remove(@Param("id") id: string) { + if ((await listWorkspaces()).length <= 1) { + throw new ConflictException( + "This is the only workspace — there would be nothing left", + ); + } + return { ok: await deleteWorkspace(id) }; + } +} diff --git a/api/tsconfig.json b/api/tsconfig.json new file mode 100644 index 0000000..f8f2ebc --- /dev/null +++ b/api/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es2022", + "lib": ["es2023"], + "types": ["node"], + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "moduleResolution": "node", + "resolveJsonModule": true, + "sourceMap": true, + "baseUrl": "..", + "paths": { "@/*": ["./*"] }, + "rootDir": "..", + "outDir": "dist" + }, + "include": ["src/**/*.ts"] +} diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.ts deleted file mode 100644 index 4a6922d..0000000 --- a/app/api/auth/login/route.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { cookies } from "next/headers"; - -import { - authenticate, - cookieOptions, - SESSION_COOKIE, - startSession, - sweepSessions, -} from "@/lib/server/auth"; -import { caught, ok, ready } from "@/lib/server/http"; - -export async function POST(request: Request) { - try { - await ready(); - const body = (await request.json().catch(() => ({}))) as { - email?: string; - password?: string; - }; - - const user = await authenticate(body.email ?? "", body.password ?? ""); - void sweepSessions(); - - const sid = await startSession( - user.id, - request.headers.get("user-agent") ?? "", - ); - (await cookies()).set(SESSION_COOKIE, sid, cookieOptions()); - return ok(user); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/auth/logout/route.ts b/app/api/auth/logout/route.ts deleted file mode 100644 index fbd986d..0000000 --- a/app/api/auth/logout/route.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { cookies } from "next/headers"; - -import { - currentSessionId, - endSession, - SESSION_COOKIE, -} from "@/lib/server/auth"; -import { caught, ok, ready } from "@/lib/server/http"; - -export async function POST() { - try { - await ready(); - // The row goes as well as the cookie: clearing only the cookie leaves a - // working session id behind for anything that kept a copy. - await endSession(await currentSessionId()); - (await cookies()).delete(SESSION_COOKIE); - return ok({ ok: true }); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/auth/me/route.ts b/app/api/auth/me/route.ts deleted file mode 100644 index 199626b..0000000 --- a/app/api/auth/me/route.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { currentUser, signupOpen } from "@/lib/server/auth"; -import { caught, ok, ready } from "@/lib/server/http"; - -/** Who is signed in, and whether anyone can sign up. Never 401s — it is the question. */ -export async function GET() { - try { - await ready(); - return ok({ user: await currentUser(), signupOpen: await signupOpen() }); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/auth/password/route.ts b/app/api/auth/password/route.ts deleted file mode 100644 index 67a3c93..0000000 --- a/app/api/auth/password/route.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { cookies } from "next/headers"; - -import { - cookieOptions, - requireUser, - SESSION_COOKIE, - startSession, - updatePassword, -} from "@/lib/server/auth"; -import { caught, ok, ready } from "@/lib/server/http"; - -export async function POST(request: Request) { - try { - await ready(); - const user = await requireUser(); - const body = (await request.json().catch(() => ({}))) as { - current?: string; - next?: string; - }; - - await updatePassword(user.id, body.current ?? "", body.next ?? ""); - - // Every session was dropped, including this one. A fresh cookie so the - // person who just changed their password is not logged out by doing it. - const sid = await startSession( - user.id, - request.headers.get("user-agent") ?? "", - ); - (await cookies()).set(SESSION_COOKIE, sid, cookieOptions()); - return ok({ ok: true }); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/auth/sessions/route.ts b/app/api/auth/sessions/route.ts deleted file mode 100644 index a060c57..0000000 --- a/app/api/auth/sessions/route.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { - currentSessionId, - endOtherSessions, - listSessions, - requireUser, -} from "@/lib/server/auth"; -import { caught, ok, ready } from "@/lib/server/http"; - -/** Where this account is signed in. The one you are using is marked. */ -export async function GET() { - try { - await ready(); - const user = await requireUser(); - return ok(await listSessions(user.id, await currentSessionId())); - } catch (e) { - return caught(e); - } -} - -/** Signs out everywhere except here. */ -export async function DELETE() { - try { - await ready(); - const user = await requireUser(); - const ended = await endOtherSessions(user.id, await currentSessionId()); - return ok({ ended }); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/auth/signup/route.ts b/app/api/auth/signup/route.ts deleted file mode 100644 index 351288b..0000000 --- a/app/api/auth/signup/route.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { cookies } from "next/headers"; - -import { - cookieOptions, - createUser, - SESSION_COOKIE, - signupOpen, - startSession, -} from "@/lib/server/auth"; -import { caught, ok, ready } from "@/lib/server/http"; - -/** Whether the console still has room for an owner. The form asks before it renders. */ -export async function GET() { - try { - await ready(); - return ok({ open: await signupOpen() }); - } catch (e) { - return caught(e); - } -} - -export async function POST(request: Request) { - try { - await ready(); - const body = (await request.json().catch(() => ({}))) as { - email?: string; - password?: string; - name?: string; - invite?: string; - }; - - const user = await createUser({ - email: body.email ?? "", - password: body.password ?? "", - name: body.name, - invite: body.invite, - }); - - // Signed in immediately. Making someone type the password they just chose - // into a second form proves nothing and loses people. - const sid = await startSession( - user.id, - request.headers.get("user-agent") ?? "", - ); - (await cookies()).set(SESSION_COOKIE, sid, cookieOptions()); - return ok(user, 201); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/integrations/route.ts b/app/api/integrations/route.ts deleted file mode 100644 index 026a5f4..0000000 --- a/app/api/integrations/route.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { brainStatuses } from "@/lib/server/brains"; -import { toolStatuses } from "@/lib/server/tools"; -import { getSettings, listSecrets, setSettings } from "@/lib/server/repos/settings"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** A section of a run reaches for tools; probing five processes can be slow. */ -export const maxDuration = 60; - -/** - * What this machine can actually do. - * - * Every field is the result of running something or reading a row — the page - * that renders this used to hold a set of ids in memory and call it a - * connection, so it would cheerfully report yt-dlp as connected on a machine - * that had never had it. - */ -export async function GET(request: Request) { - try { - await ready(); - await requireUser(); - // ?recheck=1 skips the one-minute probe cache, for the button that says - // "I have just installed it". - const recheck = new URL(request.url).searchParams.get("recheck") === "1"; - - const [brains, tools, settings, keys] = await Promise.all([ - recheck ? toolStatuses(true).then(brainStatuses) : brainStatuses(), - toolStatuses(recheck), - getSettings(), - listSecrets(), - ]); - - /* - * The model CLIs are probed with the rest, but they belong to the Models - * section — listing `claude` under Local tools as well would offer a - * switch that turns off the thing writing every section. - */ - const MEDIA = ["yt-dlp", "ffmpeg", "ffprobe", "whisper"]; - return ok({ - brains, - tools: tools.filter((t) => MEDIA.includes(t.id)), - settings, - keys: Object.keys(keys), - }); - } catch (e) { - return caught(e); - } -} - -export async function PATCH(request: Request) { - try { - await ready(); - await requireUser(); - const body = (await request.json().catch(() => ({}))) as { - brain?: string; - enabled?: string[]; - }; - - if (body.brain) { - // Refused rather than accepted-and-broken: a brain that cannot be - // reached fails at the next section, several minutes and one confusing - // error message later. - const status = (await brainStatuses()).find((b) => b.id === body.brain); - if (!status) return fail(`No model called "${body.brain}"`); - if (!status.available) return fail(status.reason, 409); - } - - return ok(await setSettings(body)); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/invites/[token]/route.ts b/app/api/invites/[token]/route.ts deleted file mode 100644 index 8c188ec..0000000 --- a/app/api/invites/[token]/route.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { requireUser, revokeInvite } from "@/lib/server/auth"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** Take a link back. Only an unused one can go — a spent invite is history. */ -export async function DELETE( - _r: Request, - { params }: { params: Promise<{ token: string }> }, -) { - try { - await ready(); - await requireUser(); - const { token } = await params; - const gone = await revokeInvite(token); - return gone ? ok({ ok: true }) : fail("That invite is already used", 409); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/invites/route.ts b/app/api/invites/route.ts deleted file mode 100644 index 6082d69..0000000 --- a/app/api/invites/route.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { createInvite, listInvites, requireUser } from "@/lib/server/auth"; -import { caught, ok, ready } from "@/lib/server/http"; - -/** - * The links that let anyone else in. - * - * Any signed-in person can make one. There is no admin tier in this console — - * everyone who is here can already read and change everything, so pretending - * invites are privileged would be a lock on a door with no walls. What stops - * a stranger is that they need a link at all. - */ -export async function GET() { - try { - await ready(); - await requireUser(); - return ok(await listInvites()); - } catch (e) { - return caught(e); - } -} - -export async function POST(request: Request) { - try { - await ready(); - const user = await requireUser(); - const body = (await request.json().catch(() => ({}))) as { - email?: string; - note?: string; - days?: number; - }; - return ok( - await createInvite({ - createdBy: user.id, - email: body.email, - note: body.note, - days: body.days, - }), - 201, - ); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/packs/[slug]/route.ts b/app/api/packs/[slug]/route.ts deleted file mode 100644 index fc799ed..0000000 --- a/app/api/packs/[slug]/route.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { - deletePack, - getPack, - restorePack, - updatePack, -} from "@/lib/server/repos/packs"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -export async function GET( - _r: Request, - { params }: { params: Promise<{ slug: string }> }, -) { - try { - await ready(); - await requireUser(); - const { slug } = await params; - const pack = await getPack(slug); - return pack ? ok(pack) : fail("No such pack", 404); - } catch (e) { - return caught(e); - } -} - -/** - * Edit a pack — any pack. - * - * The shipped ones used to be refused here, on the reasoning that a tuned - * prompt belongs with the code that reads it. That was true of a pack you - * could only read; it is the wrong trade for a library you are meant to build - * on. They are seeded into the table as ordinary rows now, and POST below puts - * one back the way it shipped if an edit goes wrong. - */ -export async function PATCH( - request: Request, - { params }: { params: Promise<{ slug: string }> }, -) { - try { - await ready(); - await requireUser(); - const { slug } = await params; - const pack = await updatePack(slug, await request.json().catch(() => ({}))); - return pack ? ok(pack) : fail("No such pack", 404); - } catch (e) { - return caught(e); - } -} - -/** Restore the shipped version of a pack, section by section. */ -export async function POST( - _r: Request, - { params }: { params: Promise<{ slug: string }> }, -) { - try { - await ready(); - await requireUser(); - const { slug } = await params; - const pack = await restorePack(slug); - return pack - ? ok(pack) - : fail("No version of that pack ships with the app", 404); - } catch (e) { - return caught(e); - } -} - -export async function DELETE( - _r: Request, - { params }: { params: Promise<{ slug: string }> }, -) { - try { - await ready(); - await requireUser(); - const { slug } = await params; - return ok({ ok: await deletePack(slug) }); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/packs/route.ts b/app/api/packs/route.ts deleted file mode 100644 index 07a0790..0000000 --- a/app/api/packs/route.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { createPack, listPacks } from "@/lib/server/repos/packs"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** - * The pack library. - * - * Instructions come back with it — the builder edits them, so it needs them. - * The list is small and read once per screen, which is a different trade from - * the run endpoints and the reason the earlier version stripped them out. - */ -export async function GET() { - try { - await ready(); - await requireUser(); - return ok(await listPacks()); - } catch (e) { - return caught(e); - } -} - -export async function POST(request: Request) { - try { - await ready(); - await requireUser(); - const body = await request.json().catch(() => ({})); - if (!body?.name?.trim()) return fail("A pack needs a name"); - return ok(await createPack(body), 201); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/research/route.ts b/app/api/research/route.ts deleted file mode 100644 index 708e0a5..0000000 --- a/app/api/research/route.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { research } from "@/lib/server/services/researcher"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** Reading eight stills with a model is minutes, not seconds. */ -export const maxDuration = 800; - -export async function POST(request: Request) { - try { - await ready(); - await requireUser(); - const body = (await request.json().catch(() => ({}))) as { - sourceId?: string; - frames?: string[]; - note?: string; - }; - if (!body.sourceId) return fail("Fetch a video first"); - return ok( - await research({ - sourceId: body.sourceId, - frames: body.frames, - note: body.note, - }), - ); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/runs/[id]/route.ts b/app/api/runs/[id]/route.ts deleted file mode 100644 index 05d24f4..0000000 --- a/app/api/runs/[id]/route.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { deleteRun, getRun, setRunDecision } from "@/lib/server/repos/runs"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -export async function GET( - _r: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const run = await getRun(id); - return run ? ok(run) : fail("No such run", 404); - } catch (e) { - return caught(e); - } -} - -/** - * Mark a run used, ready or ignored. - * - * Only the decision is patchable. A run's inputs and its sections are the - * record of what happened, and letting a PATCH rewrite them would make that - * record a guess. - */ -export async function PATCH( - request: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const body = (await request.json().catch(() => ({}))) as { - decision?: string; - }; - if ( - body.decision !== "used" && - body.decision !== "ready" && - body.decision !== "ignored" - ) { - return fail("decision must be used, ready or ignored", 400); - } - return (await setRunDecision(id, body.decision)) - ? ok({ id, decision: body.decision }) - : fail("No such run", 404); - } catch (e) { - return caught(e); - } -} - -export async function DELETE( - _r: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - return ok({ ok: await deleteRun(id) }); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/runs/[id]/sections/[sectionId]/route.ts b/app/api/runs/[id]/sections/[sectionId]/route.ts deleted file mode 100644 index 6c4e13f..0000000 --- a/app/api/runs/[id]/sections/[sectionId]/route.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { editSection, writeSection } from "@/lib/server/services/runs"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** Research reads pages and a script thinks; the default would cut both off. */ -export const maxDuration = 800; - -export async function POST( - _r: Request, - { params }: { params: Promise<{ id: string; sectionId: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id, sectionId } = await params; - return ok(await writeSection(id, sectionId)); - } catch (e) { - return caught(e); - } -} - -/** - * Save what a person typed into this section. - * - * PATCH rather than POST, which on this route means "run it": one asks the - * model for new words and costs money, the other keeps the words already on - * screen. They must not be the same verb. - */ -export async function PATCH( - request: Request, - { params }: { params: Promise<{ id: string; sectionId: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id, sectionId } = await params; - const body = (await request.json().catch(() => ({}))) as { - content?: unknown; - }; - if (typeof body.content !== "string") { - return fail("content must be text", 400); - } - return ok(await editSection(id, sectionId, body.content)); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/runs/[id]/start/route.ts b/app/api/runs/[id]/start/route.ts deleted file mode 100644 index f57400c..0000000 --- a/app/api/runs/[id]/start/route.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { driveRun, isDriving } from "@/lib/server/services/runs"; -import { getRun, requeueFailed } from "@/lib/server/repos/runs"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** - * Write the whole run, without being asked again. - * - * Answers as soon as the loop is started rather than when it finishes: a run - * is twelve model calls and several minutes, which no request should be held - * open for. The page follows along by reading the run. - * - * Failed sections go back in the queue first, which is what makes this Retry - * as well as Run. The drive deliberately skips a section that failed — looping - * on the one thing that does not work would spend the model's whole afternoon - * on it — so without this a second press finished instantly having written - * nothing, and the Retry button on a failed row did nothing at all. - */ -export async function POST( - _r: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const run = await getRun(id); - if (!run) return fail("No such run", 404); - const retried = await requeueFailed(id); - return ok({ ...driveRun(id), retried, running: true }); - } catch (e) { - return caught(e); - } -} - -/** Whether it is being written right now — for a page that just loaded. */ -export async function GET( - _r: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - return ok({ running: isDriving(id) }); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/runs/route.ts b/app/api/runs/route.ts deleted file mode 100644 index 76ea1f3..0000000 --- a/app/api/runs/route.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { listRuns } from "@/lib/server/repos/runs"; -import { startRun } from "@/lib/server/services/runs"; -import { caught, ok, ready } from "@/lib/server/http"; - -export async function GET(request: Request) { - try { - await ready(); - await requireUser(); - const workspaceId = new URL(request.url).searchParams.get("workspaceId"); - return ok(await listRuns(workspaceId ?? undefined)); - } catch (e) { - return caught(e); - } -} - -/** - * Start a run. - * - * Creates it with every section queued and returns immediately — it does not - * generate. The client drives the sections one call at a time, so progress is - * visible while it happens rather than arriving as one long silence. - */ -export async function POST(request: Request) { - try { - await ready(); - await requireUser(); - const body = (await request.json().catch(() => ({}))) as { - workspaceId?: string; - topicId?: string | null; - sourceId?: string | null; - packSlug?: string; - inputs?: Record; - title?: string; - }; - return ok( - await startRun({ - workspaceId: body.workspaceId ?? "", - topicId: body.topicId ?? null, - sourceId: body.sourceId ?? null, - packSlug: body.packSlug ?? "enbn-website-package", - inputs: body.inputs ?? {}, - title: body.title, - }), - 201, - ); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/series/[id]/merge/route.ts b/app/api/series/[id]/merge/route.ts deleted file mode 100644 index d540978..0000000 --- a/app/api/series/[id]/merge/route.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { mergeSeries } from "@/lib/server/repos/series"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** - * Fold this series into another one. - * - * A POST rather than a PATCH on the target: it deletes one row, moves every - * topic on it and renumbers them, which is a job being asked for rather than - * a field being set. - */ -export async function POST( - request: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const body = (await request.json().catch(() => ({}))) as { into?: string }; - if (!body.into) return fail("Which series should it merge into?"); - return ok(await mergeSeries(id, body.into)); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/series/[id]/route.ts b/app/api/series/[id]/route.ts deleted file mode 100644 index 52d1671..0000000 --- a/app/api/series/[id]/route.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { - DuplicateName, - addTopics, - deleteSeries, - getSeries, - updateSeries, -} from "@/lib/server/repos/series"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -export async function GET( - _r: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const s = await getSeries(id); - return s ? ok(s) : fail("No such series", 404); - } catch (e) { - return caught(e); - } -} - -export async function PATCH( - request: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const s = await updateSeries(id, await request.json().catch(() => ({}))); - return s ? ok(s) : fail("No such series", 404); - } catch (e) { - if (e instanceof DuplicateName) { - return Response.json( - { error: e.message, existing: e.existing }, - { status: 409 }, - ); - } - return caught(e); - } -} - -/** - * Delete a series, with or without what is standing on it. - * - * `?keepTopics=1` moves its topics to the holding shelf first, so the shelf - * can go without taking a dozen ideas with it. Without the flag the topics go - * too — which is what a delete usually means, and why it is the one you have - * to ask for. - */ -export async function DELETE( - request: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const keepTopics = - new URL(request.url).searchParams.get("keepTopics") === "1"; - return ok(await deleteSeries(id, { keepTopics })); - } catch (e) { - return caught(e); - } -} - -/** - * Add topics to a series. - * - * One endpoint for one topic and for fifty, because the part numbering is the - * same problem either way and splitting it would mean two places that assign - * numbers. - */ -export async function POST( - request: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const body = (await request.json().catch(() => ({}))) as { - topics?: { name: string; context?: string; status?: string }[]; - }; - const topics = (body.topics ?? []).filter((t) => t?.name?.trim()); - if (!topics.length) return fail("Nothing to add"); - - /* - * `{ added, skipped }` rather than the rows alone: a request for five - * topics that produces two is not an error, and it is not a success the - * caller can report honestly without being told which three were already - * covered and where. - */ - const result = await addTopics(id, topics); - return ok(result, result.added.length ? 201 : 200); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/series/[id]/source/route.ts b/app/api/series/[id]/source/route.ts deleted file mode 100644 index 0edd321..0000000 --- a/app/api/series/[id]/source/route.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { getSeries, updateSeries } from "@/lib/server/repos/series"; -import { FetchError, fetchSource } from "@/lib/server/services/webfetch"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** Reading a site is a network round trip, and some of them are slow. */ -export const maxDuration = 60; - -/** - * Read a page or a feed, and hang it on this series. - * - * The fetch and the save are one request rather than two: a source that was - * saved but never read, or read but never saved, is a state the UI would have - * to explain, and there is nothing useful a person could do about either. - */ -export async function POST( - request: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - if (!(await getSeries(id))) return fail("No such series", 404); - - const body = (await request.json().catch(() => ({}))) as { - url?: string; - kind?: string; - }; - const source = await fetchSource(String(body.url ?? "")); - - /* - * What the tab said, unless the site disagreed. - * - * Paste a feed into "From a link" and it is still a feed — refusing it - * would be the app correcting you about something it can plainly see. - */ - const briefFrom = source.kind === "feed" ? "feed" : "link"; - return ok(await updateSeries(id, { source, briefFrom })); - } catch (e) { - if (e instanceof FetchError) return fail(e.message, e.status); - return caught(e); - } -} - -/** Detach the source and go back to whatever was typed. */ -export async function DELETE( - _r: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const s = await updateSeries(id, { source: null, briefFrom: "typed" }); - return s ? ok(s) : fail("No such series", 404); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/series/route.ts b/app/api/series/route.ts deleted file mode 100644 index 0bf9a62..0000000 --- a/app/api/series/route.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { - DuplicateName, - createSeries, - listSeries, -} from "@/lib/server/repos/series"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -export async function GET(request: Request) { - try { - await ready(); - await requireUser(); - const workspaceId = new URL(request.url).searchParams.get("workspaceId"); - if (!workspaceId) return fail("workspaceId is required"); - return ok(await listSeries(workspaceId)); - } catch (e) { - return caught(e); - } -} - -export async function POST(request: Request) { - try { - await ready(); - await requireUser(); - const body = (await request.json().catch(() => ({}))) as { - workspaceId?: string; - name?: string; - context?: string; - pack?: string; - numbered?: boolean; - partLabel?: string; - }; - if (!body.workspaceId) return fail("workspaceId is required"); - if (!body.name?.trim()) return fail("A series needs a name"); - return ok( - await createSeries({ - workspaceId: body.workspaceId, - name: body.name.trim(), - context: body.context, - pack: body.pack, - numbered: body.numbered, - partLabel: body.partLabel, - }), - 201, - ); - } catch (e) { - // Not just a 409: the screen offers to open the shelf that has the name, - // which it can only do if it is told which one that is. - if (e instanceof DuplicateName) { - return Response.json( - { error: e.message, existing: e.existing }, - { status: 409 }, - ); - } - return caught(e); - } -} diff --git a/app/api/settings/keys/route.ts b/app/api/settings/keys/route.ts deleted file mode 100644 index bd0e339..0000000 --- a/app/api/settings/keys/route.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { - clearSecret, - listSecrets, - setSecret, -} from "@/lib/server/repos/settings"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** - * Service keys. - * - * Masked on the way out, always. The server is the only thing that ever needs - * the real value, and a key that can be read back out of an API is a key that - * leaks through any XSS this app ever has. - */ -export async function GET() { - try { - await ready(); - await requireUser(); - return ok(await listSecrets()); - } catch (e) { - return caught(e); - } -} - -export async function POST(request: Request) { - try { - await ready(); - await requireUser(); - const body = (await request.json().catch(() => ({}))) as { - id?: string; - value?: string; - }; - if (!body.id) return fail("Which key?"); - await setSecret(body.id, body.value ?? ""); - return ok(await listSecrets()); - } catch (e) { - return caught(e); - } -} - -export async function DELETE(request: Request) { - try { - await ready(); - await requireUser(); - const id = new URL(request.url).searchParams.get("id"); - if (!id) return fail("Which key?"); - await clearSecret(id); - return ok(await listSecrets()); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/settings/route.ts b/app/api/settings/route.ts deleted file mode 100644 index 216bc0b..0000000 --- a/app/api/settings/route.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { getSettings, setSettings } from "@/lib/server/repos/settings"; -import { caught, ok, ready } from "@/lib/server/http"; - -export async function GET() { - try { - await ready(); - await requireUser(); - return ok(await getSettings()); - } catch (e) { - return caught(e); - } -} - -export async function PATCH(request: Request) { - try { - await ready(); - await requireUser(); - return ok(await setSettings(await request.json().catch(() => ({})))); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/sources/[id]/frames/[file]/route.ts b/app/api/sources/[id]/frames/[file]/route.ts deleted file mode 100644 index 4c9acf1..0000000 --- a/app/api/sources/[id]/frames/[file]/route.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { frameFile } from "@/lib/server/services/ingest"; -import { caught, fail, ready } from "@/lib/server/http"; - -/** - * One still out of a downloaded video. - * - * Served through a route rather than from /public: these are somebody's - * research material, not site assets, and putting them under /public would - * make every frame of every source readable by anyone who can guess a path. - */ -export async function GET( - _r: Request, - { params }: { params: Promise<{ id: string; file: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id, file } = await params; - const bytes = await frameFile(id, file); - if (!bytes) return fail("No such frame", 404); - return new Response(new Uint8Array(bytes), { - headers: { - "content-type": "image/jpeg", - // The file for a given id never changes; a rewrite makes a new source. - "cache-control": "private, max-age=31536000, immutable", - }, - }); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/sources/[id]/frames/route.ts b/app/api/sources/[id]/frames/route.ts deleted file mode 100644 index ec8414d..0000000 --- a/app/api/sources/[id]/frames/route.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { addFrameAt } from "@/lib/server/services/ingest"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** ffmpeg seeking into a downloaded file — seconds, but not instant. */ -export const maxDuration = 120; - -/** One more still, at a moment somebody asked for. */ -export async function POST( - request: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const body = (await request.json().catch(() => ({}))) as { at?: number }; - const at = Number(body.at); - if (!Number.isFinite(at) || at < 0) return fail("Give a time in seconds"); - return ok(await addFrameAt(id, at), 201); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/sources/[id]/route.ts b/app/api/sources/[id]/route.ts deleted file mode 100644 index 3aa7a68..0000000 --- a/app/api/sources/[id]/route.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { getSource } from "@/lib/server/repos/sources"; -import { removeSource } from "@/lib/server/services/ingest"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -export async function GET( - _r: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const source = await getSource(id); - return source ? ok(source) : fail("No such source", 404); - } catch (e) { - return caught(e); - } -} - -export async function DELETE( - _r: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - return ok({ ok: await removeSource(id) }); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/sources/route.ts b/app/api/sources/route.ts deleted file mode 100644 index 1ab22c2..0000000 --- a/app/api/sources/route.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { listSources } from "@/lib/server/repos/sources"; -import { ingest } from "@/lib/server/services/ingest"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** A download, frames and a transcript. Minutes, not seconds. */ -export const maxDuration = 800; - -export async function GET(request: Request) { - try { - await ready(); - await requireUser(); - const workspaceId = new URL(request.url).searchParams.get("workspaceId"); - return ok(await listSources(workspaceId ?? undefined)); - } catch (e) { - return caught(e); - } -} - -/** - * Fetch a video. - * - * Synchronous on purpose. A background job would need a queue, a worker and a - * way to ask how it is going; this is one person's machine pulling one reel, - * and the browser can wait with a spinner on it. - */ -export async function POST(request: Request) { - try { - await ready(); - await requireUser(); - const body = (await request.json().catch(() => ({}))) as { - url?: string; - workspaceId?: string | null; - refresh?: boolean; - }; - if (!body.url?.trim()) return fail("Paste a link first"); - return ok( - await ingest({ - url: body.url, - workspaceId: body.workspaceId ?? null, - refresh: body.refresh, - }), - 201, - ); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/sources/upload/route.ts b/app/api/sources/upload/route.ts deleted file mode 100644 index bcbb858..0000000 --- a/app/api/sources/upload/route.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { MAX_UPLOAD_BYTES, ingestFile } from "@/lib/server/services/ingest"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** Frames and a transcript off an uploaded file. Minutes. */ -export const maxDuration = 800; - -/** - * A video from the person's own machine. - * - * Multipart rather than base64 JSON: a 200MB reel encodes to 270MB of string, - * and the body has to be held in memory twice to parse it. - */ -export async function POST(request: Request) { - try { - await ready(); - await requireUser(); - - const form = await request.formData().catch(() => null); - const file = form?.get("file"); - if (!(file instanceof File)) return fail("Choose a video file"); - if (!file.size) return fail("That file is empty"); - // The declared size, before a byte is read. The stream re-checks the truth. - if (file.size > MAX_UPLOAD_BYTES) { - return fail( - `That file is over ${Math.round(MAX_UPLOAD_BYTES / 1048576)}MB — trim it or export it smaller.`, - 413, - ); - } - - const workspaceId = form?.get("workspaceId"); - return ok( - await ingestFile({ - filename: file.name, - stream: file.stream(), - workspaceId: typeof workspaceId === "string" ? workspaceId : null, - }), - 201, - ); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/tools/[slug]/route.ts b/app/api/tools/[slug]/route.ts deleted file mode 100644 index 0ee3f30..0000000 --- a/app/api/tools/[slug]/route.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { getTool, updateTool } from "@/lib/server/repos/tools"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -export async function GET( - _r: Request, - { params }: { params: Promise<{ slug: string }> }, -) { - try { - await ready(); - await requireUser(); - const { slug } = await params; - const tool = await getTool(slug); - return tool ? ok(tool) : fail("No such tool", 404); - } catch (e) { - return caught(e); - } -} - -/** Rename it, recategorise it, switch it off, or say where it appears. */ -export async function PATCH( - request: Request, - { params }: { params: Promise<{ slug: string }> }, -) { - try { - await ready(); - await requireUser(); - const { slug } = await params; - const tool = await updateTool(slug, await request.json().catch(() => ({}))); - return tool ? ok(tool) : fail("No such tool", 404); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/tools/route.ts b/app/api/tools/route.ts deleted file mode 100644 index fecae74..0000000 --- a/app/api/tools/route.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { listTools, toolsFor } from "@/lib/server/repos/tools"; -import { caught, ok, ready } from "@/lib/server/http"; - -/** - * The tool bench. - * - * `?workspace=` asks for one workspace's bench — what it is allowed to - * see. Without it you get every tool and its assignment, which is what the - * screen that manages them needs and nothing else should be reading. - */ -export async function GET(request: Request) { - try { - await ready(); - await requireUser(); - const workspace = new URL(request.url).searchParams.get("workspace"); - return ok(workspace ? await toolsFor(workspace) : await listTools()); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/topics/[id]/route.ts b/app/api/topics/[id]/route.ts deleted file mode 100644 index e9ecd42..0000000 --- a/app/api/topics/[id]/route.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { deleteTopic, updateTopic } from "@/lib/server/repos/series"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -export async function PATCH( - request: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const t = await updateTopic(id, await request.json().catch(() => ({}))); - return t ? ok(t) : fail("No such topic", 404); - } catch (e) { - return caught(e); - } -} - -export async function DELETE( - _r: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - return ok({ ok: await deleteTopic(id) }); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/users/[id]/route.ts b/app/api/users/[id]/route.ts deleted file mode 100644 index 13aee8a..0000000 --- a/app/api/users/[id]/route.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { removeUser, requireUser } from "@/lib/server/auth"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -/** Remove someone. Their sessions go with them; their work stays. */ -export async function DELETE( - _r: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - const me = await requireUser(); - const { id } = await params; - const gone = await removeUser(id, me.id); - return gone ? ok({ ok: true }) : fail("No such account", 404); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/users/route.ts b/app/api/users/route.ts deleted file mode 100644 index 5f77771..0000000 --- a/app/api/users/route.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { listUsers, requireUser } from "@/lib/server/auth"; -import { caught, ok, ready } from "@/lib/server/http"; - -/** Who has access to this console. */ -export async function GET() { - try { - await ready(); - await requireUser(); - return ok(await listUsers()); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/workspaces/[id]/route.ts b/app/api/workspaces/[id]/route.ts deleted file mode 100644 index e16ab3c..0000000 --- a/app/api/workspaces/[id]/route.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { - deleteWorkspace, - getWorkspace, - listWorkspaces, - updateWorkspace, -} from "@/lib/server/repos/workspaces"; -import { listSeries } from "@/lib/server/repos/series"; -import { caught, fail, ok, ready } from "@/lib/server/http"; - -export async function GET( - _r: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const ws = await getWorkspace(id); - return ws - ? ok({ ...ws, series: await listSeries(id) }) - : fail("No such workspace", 404); - } catch (e) { - return caught(e); - } -} - -export async function PATCH( - request: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - const ws = await updateWorkspace(id, await request.json().catch(() => ({}))); - return ws - ? ok({ ...ws, series: await listSeries(id) }) - : fail("No such workspace", 404); - } catch (e) { - return caught(e); - } -} - -export async function DELETE( - _r: Request, - { params }: { params: Promise<{ id: string }> }, -) { - try { - await ready(); - await requireUser(); - const { id } = await params; - // The last one cannot go: every screen reads the current workspace's packs, - // series and voice, and an empty list is a shell with nothing to render. - if ((await listWorkspaces()).length <= 1) { - return fail("This is the only workspace — there would be nothing left", 409); - } - return ok({ ok: await deleteWorkspace(id) }); - } catch (e) { - return caught(e); - } -} diff --git a/app/api/workspaces/route.ts b/app/api/workspaces/route.ts deleted file mode 100644 index 3da1010..0000000 --- a/app/api/workspaces/route.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { requireUser } from "@/lib/server/auth"; -import { createWorkspace, listWorkspaces } from "@/lib/server/repos/workspaces"; -import { listSeries } from "@/lib/server/repos/series"; -import { caught, ok, ready } from "@/lib/server/http"; - -/** Every workspace, each with its series and their topics. */ -export async function GET() { - try { - await ready(); - await requireUser(); - const list = await listWorkspaces(); - // Concurrently rather than in sequence: the queries are independent, and - // four workspaces should cost one round trip of latency, not four. - return ok( - await Promise.all( - list.map(async (w) => ({ ...w, series: await listSeries(w.id) })), - ), - ); - } catch (e) { - return caught(e); - } -} - -export async function POST(request: Request) { - try { - await ready(); - await requireUser(); - const body = await request.json().catch(() => ({})); - return ok({ ...(await createWorkspace(body)), series: [] }, 201); - } catch (e) { - return caught(e); - } -} diff --git a/components/Header.tsx b/components/Header.tsx index f99dc0c..f9fd0fb 100644 --- a/components/Header.tsx +++ b/components/Header.tsx @@ -1,5 +1,6 @@ "use client"; +import { apiFetch } from "@/lib/api-base"; import { useEffect, useRef, useState, type CSSProperties } from "react"; import { useRouter } from "next/navigation"; @@ -370,7 +371,7 @@ function Account() { useEffect(() => { let cancelled = false; - void fetch("/api/auth/me", { cache: "no-store" }) + void apiFetch("/api/auth/me", { cache: "no-store" }) .then((r) => r.json()) .then((body: { user?: { email: string; name: string } | null }) => { if (!cancelled) setMe(body.user ?? null); @@ -455,7 +456,7 @@ function Account() { role="menuitem" onClick={() => { setOpen(false); - void fetch("/api/auth/logout", { method: "POST" }).then(() => + void apiFetch("/api/auth/logout", { method: "POST" }).then(() => router.replace("/login"), ); }} diff --git a/components/settings/TeamPanel.tsx b/components/settings/TeamPanel.tsx index 1fad791..e0ed65e 100644 --- a/components/settings/TeamPanel.tsx +++ b/components/settings/TeamPanel.tsx @@ -1,5 +1,6 @@ "use client"; +import { apiFetch } from "@/lib/api-base"; import { useCallback, useEffect, useState } from "react"; import { json } from "@/lib/api-json"; @@ -57,13 +58,13 @@ export function TeamPanel() { const [copied, setCopied] = useState(""); const load = useCallback(() => { - void fetch("/api/invites", { cache: "no-store" }) + void apiFetch("/api/invites", { cache: "no-store" }) .then((r) => json(r)) .then(setInvites) .catch((e: unknown) => setError(e instanceof Error ? e.message : "Could not read the invites"), ); - void fetch("/api/users", { cache: "no-store" }) + void apiFetch("/api/users", { cache: "no-store" }) .then((r) => json(r)) .then(setPeople) .catch(() => setPeople([])); @@ -79,7 +80,7 @@ export function TeamPanel() { setBusy(true); setError(""); try { - const made = await fetch("/api/invites", { + const made = await apiFetch("/api/invites", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: email.trim(), note: note.trim() }), @@ -102,13 +103,13 @@ export function TeamPanel() { const revoke = async (token: string) => { setInvites((prev) => (prev ?? []).filter((i) => i.token !== token)); - await fetch(`/api/invites/${token}`, { method: "DELETE" }).catch(() => {}); + await apiFetch(`/api/invites/${token}`, { method: "DELETE" }).catch(() => {}); load(); }; const removePerson = async (person: Person) => { setPeople((prev) => (prev ?? []).filter((p) => p.id !== person.id)); - await fetch(`/api/users/${person.id}`, { method: "DELETE" }).catch(() => {}); + await apiFetch(`/api/users/${person.id}`, { method: "DELETE" }).catch(() => {}); load(); }; diff --git a/components/views/AuthView.tsx b/components/views/AuthView.tsx index d22f2c8..1f9f135 100644 --- a/components/views/AuthView.tsx +++ b/components/views/AuthView.tsx @@ -1,5 +1,6 @@ "use client"; +import { apiFetch } from "@/lib/api-base"; import { useEffect, useState, type FormEvent } from "react"; import { useRouter, useSearchParams } from "next/navigation"; @@ -42,7 +43,7 @@ export function AuthView({ mode }: { mode: "login" | "signup" }) { useEffect(() => { let cancelled = false; - void fetch("/api/auth/me", { cache: "no-store" }) + void apiFetch("/api/auth/me", { cache: "no-store" }) .then(async (r) => ({ status: r.status, body: await r.json().catch(() => ({})) })) .then(({ status, body }: { status: number; body: { user?: unknown; signupOpen?: boolean; error?: string } }) => { if (cancelled) return; @@ -77,7 +78,7 @@ export function AuthView({ mode }: { mode: "login" | "signup" }) { setBusy(true); setError(""); try { - const res = await fetch(`/api/auth/${signup ? "signup" : "login"}`, { + const res = await apiFetch(`/api/auth/${signup ? "signup" : "login"}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify( diff --git a/components/views/SettingsView.tsx b/components/views/SettingsView.tsx index 67d9c0e..3ff00c5 100644 --- a/components/views/SettingsView.tsx +++ b/components/views/SettingsView.tsx @@ -1,5 +1,6 @@ "use client"; +import { apiFetch } from "@/lib/api-base"; import { useEffect, useState, type ReactNode } from "react"; import { useRouter } from "next/navigation"; @@ -397,11 +398,11 @@ function Account({ const [error, setError] = useState(""); const refresh = () => { - void fetch("/api/auth/me", { cache: "no-store" }) + void apiFetch("/api/auth/me", { cache: "no-store" }) .then((r) => r.json()) .then((b: { user?: typeof me }) => setMe(b.user ?? null)) .catch(() => {}); - void fetch("/api/auth/sessions", { cache: "no-store" }) + void apiFetch("/api/auth/sessions", { cache: "no-store" }) .then((r) => (r.ok ? r.json() : [])) .then(setSessions) .catch(() => {}); @@ -409,13 +410,13 @@ function Account({ useEffect(() => { let cancelled = false; - void fetch("/api/auth/me", { cache: "no-store" }) + void apiFetch("/api/auth/me", { cache: "no-store" }) .then((r) => r.json()) .then((b: { user?: typeof me }) => { if (!cancelled) setMe(b.user ?? null); }) .catch(() => {}); - void fetch("/api/auth/sessions", { cache: "no-store" }) + void apiFetch("/api/auth/sessions", { cache: "no-store" }) .then((r) => (r.ok ? r.json() : [])) .then((rows: Session[]) => { if (!cancelled) setSessions(rows); @@ -429,7 +430,7 @@ function Account({ async function changePassword() { setError(""); setMessage(""); - const res = await fetch("/api/auth/password", { + const res = await apiFetch("/api/auth/password", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ current, next }), @@ -459,7 +460,7 @@ function Account({ >