From 94c5e08af459c1662d7848d3ae3b0cc3194f505f Mon Sep 17 00:00:00 2001 From: Todos Date: Fri, 6 Nov 2026 15:42:51 +0800 Subject: [PATCH 1/3] feat(scenes): add scene dimension migration, DTOs and admin API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add schema_v2 (scenes table, default 通用 seed, categories.scene_id, backfill), SceneDto/AdminSceneDto plus sceneId on category DTOs, and the admin scenes CRUD/reorder endpoints with move-on-delete in one db.batch transaction. Covers DTO normalisation, validation and end-to-end tests. --- worker/src/db/queries/content.ts | 161 ++++- worker/src/lib/migrations.ts | 36 +- worker/src/routes/admin.ts | 179 +++++- worker/src/routes/private.ts | 5 +- worker/src/routes/public.ts | 5 +- worker/src/services/site-data.ts | 54 ++ worker/src/types.ts | 39 ++ worker/test/auth.test.ts | 5 +- worker/test/helpers.ts | 49 +- worker/test/migrate.test.ts | 12 +- worker/test/migrations-ledger.test.ts | 23 +- worker/test/scenes.test.ts | 884 ++++++++++++++++++++++++++ worker/test/setup.test.ts | 17 +- 13 files changed, 1427 insertions(+), 42 deletions(-) create mode 100644 worker/test/scenes.test.ts diff --git a/worker/src/db/queries/content.ts b/worker/src/db/queries/content.ts index 68b3d77..0da5357 100644 --- a/worker/src/db/queries/content.ts +++ b/worker/src/db/queries/content.ts @@ -1,7 +1,14 @@ -import type { Category, Link, SearchEngine } from "../../types"; +import type { Category, Link, Scene, SearchEngine } from "../../types"; import { nowIso } from "../sql"; -const CATEGORY_COLUMNS = ["name", "icon", "sort_order", "visibility"] as const; +const CATEGORY_COLUMNS = [ + "name", + "icon", + "sort_order", + "visibility", + "scene_id", +] as const; +const SCENE_COLUMNS = ["name", "icon", "sort_order", "is_default"] as const; const LINK_COLUMNS = [ "category_id", "title", @@ -64,13 +71,14 @@ export async function insertCategory( icon: string | null; sort_order: number; visibility: string; + scene_id: string | null; }, ): Promise { const now = nowIso(); await db .prepare( - `INSERT INTO ${prefix}categories (id, name, icon, sort_order, visibility, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?)`, + `INSERT INTO ${prefix}categories (id, name, icon, sort_order, visibility, scene_id, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, ) .bind( data.id, @@ -78,6 +86,7 @@ export async function insertCategory( data.icon, data.sort_order, data.visibility, + data.scene_id, now, now, ) @@ -93,6 +102,7 @@ export async function updateCategory( icon: string | null; sort_order: number; visibility: string; + scene_id: string | null; }>, ): Promise { assertColumns( @@ -237,6 +247,149 @@ export async function deleteLinksByCategory( .run(); } +// ─── Scenes ────────────────────────────────────────────────────────────────── + +export async function listScenes( + db: D1Database, + prefix: string, +): Promise { + const result = await db + .prepare(`SELECT * FROM ${prefix}scenes ORDER BY sort_order, created_at`) + .all(); + return result.results; +} + +export async function findScene( + db: D1Database, + prefix: string, + id: string, +): Promise { + return db + .prepare(`SELECT * FROM ${prefix}scenes WHERE id = ?`) + .bind(id) + .first(); +} + +/** + * The single default scene (`is_default = 1`). The partial unique index keeps + * it unique; the ORDER BY only makes the pick deterministic for a database that + * somehow predates that index. + */ +export async function findDefaultScene( + db: D1Database, + prefix: string, +): Promise { + return db + .prepare( + `SELECT * FROM ${prefix}scenes WHERE is_default = 1 ORDER BY sort_order, created_at LIMIT 1`, + ) + .first(); +} + +/** Next append-at-the-end sort order: MAX(sort_order) + 1 (0 on an empty table). */ +export async function nextSceneSortOrder( + db: D1Database, + prefix: string, +): Promise { + const row = await db + .prepare( + `SELECT COALESCE(MAX(sort_order), -1) + 1 AS next FROM ${prefix}scenes`, + ) + .first<{ next: number }>(); + return row?.next ?? 0; +} + +export async function insertScene( + db: D1Database, + prefix: string, + data: { + id: string; + name: string; + icon: string | null; + sort_order: number; + is_default: number; + }, +): Promise { + const now = nowIso(); + await db + .prepare( + `INSERT INTO ${prefix}scenes (id, name, icon, sort_order, is_default, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + ) + .bind( + data.id, + data.name, + data.icon, + data.sort_order, + data.is_default, + now, + now, + ) + .run(); +} + +export async function updateScene( + db: D1Database, + prefix: string, + id: string, + data: Partial<{ + name: string; + icon: string | null; + sort_order: number; + is_default: number; + }>, +): Promise { + assertColumns("updateScene", data as Record, SCENE_COLUMNS); + const fields = Object.keys(data); + if (fields.length === 0) return; + const sets = fields.map((f) => `${f} = ?`); + sets.push("updated_at = ?"); + const values = [ + ...fields.map((f) => (data as Record)[f]), + nowIso(), + id, + ]; + await db + .prepare(`UPDATE ${prefix}scenes SET ${sets.join(", ")} WHERE id = ?`) + .bind(...values) + .run(); +} + +/** + * Deletes a non-default scene, moving its categories (and with them their + * links, by reference) into the default scene first. Both statements run in one + * D1 transaction; the `is_default = 0` guard makes deleting the default scene a + * no-op instead of user-data loss. Categories keep their relative order, appended + * after the default scene's existing ones via `base` (default-scene MAX + 1). + */ +export async function deleteSceneMovingCategories( + db: D1Database, + prefix: string, + sceneId: string, + defaultSceneId: string, +): Promise { + const row = await db + .prepare( + `SELECT COALESCE(MAX(sort_order), -1) + 1 AS base FROM ${prefix}categories WHERE scene_id = ?`, + ) + .bind(defaultSceneId) + .first<{ base: number }>(); + const base = row?.base ?? 0; + + await db.batch([ + db + .prepare( + `UPDATE ${prefix}categories + SET scene_id = ?, sort_order = sort_order + ? + WHERE scene_id = ?`, + ) + .bind(defaultSceneId, base, sceneId), + db + .prepare(`DELETE FROM ${prefix}scenes WHERE id = ? AND is_default = 0`) + .bind(sceneId), + ]); +} + // ─── Search engines ────────────────────────────────────────────────────────── export async function listSearchEngines( diff --git a/worker/src/lib/migrations.ts b/worker/src/lib/migrations.ts index e90febc..eef256e 100644 --- a/worker/src/lib/migrations.ts +++ b/worker/src/lib/migrations.ts @@ -44,9 +44,10 @@ export interface Migration { } /** - * The migration list for a prefix. `schema_v1` is the whole current nav schema + * The migration list for a prefix. `schema_v1` is the whole nav v1 schema * (tables, indexes and the `setup_completed` seed): nav v1 shipped without a - * ledger, so its history is collapsed into one baseline migration. + * ledger, so its history is collapsed into one baseline migration. `schema_v2` + * adds the scene dimension (scenes table + `categories.scene_id`). */ export function getMigrations(prefix: string): Migration[] { const t = (name: string) => `${prefix}${name}`; @@ -162,6 +163,37 @@ CREATE TABLE IF NOT EXISTS ${t("settings")} ( INSERT OR IGNORE INTO ${t("settings")} (key, value, updated_at) VALUES ('setup_completed', '0', strftime('%Y-%m-%dT%H:%M:%fZ', 'now')); +`, + }, + { + name: "schema_v2", + sql: ` +CREATE TABLE IF NOT EXISTS ${t("scenes")} ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + icon TEXT, + sort_order INTEGER NOT NULL DEFAULT 0, + is_default INTEGER NOT NULL DEFAULT 0 CHECK (is_default IN (0, 1)), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE UNIQUE INDEX IF NOT EXISTS ${idx("scenes_single_default")} + ON ${t("scenes")}(is_default) WHERE is_default = 1; + +INSERT OR IGNORE INTO ${t("scenes")} (id, name, icon, sort_order, is_default, created_at, updated_at) +VALUES ('scene_default', '通用', NULL, 0, 1, + strftime('%Y-%m-%dT%H:%M:%fZ', 'now'), + strftime('%Y-%m-%dT%H:%M:%fZ', 'now')); + +ALTER TABLE ${t("categories")} ADD COLUMN scene_id TEXT REFERENCES ${t("scenes")}(id); + +CREATE INDEX IF NOT EXISTS ${idx("categories_scene_id")} + ON ${t("categories")}(scene_id); + +UPDATE ${t("categories")} + SET scene_id = (SELECT id FROM ${t("scenes")} WHERE is_default = 1 ORDER BY sort_order, created_at LIMIT 1) + WHERE scene_id IS NULL; `, }, ]; diff --git a/worker/src/routes/admin.ts b/worker/src/routes/admin.ts index 5450c60..3a343ba 100644 --- a/worker/src/routes/admin.ts +++ b/worker/src/routes/admin.ts @@ -11,25 +11,37 @@ import { deleteCategory, deleteLinksByCategory, deleteLink, + deleteSceneMovingCategories, deleteSearchEngine, findCategory, + findDefaultScene, findLink, + findScene, findSearchEngine, insertCategory, insertLink, + insertScene, insertSearchEngine, listCategories, listLinks, + listScenes, listSearchEngines, + nextSceneSortOrder, updateCategory, updateLink, + updateScene, updateSearchEngine, } from "../db/queries/content"; import { getAllSettings, setSetting } from "../db/queries/settings"; import { listRecordedMigrations } from "../lib/migrations-runner"; import { generateId } from "../core/auth"; -import type { Link } from "../types"; -import { toSearchEngineDto, toSiteSettingsDto } from "../services/site-data"; +import type { Category, Link, Scene } from "../types"; +import { + normalizeSceneId, + toAdminSceneDto, + toSearchEngineDto, + toSiteSettingsDto, +} from "../services/site-data"; import { deleteAssetByPublicPath } from "../services/assets"; import { deleteAsset, uploadAsset } from "./assets"; import { @@ -67,19 +79,28 @@ function parseSortOrder(value: unknown, fallback: number): number { // ─── Categories ────────────────────────────────────────────────────────────── +/** Admin category DTO: full row plus the normalised `sceneId`. */ +function adminCategoryDto(category: Category, scenes: Scene[]) { + return { + id: category.id, + name: category.name, + icon: category.icon, + sortOrder: category.sort_order, + visibility: category.visibility, + sceneId: normalizeSceneId(category.scene_id, scenes), + createdAt: category.created_at, + updatedAt: category.updated_at, + }; +} + adminRoutes.get("/categories", async (c) => { const prefix = getTablePrefix(c.env); - const categories = await listCategories(c.env.DB, prefix); + const [categories, scenes] = await Promise.all([ + listCategories(c.env.DB, prefix), + listScenes(c.env.DB, prefix), + ]); return c.json({ - categories: categories.map((cat) => ({ - id: cat.id, - name: cat.name, - icon: cat.icon, - sortOrder: cat.sort_order, - visibility: cat.visibility, - createdAt: cat.created_at, - updatedAt: cat.updated_at, - })), + categories: categories.map((cat) => adminCategoryDto(cat, scenes)), }); }); @@ -91,6 +112,7 @@ adminRoutes.post("/categories", async (c) => { icon?: unknown; sortOrder?: unknown; visibility?: unknown; + sceneId?: unknown; }>() .catch( (): { @@ -98,6 +120,7 @@ adminRoutes.post("/categories", async (c) => { icon?: unknown; sortOrder?: unknown; visibility?: unknown; + sceneId?: unknown; } => ({}), ); @@ -108,21 +131,41 @@ adminRoutes.post("/categories", async (c) => { return badRequest("visibility must be 'public' or 'private'"); const id = generateId(); + const icon = typeof body.icon === "string" ? body.icon : null; + const sortOrder = parseSortOrder(body.sortOrder, 0); + + // sceneId omitted → the category belongs to the default scene (the seeded + // 通用 scene); an explicit but unknown scene is a client error. + let sceneId: string; + if (body.sceneId !== undefined) { + const requested = + typeof body.sceneId === "string" ? body.sceneId.trim() : ""; + const scene = requested + ? await findScene(c.env.DB, prefix, requested) + : null; + if (!scene) return badRequest("sceneId does not exist"); + sceneId = scene.id; + } else { + sceneId = (await findDefaultScene(c.env.DB, prefix))?.id ?? ""; + } + await insertCategory(c.env.DB, prefix, { id, name, - icon: typeof body.icon === "string" ? body.icon : null, - sort_order: parseSortOrder(body.sortOrder, 0), + icon, + sort_order: sortOrder, visibility, + scene_id: sceneId === "" ? null : sceneId, }); return c.json( { id, name, - icon: typeof body.icon === "string" ? body.icon : null, - sortOrder: parseSortOrder(body.sortOrder, 0), + icon, + sortOrder, visibility, + sceneId, }, 201, ); @@ -151,14 +194,28 @@ adminRoutes.put("/categories/:id", async (c) => { data.visibility = body.visibility; } + if (body.sceneId !== undefined) { + const requested = + typeof body.sceneId === "string" ? body.sceneId.trim() : ""; + const scene = requested + ? await findScene(c.env.DB, prefix, requested) + : null; + if (!scene) return badRequest("sceneId does not exist"); + // Moving a category to another scene is a plain scene_id rewrite; links + // follow their category, so nothing else has to move. + data.scene_id = scene.id; + } + await updateCategory(c.env.DB, prefix, id, data); const updated = await findCategory(c.env.DB, prefix, id); + const scenes = await listScenes(c.env.DB, prefix); return c.json({ id: updated?.id, name: updated?.name, icon: updated?.icon, sortOrder: updated?.sort_order, visibility: updated?.visibility, + sceneId: normalizeSceneId(updated?.scene_id, scenes), }); }); @@ -172,6 +229,83 @@ adminRoutes.delete("/categories/:id", async (c) => { return c.json({ success: true }); }); +// ─── Scenes ────────────────────────────────────────────────────────────────── + +adminRoutes.get("/scenes", async (c) => { + const prefix = getTablePrefix(c.env); + const scenes = await listScenes(c.env.DB, prefix); + return c.json({ scenes: scenes.map(toAdminSceneDto) }); +}); + +adminRoutes.post("/scenes", async (c) => { + const prefix = getTablePrefix(c.env); + const body = await c.req.json().catch(() => ({})); + + const name = typeof body.name === "string" ? body.name.trim() : ""; + if (!name) return badRequest("name is required"); + + const id = generateId(); + const sortOrder = parseSortOrder( + body.sortOrder, + await nextSceneSortOrder(c.env.DB, prefix), + ); + // `isDefault` is read-only: the seeded 通用 scene stays the only default, so + // any isDefault in the payload is ignored (same rule as PUT). + await insertScene(c.env.DB, prefix, { + id, + name, + icon: typeof body.icon === "string" ? body.icon : null, + sort_order: sortOrder, + is_default: 0, + }); + + const created = await findScene(c.env.DB, prefix, id); + if (!created) return c.json({ error: "not found" }, 404); + return c.json(toAdminSceneDto(created), 201); +}); + +adminRoutes.put("/scenes/:id", async (c) => { + const prefix = getTablePrefix(c.env); + const id = c.req.param("id"); + const existing = await findScene(c.env.DB, prefix, id); + if (!existing) return c.json({ error: "not found" }, 404); + + const body = await c.req.json().catch(() => ({})); + const data: Record = {}; + if (body.name !== undefined) { + const name = typeof body.name === "string" ? body.name.trim() : ""; + if (!name) return badRequest("name must not be empty"); + data.name = name; + } + if (body.icon !== undefined) + data.icon = typeof body.icon === "string" ? body.icon : null; + if (body.sortOrder !== undefined) + data.sort_order = parseSortOrder(body.sortOrder, existing.sort_order); + // `isDefault` is read-only — silently ignored, exactly as frozen in #16. + + await updateScene(c.env.DB, prefix, id, data); + const updated = await findScene(c.env.DB, prefix, id); + if (!updated) return c.json({ error: "not found" }, 404); + return c.json(toAdminSceneDto(updated)); +}); + +adminRoutes.delete("/scenes/:id", async (c) => { + const prefix = getTablePrefix(c.env); + const id = c.req.param("id"); + const existing = await findScene(c.env.DB, prefix, id); + if (!existing) return c.json({ error: "not found" }, 404); + if (existing.is_default === 1) + return badRequest("default scene cannot be deleted"); + + const defaultScene = await findDefaultScene(c.env.DB, prefix); + if (!defaultScene) return c.json({ error: "default scene not found" }, 500); + + // One transaction: move categories (links follow by reference) into the + // default scene, then delete the scene with an `is_default = 0` guard. + await deleteSceneMovingCategories(c.env.DB, prefix, id, defaultScene.id); + return c.json({ success: true }); +}); + // ─── Links ─────────────────────────────────────────────────────────────────── /** Admin link DTO: full row incl. visibility + timestamps (contract: docs/api-contract.md). */ @@ -379,6 +513,19 @@ adminRoutes.post("/categories/reorder", async (c) => { return c.json({ success: true }); }); +adminRoutes.post("/scenes/reorder", async (c) => { + const prefix = getTablePrefix(c.env); + const body = await c.req.json().catch(() => ({})); + if (!Array.isArray(body.ids)) + return badRequest("ids must be an array of scene ids"); + for (const [index, id] of body.ids.entries()) { + if (typeof id !== "string") + return badRequest("ids must be an array of scene ids"); + await updateScene(c.env.DB, prefix, id, { sort_order: index }); + } + return c.json({ success: true }); +}); + adminRoutes.post("/links/reorder", async (c) => { const prefix = getTablePrefix(c.env); const body = await c.req.json().catch(() => ({})); diff --git a/worker/src/routes/private.ts b/worker/src/routes/private.ts index 08c0de1..71350ca 100644 --- a/worker/src/routes/private.ts +++ b/worker/src/routes/private.ts @@ -4,6 +4,7 @@ import { authMiddleware } from "../middleware/auth"; import { listCategories, listLinks, + listScenes, listSearchEngines, } from "../db/queries/content"; import { getAllSettings } from "../db/queries/settings"; @@ -22,11 +23,12 @@ privateRoutes.use("*", authMiddleware); privateRoutes.get("/", async (c) => { const prefix = getTablePrefix(c.env); await ensureSchema(c.env); - const [categories, links, engines, settings] = await Promise.all([ + const [categories, links, engines, settings, scenes] = await Promise.all([ listCategories(c.env.DB, prefix), listLinks(c.env.DB, prefix), listSearchEngines(c.env.DB, prefix), getAllSettings(c.env.DB, prefix), + listScenes(c.env.DB, prefix), ]); const data: SiteDataDto = buildSiteData( @@ -34,6 +36,7 @@ privateRoutes.get("/", async (c) => { links, engines, settings, + scenes, { includePrivate: true, }, diff --git a/worker/src/routes/public.ts b/worker/src/routes/public.ts index a4f9a6e..1245a48 100644 --- a/worker/src/routes/public.ts +++ b/worker/src/routes/public.ts @@ -3,6 +3,7 @@ import { getTablePrefix, type HonoEnv, type SiteDataDto } from "../types"; import { listCategories, listLinks, + listScenes, listSearchEngines, } from "../db/queries/content"; import { getAllSettings } from "../db/queries/settings"; @@ -19,11 +20,12 @@ export const publicRoutes = new Hono(); publicRoutes.get("/", async (c) => { const prefix = getTablePrefix(c.env); await ensureSchema(c.env); - const [categories, links, engines, settings] = await Promise.all([ + const [categories, links, engines, settings, scenes] = await Promise.all([ listCategories(c.env.DB, prefix), listLinks(c.env.DB, prefix), listSearchEngines(c.env.DB, prefix), getAllSettings(c.env.DB, prefix), + listScenes(c.env.DB, prefix), ]); // Visibility = stricter of category and link: drop public links that live in @@ -43,6 +45,7 @@ publicRoutes.get("/", async (c) => { publicLinks, engines, settings, + scenes, { includePrivate: false }, ); diff --git a/worker/src/services/site-data.ts b/worker/src/services/site-data.ts index e6aaca9..7cb4758 100644 --- a/worker/src/services/site-data.ts +++ b/worker/src/services/site-data.ts @@ -1,8 +1,11 @@ import type { + AdminSceneDto, Category, Link, PublicCategoryDto, PublicLinkDto, + Scene, + SceneDto, SearchEngine, SearchEngineDto, SiteDataDto, @@ -57,6 +60,7 @@ export function buildSiteData( links: Link[], engines: SearchEngine[], settings: Record, + scenes: Scene[], opts: { includePrivate: boolean }, ): SiteDataDto { const linksByCategory = new Map(); @@ -66,6 +70,9 @@ export function buildSiteData( linksByCategory.set(link.category_id, bucket); } + const sceneIds = new Set(scenes.map((scene) => scene.id)); + const fallbackSceneId = defaultSceneId(scenes); + const dtoCategories: PublicCategoryDto[] = []; for (const category of categories) { const categoryPrivate = category.visibility === "private"; @@ -83,13 +90,60 @@ export function buildSiteData( name: category.name, icon: category.icon, sortOrder: category.sort_order, + // Defensive normalisation only: every write path supplies a scene, but a + // legacy row written before schema_v2 may still be NULL/dangling. + sceneId: + category.scene_id !== null && sceneIds.has(category.scene_id) + ? category.scene_id + : fallbackSceneId, links: visibleLinks.map(toPublicLinkDto), }); } return { categories: dtoCategories, + scenes: scenes.map(toSceneDto), searchEngines: engines.map(toSearchEngineDto), settings: toSiteSettingsDto(settings), }; } + +// ─── Scenes ────────────────────────────────────────────────────────────────── + +export function toSceneDto(scene: Scene): SceneDto { + return { + id: scene.id, + name: scene.name, + icon: scene.icon, + sortOrder: scene.sort_order, + isDefault: scene.is_default === 1, + }; +} + +export function toAdminSceneDto(scene: Scene): AdminSceneDto { + return { + ...toSceneDto(scene), + createdAt: scene.created_at, + updatedAt: scene.updated_at, + }; +} + +/** + * The default scene is identified by `is_default = 1` only — never by id or by + * the name「通用」(the name is editable). Falls back to the first scene, then to + * "", so a corrupt database still yields a well-formed DTO. + */ +export function defaultSceneId(scenes: Scene[]): string { + return ( + scenes.find((scene) => scene.is_default === 1)?.id ?? scenes[0]?.id ?? "" + ); +} + +/** Normalises a category's scene to the default scene when it is unset/unknown. */ +export function normalizeSceneId( + sceneId: string | null | undefined, + scenes: Scene[], +): string { + if (sceneId && scenes.some((scene) => scene.id === sceneId)) return sceneId; + return defaultSceneId(scenes); +} diff --git a/worker/src/types.ts b/worker/src/types.ts index e6e028e..2893fdc 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -78,6 +78,22 @@ export interface Category { icon: string | null; sort_order: number; visibility: "public" | "private"; + /** + * Owning scene (schema_v2). Nullable because SQLite's ALTER TABLE cannot add + * a NOT NULL column; NULL/dangling values are normalised to the default scene + * at the DTO layer. + */ + scene_id: string | null; + created_at: string; + updated_at: string; +} + +export interface Scene { + id: string; + name: string; + icon: string | null; + sort_order: number; + is_default: number; created_at: string; updated_at: string; } @@ -120,11 +136,28 @@ export interface Setting { // ─── Frozen API DTOs (camelCase, contract ONE-168) ─────────────────────────── +/** Scene DTO shared by the public/private surface and the admin surface. */ +export interface SceneDto { + id: string; + name: string; + icon: string | null; + sortOrder: number; + isDefault: boolean; +} + +/** `GET/POST/PUT /api/admin/scenes` — SceneDto plus timestamps. */ +export interface AdminSceneDto extends SceneDto { + createdAt: string; + updatedAt: string; +} + export interface PublicCategoryDto { id: string; name: string; icon: string | null; sortOrder: number; + /** Owning scene, normalised to the default scene for NULL/dangling ids. */ + sceneId: string; links: PublicLinkDto[]; } @@ -162,6 +195,12 @@ export interface SiteSettingsDto { export interface SiteDataDto { categories: PublicCategoryDto[]; + /** + * Every scene, ordered by sort_order, created_at — including scenes whose + * only categories are private. The server never filters by scene; clients + * filter locally. + */ + scenes: SceneDto[]; searchEngines: SearchEngineDto[]; settings: SiteSettingsDto; } diff --git a/worker/test/auth.test.ts b/worker/test/auth.test.ts index fd56a19..b641706 100644 --- a/worker/test/auth.test.ts +++ b/worker/test/auth.test.ts @@ -220,7 +220,10 @@ describe("setup response (ledgered migrations)", () => { const body = await readJson(res); expect(body.success).toBe(true); expect(body.tablePrefix).toBe(""); - expect(body.migrations).toEqual([{ name: "schema_v1", status: "applied" }]); + expect(body.migrations).toEqual([ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + ]); }); it("turns a table-prefix conflict into 409 instead of building a second schema", async () => { diff --git a/worker/test/helpers.ts b/worker/test/helpers.ts index 8271985..ec8e0ff 100644 --- a/worker/test/helpers.ts +++ b/worker/test/helpers.ts @@ -15,25 +15,64 @@ export class SqliteD1 { this.queries.push(sql); const statement = () => db.prepare(sql); - return { - bind: (...args: unknown[]) => ({ + const execute = (args: unknown[]) => { + statement().run(...(args as any[])); + }; + + const withArgs = (args: unknown[]) => { + const stub: any = { first: async () => (statement().get(...(args as any[])) ?? null) as T | null, all: async () => ({ results: statement().all(...(args as any[])) as T[], }), run: async () => { - statement().run(...(args as any[])); + execute(args); return { success: true }; }, - }), + }; + // Internal hook used by batch(): D1 statements are executed by their + // prepared form, not by re-parsing the bound stub. + stub._execute = () => execute(args); + return stub; + }; + + const stub: any = { + bind: (...args: unknown[]) => withArgs(args), first: async () => (statement().get() ?? null) as T | null, all: async () => ({ results: statement().all() as T[] }), run: async () => { - statement().run(); + execute([]); return { success: true }; }, }; + stub._execute = () => execute([]); + return stub; + } + + /** + * Minimal D1 batch(): one BEGIN, every statement in order, COMMIT; any error + * rolls the whole batch back and is rethrown (matching D1's all-or-nothing + * transaction semantics for scene deletion). + */ + async batch(statements: any[]): Promise> { + this.db.exec("BEGIN"); + try { + const results = statements.map((statement) => { + if (typeof statement?._execute !== "function") { + throw new Error( + "SqliteD1.batch only supports statements created by prepare()", + ); + } + statement._execute(); + return { success: true }; + }); + this.db.exec("COMMIT"); + return results; + } catch (err) { + this.db.exec("ROLLBACK"); + throw err; + } } // D1Database.exec(): runs one or more semicolon-separated statements. Backed diff --git a/worker/test/migrate.test.ts b/worker/test/migrate.test.ts index 8d01bc2..dfe6097 100644 --- a/worker/test/migrate.test.ts +++ b/worker/test/migrate.test.ts @@ -8,6 +8,7 @@ describe("D1 migration", () => { const result = await runMigrations(env); expect(result.migrations).toEqual([ { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, ]); const db = (env.DB as unknown as SqliteD1).db; @@ -28,6 +29,7 @@ describe("D1 migration", () => { "links", "search_engines", "settings", + "scenes", ]) { expect(tables).toContain(table); } @@ -38,11 +40,17 @@ describe("D1 migration", () => { await runMigrations(env); await expect(runMigrations(env)).resolves.toEqual({ prefix: "", - migrations: [{ name: "schema_v1", status: "skipped" }], + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "skipped" }, + ], }); await expect(runMigrations(env)).resolves.toEqual({ prefix: "", - migrations: [{ name: "schema_v1", status: "skipped" }], + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "skipped" }, + ], }); }); diff --git a/worker/test/migrations-ledger.test.ts b/worker/test/migrations-ledger.test.ts index 2bf55ac..0df7665 100644 --- a/worker/test/migrations-ledger.test.ts +++ b/worker/test/migrations-ledger.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { migrationsTable } from "../src/lib/migrations"; +import { getMigrations, migrationsTable } from "../src/lib/migrations"; import { applyMigrationList, runMigrations, @@ -46,17 +46,18 @@ describe("migrationsTable() naming (three states + case preserved)", () => { }); describe("ledgered migration runner", () => { - it("applies everything on an empty database and records exactly schema_v1", async () => { + it("applies everything on an empty database and records both migrations", async () => { const env = makeEnv({ TABLE_PREFIX: undefined }); // → nav_ const result = await runMigrations(env); expect(result.prefix).toBe("nav_"); expect(result.migrations.map((m) => [m.name, m.status])).toEqual([ ["schema_v1", "applied"], + ["schema_v2", "applied"], ]); const ledger = ledgerRows(env.DB, "nav_"); - expect(ledger.map((row) => row.name)).toEqual(["schema_v1"]); + expect(ledger.map((row) => row.name)).toEqual(["schema_v1", "schema_v2"]); expect(ledger[0]?.applied_at).toBeGreaterThan(0); const tables = tableNames(env.DB); @@ -71,6 +72,7 @@ describe("ledgered migration runner", () => { "links", "search_engines", "settings", + "scenes", ]) { expect(tables).toContain(`nav_${table}`); } @@ -91,6 +93,7 @@ describe("ledgered migration runner", () => { const second = await runMigrations(env); expect(second.migrations).toEqual([ { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "skipped" }, ]); expect(tableNames(env.DB)).toEqual(schemaBefore); @@ -112,24 +115,31 @@ describe("ledgered migration runner", () => { expect(tableNames(env.DB)).toContain("_schema_migrations"); expect(ledgerRows(env.DB, "").map((row) => row.name)).toEqual([ "schema_v1", + "schema_v2", ]); }); it("adopts an existing nav_* schema that predates the ledger", async () => { - // Simulates a nav v1 database: all business tables present, no ledger yet. + // Simulates a nav v1 database: schema_v1 tables present, no ledger yet, and + // no scene dimension. schema_v1 (IF NOT EXISTS) adopts it, then schema_v2 + // adds scenes + categories.scene_id. const env = makeEnv({ TABLE_PREFIX: "nav_" }); - await runMigrations(env); - sqliteOf(env.DB).exec("DROP TABLE _nav_schema_migrations;"); + const v1 = getMigrations("nav_")[0]; + if (!v1) throw new Error("schema_v1 missing"); + sqliteOf(env.DB).exec(v1.sql); const result = await runMigrations(env); expect(result.prefix).toBe("nav_"); expect(result.migrations).toEqual([ { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, ]); expect(ledgerRows(env.DB, "nav_").map((row) => row.name)).toEqual([ "schema_v1", + "schema_v2", ]); expect(tableNames(env.DB)).toContain("_nav_schema_migrations"); + expect(tableNames(env.DB)).toContain("nav_scenes"); }); it("aborts instead of quietly switching to a different prefix", async () => { @@ -177,6 +187,7 @@ describe("ledgered migration runner", () => { expect(result.prefix).toBe("nav_"); expect(result.migrations).toEqual([ { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, ]); }); diff --git a/worker/test/scenes.test.ts b/worker/test/scenes.test.ts new file mode 100644 index 0000000..1528557 --- /dev/null +++ b/worker/test/scenes.test.ts @@ -0,0 +1,884 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { Hono } from "hono"; +import { + applyMigrationList, + runMigrations, +} from "../src/lib/migrations-runner"; +import { getMigrations } from "../src/lib/migrations"; +import { publicRoutes } from "../src/routes/public"; +import { privateRoutes } from "../src/routes/private"; +import { adminRoutes } from "../src/routes/admin"; +import { authRoutes } from "../src/routes/auth"; +import type { Env } from "../src/types"; +import { makeEnv, readJson, type SqliteD1 } from "./helpers"; + +const SETUP_SECRET = "test-setup-secret"; + +function makeApp(): Hono { + const app = new Hono(); + app.route("/api/auth", authRoutes); + app.route("/api/public", publicRoutes); + app.route("/api/private", privateRoutes); + app.route("/api/admin", adminRoutes); + return app; +} + +async function ownerCookie(app: Hono, env: Env): Promise { + const res = await app.request( + "/api/auth/setup", + { + method: "POST", + body: JSON.stringify({ username: "owner", password: "password123" }), + headers: { + "content-type": "application/json", + "X-Setup-Secret": SETUP_SECRET, + }, + }, + env, + ); + expect(res.status).toBe(201); + return res.headers.get("set-cookie") ?? ""; +} + +function adminRequest( + app: Hono, + env: Env, + cookie: string, + path: string, + init: { method?: string; body?: unknown } = {}, +): Promise { + return app.request( + path, + { + method: init.method ?? "GET", + headers: { "content-type": "application/json", cookie }, + body: init.body === undefined ? undefined : JSON.stringify(init.body), + }, + env, + ); +} + +function sqliteOf(env: Env): SqliteD1["db"] { + return (env.DB as unknown as SqliteD1).db; +} + +function count(env: Env, sql: string, ...args: unknown[]): number { + return ( + sqliteOf(env) + .prepare(sql) + .get(...(args as never[])) as { n: number } + ).n; +} + +const NOW = "2026-11-06T00:00:00.000Z"; + +function insertSceneRow( + env: Env, + scene: { + id: string; + name: string; + sortOrder: number; + isDefault?: boolean; + }, +): void { + sqliteOf(env) + .prepare( + "INSERT INTO scenes (id, name, icon, sort_order, is_default, created_at, updated_at) VALUES (?, ?, NULL, ?, ?, ?, ?)", + ) + .run( + scene.id, + scene.name, + scene.sortOrder, + scene.isDefault ? 1 : 0, + NOW, + NOW, + ); +} + +function insertCategoryRow( + env: Env, + category: { + id: string; + name: string; + sortOrder: number; + sceneId?: string | null; + visibility?: "public" | "private"; + }, +): void { + sqliteOf(env) + .prepare( + "INSERT INTO categories (id, name, icon, sort_order, visibility, scene_id, created_at, updated_at) VALUES (?, ?, NULL, ?, ?, ?, ?, ?)", + ) + .run( + category.id, + category.name, + category.sortOrder, + category.visibility ?? "public", + category.sceneId === undefined ? "scene_default" : category.sceneId, + NOW, + NOW, + ); +} + +/** nav v1 row: the pre-schema_v2 categories table has no scene_id column. */ +function insertLegacyCategoryRow(env: Env, id: string, name: string): void { + sqliteOf(env) + .prepare( + "INSERT INTO categories (id, name, icon, sort_order, visibility, created_at, updated_at) VALUES (?, ?, NULL, 0, 'public', ?, ?)", + ) + .run(id, name, NOW, NOW); +} + +function insertLinkRow( + env: Env, + link: { id: string; categoryId: string; visibility?: "public" | "private" }, +): void { + sqliteOf(env) + .prepare( + "INSERT INTO links (id, category_id, title, url, icon_url, description, sort_order, visibility, created_at, updated_at) VALUES (?, ?, ?, ?, NULL, NULL, 0, ?, ?, ?)", + ) + .run( + link.id, + link.categoryId, + link.id, + `https://${link.id}.example.com`, + link.visibility ?? "public", + NOW, + NOW, + ); +} + +describe("schema_v2 migration (scenes)", () => { + it("creates scenes, seeds the single default and backfills legacy categories", async () => { + const env = makeEnv(); + // Simulate a nav v1 database: schema_v1 applied, one category, no scenes. + const v1 = getMigrations("")[0]; + if (!v1) throw new Error("schema_v1 missing"); + await applyMigrationList(env.DB, "", [v1]); + insertLegacyCategoryRow(env, "legacy", "Legacy"); + + const result = await runMigrations(env); + expect(result.migrations).toEqual([ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "applied" }, + ]); + + const scenes = sqliteOf(env).prepare("SELECT * FROM scenes").all() as Array< + Record + >; + expect(scenes).toHaveLength(1); + expect(scenes[0]).toMatchObject({ + id: "scene_default", + name: "通用", + icon: null, + sort_order: 0, + is_default: 1, + }); + expect(scenes[0]?.created_at).toBeTruthy(); + + const category = sqliteOf(env) + .prepare("SELECT scene_id FROM categories WHERE id = 'legacy'") + .get() as { scene_id: string }; + expect(category.scene_id).toBe("scene_default"); + + const indexes = sqliteOf(env) + .prepare("SELECT name FROM sqlite_master WHERE type = 'index'") + .all() + .map((row: { name: string }) => row.name); + expect(indexes).toContain("idx_scenes_single_default"); + expect(indexes).toContain("idx_categories_scene_id"); + }); + + it("prefixes the scenes table, indexes and seed id like every other table", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + await runMigrations(env); + + const tables = sqliteOf(env) + .prepare("SELECT name FROM sqlite_master WHERE type = 'table'") + .all() + .map((row: { name: string }) => row.name); + expect(tables).toContain("nav_scenes"); + + const indexes = sqliteOf(env) + .prepare("SELECT name FROM sqlite_master WHERE type = 'index'") + .all() + .map((row: { name: string }) => row.name); + expect(indexes).toContain("idx_nav_scenes_single_default"); + expect(indexes).toContain("idx_nav_categories_scene_id"); + + expect( + count( + env, + "SELECT COUNT(*) AS n FROM nav_scenes WHERE id = 'scene_default' AND is_default = 1", + ), + ).toBe(1); + }); + + it("rejects a second default scene at the database level", async () => { + const env = makeEnv(); + await runMigrations(env); + + expect(() => + sqliteOf(env) + .prepare( + "INSERT INTO scenes (id, name, icon, sort_order, is_default, created_at, updated_at) VALUES ('second', 'x', NULL, 1, 1, ?, ?)", + ) + .run(NOW, NOW), + ).toThrow(); + }); +}); + +describe("site data DTOs carry scenes + category sceneId", () => { + let env: Env; + let app: Hono; + let cookie: string; + + beforeEach(async () => { + env = makeEnv(); + app = makeApp(); + await runMigrations(env); + cookie = await ownerCookie(app, env); + + insertSceneRow(env, { id: "scene_work", name: "工作", sortOrder: 1 }); + insertSceneRow(env, { + id: "scene_private", + name: "私密场景", + sortOrder: 2, + }); + + insertCategoryRow(env, { + id: "cat-default", + name: "通用分类", + sortOrder: 0, + }); + insertCategoryRow(env, { + id: "cat-work", + name: "工作分类", + sortOrder: 0, + sceneId: "scene_work", + }); + insertCategoryRow(env, { + id: "cat-legacy", + name: "存量空场景", + sortOrder: 1, + sceneId: null, + }); + // D1 does not enforce foreign keys, so a dangling scene_id can exist in + // production; node:sqlite does enforce them, so turn the check off for this + // one defensive-path row. + sqliteOf(env).exec("PRAGMA foreign_keys = OFF"); + insertCategoryRow(env, { + id: "cat-dangling", + name: "悬空场景", + sortOrder: 2, + sceneId: "ghost", + }); + sqliteOf(env).exec("PRAGMA foreign_keys = ON"); + insertCategoryRow(env, { + id: "cat-private", + name: "私密分类", + sortOrder: 0, + sceneId: "scene_private", + visibility: "private", + }); + + insertLinkRow(env, { id: "link-default", categoryId: "cat-default" }); + insertLinkRow(env, { id: "link-work", categoryId: "cat-work" }); + insertLinkRow(env, { + id: "link-private", + categoryId: "cat-private", + visibility: "private", + }); + }); + + it("GET /api/public returns every scene (incl. private-only ones) in sort order", async () => { + const res = await app.request("/api/public", {}, env); + expect(res.status).toBe(200); + const body = await readJson(res); + + expect(body.scenes).toEqual([ + { + id: "scene_default", + name: "通用", + icon: null, + sortOrder: 0, + isDefault: true, + }, + { + id: "scene_work", + name: "工作", + icon: null, + sortOrder: 1, + isDefault: false, + }, + { + id: "scene_private", + name: "私密场景", + icon: null, + sortOrder: 2, + isDefault: false, + }, + ]); + + // Private data stays hidden, but the scene list itself is complete. + expect(JSON.stringify(body)).not.toContain("私密分类"); + expect(body.categories.map((cat: { id: string }) => cat.id)).toEqual([ + "cat-default", + "cat-work", + "cat-legacy", + "cat-dangling", + ]); + + const byId = Object.fromEntries( + body.categories.map((cat: { id: string; sceneId: string }) => [ + cat.id, + cat.sceneId, + ]), + ); + expect(byId["cat-default"]).toBe("scene_default"); + expect(byId["cat-work"]).toBe("scene_work"); + // NULL / dangling scene ids normalise to the default scene. + expect(byId["cat-legacy"]).toBe("scene_default"); + expect(byId["cat-dangling"]).toBe("scene_default"); + }); + + it("GET /api/private carries full data with sceneId, no-store unchanged", async () => { + const res = await app.request("/api/private", { headers: { cookie } }, env); + expect(res.status).toBe(200); + expect(res.headers.get("cache-control")).toBe("no-store"); + const body = await readJson(res); + + expect(body.scenes).toHaveLength(3); + const privateCat = body.categories.find( + (cat: { id: string }) => cat.id === "cat-private", + ); + expect(privateCat.sceneId).toBe("scene_private"); + expect(privateCat.links).toHaveLength(1); + }); + + it("admin GET /api/admin/categories returns the normalised sceneId", async () => { + const res = await adminRequest(app, env, cookie, "/api/admin/categories"); + expect(res.status).toBe(200); + const body = await readJson(res); + const byId = Object.fromEntries( + body.categories.map((cat: { id: string; sceneId: string }) => [ + cat.id, + cat.sceneId, + ]), + ); + expect(byId["cat-work"]).toBe("scene_work"); + expect(byId["cat-legacy"]).toBe("scene_default"); + expect(byId["cat-dangling"]).toBe("scene_default"); + }); +}); + +describe("admin scenes CRUD", () => { + let env: Env; + let app: Hono; + let cookie: string; + + beforeEach(async () => { + env = makeEnv(); + app = makeApp(); + await runMigrations(env); + cookie = await ownerCookie(app, env); + }); + + it("requires a session on every scene endpoint", async () => { + for (const [path, init] of [ + ["/api/admin/scenes", {}], + ["/api/admin/scenes", { method: "POST" }], + ["/api/admin/scenes/x", { method: "PUT" }], + ["/api/admin/scenes/x", { method: "DELETE" }], + ["/api/admin/scenes/reorder", { method: "POST" }], + ] as Array<[string, RequestInit]>) { + const res = await app.request(path, init, env); + expect(res.status).toBe(401); + expect(await readJson(res)).toEqual({ error: "unauthorized" }); + } + }); + + it("GET returns the seeded default scene with timestamps", async () => { + const res = await adminRequest(app, env, cookie, "/api/admin/scenes"); + expect(res.status).toBe(200); + const body = await readJson(res); + expect(body.scenes).toHaveLength(1); + expect(body.scenes[0]).toMatchObject({ + id: "scene_default", + name: "通用", + icon: null, + sortOrder: 0, + isDefault: true, + }); + expect(body.scenes[0].createdAt).toBeTruthy(); + expect(body.scenes[0].updatedAt).toBeTruthy(); + }); + + it("POST validates the name and appends to the end by default", async () => { + const missing = await adminRequest(app, env, cookie, "/api/admin/scenes", { + method: "POST", + body: { icon: "icon" }, + }); + expect(missing.status).toBe(400); + expect(await readJson(missing)).toEqual({ error: "name is required" }); + + const blank = await adminRequest(app, env, cookie, "/api/admin/scenes", { + method: "POST", + body: { name: " " }, + }); + expect(blank.status).toBe(400); + expect(await readJson(blank)).toEqual({ error: "name is required" }); + + const created = await adminRequest(app, env, cookie, "/api/admin/scenes", { + method: "POST", + body: { name: " 工作 ", icon: 42, isDefault: true }, + }); + expect(created.status).toBe(201); + const body = await readJson(created); + expect(body).toMatchObject({ + name: "工作", + icon: null, + sortOrder: 1, + isDefault: false, + }); + expect(body.id).toBeTruthy(); + expect(body.createdAt).toBeTruthy(); + + // isDefault in the payload is read-only and never creates a second default. + expect( + count(env, "SELECT COUNT(*) AS n FROM scenes WHERE is_default = 1"), + ).toBe(1); + }); + + it("POST honours an explicit sortOrder and requires string icon only", async () => { + const res = await adminRequest(app, env, cookie, "/api/admin/scenes", { + method: "POST", + body: { name: "阅读", icon: "book", sortOrder: 7 }, + }); + expect(res.status).toBe(201); + expect(await readJson(res)).toMatchObject({ + name: "阅读", + icon: "book", + sortOrder: 7, + isDefault: false, + }); + }); + + it("PUT renames/re-icons/sorts and silently ignores isDefault", async () => { + const created = await readJson( + await adminRequest(app, env, cookie, "/api/admin/scenes", { + method: "POST", + body: { name: "工作" }, + }), + ); + + const updated = await adminRequest( + app, + env, + cookie, + `/api/admin/scenes/${created.id}`, + { + method: "PUT", + body: { + name: " 办公 ", + icon: 7, + sortOrder: 3, + isDefault: true, + }, + }, + ); + expect(updated.status).toBe(200); + expect(await readJson(updated)).toMatchObject({ + id: created.id, + name: "办公", + icon: null, + sortOrder: 3, + isDefault: false, + }); + expect( + count(env, "SELECT COUNT(*) AS n FROM scenes WHERE is_default = 1"), + ).toBe(1); + + const empty = await adminRequest( + app, + env, + cookie, + `/api/admin/scenes/${created.id}`, + { method: "PUT", body: { name: " " } }, + ); + expect(empty.status).toBe(400); + expect(await readJson(empty)).toEqual({ error: "name must not be empty" }); + + const missing = await adminRequest( + app, + env, + cookie, + "/api/admin/scenes/nope", + { method: "PUT", body: { name: "x" } }, + ); + expect(missing.status).toBe(404); + expect(await readJson(missing)).toEqual({ error: "not found" }); + }); + + it("the default scene can be renamed/sorted but not deleted", async () => { + const renamed = await adminRequest( + app, + env, + cookie, + "/api/admin/scenes/scene_default", + { method: "PUT", body: { name: "首页" } }, + ); + expect(renamed.status).toBe(200); + expect(await readJson(renamed)).toMatchObject({ + id: "scene_default", + name: "首页", + isDefault: true, + }); + + // Default detection is by is_default, never by the name or id. + const del = await adminRequest( + app, + env, + cookie, + "/api/admin/scenes/scene_default", + { method: "DELETE" }, + ); + expect(del.status).toBe(400); + expect(await readJson(del)).toEqual({ + error: "default scene cannot be deleted", + }); + + const missing = await adminRequest( + app, + env, + cookie, + "/api/admin/scenes/nope", + { method: "DELETE" }, + ); + expect(missing.status).toBe(404); + expect(await readJson(missing)).toEqual({ error: "not found" }); + }); + + it("reorder rewrites sort_order in payload order", async () => { + const work = await readJson( + await adminRequest(app, env, cookie, "/api/admin/scenes", { + method: "POST", + body: { name: "工作" }, + }), + ); + const life = await readJson( + await adminRequest(app, env, cookie, "/api/admin/scenes", { + method: "POST", + body: { name: "生活" }, + }), + ); + + const res = await adminRequest( + app, + env, + cookie, + "/api/admin/scenes/reorder", + { method: "POST", body: { ids: [life.id, "scene_default", work.id] } }, + ); + expect(res.status).toBe(200); + expect(await readJson(res)).toEqual({ success: true }); + + const list = await readJson( + await adminRequest(app, env, cookie, "/api/admin/scenes"), + ); + expect(list.scenes.map((scene: { name: string }) => scene.name)).toEqual([ + "生活", + "通用", + "工作", + ]); + + const bad = await adminRequest( + app, + env, + cookie, + "/api/admin/scenes/reorder", + { method: "POST", body: { ids: "x" } }, + ); + expect(bad.status).toBe(400); + expect(await readJson(bad)).toEqual({ + error: "ids must be an array of scene ids", + }); + }); + + it("DELETE moves categories (and their links) into the default scene", async () => { + const work = await readJson( + await adminRequest(app, env, cookie, "/api/admin/scenes", { + method: "POST", + body: { name: "工作" }, + }), + ); + + // Default scene already has a category at sort_order 5 → move target starts at 6. + insertCategoryRow(env, { + id: "cat-default", + name: "通用分类", + sortOrder: 5, + }); + insertCategoryRow(env, { + id: "cat-work-a", + name: "工作 A", + sortOrder: 0, + sceneId: work.id, + }); + insertCategoryRow(env, { + id: "cat-work-b", + name: "工作 B", + sortOrder: 3, + sceneId: work.id, + }); + insertLinkRow(env, { id: "link-a", categoryId: "cat-work-a" }); + + const res = await adminRequest( + app, + env, + cookie, + `/api/admin/scenes/${work.id}`, + { method: "DELETE" }, + ); + expect(res.status).toBe(200); + expect(await readJson(res)).toEqual({ success: true }); + + expect( + count(env, "SELECT COUNT(*) AS n FROM scenes WHERE id = ?", work.id), + ).toBe(0); + expect( + sqliteOf(env) + .prepare( + "SELECT id, scene_id, sort_order FROM categories WHERE id IN ('cat-work-a', 'cat-work-b') ORDER BY id", + ) + .all(), + ).toEqual([ + { id: "cat-work-a", scene_id: "scene_default", sort_order: 6 }, + { id: "cat-work-b", scene_id: "scene_default", sort_order: 9 }, + ]); + // Links are untouched — they follow their category. + expect( + count( + env, + "SELECT COUNT(*) AS n FROM links WHERE id = 'link-a' AND category_id = 'cat-work-a'", + ), + ).toBe(1); + }); + + it("DELETE works for an empty scene even when the default scene is empty", async () => { + // No category in the default scene → COALESCE(MAX, -1) + 1 = 0 base. + const work = await readJson( + await adminRequest(app, env, cookie, "/api/admin/scenes", { + method: "POST", + body: { name: "工作" }, + }), + ); + const res = await adminRequest( + app, + env, + cookie, + `/api/admin/scenes/${work.id}`, + { method: "DELETE" }, + ); + expect(res.status).toBe(200); + expect( + count(env, "SELECT COUNT(*) AS n FROM scenes WHERE id = ?", work.id), + ).toBe(0); + }); +}); + +describe("admin categories accept sceneId (incl. moving a category)", () => { + let env: Env; + let app: Hono; + let cookie: string; + let workId: string; + + beforeEach(async () => { + env = makeEnv(); + app = makeApp(); + await runMigrations(env); + cookie = await ownerCookie(app, env); + const work = await readJson( + await adminRequest(app, env, cookie, "/api/admin/scenes", { + method: "POST", + body: { name: "工作" }, + }), + ); + workId = work.id; + }); + + it("POST without sceneId assigns the default scene", async () => { + const res = await adminRequest(app, env, cookie, "/api/admin/categories", { + method: "POST", + body: { name: "默认分类" }, + }); + expect(res.status).toBe(201); + const body = await readJson(res); + expect(body.sceneId).toBe("scene_default"); + + const list = await readJson( + await adminRequest(app, env, cookie, "/api/admin/categories"), + ); + expect(list.categories[0].sceneId).toBe("scene_default"); + }); + + it("POST with a valid sceneId assigns it, unknown sceneId is a 400", async () => { + const ok = await adminRequest(app, env, cookie, "/api/admin/categories", { + method: "POST", + body: { name: "工作分类", sceneId: workId }, + }); + expect(ok.status).toBe(201); + expect(await readJson(ok)).toMatchObject({ + name: "工作分类", + sceneId: workId, + }); + + for (const sceneId of ["ghost", "", 7, null]) { + const bad = await adminRequest( + app, + env, + cookie, + "/api/admin/categories", + { method: "POST", body: { name: "x", sceneId } }, + ); + expect(bad.status).toBe(400); + expect(await readJson(bad)).toEqual({ + error: "sceneId does not exist", + }); + } + }); + + it("PUT sceneId moves the whole category and leaves its links alone", async () => { + const cat = await readJson( + await adminRequest(app, env, cookie, "/api/admin/categories", { + method: "POST", + body: { name: "要搬的分类" }, + }), + ); + insertLinkRow(env, { id: "moved-link", categoryId: cat.id }); + + const moved = await adminRequest( + app, + env, + cookie, + `/api/admin/categories/${cat.id}`, + { method: "PUT", body: { sceneId: workId } }, + ); + expect(moved.status).toBe(200); + expect(await readJson(moved)).toMatchObject({ + id: cat.id, + sceneId: workId, + }); + + expect( + count( + env, + "SELECT COUNT(*) AS n FROM links WHERE id = 'moved-link' AND category_id = ?", + cat.id, + ), + ).toBe(1); + + const publicBody = await readJson( + await app.request("/api/public", {}, env), + ); + expect( + publicBody.categories.find((row: { id: string }) => row.id === cat.id) + .sceneId, + ).toBe(workId); + + const bad = await adminRequest( + app, + env, + cookie, + `/api/admin/categories/${cat.id}`, + { method: "PUT", body: { sceneId: "ghost" } }, + ); + expect(bad.status).toBe(400); + expect(await readJson(bad)).toEqual({ error: "sceneId does not exist" }); + }); + + it("category reorder only touches the submitted ids (scene-local by client contract)", async () => { + const a = await readJson( + await adminRequest(app, env, cookie, "/api/admin/categories", { + method: "POST", + body: { name: "A", sceneId: workId }, + }), + ); + const b = await readJson( + await adminRequest(app, env, cookie, "/api/admin/categories", { + method: "POST", + body: { name: "B", sceneId: workId }, + }), + ); + const other = await readJson( + await adminRequest(app, env, cookie, "/api/admin/categories", { + method: "POST", + body: { name: "Other" }, + }), + ); + + const res = await adminRequest( + app, + env, + cookie, + "/api/admin/categories/reorder", + { method: "POST", body: { ids: [b.id, a.id] } }, + ); + expect(res.status).toBe(200); + + const rows = sqliteOf(env) + .prepare( + "SELECT id, sort_order FROM categories WHERE id IN (?, ?, ?) ORDER BY id", + ) + .all(a.id, b.id, other.id) as Array<{ id: string; sort_order: number }>; + const byId = Object.fromEntries( + rows.map((row) => [row.id, row.sort_order]), + ); + expect(byId[b.id]).toBe(0); + expect(byId[a.id]).toBe(1); + expect(byId[other.id]).toBe(0); + }); +}); + +describe("SqliteD1.batch transaction semantics", () => { + it("commits all statements and rolls the whole batch back on error", async () => { + const env = makeEnv(); + await runMigrations(env); + const db = env.DB as unknown as SqliteD1; + + await db.batch([ + db + .prepare( + "INSERT INTO scenes (id, name, icon, sort_order, is_default, created_at, updated_at) VALUES ('batch-a', 'a', NULL, 1, 0, ?, ?)", + ) + .bind(NOW, NOW), + db + .prepare( + "INSERT INTO scenes (id, name, icon, sort_order, is_default, created_at, updated_at) VALUES ('batch-b', 'b', NULL, 2, 0, ?, ?)", + ) + .bind(NOW, NOW), + ]); + expect(count(env, "SELECT COUNT(*) AS n FROM scenes")).toBe(3); + + await expect( + db.batch([ + db + .prepare( + "INSERT INTO scenes (id, name, icon, sort_order, is_default, created_at, updated_at) VALUES ('batch-c', 'c', NULL, 3, 0, ?, ?)", + ) + .bind(NOW, NOW), + db + .prepare( + "INSERT INTO scenes (id, name, icon, sort_order, is_default, created_at, updated_at) VALUES ('batch-a', 'dup', NULL, 4, 0, ?, ?)", + ) + .bind(NOW, NOW), + ]), + ).rejects.toThrow(); + + // The first insert of the failed batch was rolled back. + expect(count(env, "SELECT COUNT(*) AS n FROM scenes")).toBe(3); + expect( + count(env, "SELECT COUNT(*) AS n FROM scenes WHERE id = 'batch-c'"), + ).toBe(0); + }); +}); diff --git a/worker/test/setup.test.ts b/worker/test/setup.test.ts index 5b1aea1..528007a 100644 --- a/worker/test/setup.test.ts +++ b/worker/test/setup.test.ts @@ -214,7 +214,10 @@ describe("POST /api/setup (secret-gated upgrade)", () => { expect(await readJson(res)).toEqual({ success: true, tablePrefix: "", - migrations: [{ name: "schema_v1", status: "applied" }], + migrations: [ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + ], ownerExists: false, }); expect(res.headers.get("set-cookie")).toBeNull(); @@ -234,7 +237,10 @@ describe("POST /api/setup (secret-gated upgrade)", () => { expect(await readJson(res)).toEqual({ success: true, tablePrefix: "", - migrations: [{ name: "schema_v1", status: "skipped" }], + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "skipped" }, + ], ownerExists: true, }); // No account created/changed, no session handed to an anonymous caller. @@ -299,7 +305,7 @@ describe("admin system endpoints", () => { expect(await readJson(res)).toEqual({ tablePrefix: "", setupPageEnabled: false, - ledger: ["schema_v1"], + ledger: ["schema_v1", "schema_v2"], }); }); @@ -316,7 +322,10 @@ describe("admin system endpoints", () => { expect(adminBody).toEqual({ success: true, tablePrefix: "", - migrations: [{ name: "schema_v1", status: "skipped" }], + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "skipped" }, + ], ownerExists: true, }); From ae9f76630191540b555fb10ff9381c9613a58bbd Mon Sep 17 00:00:00 2001 From: Todos Date: Fri, 6 Nov 2026 15:59:21 +0800 Subject: [PATCH 2/3] docs(api): document scene dimension, DTOs and admin endpoints Sync docs/api-contract.md with the frozen v1.1 scene contract: schema_v2 data model and semantics, SceneDto/AdminSceneDto, sceneId on category payloads, the admin scenes CRUD/reorder/delete behaviour, and moving a whole category between scenes. --- docs/api-contract.md | 56 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 4 deletions(-) diff --git a/docs/api-contract.md b/docs/api-contract.md index d44302e..34800a2 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -2,6 +2,27 @@ 字段命名 camelCase。变更须回父单 ONE-167 由 Mike 裁决。 +## 场景维度(v1.1,nav #16 冻结契约) + +场景与分类是正交的两个维度:分类回答「链接是什么」,场景回答「当前处于哪种状态」。不同场景各自拥有一套分类与链接,互不影响。 + +### 数据模型(迁移 `schema_v2`) + +- 新增 `{prefix}scenes`:`id`、`name`、`icon`(可空)、`sort_order`、`is_default`(0/1)、`created_at`、`updated_at`。 +- `is_default = 1` 上有部分唯一索引 `idx_{prefix}scenes_single_default`,保证默认场景至多一个。 +- 迁移写入一行种子:`id = 'scene_default'`、`name = '通用'`、`is_default = 1`。默认场景可改名/改图标/排序,不可删除。 +- `{prefix}categories` 增加可空列 `scene_id`(`REFERENCES {prefix}scenes(id)`)与索引 `idx_{prefix}categories_scene_id`;存量分类在迁移中回填默认场景。列可空是 SQLite `ALTER TABLE ADD COLUMN` 的限制,所有 DTO 都会把 `NULL`/悬空 id 归一化为默认场景 id。 +- 迁移只增不删,由账本保证只执行一次;表名/索引名随 `TABLE_PREFIX` 三态(未配置=`nav_`、自定义值、显式置空)变化。 + +### 语义 + +- 每个分类属于且只属于一个场景;链接**没有**场景字段,其场景由所属分类唯一决定。 +- 分类的 `sort_order` 表示**场景内**排序;链接保持原有全局排序语义不变。 +- 默认场景只认 `is_default = 1`,不按 id 或名字「通用」查找;`is_default` 只读,API 不提供转移默认场景的能力。 +- 搜索引擎不属于任何场景,全场景共用;`visibility` 逻辑完全不变。 +- `/api/public`、`/api/private` 返回**全量**分类与全部场景,服务端不按场景裁剪,场景切换由客户端本地过滤。 +- DTO 形状:`SceneDto{id,name,icon,sortOrder,isDefault}`;后台场景额外返回 `AdminSceneDto = SceneDto + {createdAt,updatedAt}`;分类 DTO 增加 `sceneId`。 + ## 公开 ### GET /api/public @@ -16,6 +37,7 @@ "name": "分类名", "icon": null, "sortOrder": 0, + "sceneId": "scene_default", "links": [ { "id": "uuid", @@ -29,6 +51,15 @@ ] } ], + "scenes": [ + { + "id": "scene_default", + "name": "通用", + "icon": null, + "sortOrder": 0, + "isDefault": true + } + ], "searchEngines": [ { "id": "uuid", @@ -50,6 +81,8 @@ } ``` +`scenes`:全部场景,按 `sortOrder, createdAt` 排序,**包含只有私有分类的场景**(场景本身没有 visibility;私有分类与链接仍按原可见性规则不出现)。`/api/private` 与 `/api/public` 同结构,两者都返回全量场景,服务端不按场景裁剪;分类的 `sceneId` 为该分类所属场景,`NULL`/悬空 id 会归一化为默认场景 id。 + `wallpaperSource`:首页壁纸来源,`bing`(默认,Bing 每日壁纸)| `custom`(用 `backgroundUrl` 自定义图)。存量库无此键时按 `bing` 返回。 ### GET /api/wallpaper/today @@ -111,13 +144,28 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14): ## 后台(/api/admin/*,全部需会话,未登录 401 JSON `{"error":"unauthorized"}`) +### 场景 + +- `GET /api/admin/scenes` → `{scenes:[AdminSceneDto]}`(按 `sortOrder, createdAt` 排序,含默认场景) +- `POST /api/admin/scenes` body `{name, icon?, sortOrder?}` → 201 `AdminSceneDto` + - `name` 去空格后不可为空,否则 400 `{"error":"name is required"}`;`icon` 非字符串按 `null`;省略 `sortOrder` 时追加到末尾(现有 `MAX(sort_order)+1`)。 + - `isDefault` 只读,传入会被忽略;场景名不做库级唯一约束。 +- `PUT /api/admin/scenes/:id` body `{name?, icon?, sortOrder?}` → 更新后的 `AdminSceneDto` + - `name` 去空格后不可为空,否则 400 `{"error":"name must not be empty"}`;`isDefault` 静默忽略;不存在 → 404 `{"error":"not found"}`。 +- `DELETE /api/admin/scenes/:id` → `{success:true}` + - 默认场景 → 400 `{"error":"default scene cannot be deleted"}`;不存在 → 404 `{"error":"not found"}`。 + - 非默认场景:在**单个 `db.batch` 事务**里,先把该场景的全部分类移动到默认场景,`sort_order` 追加到默认场景现有分类之后(以默认场景内 `MAX(sort_order)+1` 为基数,保持分类相对顺序),再删除场景(SQL 层带 `is_default = 0` 守卫);链接随分类走,不搬不改。 +- `POST /api/admin/scenes/reorder` body `{ids:[…]}`(顺序即 `sortOrder`)→ `{success:true}` + ### 分类 -- `GET /api/admin/categories` → `{categories:[{id,name,icon,sortOrder,visibility,createdAt,updatedAt}]}` -- `POST /api/admin/categories` body `{name, icon?, sortOrder?, visibility?}`(visibility: `public`|`private`)→ 201 `{id,…}` -- `PUT /api/admin/categories/:id`(字段同上,部分更新)→ 更新后对象 +- `GET /api/admin/categories` → `{categories:[{id,name,icon,sortOrder,visibility,sceneId,createdAt,updatedAt}]}`(全量,不按场景裁剪) +- `POST /api/admin/categories` body `{name, icon?, sortOrder?, visibility?, sceneId?}`(visibility: `public`|`private`)→ 201 `{id,…}`(含 `sceneId`) + - 省略 `sceneId` 时归入默认场景;显式传入但场景不存在 → 400 `{"error":"sceneId does not exist"}`。 +- `PUT /api/admin/categories/:id`(字段同上,部分更新)→ 更新后对象(含 `sceneId`) + - 改 `sceneId` 即把整个分类移到目标场景(不另开端点);链接随分类走,不删不改。`sceneId` 不存在 → 400 `{"error":"sceneId does not exist"}`。 - `DELETE /api/admin/categories/:id` → `{success:true}`(级联删除其链接) -- `POST /api/admin/categories/reorder` body `{ids:[…]}`(顺序即 sortOrder)→ `{success:true}` +- `POST /api/admin/categories/reorder` body `{ids:[…]}`(顺序即场景内 sortOrder;客户端只提交当前场景的分类全集,服务端不按场景校验)→ `{success:true}` ### 链接 From 75c7f191845ad3a37d84b4108efb4b76fe395328 Mon Sep 17 00:00:00 2001 From: Todos Date: Fri, 6 Nov 2026 17:26:59 +0800 Subject: [PATCH 3/3] fix(admin): migrate schema before scene-aware admin handlers Run ensureSchema in the category/scene admin handlers so a Worker-only deploy cannot 500 on `no such table: scenes` before /api/private triggers the lazy upgrade. Add a schema_v1-only regression test. When moving a category without an explicit sortOrder, append it to the target scene (MAX+1), matching the delete-scene rule and avoiding collisions; document the move semantics and correct the public/private wording in docs/api-contract.md. --- docs/api-contract.md | 3 +- worker/src/db/queries/content.ts | 19 +++++++ worker/src/routes/admin.ts | 24 +++++++- worker/test/admin-upgrade.test.ts | 92 +++++++++++++++++++++++++++++++ worker/test/scenes.test.ts | 50 +++++++++++++++++ 5 files changed, 185 insertions(+), 3 deletions(-) create mode 100644 worker/test/admin-upgrade.test.ts diff --git a/docs/api-contract.md b/docs/api-contract.md index 34800a2..ae5733f 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -20,7 +20,7 @@ - 分类的 `sort_order` 表示**场景内**排序;链接保持原有全局排序语义不变。 - 默认场景只认 `is_default = 1`,不按 id 或名字「通用」查找;`is_default` 只读,API 不提供转移默认场景的能力。 - 搜索引擎不属于任何场景,全场景共用;`visibility` 逻辑完全不变。 -- `/api/public`、`/api/private` 返回**全量**分类与全部场景,服务端不按场景裁剪,场景切换由客户端本地过滤。 +- `/api/public`、`/api/private` 返回全部场景,以及各场景下按既有可见性规则可见的分类;服务端不按场景裁剪,场景切换由客户端本地过滤。 - DTO 形状:`SceneDto{id,name,icon,sortOrder,isDefault}`;后台场景额外返回 `AdminSceneDto = SceneDto + {createdAt,updatedAt}`;分类 DTO 增加 `sceneId`。 ## 公开 @@ -164,6 +164,7 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14): - 省略 `sceneId` 时归入默认场景;显式传入但场景不存在 → 400 `{"error":"sceneId does not exist"}`。 - `PUT /api/admin/categories/:id`(字段同上,部分更新)→ 更新后对象(含 `sceneId`) - 改 `sceneId` 即把整个分类移到目标场景(不另开端点);链接随分类走,不删不改。`sceneId` 不存在 → 400 `{"error":"sceneId does not exist"}`。 + - 移场景时若同时给了 `sortOrder` 则以它为准;未给 `sortOrder` 时追加到目标场景末尾(目标场景内 `MAX(sort_order)+1`),不会与目标场景现有排序撞号。 - `DELETE /api/admin/categories/:id` → `{success:true}`(级联删除其链接) - `POST /api/admin/categories/reorder` body `{ids:[…]}`(顺序即场景内 sortOrder;客户端只提交当前场景的分类全集,服务端不按场景校验)→ `{success:true}` diff --git a/worker/src/db/queries/content.ts b/worker/src/db/queries/content.ts index 0da5357..73c6985 100644 --- a/worker/src/db/queries/content.ts +++ b/worker/src/db/queries/content.ts @@ -247,6 +247,25 @@ export async function deleteLinksByCategory( .run(); } +/** + * Next append-at-the-end sort order within one scene: MAX(sort_order) + 1 (0 on + * an empty scene). Used when a category moves scenes without an explicit + * position, mirroring the delete-scene append rule. + */ +export async function nextCategorySortOrder( + db: D1Database, + prefix: string, + sceneId: string, +): Promise { + const row = await db + .prepare( + `SELECT COALESCE(MAX(sort_order), -1) + 1 AS next FROM ${prefix}categories WHERE scene_id = ?`, + ) + .bind(sceneId) + .first<{ next: number }>(); + return row?.next ?? 0; +} + // ─── Scenes ────────────────────────────────────────────────────────────────── export async function listScenes( diff --git a/worker/src/routes/admin.ts b/worker/src/routes/admin.ts index 3a343ba..8957cba 100644 --- a/worker/src/routes/admin.ts +++ b/worker/src/routes/admin.ts @@ -26,6 +26,7 @@ import { listLinks, listScenes, listSearchEngines, + nextCategorySortOrder, nextSceneSortOrder, updateCategory, updateLink, @@ -33,6 +34,7 @@ import { updateSearchEngine, } from "../db/queries/content"; import { getAllSettings, setSetting } from "../db/queries/settings"; +import { ensureSchema } from "../lib/migrate"; import { listRecordedMigrations } from "../lib/migrations-runner"; import { generateId } from "../core/auth"; import type { Category, Link, Scene } from "../types"; @@ -95,6 +97,11 @@ function adminCategoryDto(category: Category, scenes: Scene[]) { adminRoutes.get("/categories", async (c) => { const prefix = getTablePrefix(c.env); + // Scene-aware handlers need schema_v2. A Worker-only deploy upgrades the + // database on the first read path, and the admin SPA can mount before + // /api/private finishes — run the same guard here so it never reads `scenes` + // before the migration has been applied. + await ensureSchema(c.env); const [categories, scenes] = await Promise.all([ listCategories(c.env.DB, prefix), listScenes(c.env.DB, prefix), @@ -106,6 +113,7 @@ adminRoutes.get("/categories", async (c) => { adminRoutes.post("/categories", async (c) => { const prefix = getTablePrefix(c.env); + await ensureSchema(c.env); const body = await c.req .json<{ name?: unknown; @@ -173,6 +181,7 @@ adminRoutes.post("/categories", async (c) => { adminRoutes.put("/categories/:id", async (c) => { const prefix = getTablePrefix(c.env); + await ensureSchema(c.env); const id = c.req.param("id"); const existing = await findCategory(c.env.DB, prefix, id); if (!existing) return c.json({ error: "not found" }, 404); @@ -201,8 +210,14 @@ adminRoutes.put("/categories/:id", async (c) => { ? await findScene(c.env.DB, prefix, requested) : null; if (!scene) return badRequest("sceneId does not exist"); - // Moving a category to another scene is a plain scene_id rewrite; links - // follow their category, so nothing else has to move. + // When a category changes scene and no explicit position was sent, append + // it after the target scene's existing categories (MAX+1, the same rule as + // deleting a scene) so sort_order cannot collide with target rows. An + // explicit sortOrder above wins and is kept verbatim. + if (scene.id !== existing.scene_id && body.sortOrder === undefined) { + data.sort_order = await nextCategorySortOrder(c.env.DB, prefix, scene.id); + } + // Links follow their category, so nothing else has to move. data.scene_id = scene.id; } @@ -233,12 +248,14 @@ adminRoutes.delete("/categories/:id", async (c) => { adminRoutes.get("/scenes", async (c) => { const prefix = getTablePrefix(c.env); + await ensureSchema(c.env); const scenes = await listScenes(c.env.DB, prefix); return c.json({ scenes: scenes.map(toAdminSceneDto) }); }); adminRoutes.post("/scenes", async (c) => { const prefix = getTablePrefix(c.env); + await ensureSchema(c.env); const body = await c.req.json().catch(() => ({})); const name = typeof body.name === "string" ? body.name.trim() : ""; @@ -266,6 +283,7 @@ adminRoutes.post("/scenes", async (c) => { adminRoutes.put("/scenes/:id", async (c) => { const prefix = getTablePrefix(c.env); + await ensureSchema(c.env); const id = c.req.param("id"); const existing = await findScene(c.env.DB, prefix, id); if (!existing) return c.json({ error: "not found" }, 404); @@ -291,6 +309,7 @@ adminRoutes.put("/scenes/:id", async (c) => { adminRoutes.delete("/scenes/:id", async (c) => { const prefix = getTablePrefix(c.env); + await ensureSchema(c.env); const id = c.req.param("id"); const existing = await findScene(c.env.DB, prefix, id); if (!existing) return c.json({ error: "not found" }, 404); @@ -515,6 +534,7 @@ adminRoutes.post("/categories/reorder", async (c) => { adminRoutes.post("/scenes/reorder", async (c) => { const prefix = getTablePrefix(c.env); + await ensureSchema(c.env); const body = await c.req.json().catch(() => ({})); if (!Array.isArray(body.ids)) return badRequest("ids must be an array of scene ids"); diff --git a/worker/test/admin-upgrade.test.ts b/worker/test/admin-upgrade.test.ts new file mode 100644 index 0000000..661ebd2 --- /dev/null +++ b/worker/test/admin-upgrade.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from "vitest"; +import { Hono } from "hono"; +import { applyMigrationList } from "../src/lib/migrations-runner"; +import { getMigrations, migrationsTable } from "../src/lib/migrations"; +import { adminRoutes } from "../src/routes/admin"; +import { generateId, signJWT } from "../src/core/auth"; +import { insertSession } from "../src/db/queries/users"; +import { makeEnv, readJson, type SqliteD1 } from "./helpers"; + +/** + * A Worker-only deploy leaves an existing database at schema_v1: the ledger + * records only schema_v1 and `{prefix}scenes` does not exist yet. The admin SPA + * can mount before /api/private has triggered the lazy upgrade, so scene-aware + * admin handlers must run the same guard instead of 500ing on `no such table`. + */ +describe("admin upgrade path (schema_v1-only database)", () => { + it("migrates before serving GET /api/admin/categories", async () => { + const env = makeEnv(); + const v1 = getMigrations("")[0]; + if (!v1) throw new Error("schema_v1 missing"); + await applyMigrationList(env.DB, "", [v1]); + + const db = (env.DB as unknown as SqliteD1).db; + const now = new Date().toISOString(); + const userId = "legacy-owner"; + db.prepare( + "INSERT INTO users (id, username, password_hash, is_active, created_at, updated_at) VALUES (?, ?, ?, 1, ?, ?)", + ).run(userId, "owner", "hash", now, now); + db.prepare( + "INSERT INTO categories (id, name, icon, sort_order, visibility, created_at, updated_at) VALUES (?, ?, NULL, 0, 'public', ?, ?)", + ).run("legacy-cat", "Legacy Cat", now, now); + + // A valid session without going through /api/auth/setup (which would run + // the migrations and hide the bug). + const sid = generateId(); + const iat = Math.floor(Date.now() / 1000); + await insertSession(env.DB, "", { + id: sid, + user_id: userId, + expires_at: new Date((iat + 3600) * 1000).toISOString(), + ip: null, + user_agent: null, + }); + const token = await signJWT( + { + typ: "access", + sub: userId, + jti: generateId(), + sid, + iat, + exp: iat + 3600, + }, + env.SESSION_SECRET, + ); + const cookie = `nav_session=${token}`; + + const app = new Hono(); + app.route("/api/admin", adminRoutes); + + const res = await app.request( + "/api/admin/categories", + { headers: { cookie } }, + env, + ); + expect(res.status).toBe(200); + const body = await readJson(res); + expect(body.categories).toEqual([ + expect.objectContaining({ id: "legacy-cat", sceneId: "scene_default" }), + ]); + + // The guard applied schema_v2 and backfilled the legacy row. + expect( + db + .prepare(`SELECT name FROM ${migrationsTable("")} ORDER BY rowid`) + .all() + .map((row: { name: string }) => row.name), + ).toEqual(["schema_v1", "schema_v2"]); + expect( + db + .prepare("SELECT scene_id FROM categories WHERE id = 'legacy-cat'") + .get(), + ).toEqual({ scene_id: "scene_default" }); + + const scenesRes = await app.request( + "/api/admin/scenes", + { headers: { cookie } }, + env, + ); + expect(scenesRes.status).toBe(200); + expect((await readJson(scenesRes)).scenes).toHaveLength(1); + }); +}); diff --git a/worker/test/scenes.test.ts b/worker/test/scenes.test.ts index 1528557..3334ccf 100644 --- a/worker/test/scenes.test.ts +++ b/worker/test/scenes.test.ts @@ -797,6 +797,56 @@ describe("admin categories accept sceneId (incl. moving a category)", () => { expect(await readJson(bad)).toEqual({ error: "sceneId does not exist" }); }); + it("moving without sortOrder appends to the target scene; explicit sortOrder wins", async () => { + // Target scene already has sort_order 5 → append at 6. + insertCategoryRow(env, { + id: "work-existing", + name: "工作已有", + sortOrder: 5, + sceneId: workId, + }); + const first = await readJson( + await adminRequest(app, env, cookie, "/api/admin/categories", { + method: "POST", + body: { name: "默认 A", sortOrder: 2 }, + }), + ); + const moved = await adminRequest( + app, + env, + cookie, + `/api/admin/categories/${first.id}`, + { method: "PUT", body: { sceneId: workId } }, + ); + expect(moved.status).toBe(200); + expect(await readJson(moved)).toMatchObject({ + id: first.id, + sceneId: workId, + sortOrder: 6, + }); + + // An explicit position is kept verbatim instead of appended. + const second = await readJson( + await adminRequest(app, env, cookie, "/api/admin/categories", { + method: "POST", + body: { name: "默认 B", sortOrder: 1 }, + }), + ); + const placed = await adminRequest( + app, + env, + cookie, + `/api/admin/categories/${second.id}`, + { method: "PUT", body: { sceneId: workId, sortOrder: 2 } }, + ); + expect(placed.status).toBe(200); + expect(await readJson(placed)).toMatchObject({ + id: second.id, + sceneId: workId, + sortOrder: 2, + }); + }); + it("category reorder only touches the submitted ids (scene-local by client contract)", async () => { const a = await readJson( await adminRequest(app, env, cookie, "/api/admin/categories", {