0.6 rust重构01
This commit is contained in:
@@ -1,16 +1,44 @@
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { DocumentShell } from "@/components/editor/document-shell";
|
||||
import type { PageOptionsState, DocumentStats } from "@/types/page-options";
|
||||
import type { PageFont, PageLayoutDensity, PageOptionsState, DocumentStats } from "@/types/page-options";
|
||||
import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import { fetchDocumentMetaViaBridge } from "@/lib/documents/bridge-server";
|
||||
|
||||
interface DocumentPageProps {
|
||||
params: Promise<{ id: string }>;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
searchParams?: Promise<Record<string, any>>;
|
||||
searchParams?: Promise<Record<string, string | string[] | undefined>>;
|
||||
}
|
||||
|
||||
type DocumentMetaPayload = {
|
||||
id: string;
|
||||
workspace_id: string;
|
||||
title: string | null;
|
||||
updated_at: string | null;
|
||||
can_edit?: boolean | null;
|
||||
disable_download?: boolean | null;
|
||||
disable_copy?: boolean | null;
|
||||
wide_layout?: boolean | null;
|
||||
use_small_text?: boolean | null;
|
||||
show_heading_numbers?: boolean | null;
|
||||
show_toc?: boolean | null;
|
||||
show_structure?: boolean | null;
|
||||
protect_editing?: boolean | null;
|
||||
show_word_count?: boolean | null;
|
||||
collapse_backlinks?: boolean | null;
|
||||
page_font?: PageFont | null;
|
||||
layout_density?: PageLayoutDensity | null;
|
||||
hide_child_pages?: boolean | null;
|
||||
show_block_ref_count?: boolean | null;
|
||||
embed_default_block_id?: string | null;
|
||||
word_count?: number | null;
|
||||
character_count?: number | null;
|
||||
block_count?: number | null;
|
||||
todo_total?: number | null;
|
||||
todo_total_count?: number | null;
|
||||
todo_done?: number | null;
|
||||
todo_done_count?: number | null;
|
||||
};
|
||||
|
||||
export default async function DocumentPage({ params, searchParams }: DocumentPageProps) {
|
||||
const { id } = await params;
|
||||
const resolvedSearch = (await searchParams) ?? {};
|
||||
@@ -18,14 +46,19 @@ export default async function DocumentPage({ params, searchParams }: DocumentPag
|
||||
const openTableId = typeof openTableIdRaw === "string" ? openTableIdRaw : null;
|
||||
|
||||
if (isConvexEnabled()) {
|
||||
const { client } = await getAuthedConvexClient();
|
||||
const doc = await client.query(api.documents.getMeta, { id });
|
||||
const workspaceIdRaw = resolvedSearch?.workspaceId;
|
||||
const workspaceId = typeof workspaceIdRaw === "string" ? workspaceIdRaw : null;
|
||||
const result = await fetchDocumentMetaViaBridge<DocumentMetaPayload>({
|
||||
documentId: id,
|
||||
workspaceId,
|
||||
});
|
||||
const doc = result?.doc;
|
||||
if (!doc) {
|
||||
notFound();
|
||||
}
|
||||
const readOnly = (doc as any).can_edit === false;
|
||||
const disableDownload = Boolean((doc as any).disable_download);
|
||||
const disableCopy = Boolean((doc as any).disable_copy);
|
||||
const readOnly = doc.can_edit === false;
|
||||
const disableDownload = Boolean(doc.disable_download);
|
||||
const disableCopy = Boolean(doc.disable_copy);
|
||||
|
||||
const initialOptions: PageOptionsState = {
|
||||
wideLayout: doc.wide_layout ?? false,
|
||||
@@ -35,20 +68,20 @@ export default async function DocumentPage({ params, searchParams }: DocumentPag
|
||||
showStructure: doc.show_structure ?? false,
|
||||
protectEditing: doc.protect_editing ?? false,
|
||||
showWordCount: doc.show_word_count ?? true,
|
||||
collapseBacklinks: (doc as any).collapse_backlinks ?? false,
|
||||
pageFont: (doc as any).page_font ?? "default",
|
||||
layoutDensity: (doc as any).layout_density ?? "normal",
|
||||
hideChildPages: (doc as any).hide_child_pages ?? false,
|
||||
showBlockRefCount: (doc as any).show_block_ref_count ?? false,
|
||||
embedDefaultBlockId: (doc as any).embed_default_block_id ?? null,
|
||||
collapseBacklinks: doc.collapse_backlinks ?? false,
|
||||
pageFont: doc.page_font ?? "default",
|
||||
layoutDensity: doc.layout_density ?? "normal",
|
||||
hideChildPages: doc.hide_child_pages ?? false,
|
||||
showBlockRefCount: doc.show_block_ref_count ?? false,
|
||||
embedDefaultBlockId: doc.embed_default_block_id ?? null,
|
||||
};
|
||||
|
||||
const initialStats: DocumentStats = {
|
||||
wordCount: doc.word_count ?? 0,
|
||||
characterCount: doc.character_count ?? 0,
|
||||
blockCount: doc.block_count ?? 0,
|
||||
todoTotal: (doc as any).todo_total ?? (doc as any).todo_total_count ?? 0,
|
||||
todoDone: (doc as any).todo_done ?? (doc as any).todo_done_count ?? 0,
|
||||
todoTotal: doc.todo_total ?? doc.todo_total_count ?? 0,
|
||||
todoDone: doc.todo_done ?? doc.todo_done_count ?? 0,
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -4,236 +4,23 @@ import { Sidebar } from "@/components/sidebar/sidebar";
|
||||
import { GlobalAiAgentHost } from "@/components/ai-agent/GlobalAiAgentHost";
|
||||
import { Breadcrumb } from "@/components/breadcrumb";
|
||||
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger";
|
||||
import type { DocumentRecord } from "@/lib/documents";
|
||||
import type { SidebarInitialData } from "@/components/sidebar/types";
|
||||
import { SearchPalette } from "@/components/search/search-palette";
|
||||
import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import type { MediaAsset } from "@/types/media";
|
||||
|
||||
function extractMindmapImageAssetIdsFromData(input: unknown): string[] {
|
||||
const root = (() => {
|
||||
if (!input || typeof input !== "object") return input;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const record = input as any;
|
||||
return record && typeof record === "object" && "root" in record ? record.root : input;
|
||||
})();
|
||||
|
||||
const ids: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
const push = (value: unknown) => {
|
||||
if (typeof value !== "string") return;
|
||||
if (!value.startsWith("asset:")) return;
|
||||
const id = value.slice("asset:".length).trim();
|
||||
if (!id) return;
|
||||
if (seen.has(id)) return;
|
||||
seen.add(id);
|
||||
ids.push(id);
|
||||
};
|
||||
|
||||
const get = (obj: unknown, key: string): unknown => {
|
||||
if (!obj || typeof obj !== "object") return undefined;
|
||||
return (obj as Record<string, unknown>)[key];
|
||||
};
|
||||
|
||||
const walk = (node: unknown) => {
|
||||
if (!node || typeof node !== "object") return;
|
||||
const data = get(node, "data");
|
||||
const image = get(node, "image");
|
||||
push(get(data, "image"));
|
||||
push(image);
|
||||
push(get(image, "url"));
|
||||
push(get(get(data, "image"), "url"));
|
||||
const children = get(node, "children");
|
||||
if (Array.isArray(children)) children.forEach(walk);
|
||||
};
|
||||
|
||||
walk(root);
|
||||
return ids;
|
||||
}
|
||||
|
||||
function makeId(): string {
|
||||
return typeof crypto.randomUUID === "function"
|
||||
? crypto.randomUUID()
|
||||
: `${Date.now()}_${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
import { loadSidebarDataFromConvex } from "@/lib/server/sidebar-data";
|
||||
|
||||
export default async function AppLayout({ children }: { children: ReactNode }) {
|
||||
if (isConvexEnabled()) {
|
||||
const { auth, client } = await getAuthedConvexClient();
|
||||
|
||||
const ensured = await client.mutation(api.workspaces.ensureDefaultWorkspace, {
|
||||
const {
|
||||
documents,
|
||||
sidebarInitialData,
|
||||
} = await loadSidebarDataFromConvex({
|
||||
client,
|
||||
userId: auth.userId,
|
||||
fallbackName: auth.name ?? auth.email ?? "我的空间",
|
||||
workspaceIdIfCreate: makeId(),
|
||||
});
|
||||
|
||||
const workspaces = ensured.workspaces;
|
||||
const activeWorkspaceId = ensured.activeWorkspaceId;
|
||||
|
||||
let documents: DocumentRecord[] = [];
|
||||
let sidebarInitialData: SidebarInitialData | null = null;
|
||||
|
||||
if (activeWorkspaceId) {
|
||||
const [docRows, trashedDocs] = await Promise.all([
|
||||
client.query(api.documents.listByWorkspace, {
|
||||
workspaceId: activeWorkspaceId,
|
||||
}),
|
||||
client.query(api.documents.listTrashedByWorkspace, {
|
||||
workspaceId: activeWorkspaceId,
|
||||
}),
|
||||
]);
|
||||
|
||||
documents = docRows as unknown as DocumentRecord[];
|
||||
|
||||
const mindmapRows = await client.query(api.mindmaps.listByWorkspace, {
|
||||
workspaceId: activeWorkspaceId,
|
||||
includeDeleted: true,
|
||||
});
|
||||
|
||||
const activeMindmaps = (mindmapRows ?? []).filter((r) => !r.deleted_at);
|
||||
const trashedMindmaps = (mindmapRows ?? []).filter((r) => !!r.deleted_at);
|
||||
|
||||
const mindmapDocs = Array.from(new Set(activeMindmaps.map((r) => r.document_id)));
|
||||
|
||||
const mindmapAssetChildren: Record<string, string[]> = {};
|
||||
activeMindmaps.forEach((r) => {
|
||||
const ids = extractMindmapImageAssetIdsFromData(r.data);
|
||||
if (ids.length > 0) mindmapAssetChildren[r.mindmap_id] = ids;
|
||||
});
|
||||
|
||||
const mindmapAssets: MediaAsset[] = activeMindmaps.map((r) => {
|
||||
const isLegacy = r.mindmap_id.startsWith("legacy-");
|
||||
return {
|
||||
id: r.mindmap_id,
|
||||
workspace_id: r.workspace_id ?? activeWorkspaceId,
|
||||
document_id: r.document_id,
|
||||
asset_type: "mindmap",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: isLegacy ? "mindmap.json" : `mindmap-${r.mindmap_id}.json`,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
signed_url: null,
|
||||
created_at: r.created_at ?? "",
|
||||
updated_at: r.updated_at ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
const trashedMindmapAssets: MediaAsset[] = trashedMindmaps.map((r) => {
|
||||
const isLegacy = r.mindmap_id.startsWith("legacy-");
|
||||
return {
|
||||
id: r.mindmap_id,
|
||||
workspace_id: r.workspace_id ?? activeWorkspaceId,
|
||||
document_id: r.document_id,
|
||||
asset_type: "mindmap",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: isLegacy ? "mindmap.json" : `mindmap-${r.mindmap_id}.json`,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
deleted_at: r.deleted_at ?? null,
|
||||
deleted_by: r.deleted_by ?? null,
|
||||
purged_at: null,
|
||||
signed_url: null,
|
||||
created_at: r.created_at ?? "",
|
||||
updated_at: r.updated_at ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
const tables = await client.query(api.tables.listByWorkspaceForSearch, {
|
||||
userId: auth.userId,
|
||||
workspaceId: activeWorkspaceId,
|
||||
includeArchived: true,
|
||||
limit: 3000,
|
||||
});
|
||||
|
||||
const tableAssets: MediaAsset[] = (tables ?? [])
|
||||
.filter((row) => !row.is_archived)
|
||||
.map((row) => {
|
||||
const base = String(row.title ?? "未命名表格").trim() || "未命名表格";
|
||||
const fileName = base.toLowerCase().endsWith(".luckysheet") ? base : `${base}.luckysheet`;
|
||||
return {
|
||||
id: row.id,
|
||||
workspace_id: row.workspace_id ?? activeWorkspaceId,
|
||||
document_id: row.document_id,
|
||||
asset_type: "luckysheet",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: fileName,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
signed_url: null,
|
||||
created_at: row.created_at ?? "",
|
||||
updated_at: row.updated_at ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
const trashedTableAssets: MediaAsset[] = (tables ?? [])
|
||||
.filter((row) => Boolean(row.is_archived))
|
||||
.map((row) => {
|
||||
const base = String(row.title ?? "未命名表格").trim() || "未命名表格";
|
||||
const fileName = base.toLowerCase().endsWith(".luckysheet") ? base : `${base}.luckysheet`;
|
||||
return {
|
||||
id: row.id,
|
||||
workspace_id: row.workspace_id ?? activeWorkspaceId,
|
||||
document_id: row.document_id,
|
||||
asset_type: "luckysheet",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: fileName,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
deleted_at: row.deleted_at ?? row.updated_at ?? null,
|
||||
deleted_by: row.deleted_by ?? null,
|
||||
purged_at: row.purged_at ?? null,
|
||||
signed_url: null,
|
||||
created_at: row.created_at ?? "",
|
||||
updated_at: row.updated_at ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
sidebarInitialData = {
|
||||
activeWorkspaceId,
|
||||
workspaces,
|
||||
documents: docRows as unknown as DocumentRecord[],
|
||||
trashedDocuments: trashedDocs as unknown as SidebarInitialData["trashedDocuments"],
|
||||
trashedMediaAssets: [],
|
||||
trashedMindmapAssets,
|
||||
trashedTableAssets,
|
||||
mediaAssets: [],
|
||||
mindmapDocs,
|
||||
mindmapAssets,
|
||||
mindmapAssetChildren,
|
||||
tableAssets,
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-screen w-full overflow-hidden bg-wolai-bg text-wolai-text-primary">
|
||||
{sidebarInitialData && <Sidebar initialData={sidebarInitialData} />}
|
||||
|
||||
@@ -3,32 +3,104 @@ import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import { getBlocksFromDocumentContent, replaceBlockInTree, withBlocksWrittenBack } from "@/lib/blocks";
|
||||
import {
|
||||
assertBlockId,
|
||||
assertDocumentId,
|
||||
assertNextBlock,
|
||||
buildDocumentBridgeContext,
|
||||
buildDocumentCommandEnvelope,
|
||||
documentBridgeErrorResponse,
|
||||
} from "@/lib/documents/bridge";
|
||||
import { recordBridgeCommandArtifacts } from "@/lib/documents/bridge-log";
|
||||
|
||||
type PatchPayload = {
|
||||
sourceDocumentId: string;
|
||||
workspaceId?: string | null;
|
||||
blockId: string;
|
||||
nextBlock: unknown;
|
||||
};
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { sourceDocumentId, blockId, nextBlock }: PatchPayload = await request.json();
|
||||
|
||||
if (!sourceDocumentId || !blockId || !nextBlock) {
|
||||
return NextResponse.json({ error: "缺少参数" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (isConvexEnabled()) {
|
||||
const { client } = await getAuthedConvexClient();
|
||||
const doc = await client.query(api.documents.getContent, { id: sourceDocumentId });
|
||||
if (!doc) return NextResponse.json({ error: "页面不存在或无权限" }, { status: 404 });
|
||||
try {
|
||||
const { sourceDocumentId, workspaceId, blockId, nextBlock }: PatchPayload = await request.json();
|
||||
const normalizedDocumentId = assertDocumentId(sourceDocumentId);
|
||||
const normalizedWorkspaceId = workspaceId?.trim() || null;
|
||||
const normalizedBlockId = assertBlockId(blockId);
|
||||
assertNextBlock(nextBlock);
|
||||
|
||||
const blocks = getBlocksFromDocumentContent(doc.content);
|
||||
const replaced = replaceBlockInTree(blocks, blockId, nextBlock as any);
|
||||
if (!replaced.ok) return NextResponse.json({ error: "块不存在或无权限" }, { status: 404 });
|
||||
const bridgeContext = await buildDocumentBridgeContext({
|
||||
request,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
});
|
||||
const envelope = buildDocumentCommandEnvelope({
|
||||
name: "blocks.patch",
|
||||
payload: {
|
||||
documentId: normalizedDocumentId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
blockId: normalizedBlockId,
|
||||
nextBlock,
|
||||
},
|
||||
context: bridgeContext,
|
||||
target: {
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
pageId: normalizedDocumentId,
|
||||
blockId: normalizedBlockId,
|
||||
},
|
||||
});
|
||||
|
||||
const payload = withBlocksWrittenBack(doc.content, replaced.nextBlocks);
|
||||
await client.mutation(api.documents.updateContent, { id: sourceDocumentId, content: payload });
|
||||
return NextResponse.json({ ok: true });
|
||||
const { client } = await getAuthedConvexClient();
|
||||
const doc = await client.query(api.documents.getContent, { id: normalizedDocumentId });
|
||||
if (!doc) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "页面不存在或无权限",
|
||||
meta: {
|
||||
requestId: bridgeContext.requestId,
|
||||
traceId: bridgeContext.traceId,
|
||||
commandId: envelope.commandId,
|
||||
commandName: envelope.name,
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
const blocks = getBlocksFromDocumentContent(doc.content);
|
||||
const replaced = replaceBlockInTree(blocks, normalizedBlockId, nextBlock as any);
|
||||
if (!replaced.ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "块不存在或无权限",
|
||||
meta: {
|
||||
requestId: bridgeContext.requestId,
|
||||
traceId: bridgeContext.traceId,
|
||||
commandId: envelope.commandId,
|
||||
commandName: envelope.name,
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
const payload = withBlocksWrittenBack(doc.content, replaced.nextBlocks);
|
||||
await client.mutation(api.documents.updateContent, { id: normalizedDocumentId, content: payload });
|
||||
await recordBridgeCommandArtifacts({
|
||||
context: bridgeContext,
|
||||
envelope,
|
||||
});
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
meta: {
|
||||
requestId: bridgeContext.requestId,
|
||||
traceId: bridgeContext.traceId,
|
||||
commandId: envelope.commandId,
|
||||
commandName: envelope.name,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return documentBridgeErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import { documentBridgeErrorResponse } from "@/lib/documents/bridge";
|
||||
|
||||
const bridgeLogsApi = api as any;
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url);
|
||||
const workspaceId = url.searchParams.get("workspaceId")?.trim() ?? "";
|
||||
const requestId = url.searchParams.get("requestId")?.trim() ?? "";
|
||||
if (!workspaceId || !requestId) {
|
||||
return NextResponse.json({ error: "缺少 workspaceId 或 requestId" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { client } = await getAuthedConvexClient();
|
||||
const result = await client.query(bridgeLogsApi.bridgeLogs.listByRequest, {
|
||||
workspaceId,
|
||||
requestId,
|
||||
});
|
||||
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
return documentBridgeErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import { documentBridgeErrorResponse } from "@/lib/documents/bridge";
|
||||
|
||||
const bridgeLogsApi = api as any;
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url);
|
||||
const workspaceId = url.searchParams.get("workspaceId")?.trim() ?? "";
|
||||
const traceId = url.searchParams.get("traceId")?.trim() ?? "";
|
||||
if (!workspaceId || !traceId) {
|
||||
return NextResponse.json({ error: "缺少 workspaceId 或 traceId" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { client } = await getAuthedConvexClient();
|
||||
const result = await client.query(bridgeLogsApi.bridgeLogs.listByTrace, {
|
||||
workspaceId,
|
||||
traceId,
|
||||
});
|
||||
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
return documentBridgeErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -2,28 +2,57 @@ import { NextResponse } from "next/server";
|
||||
import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import {
|
||||
assertDocumentId,
|
||||
buildDocumentBridgeContext,
|
||||
buildDocumentQueryEnvelope,
|
||||
documentBridgeErrorResponse,
|
||||
} from "@/lib/documents/bridge";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
if (isConvexEnabled()) {
|
||||
const url = new URL(request.url);
|
||||
const documentId = url.searchParams.get("documentId") ?? "";
|
||||
try {
|
||||
const url = new URL(request.url);
|
||||
const documentId = assertDocumentId(url.searchParams.get("documentId"));
|
||||
const workspaceId = url.searchParams.get("workspaceId")?.trim() || null;
|
||||
const { client } = await getAuthedConvexClient();
|
||||
const bridgeContext = await buildDocumentBridgeContext({ request, workspaceId });
|
||||
const envelope = buildDocumentQueryEnvelope({
|
||||
name: "documents.content.get",
|
||||
payload: { documentId, workspaceId },
|
||||
});
|
||||
|
||||
if (!documentId) {
|
||||
return NextResponse.json({ error: "缺少 documentId" }, { status: 400 });
|
||||
const result = await client.query(api.documents.getContent, {
|
||||
id: documentId,
|
||||
});
|
||||
|
||||
if (!result) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "页面不存在",
|
||||
meta: {
|
||||
requestId: bridgeContext.requestId,
|
||||
traceId: bridgeContext.traceId,
|
||||
queryName: envelope.name,
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
content: result.content ?? null,
|
||||
meta: {
|
||||
requestId: bridgeContext.requestId,
|
||||
traceId: bridgeContext.traceId,
|
||||
queryName: envelope.name,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return documentBridgeErrorResponse(error);
|
||||
}
|
||||
|
||||
const { client } = await getAuthedConvexClient();
|
||||
const result = await client.query(api.documents.getContent, {
|
||||
id: documentId,
|
||||
});
|
||||
|
||||
if (!result) {
|
||||
return NextResponse.json({ error: "页面不存在" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ content: result.content ?? null });
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import {
|
||||
assertDocumentId,
|
||||
buildDocumentBridgeContext,
|
||||
buildDocumentQueryEnvelope,
|
||||
documentBridgeErrorResponse,
|
||||
} from "@/lib/documents/bridge";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
if (isConvexEnabled()) {
|
||||
try {
|
||||
const url = new URL(request.url);
|
||||
const documentId = assertDocumentId(url.searchParams.get("documentId"));
|
||||
const workspaceId = url.searchParams.get("workspaceId")?.trim() || null;
|
||||
const { client } = await getAuthedConvexClient();
|
||||
const bridgeContext = await buildDocumentBridgeContext({ request, workspaceId });
|
||||
const envelope = buildDocumentQueryEnvelope({
|
||||
name: "documents.meta.get",
|
||||
payload: { documentId, workspaceId },
|
||||
});
|
||||
|
||||
const doc = await client.query(api.documents.getMeta, { id: documentId });
|
||||
|
||||
if (!doc) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "页面不存在",
|
||||
meta: {
|
||||
requestId: bridgeContext.requestId,
|
||||
traceId: bridgeContext.traceId,
|
||||
queryName: envelope.name,
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
doc,
|
||||
meta: {
|
||||
requestId: bridgeContext.requestId,
|
||||
traceId: bridgeContext.traceId,
|
||||
queryName: envelope.name,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return documentBridgeErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
|
||||
}
|
||||
@@ -1,42 +1,65 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import type { PageOptionsState } from "@/types/page-options";
|
||||
import {
|
||||
assertDocumentId,
|
||||
assertOptionsPatch,
|
||||
buildDocumentBridgeContext,
|
||||
buildDocumentCommandEnvelope,
|
||||
documentBridgeErrorResponse,
|
||||
} from "@/lib/documents/bridge";
|
||||
import {
|
||||
executeMetadataBridgeCommand,
|
||||
type DocumentOptionsUpdatePayload,
|
||||
} from "@/lib/documents/metadata-command-adapter";
|
||||
|
||||
type OptionsPayload = {
|
||||
documentId: string;
|
||||
workspaceId?: string | null;
|
||||
options: Partial<PageOptionsState>;
|
||||
};
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (isConvexEnabled()) {
|
||||
const { documentId, options }: OptionsPayload = await request.json();
|
||||
if (!documentId || !options) {
|
||||
return NextResponse.json({ error: "缺少参数" }, { status: 400 });
|
||||
try {
|
||||
const { documentId, workspaceId, options }: OptionsPayload = await request.json();
|
||||
const normalizedDocumentId = assertDocumentId(documentId);
|
||||
assertOptionsPatch(options);
|
||||
const normalizedWorkspaceId = workspaceId?.trim() || null;
|
||||
const bridgeContext = await buildDocumentBridgeContext({
|
||||
request,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
});
|
||||
const envelope = buildDocumentCommandEnvelope({
|
||||
name: "documents.options.update",
|
||||
payload: {
|
||||
documentId: normalizedDocumentId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
options,
|
||||
} satisfies DocumentOptionsUpdatePayload,
|
||||
context: bridgeContext,
|
||||
target: {
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
pageId: normalizedDocumentId,
|
||||
},
|
||||
});
|
||||
const result = await executeMetadataBridgeCommand({
|
||||
context: bridgeContext,
|
||||
envelope,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
meta: {
|
||||
requestId: result.requestId,
|
||||
traceId: result.traceId,
|
||||
commandId: result.commandId,
|
||||
commandName: result.commandName,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return documentBridgeErrorResponse(error);
|
||||
}
|
||||
|
||||
const { client } = await getAuthedConvexClient();
|
||||
await client.mutation(api.documents.updateOptions, {
|
||||
id: documentId,
|
||||
options: {
|
||||
wideLayout: options.wideLayout,
|
||||
smallText: options.smallText,
|
||||
showHeadingNumbers: options.showHeadingNumbers,
|
||||
showToc: options.showToc,
|
||||
showStructure: options.showStructure,
|
||||
protectEditing: options.protectEditing,
|
||||
showWordCount: options.showWordCount,
|
||||
collapseBacklinks: options.collapseBacklinks,
|
||||
pageFont: options.pageFont,
|
||||
layoutDensity: options.layoutDensity,
|
||||
hideChildPages: options.hideChildPages,
|
||||
showBlockRefCount: options.showBlockRefCount,
|
||||
embedDefaultBlockId: typeof options.embedDefaultBlockId === "string" ? options.embedDefaultBlockId : null,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
|
||||
|
||||
@@ -2,21 +2,62 @@ import { NextResponse } from "next/server";
|
||||
import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import {
|
||||
assertDocumentId,
|
||||
buildDocumentBridgeContext,
|
||||
buildDocumentCommandEnvelope,
|
||||
documentBridgeErrorResponse,
|
||||
} from "@/lib/documents/bridge";
|
||||
import { recordBridgeCommandArtifacts } from "@/lib/documents/bridge-log";
|
||||
|
||||
interface SavePayload {
|
||||
documentId: string;
|
||||
workspaceId?: string | null;
|
||||
content: unknown;
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (isConvexEnabled()) {
|
||||
const { documentId, content }: SavePayload = await request.json();
|
||||
const { client } = await getAuthedConvexClient();
|
||||
await client.mutation(api.documents.updateContent, {
|
||||
id: documentId,
|
||||
content,
|
||||
});
|
||||
return NextResponse.json({ ok: true });
|
||||
try {
|
||||
const { documentId, workspaceId, content }: SavePayload = await request.json();
|
||||
const normalizedDocumentId = assertDocumentId(documentId);
|
||||
const normalizedWorkspaceId = workspaceId?.trim() || null;
|
||||
const bridgeContext = await buildDocumentBridgeContext({ request, workspaceId: normalizedWorkspaceId });
|
||||
const envelope = buildDocumentCommandEnvelope({
|
||||
name: "documents.save",
|
||||
payload: {
|
||||
documentId: normalizedDocumentId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
content,
|
||||
},
|
||||
context: bridgeContext,
|
||||
target: {
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
pageId: normalizedDocumentId,
|
||||
},
|
||||
});
|
||||
|
||||
const { client } = await getAuthedConvexClient();
|
||||
await client.mutation(api.documents.updateContent, {
|
||||
id: normalizedDocumentId,
|
||||
content: envelope.payload.content,
|
||||
});
|
||||
await recordBridgeCommandArtifacts({
|
||||
context: bridgeContext,
|
||||
envelope,
|
||||
});
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
meta: {
|
||||
requestId: bridgeContext.requestId,
|
||||
traceId: bridgeContext.traceId,
|
||||
commandId: envelope.commandId,
|
||||
commandName: envelope.name,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return documentBridgeErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
|
||||
|
||||
@@ -1,32 +1,65 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import type { DocumentStats } from "@/types/page-options";
|
||||
import {
|
||||
assertDocumentId,
|
||||
assertStats,
|
||||
buildDocumentBridgeContext,
|
||||
buildDocumentCommandEnvelope,
|
||||
documentBridgeErrorResponse,
|
||||
} from "@/lib/documents/bridge";
|
||||
import {
|
||||
executeMetadataBridgeCommand,
|
||||
type DocumentStatsUpdatePayload,
|
||||
} from "@/lib/documents/metadata-command-adapter";
|
||||
|
||||
interface StatsPayload {
|
||||
documentId: string;
|
||||
workspaceId?: string | null;
|
||||
stats: DocumentStats;
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (isConvexEnabled()) {
|
||||
const { documentId, stats }: StatsPayload = await request.json();
|
||||
if (!documentId || !stats) {
|
||||
return NextResponse.json({ error: "缺少参数" }, { status: 400 });
|
||||
try {
|
||||
const { documentId, workspaceId, stats }: StatsPayload = await request.json();
|
||||
const normalizedDocumentId = assertDocumentId(documentId);
|
||||
assertStats(stats);
|
||||
const normalizedWorkspaceId = workspaceId?.trim() || null;
|
||||
const bridgeContext = await buildDocumentBridgeContext({
|
||||
request,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
});
|
||||
const envelope = buildDocumentCommandEnvelope({
|
||||
name: "documents.stats.update",
|
||||
payload: {
|
||||
documentId: normalizedDocumentId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
stats,
|
||||
} satisfies DocumentStatsUpdatePayload,
|
||||
context: bridgeContext,
|
||||
target: {
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
pageId: normalizedDocumentId,
|
||||
},
|
||||
});
|
||||
const result = await executeMetadataBridgeCommand({
|
||||
context: bridgeContext,
|
||||
envelope,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
meta: {
|
||||
requestId: result.requestId,
|
||||
traceId: result.traceId,
|
||||
commandId: result.commandId,
|
||||
commandName: result.commandName,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return documentBridgeErrorResponse(error);
|
||||
}
|
||||
|
||||
const { client } = await getAuthedConvexClient();
|
||||
await client.mutation(api.documents.updateStats, {
|
||||
id: documentId,
|
||||
wordCount: stats.wordCount,
|
||||
characterCount: stats.characterCount,
|
||||
blockCount: stats.blockCount,
|
||||
todoTotal: stats.todoTotal,
|
||||
todoDone: stats.todoDone,
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
|
||||
|
||||
@@ -1,22 +1,61 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import {
|
||||
assertDocumentId,
|
||||
assertTitle,
|
||||
buildDocumentBridgeContext,
|
||||
buildDocumentCommandEnvelope,
|
||||
documentBridgeErrorResponse,
|
||||
} from "@/lib/documents/bridge";
|
||||
import {
|
||||
executeMetadataBridgeCommand,
|
||||
type DocumentTitleUpdatePayload,
|
||||
} from "@/lib/documents/metadata-command-adapter";
|
||||
|
||||
interface RenamePayload {
|
||||
documentId: string;
|
||||
workspaceId?: string | null;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (isConvexEnabled()) {
|
||||
const { documentId, title }: RenamePayload = await request.json();
|
||||
const { client } = await getAuthedConvexClient();
|
||||
await client.mutation(api.documents.updateTitle, {
|
||||
id: documentId,
|
||||
title,
|
||||
});
|
||||
return NextResponse.json({ ok: true });
|
||||
try {
|
||||
const { documentId, workspaceId, title }: RenamePayload = await request.json();
|
||||
const normalizedDocumentId = assertDocumentId(documentId);
|
||||
const normalizedTitle = assertTitle(title);
|
||||
const normalizedWorkspaceId = workspaceId?.trim() || null;
|
||||
const bridgeContext = await buildDocumentBridgeContext({ request, workspaceId: normalizedWorkspaceId });
|
||||
const envelope = buildDocumentCommandEnvelope({
|
||||
name: "documents.title.update",
|
||||
payload: {
|
||||
documentId: normalizedDocumentId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
title: normalizedTitle,
|
||||
} satisfies DocumentTitleUpdatePayload,
|
||||
context: bridgeContext,
|
||||
target: {
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
pageId: normalizedDocumentId,
|
||||
},
|
||||
});
|
||||
const result = await executeMetadataBridgeCommand({
|
||||
context: bridgeContext,
|
||||
envelope,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
meta: {
|
||||
requestId: result.requestId,
|
||||
traceId: result.traceId,
|
||||
commandId: result.commandId,
|
||||
commandName: result.commandName,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return documentBridgeErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
|
||||
|
||||
@@ -1,263 +1,58 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { SidebarInitialData } from "@/components/sidebar/types";
|
||||
import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import { randomUUID } from "crypto";
|
||||
import type { MediaAsset } from "@/types/media";
|
||||
import {
|
||||
buildDocumentBridgeContext,
|
||||
buildDocumentQueryEnvelope,
|
||||
documentBridgeErrorResponse,
|
||||
} from "@/lib/documents/bridge";
|
||||
import { loadSidebarDataFromConvex } from "@/lib/server/sidebar-data";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
function extractMindmapImageAssetIdsFromData(input: unknown): string[] {
|
||||
const root = (() => {
|
||||
if (!input || typeof input !== "object") return input;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const record = input as any;
|
||||
// 兼容:某些导图结构为 { root: ... }
|
||||
return record && typeof record === "object" && "root" in record ? record.root : input;
|
||||
})();
|
||||
|
||||
const ids: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
const push = (value: unknown) => {
|
||||
if (typeof value !== "string") return;
|
||||
if (!value.startsWith("asset:")) return;
|
||||
const id = value.slice("asset:".length).trim();
|
||||
if (!id) return;
|
||||
if (seen.has(id)) return;
|
||||
seen.add(id);
|
||||
ids.push(id);
|
||||
};
|
||||
|
||||
const get = (obj: unknown, key: string): unknown => {
|
||||
if (!obj || typeof obj !== "object") return undefined;
|
||||
return (obj as Record<string, unknown>)[key];
|
||||
};
|
||||
|
||||
const walk = (node: unknown) => {
|
||||
if (!node || typeof node !== "object") return;
|
||||
|
||||
const data = get(node, "data");
|
||||
const image = get(node, "image");
|
||||
|
||||
// 常见:node.data.image = "asset:xxx"
|
||||
push(get(data, "image"));
|
||||
// 兼容:node.image = "asset:xxx"
|
||||
push(image);
|
||||
// 兼容:node.image.url = "asset:xxx"
|
||||
push(get(image, "url"));
|
||||
// 兼容:node.data.image.url = "asset:xxx"
|
||||
push(get(get(data, "image"), "url"));
|
||||
|
||||
const children = get(node, "children");
|
||||
if (Array.isArray(children)) {
|
||||
children.forEach(walk);
|
||||
}
|
||||
};
|
||||
|
||||
walk(root);
|
||||
return ids;
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
if (isConvexEnabled()) {
|
||||
const { auth, client } = await getAuthedConvexClient();
|
||||
|
||||
const url = new URL(request.url);
|
||||
const workspaceIdParam = url.searchParams.get("workspaceId");
|
||||
|
||||
const bootstrap = await client.mutation(api.workspaces.ensureDefaultWorkspace, {
|
||||
const {
|
||||
targetWorkspaceId,
|
||||
sidebarInitialData,
|
||||
} = await loadSidebarDataFromConvex({
|
||||
client,
|
||||
userId: auth.userId,
|
||||
fallbackName: auth.email ?? auth.name ?? "我的空间",
|
||||
workspaceIdIfCreate: randomUUID(),
|
||||
requestedWorkspaceId: workspaceIdParam,
|
||||
});
|
||||
|
||||
const summaries = await client.query(api.workspaces.fetchWorkspaceSummaries, {
|
||||
});
|
||||
|
||||
const workspaces = summaries.workspaces.length > 0 ? summaries.workspaces : bootstrap.workspaces;
|
||||
const activeWorkspaceId = summaries.activeWorkspaceId || bootstrap.activeWorkspaceId;
|
||||
const targetWorkspaceId = workspaceIdParam || activeWorkspaceId;
|
||||
|
||||
if (!targetWorkspaceId) {
|
||||
return NextResponse.json({ error: "暂无可用工作空间" }, { status: 404 });
|
||||
}
|
||||
|
||||
try {
|
||||
const documents = await client.query(api.documents.listByWorkspace, {
|
||||
const bridgeContext = await buildDocumentBridgeContext({
|
||||
request,
|
||||
workspaceId: targetWorkspaceId,
|
||||
});
|
||||
|
||||
const trashedDocuments = await client.query(api.documents.listTrashedByWorkspace, {
|
||||
workspaceId: targetWorkspaceId,
|
||||
const envelope = buildDocumentQueryEnvelope({
|
||||
name: "sidebar.dataset.list",
|
||||
payload: { workspaceId: targetWorkspaceId },
|
||||
});
|
||||
if (!sidebarInitialData) {
|
||||
return NextResponse.json({ error: "暂无可用工作空间" }, { status: 404 });
|
||||
}
|
||||
|
||||
const mindmapRows = await client.query(api.mindmaps.listByWorkspace, {
|
||||
workspaceId: targetWorkspaceId,
|
||||
includeDeleted: true,
|
||||
return NextResponse.json({
|
||||
...sidebarInitialData,
|
||||
meta: {
|
||||
requestId: bridgeContext.requestId,
|
||||
traceId: bridgeContext.traceId,
|
||||
queryName: envelope.name,
|
||||
},
|
||||
});
|
||||
|
||||
const mediaAssets = await client.query(api.mediaAssets.listByWorkspace, {
|
||||
userId: auth.userId,
|
||||
workspaceId: targetWorkspaceId,
|
||||
limit: 200,
|
||||
});
|
||||
|
||||
const trashedMediaAssets = await client.query(api.mediaAssets.listDeletedByWorkspace, {
|
||||
userId: auth.userId,
|
||||
workspaceId: targetWorkspaceId,
|
||||
limit: 2000,
|
||||
});
|
||||
|
||||
const tables = await client.query(api.tables.listByWorkspaceForSearch, {
|
||||
userId: auth.userId,
|
||||
workspaceId: targetWorkspaceId,
|
||||
includeArchived: true,
|
||||
limit: 3000,
|
||||
});
|
||||
|
||||
const activeMindmaps = (mindmapRows ?? []).filter((r) => !r.deleted_at);
|
||||
const trashedMindmaps = (mindmapRows ?? []).filter((r) => !!r.deleted_at);
|
||||
|
||||
const mindmapDocs = Array.from(new Set(activeMindmaps.map((r) => r.document_id)));
|
||||
|
||||
const mindmapAssetChildren: Record<string, string[]> = {};
|
||||
activeMindmaps.forEach((r) => {
|
||||
const ids = extractMindmapImageAssetIdsFromData(r.data);
|
||||
if (ids.length > 0) {
|
||||
mindmapAssetChildren[r.mindmap_id] = ids;
|
||||
}
|
||||
});
|
||||
|
||||
const mindmapAssets: MediaAsset[] = activeMindmaps.map((r) => {
|
||||
const isLegacy = r.mindmap_id.startsWith("legacy-");
|
||||
return {
|
||||
id: r.mindmap_id,
|
||||
workspace_id: r.workspace_id ?? targetWorkspaceId,
|
||||
document_id: r.document_id,
|
||||
asset_type: "mindmap",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: isLegacy ? "mindmap.json" : `mindmap-${r.mindmap_id}.json`,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
signed_url: null,
|
||||
created_at: r.created_at ?? "",
|
||||
updated_at: r.updated_at ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
const trashedMindmapAssets: MediaAsset[] = trashedMindmaps.map((r) => {
|
||||
const isLegacy = r.mindmap_id.startsWith("legacy-");
|
||||
return {
|
||||
id: r.mindmap_id,
|
||||
workspace_id: r.workspace_id ?? targetWorkspaceId,
|
||||
document_id: r.document_id,
|
||||
asset_type: "mindmap",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: isLegacy ? "mindmap.json" : `mindmap-${r.mindmap_id}.json`,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
deleted_at: r.deleted_at ?? null,
|
||||
deleted_by: r.deleted_by ?? null,
|
||||
purged_at: null,
|
||||
signed_url: null,
|
||||
created_at: r.created_at ?? "",
|
||||
updated_at: r.updated_at ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
const tableAssets: MediaAsset[] = (tables ?? [])
|
||||
.filter((row) => !row.is_archived)
|
||||
.map((row) => {
|
||||
const base = String(row.title ?? "未命名表格").trim() || "未命名表格";
|
||||
const fileName = base.toLowerCase().endsWith(".luckysheet") ? base : `${base}.luckysheet`;
|
||||
return {
|
||||
id: row.id,
|
||||
workspace_id: row.workspace_id ?? targetWorkspaceId,
|
||||
document_id: row.document_id,
|
||||
asset_type: "luckysheet",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: fileName,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
signed_url: null,
|
||||
created_at: row.created_at ?? "",
|
||||
updated_at: row.updated_at ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
const trashedTableAssets: MediaAsset[] = (tables ?? [])
|
||||
.filter((row) => Boolean(row.is_archived))
|
||||
.map((row) => {
|
||||
const base = String(row.title ?? "未命名表格").trim() || "未命名表格";
|
||||
const fileName = base.toLowerCase().endsWith(".luckysheet") ? base : `${base}.luckysheet`;
|
||||
return {
|
||||
id: row.id,
|
||||
workspace_id: row.workspace_id ?? targetWorkspaceId,
|
||||
document_id: row.document_id,
|
||||
asset_type: "luckysheet",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: fileName,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
deleted_at: row.deleted_at ?? row.updated_at ?? null,
|
||||
deleted_by: row.deleted_by ?? null,
|
||||
purged_at: row.purged_at ?? null,
|
||||
signed_url: null,
|
||||
created_at: row.created_at ?? "",
|
||||
updated_at: row.updated_at ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
const payload: SidebarInitialData = {
|
||||
activeWorkspaceId: targetWorkspaceId,
|
||||
workspaces,
|
||||
documents,
|
||||
trashedDocuments,
|
||||
trashedMediaAssets: (trashedMediaAssets ?? []) as MediaAsset[],
|
||||
trashedMindmapAssets,
|
||||
trashedTableAssets,
|
||||
mindmapDocs,
|
||||
mindmapAssets,
|
||||
mindmapAssetChildren,
|
||||
tableAssets,
|
||||
mediaAssets: (mediaAssets ?? []) as MediaAsset[],
|
||||
};
|
||||
|
||||
return NextResponse.json(payload);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "拉取侧边栏数据失败" },
|
||||
{ status: 500 },
|
||||
);
|
||||
return documentBridgeErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -268,22 +63,22 @@ export async function GET(request: Request) {
|
||||
const {
|
||||
data: { session },
|
||||
} = await supabase.auth.getSession();
|
||||
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const workspaceIdParam = url.searchParams.get("workspaceId");
|
||||
|
||||
await ensureDefaultWorkspace(supabase, session.user.id, session.user.email ?? "我的空间");
|
||||
const { workspaces, activeWorkspaceId } = await fetchWorkspaceSummaries(supabase, session.user.id);
|
||||
const targetWorkspaceId = workspaceIdParam || activeWorkspaceId;
|
||||
|
||||
if (!targetWorkspaceId) {
|
||||
return NextResponse.json({ error: "暂无可用工作空间" }, { status: 404 });
|
||||
}
|
||||
|
||||
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const workspaceIdParam = url.searchParams.get("workspaceId");
|
||||
|
||||
await ensureDefaultWorkspace(supabase, session.user.id, session.user.email ?? "我的空间");
|
||||
const { workspaces, activeWorkspaceId } = await fetchWorkspaceSummaries(supabase, session.user.id);
|
||||
const targetWorkspaceId = workspaceIdParam || activeWorkspaceId;
|
||||
|
||||
if (!targetWorkspaceId) {
|
||||
return NextResponse.json({ error: "暂无可用工作空间" }, { status: 404 });
|
||||
}
|
||||
|
||||
try {
|
||||
const dataset = await fetchSidebarDataset(supabase, targetWorkspaceId);
|
||||
const docIds = dataset.documents.map((d) => d.id);
|
||||
@@ -360,10 +155,10 @@ export async function GET(request: Request) {
|
||||
|
||||
return NextResponse.json(payload);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "拉取侧边栏数据失败" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "拉取侧边栏数据失败" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -232,11 +232,14 @@ export function DocumentContent({
|
||||
}, CONTENT_LOADING_DELAY_MS);
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/documents/content?documentId=${encodeURIComponent(documentId)}`, {
|
||||
const response = await fetch(
|
||||
`/api/documents/content?documentId=${encodeURIComponent(documentId)}&workspaceId=${encodeURIComponent(workspaceId)}`,
|
||||
{
|
||||
method: "GET",
|
||||
credentials: "include",
|
||||
signal: controller.signal,
|
||||
});
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
throw new Error(payload?.error ?? "加载页面内容失败");
|
||||
@@ -270,7 +273,7 @@ export function DocumentContent({
|
||||
contentLoadingTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [documentId, initialContent, contentReloadKey]);
|
||||
}, [documentId, initialContent, contentReloadKey, workspaceId]);
|
||||
|
||||
const persistTitle = useCallback(
|
||||
async (nextTitle: string) => {
|
||||
@@ -279,10 +282,10 @@ export function DocumentContent({
|
||||
await fetch("/api/documents/title", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ documentId, title: payload }),
|
||||
body: JSON.stringify({ documentId, workspaceId, title: payload }),
|
||||
});
|
||||
},
|
||||
[documentId, readOnly],
|
||||
[documentId, readOnly, workspaceId],
|
||||
);
|
||||
|
||||
const debouncedPersistTitle = useDebouncedCallback((value: string) => {
|
||||
@@ -315,7 +318,7 @@ export function DocumentContent({
|
||||
const response = await fetch("/api/documents/options", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ documentId, options: patch }),
|
||||
body: JSON.stringify({ documentId, workspaceId, options: patch }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null);
|
||||
@@ -325,7 +328,7 @@ export function DocumentContent({
|
||||
console.error(error);
|
||||
}
|
||||
},
|
||||
[documentId, readOnly],
|
||||
[documentId, readOnly, workspaceId],
|
||||
);
|
||||
|
||||
const toggleOption = useCallback(
|
||||
@@ -600,9 +603,9 @@ export function DocumentContent({
|
||||
void fetch("/api/documents/stats", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ documentId, stats: next }),
|
||||
body: JSON.stringify({ documentId, workspaceId, stats: next }),
|
||||
}).catch((error) => console.error(error));
|
||||
}, [documentId]);
|
||||
}, [documentId, workspaceId]);
|
||||
|
||||
const persistStats = useDebouncedCallback(persistStatsRequest, 1500);
|
||||
|
||||
|
||||
@@ -1431,7 +1431,11 @@ function SidebarContent({ initialData, sidebarQuery }: SidebarContentProps) {
|
||||
await fetch("/api/documents/title", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ documentId, title: title.trim() }),
|
||||
body: JSON.stringify({
|
||||
documentId,
|
||||
workspaceId: sidebarData.activeWorkspaceId ?? null,
|
||||
title: title.trim(),
|
||||
}),
|
||||
});
|
||||
await refreshTree();
|
||||
},
|
||||
|
||||
@@ -3,7 +3,12 @@ import { useQuery, useConvexAuth } from "convex/react";
|
||||
import type { SidebarInitialData } from "@/components/sidebar/types";
|
||||
import type { MediaAsset } from "@/types/media";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import { buildSidebarInitialData } from "@/lib/sidebar-data";
|
||||
import { toBrowserAccessibleUrl } from "@/lib/url/browser-file-url";
|
||||
|
||||
type CurrentUserRecord = {
|
||||
_id?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convex 模式下的侧边栏数据 hook
|
||||
@@ -23,9 +28,11 @@ export function useConvexSidebarData(workspaceId: string): {
|
||||
// 显式转为 boolean,确保类型正确
|
||||
const shouldFetch = Boolean(isAuthenticated && workspaceId);
|
||||
const currentUser = useQuery(api.users.currentUser, shouldFetch ? {} : "skip");
|
||||
const currentUserRecord =
|
||||
currentUser && typeof currentUser === "object" ? (currentUser as CurrentUserRecord) : null;
|
||||
const userId =
|
||||
currentUser && typeof currentUser === "object" && typeof (currentUser as any)._id === "string"
|
||||
? String((currentUser as any)._id)
|
||||
currentUserRecord && typeof currentUserRecord._id === "string"
|
||||
? currentUserRecord._id
|
||||
: "";
|
||||
|
||||
const shouldFetchAuthed = Boolean(shouldFetch && userId);
|
||||
@@ -87,133 +94,16 @@ export function useConvexSidebarData(workspaceId: string): {
|
||||
return null;
|
||||
}
|
||||
|
||||
const activeMindmaps = (mindmaps ?? []).filter((r) => !r.deleted_at);
|
||||
const trashedMindmaps = (mindmaps ?? []).filter((r) => !!r.deleted_at);
|
||||
|
||||
const mindmapDocs = Array.from(new Set(activeMindmaps.map((r) => r.document_id)));
|
||||
|
||||
const mindmapAssets: MediaAsset[] = activeMindmaps.map((r) => {
|
||||
const isLegacy = r.mindmap_id.startsWith("legacy-");
|
||||
return {
|
||||
id: r.mindmap_id,
|
||||
workspace_id: r.workspace_id ?? workspaceId,
|
||||
document_id: r.document_id,
|
||||
asset_type: "mindmap",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: isLegacy ? "mindmap.json" : `mindmap-${r.mindmap_id}.json`,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
signed_url: null,
|
||||
created_at: r.created_at ?? "",
|
||||
updated_at: r.updated_at ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
const trashedMindmapAssets: MediaAsset[] = trashedMindmaps.map((r) => {
|
||||
const isLegacy = r.mindmap_id.startsWith("legacy-");
|
||||
return {
|
||||
id: r.mindmap_id,
|
||||
workspace_id: r.workspace_id ?? workspaceId,
|
||||
document_id: r.document_id,
|
||||
asset_type: "mindmap",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: isLegacy ? "mindmap.json" : `mindmap-${r.mindmap_id}.json`,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
deleted_at: r.deleted_at ?? null,
|
||||
deleted_by: r.deleted_by ?? null,
|
||||
purged_at: null,
|
||||
signed_url: null,
|
||||
created_at: r.created_at ?? "",
|
||||
updated_at: r.updated_at ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
const tableAssets: MediaAsset[] = (tables ?? [])
|
||||
.filter((row) => !row.is_archived)
|
||||
.map((row) => {
|
||||
const base = String(row.title ?? "未命名表格").trim() || "未命名表格";
|
||||
const fileName = base.toLowerCase().endsWith(".luckysheet") ? base : `${base}.luckysheet`;
|
||||
return {
|
||||
id: row.id,
|
||||
workspace_id: row.workspace_id ?? workspaceId,
|
||||
document_id: row.document_id,
|
||||
asset_type: "luckysheet",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: fileName,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
signed_url: null,
|
||||
created_at: row.created_at ?? "",
|
||||
updated_at: row.updated_at ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
const trashedTableAssets: MediaAsset[] = (tables ?? [])
|
||||
.filter((row) => Boolean(row.is_archived))
|
||||
.map((row) => {
|
||||
const base = String(row.title ?? "未命名表格").trim() || "未命名表格";
|
||||
const fileName = base.toLowerCase().endsWith(".luckysheet") ? base : `${base}.luckysheet`;
|
||||
return {
|
||||
id: row.id,
|
||||
workspace_id: row.workspace_id ?? workspaceId,
|
||||
document_id: row.document_id,
|
||||
asset_type: "luckysheet",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: fileName,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
deleted_at: row.deleted_at ?? row.updated_at ?? null,
|
||||
deleted_by: row.deleted_by ?? null,
|
||||
purged_at: row.purged_at ?? null,
|
||||
signed_url: null,
|
||||
created_at: row.created_at ?? "",
|
||||
updated_at: row.updated_at ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
return buildSidebarInitialData({
|
||||
activeWorkspaceId: workspacesResult.activeWorkspaceId || workspaceId,
|
||||
workspaces: workspacesResult.workspaces,
|
||||
documents,
|
||||
trashedDocuments,
|
||||
trashedMediaAssets: ((trashedMediaAssets ?? []) as MediaAsset[]).map(normalizeAssetUrls),
|
||||
trashedMindmapAssets,
|
||||
trashedTableAssets,
|
||||
mindmapDocs,
|
||||
mindmapAssets,
|
||||
mindmapAssetChildren: {},
|
||||
tableAssets,
|
||||
mindmaps,
|
||||
mediaAssets: ((mediaAssets ?? []) as MediaAsset[]).map(normalizeAssetUrls),
|
||||
};
|
||||
trashedMediaAssets: ((trashedMediaAssets ?? []) as MediaAsset[]).map(normalizeAssetUrls),
|
||||
tables,
|
||||
});
|
||||
}, [
|
||||
currentUser,
|
||||
documents,
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { api } from "@/lib/convex/api";
|
||||
import type { BridgeContext, BridgeTarget, CommandEnvelope } from "@/lib/documents/bridge";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
|
||||
const bridgeLogsApi = api as any;
|
||||
|
||||
function buildPayloadSummary(commandName: string, context: BridgeContext): string {
|
||||
return `command=${commandName};request_id=${context.requestId};trace_id=${context.traceId}`;
|
||||
}
|
||||
|
||||
function normalizeWorkspaceId(context: BridgeContext, target?: BridgeTarget | null): string | null {
|
||||
return target?.workspaceId?.trim() || context.workspaceId?.trim() || null;
|
||||
}
|
||||
|
||||
export async function recordBridgeCommandArtifacts<T>(input: {
|
||||
context: BridgeContext;
|
||||
envelope: CommandEnvelope<T>;
|
||||
}): Promise<void> {
|
||||
const workspaceId = normalizeWorkspaceId(input.context, input.envelope.target);
|
||||
if (!workspaceId) return;
|
||||
|
||||
const { client } = await getAuthedConvexClient();
|
||||
const commandLogId = `clog_${input.envelope.commandId}`;
|
||||
const eventId = `evt_${input.envelope.commandId}`;
|
||||
const now = new Date().toISOString();
|
||||
const payload = input.envelope.payload as Record<string, unknown>;
|
||||
|
||||
await client.mutation(bridgeLogsApi.bridgeLogs.recordCommandLog, {
|
||||
workspaceId,
|
||||
id: commandLogId,
|
||||
requestId: input.context.requestId,
|
||||
traceId: input.context.traceId,
|
||||
commandId: input.envelope.commandId,
|
||||
commandName: input.envelope.name,
|
||||
actorId: input.context.actor.actorId,
|
||||
actorType: input.context.actor.actorType,
|
||||
sourceChannel: input.context.source.channel,
|
||||
sourceClient: input.context.source.client,
|
||||
status: "succeeded",
|
||||
targetPageId: input.envelope.target?.pageId ?? null,
|
||||
targetBlockId: input.envelope.target?.blockId ?? null,
|
||||
payload,
|
||||
payloadSummary: buildPayloadSummary(input.envelope.name, input.context),
|
||||
refs: input.envelope.refs,
|
||||
idempotencyKey: input.envelope.idempotencyKey,
|
||||
error: null,
|
||||
createdAt: now,
|
||||
finishedAt: now,
|
||||
});
|
||||
|
||||
await client.mutation(bridgeLogsApi.bridgeLogs.recordDomainEvent, {
|
||||
workspaceId,
|
||||
id: eventId,
|
||||
requestId: input.context.requestId,
|
||||
traceId: input.context.traceId,
|
||||
commandId: input.envelope.commandId,
|
||||
commandLogId,
|
||||
eventType: `${input.envelope.name}.requested`,
|
||||
aggregateType: input.envelope.target?.blockId ? "block" : "page",
|
||||
aggregateId:
|
||||
input.envelope.target?.blockId ?? input.envelope.target?.pageId ?? workspaceId,
|
||||
eventVersion: 1,
|
||||
status: "committed",
|
||||
actorType: input.context.actor.actorType,
|
||||
payload: {
|
||||
request_id: input.context.requestId,
|
||||
trace_id: input.context.traceId,
|
||||
command_id: input.envelope.commandId,
|
||||
command_name: input.envelope.name,
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { headers } from "next/headers";
|
||||
import { ApiError } from "@/lib/api-utils";
|
||||
|
||||
type BridgeMeta = {
|
||||
requestId: string;
|
||||
traceId: string;
|
||||
queryName: string;
|
||||
};
|
||||
|
||||
type DocumentMetaResponse<T> = {
|
||||
doc: T;
|
||||
meta: BridgeMeta;
|
||||
};
|
||||
|
||||
function getServerRequestOrigin(headerList: Headers): string {
|
||||
const forwardedProto = headerList.get("x-forwarded-proto")?.split(",")[0]?.trim();
|
||||
const forwardedHost = headerList.get("x-forwarded-host")?.split(",")[0]?.trim();
|
||||
const host = forwardedHost || headerList.get("host");
|
||||
|
||||
if (!host) {
|
||||
throw new Error("缺少 host 头,无法构造 bridge 请求地址");
|
||||
}
|
||||
|
||||
return `${forwardedProto || "http"}://${host}`;
|
||||
}
|
||||
|
||||
function copyHeaderIfPresent(target: Headers, source: Headers, name: string) {
|
||||
const value = source.get(name);
|
||||
if (value) {
|
||||
target.set(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchDocumentMetaViaBridge<T>(input: {
|
||||
documentId: string;
|
||||
workspaceId?: string | null;
|
||||
}): Promise<DocumentMetaResponse<T> | null> {
|
||||
const headerList = await headers();
|
||||
const requestHeaders = new Headers();
|
||||
const origin = getServerRequestOrigin(headerList);
|
||||
const url = new URL("/api/documents/meta", origin);
|
||||
|
||||
url.searchParams.set("documentId", input.documentId);
|
||||
if (input.workspaceId?.trim()) {
|
||||
url.searchParams.set("workspaceId", input.workspaceId.trim());
|
||||
}
|
||||
|
||||
copyHeaderIfPresent(requestHeaders, headerList, "cookie");
|
||||
copyHeaderIfPresent(requestHeaders, headerList, "authorization");
|
||||
copyHeaderIfPresent(requestHeaders, headerList, "x-request-id");
|
||||
copyHeaderIfPresent(requestHeaders, headerList, "x-trace-id");
|
||||
copyHeaderIfPresent(requestHeaders, headerList, "x-session-id");
|
||||
copyHeaderIfPresent(requestHeaders, headerList, "x-source-channel");
|
||||
copyHeaderIfPresent(requestHeaders, headerList, "x-source-client");
|
||||
copyHeaderIfPresent(requestHeaders, headerList, "user-agent");
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: requestHeaders,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (response.status === 404) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
let message = "加载页面元信息失败";
|
||||
try {
|
||||
const payload = (await response.json()) as { error?: string };
|
||||
if (typeof payload?.error === "string" && payload.error.trim()) {
|
||||
message = payload.error;
|
||||
}
|
||||
} catch {
|
||||
// 说明:这里保留默认错误消息,避免 JSON 解析失败覆盖真实状态码。
|
||||
}
|
||||
throw new ApiError(message, response.status);
|
||||
}
|
||||
|
||||
return (await response.json()) as DocumentMetaResponse<T>;
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { ConvexHttpClient } from "convex/browser";
|
||||
|
||||
vi.mock("@/lib/auth/authContext", () => ({
|
||||
HttpError: class HttpError extends Error {
|
||||
status: number;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
},
|
||||
requireAuthContext: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api-utils", () => ({
|
||||
apiErrorResponse: vi.fn((message: string, status = 500, details?: unknown) => ({
|
||||
message,
|
||||
status,
|
||||
details,
|
||||
})),
|
||||
}));
|
||||
|
||||
import {
|
||||
DocumentBridgeError,
|
||||
assertDocumentId,
|
||||
assertBlockId,
|
||||
assertNextBlock,
|
||||
assertOptionsPatch,
|
||||
assertStats,
|
||||
assertTitle,
|
||||
buildDocumentCommandEnvelope,
|
||||
buildDocumentQueryEnvelope,
|
||||
type BridgeContext,
|
||||
} from "@/lib/documents/bridge";
|
||||
import { executeMetadataBridgeCommand } from "@/lib/documents/metadata-command-adapter";
|
||||
|
||||
vi.mock("@/lib/convex/route", () => ({
|
||||
getAuthedConvexClient: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/documents/bridge-log", () => ({
|
||||
recordBridgeCommandArtifacts: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockContext: BridgeContext = {
|
||||
deploymentId: null,
|
||||
projectId: null,
|
||||
workspaceId: "ws_1",
|
||||
requestId: "req_1",
|
||||
traceId: "trace_1",
|
||||
actor: {
|
||||
actorType: "user",
|
||||
actorId: "user_1",
|
||||
sessionId: "sess_1",
|
||||
},
|
||||
source: {
|
||||
channel: "next-route",
|
||||
client: "vitest",
|
||||
},
|
||||
tenantId: null,
|
||||
authToken: null,
|
||||
idempotencyKey: "idem_1",
|
||||
validateOnly: false,
|
||||
dryRun: false,
|
||||
};
|
||||
|
||||
describe("documents bridge helpers", () => {
|
||||
it("assertDocumentId returns trimmed id", () => {
|
||||
expect(assertDocumentId(" doc_1 ")).toBe("doc_1");
|
||||
});
|
||||
|
||||
it("assertDocumentId throws on empty value", () => {
|
||||
expect(() => assertDocumentId(" ")).toThrow(DocumentBridgeError);
|
||||
});
|
||||
|
||||
it("assertTitle normalizes empty title", () => {
|
||||
expect(assertTitle(" ")).toBe("无标题");
|
||||
});
|
||||
|
||||
it("assertBlockId returns trimmed block id", () => {
|
||||
expect(assertBlockId(" blk_1 ")).toBe("blk_1");
|
||||
});
|
||||
|
||||
it("assertNextBlock accepts plain object", () => {
|
||||
expect(() => assertNextBlock({ id: "blk_1" })).not.toThrow();
|
||||
});
|
||||
|
||||
it("assertStats accepts finite numeric stats", () => {
|
||||
expect(() =>
|
||||
assertStats({
|
||||
wordCount: 1,
|
||||
characterCount: 2,
|
||||
blockCount: 3,
|
||||
todoTotal: 4,
|
||||
todoDone: 5,
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("assertOptionsPatch accepts stable page options patch", () => {
|
||||
expect(() =>
|
||||
assertOptionsPatch({
|
||||
showToc: true,
|
||||
layoutDensity: "compact",
|
||||
embedDefaultBlockId: null,
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("buildDocumentCommandEnvelope keeps context flags", () => {
|
||||
const envelope = buildDocumentCommandEnvelope({
|
||||
name: "documents.save",
|
||||
payload: { documentId: "doc_1" },
|
||||
context: mockContext,
|
||||
target: { workspaceId: "ws_1", pageId: "doc_1" },
|
||||
});
|
||||
|
||||
expect(envelope.name).toBe("documents.save");
|
||||
expect(envelope.actor.actorId).toBe("user_1");
|
||||
expect(envelope.idempotencyKey).toBe("idem_1");
|
||||
expect(envelope.target?.pageId).toBe("doc_1");
|
||||
});
|
||||
|
||||
it("buildDocumentQueryEnvelope keeps payload", () => {
|
||||
const envelope = buildDocumentQueryEnvelope({
|
||||
name: "documents.content.get",
|
||||
payload: { documentId: "doc_1" },
|
||||
});
|
||||
|
||||
expect(envelope.payload).toEqual({ documentId: "doc_1" });
|
||||
});
|
||||
|
||||
it("executeMetadataBridgeCommand routes title update through adapter", async () => {
|
||||
const mutation = vi.fn().mockResolvedValue({ ok: true });
|
||||
const { getAuthedConvexClient } = await import("@/lib/convex/route");
|
||||
vi.mocked(getAuthedConvexClient).mockResolvedValue({
|
||||
auth: { userId: "user_1" },
|
||||
client: {
|
||||
mutation,
|
||||
} as unknown as ConvexHttpClient,
|
||||
});
|
||||
|
||||
const result = await executeMetadataBridgeCommand({
|
||||
context: mockContext,
|
||||
envelope: buildDocumentCommandEnvelope({
|
||||
name: "documents.title.update",
|
||||
payload: {
|
||||
documentId: "doc_1",
|
||||
workspaceId: "ws_1",
|
||||
title: "新标题",
|
||||
},
|
||||
context: mockContext,
|
||||
target: { workspaceId: "ws_1", pageId: "doc_1" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(mutation).toHaveBeenCalledTimes(1);
|
||||
expect(mutation.mock.calls[0]?.[1]).toEqual({
|
||||
id: "doc_1",
|
||||
title: "新标题",
|
||||
});
|
||||
expect(result.commandName).toBe("documents.title.update");
|
||||
});
|
||||
|
||||
it("executeMetadataBridgeCommand routes options update through adapter", async () => {
|
||||
const mutation = vi.fn().mockResolvedValue({ ok: true });
|
||||
const { getAuthedConvexClient } = await import("@/lib/convex/route");
|
||||
vi.mocked(getAuthedConvexClient).mockResolvedValue({
|
||||
auth: { userId: "user_1" },
|
||||
client: {
|
||||
mutation,
|
||||
} as unknown as ConvexHttpClient,
|
||||
});
|
||||
|
||||
const result = await executeMetadataBridgeCommand({
|
||||
context: mockContext,
|
||||
envelope: buildDocumentCommandEnvelope({
|
||||
name: "documents.options.update",
|
||||
payload: {
|
||||
documentId: "doc_1",
|
||||
workspaceId: "ws_1",
|
||||
options: {
|
||||
showToc: true,
|
||||
layoutDensity: "compact",
|
||||
embedDefaultBlockId: null,
|
||||
},
|
||||
},
|
||||
context: mockContext,
|
||||
target: { workspaceId: "ws_1", pageId: "doc_1" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(mutation).toHaveBeenCalledTimes(1);
|
||||
expect(mutation.mock.calls[0]?.[1]).toEqual({
|
||||
id: "doc_1",
|
||||
options: {
|
||||
wideLayout: undefined,
|
||||
smallText: undefined,
|
||||
showHeadingNumbers: undefined,
|
||||
showToc: true,
|
||||
showStructure: undefined,
|
||||
protectEditing: undefined,
|
||||
showWordCount: undefined,
|
||||
collapseBacklinks: undefined,
|
||||
pageFont: undefined,
|
||||
layoutDensity: "compact",
|
||||
hideChildPages: undefined,
|
||||
showBlockRefCount: undefined,
|
||||
embedDefaultBlockId: null,
|
||||
},
|
||||
});
|
||||
expect(result.commandName).toBe("documents.options.update");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,345 @@
|
||||
import { randomUUID } from "crypto";
|
||||
import { HttpError, requireAuthContext } from "@/lib/auth/authContext";
|
||||
import { apiErrorResponse } from "@/lib/api-utils";
|
||||
import type { PageOptionsState } from "@/types/page-options";
|
||||
|
||||
export type BridgeActor = {
|
||||
actorType: string;
|
||||
actorId: string;
|
||||
sessionId: string | null;
|
||||
};
|
||||
|
||||
export type BridgeSource = {
|
||||
channel: string;
|
||||
client: string;
|
||||
};
|
||||
|
||||
export type BridgeTarget = {
|
||||
workspaceId?: string | null;
|
||||
pageId?: string | null;
|
||||
blockId?: string | null;
|
||||
};
|
||||
|
||||
export type BridgeRequestMeta = {
|
||||
idempotencyKey: string | null;
|
||||
validateOnly: boolean;
|
||||
dryRun: boolean;
|
||||
};
|
||||
|
||||
export type BridgeContext = {
|
||||
deploymentId: string | null;
|
||||
projectId: string | null;
|
||||
workspaceId: string | null;
|
||||
requestId: string;
|
||||
traceId: string;
|
||||
actor: BridgeActor;
|
||||
source: BridgeSource;
|
||||
tenantId: string | null;
|
||||
authToken: string | null;
|
||||
idempotencyKey: string | null;
|
||||
validateOnly: boolean;
|
||||
dryRun: boolean;
|
||||
};
|
||||
|
||||
export type BridgeErrorCode =
|
||||
| "VALIDATION_ERROR"
|
||||
| "UNAUTHORIZED"
|
||||
| "FORBIDDEN"
|
||||
| "NOT_FOUND"
|
||||
| "TRANSPORT_ERROR"
|
||||
| "REJECTED";
|
||||
|
||||
export class DocumentBridgeError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number,
|
||||
public readonly code: BridgeErrorCode,
|
||||
public readonly details?: unknown,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "DocumentBridgeError";
|
||||
}
|
||||
}
|
||||
|
||||
export type CommandEnvelope<T> = {
|
||||
name: string;
|
||||
commandId: string;
|
||||
idempotencyKey: string | null;
|
||||
actor: BridgeActor;
|
||||
source: BridgeSource;
|
||||
target: BridgeTarget | null;
|
||||
payload: T;
|
||||
reason: string | null;
|
||||
refs: string[];
|
||||
dryRun: boolean;
|
||||
validateOnly: boolean;
|
||||
};
|
||||
|
||||
export type QueryEnvelope<T> = {
|
||||
name: string;
|
||||
payload: T;
|
||||
};
|
||||
|
||||
function readHeaderValue(headerList: Headers, ...candidates: string[]): string | null {
|
||||
for (const candidate of candidates) {
|
||||
const value = headerList.get(candidate);
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function toBooleanFlag(raw: string | null): boolean {
|
||||
if (!raw) return false;
|
||||
return raw === "1" || raw.toLowerCase() === "true";
|
||||
}
|
||||
|
||||
function makeFallbackId(prefix: string): string {
|
||||
return `${prefix}_${randomUUID()}`;
|
||||
}
|
||||
|
||||
export async function buildDocumentBridgeContext(input: {
|
||||
request: Request;
|
||||
workspaceId?: string | null;
|
||||
idempotencyKey?: string | null;
|
||||
validateOnly?: boolean;
|
||||
dryRun?: boolean;
|
||||
}): Promise<BridgeContext> {
|
||||
let auth;
|
||||
try {
|
||||
auth = await requireAuthContext();
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) {
|
||||
throw new DocumentBridgeError(error.message || "未登录", error.status, "UNAUTHORIZED");
|
||||
}
|
||||
throw new DocumentBridgeError("未登录", 401, "UNAUTHORIZED");
|
||||
}
|
||||
|
||||
const headerList = input.request.headers;
|
||||
const requestId =
|
||||
readHeaderValue(headerList, "x-request-id", "x-mnote-request-id") ?? makeFallbackId("req");
|
||||
const traceId =
|
||||
readHeaderValue(headerList, "x-trace-id", "x-mnote-trace-id", "x-request-id") ?? makeFallbackId("trace");
|
||||
const sessionId = readHeaderValue(headerList, "x-session-id", "x-mnote-session-id");
|
||||
const sourceChannel = readHeaderValue(headerList, "x-source-channel") ?? "next-route";
|
||||
const sourceClient = readHeaderValue(headerList, "x-source-client", "user-agent") ?? "wolai-frontend";
|
||||
const deploymentId =
|
||||
readHeaderValue(headerList, "x-deployment-id") ?? process.env.VERCEL_DEPLOYMENT_ID ?? null;
|
||||
const projectId = readHeaderValue(headerList, "x-project-id") ?? process.env.VERCEL_PROJECT_ID ?? null;
|
||||
const tenantId = readHeaderValue(headerList, "x-tenant-id");
|
||||
const authToken = readHeaderValue(headerList, "authorization");
|
||||
const idempotencyKey =
|
||||
input.idempotencyKey ?? readHeaderValue(headerList, "idempotency-key", "x-idempotency-key");
|
||||
const validateOnly = input.validateOnly ?? toBooleanFlag(readHeaderValue(headerList, "x-validate-only"));
|
||||
const dryRun = input.dryRun ?? toBooleanFlag(readHeaderValue(headerList, "x-dry-run"));
|
||||
|
||||
return {
|
||||
deploymentId,
|
||||
projectId,
|
||||
workspaceId: input.workspaceId ?? null,
|
||||
requestId,
|
||||
traceId,
|
||||
actor: {
|
||||
actorType: "user",
|
||||
actorId: auth.userId,
|
||||
sessionId,
|
||||
},
|
||||
source: {
|
||||
channel: sourceChannel,
|
||||
client: sourceClient,
|
||||
},
|
||||
tenantId,
|
||||
authToken,
|
||||
idempotencyKey,
|
||||
validateOnly,
|
||||
dryRun,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildDocumentCommandEnvelope<T>(input: {
|
||||
name: string;
|
||||
payload: T;
|
||||
context: BridgeContext;
|
||||
target?: BridgeTarget | null;
|
||||
reason?: string | null;
|
||||
refs?: string[];
|
||||
}): CommandEnvelope<T> {
|
||||
return {
|
||||
name: input.name,
|
||||
commandId: makeFallbackId("cmd"),
|
||||
idempotencyKey: input.context.idempotencyKey,
|
||||
actor: input.context.actor,
|
||||
source: input.context.source,
|
||||
target: input.target ?? null,
|
||||
payload: input.payload,
|
||||
reason: input.reason ?? null,
|
||||
refs: input.refs ?? [],
|
||||
dryRun: input.context.dryRun,
|
||||
validateOnly: input.context.validateOnly,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildDocumentQueryEnvelope<T>(input: { name: string; payload: T }): QueryEnvelope<T> {
|
||||
return {
|
||||
name: input.name,
|
||||
payload: input.payload,
|
||||
};
|
||||
}
|
||||
|
||||
export function assertDocumentId(documentId: string | null | undefined): string {
|
||||
const normalized = typeof documentId === "string" ? documentId.trim() : "";
|
||||
if (!normalized) {
|
||||
throw new DocumentBridgeError("缺少 documentId", 400, "VALIDATION_ERROR", [
|
||||
{ field: "documentId", reason: "required" },
|
||||
]);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function assertTitle(title: string | null | undefined): string {
|
||||
if (typeof title !== "string") {
|
||||
throw new DocumentBridgeError("缺少 title", 400, "VALIDATION_ERROR", [
|
||||
{ field: "title", reason: "required" },
|
||||
]);
|
||||
}
|
||||
const normalized = title.trim() || "无标题";
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function assertBlockId(blockId: string | null | undefined): string {
|
||||
const normalized = typeof blockId === "string" ? blockId.trim() : "";
|
||||
if (!normalized) {
|
||||
throw new DocumentBridgeError("缺少 blockId", 400, "VALIDATION_ERROR", [
|
||||
{ field: "blockId", reason: "required" },
|
||||
]);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function assertNextBlock(nextBlock: unknown): asserts nextBlock is Record<string, unknown> {
|
||||
if (!nextBlock || typeof nextBlock !== "object" || Array.isArray(nextBlock)) {
|
||||
throw new DocumentBridgeError("缺少 nextBlock", 400, "VALIDATION_ERROR", [
|
||||
{ field: "nextBlock", reason: "required object" },
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertStats(stats: unknown): asserts stats is {
|
||||
wordCount: number;
|
||||
characterCount: number;
|
||||
blockCount: number;
|
||||
todoTotal: number;
|
||||
todoDone: number;
|
||||
} {
|
||||
if (!stats || typeof stats !== "object") {
|
||||
throw new DocumentBridgeError("缺少 stats", 400, "VALIDATION_ERROR", [
|
||||
{ field: "stats", reason: "required" },
|
||||
]);
|
||||
}
|
||||
const record = stats as Record<string, unknown>;
|
||||
const fields = ["wordCount", "characterCount", "blockCount", "todoTotal", "todoDone"] as const;
|
||||
for (const field of fields) {
|
||||
if (typeof record[field] !== "number" || !Number.isFinite(record[field] as number)) {
|
||||
throw new DocumentBridgeError("stats 字段非法", 400, "VALIDATION_ERROR", [
|
||||
{ field, reason: "must be finite number" },
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const PAGE_FONT_VALUES = new Set<PageOptionsState["pageFont"]>(["default", "song", "kai"]);
|
||||
const PAGE_LAYOUT_DENSITY_VALUES = new Set<PageOptionsState["layoutDensity"]>(["compact", "normal", "spacious"]);
|
||||
const PAGE_OPTION_BOOLEAN_FIELDS = [
|
||||
"wideLayout",
|
||||
"smallText",
|
||||
"showHeadingNumbers",
|
||||
"showToc",
|
||||
"showStructure",
|
||||
"protectEditing",
|
||||
"showWordCount",
|
||||
"collapseBacklinks",
|
||||
"hideChildPages",
|
||||
"showBlockRefCount",
|
||||
] as const satisfies readonly (keyof PageOptionsState)[];
|
||||
const PAGE_OPTION_ALLOWED_FIELDS = new Set<keyof PageOptionsState>([
|
||||
...PAGE_OPTION_BOOLEAN_FIELDS,
|
||||
"pageFont",
|
||||
"layoutDensity",
|
||||
"embedDefaultBlockId",
|
||||
]);
|
||||
|
||||
export function assertOptionsPatch(
|
||||
options: unknown,
|
||||
): asserts options is Partial<Pick<PageOptionsState, keyof PageOptionsState>> {
|
||||
if (!options || typeof options !== "object" || Array.isArray(options)) {
|
||||
throw new DocumentBridgeError("缺少 options", 400, "VALIDATION_ERROR", [
|
||||
{ field: "options", reason: "required object" },
|
||||
]);
|
||||
}
|
||||
|
||||
const record = options as Record<string, unknown>;
|
||||
const entries = Object.entries(record);
|
||||
if (entries.length === 0) {
|
||||
throw new DocumentBridgeError("缺少 options", 400, "VALIDATION_ERROR", [
|
||||
{ field: "options", reason: "must not be empty" },
|
||||
]);
|
||||
}
|
||||
|
||||
for (const [field, value] of entries) {
|
||||
if (!PAGE_OPTION_ALLOWED_FIELDS.has(field as keyof PageOptionsState)) {
|
||||
throw new DocumentBridgeError("options 字段非法", 400, "VALIDATION_ERROR", [
|
||||
{ field, reason: "unexpected field" },
|
||||
]);
|
||||
}
|
||||
|
||||
if ((PAGE_OPTION_BOOLEAN_FIELDS as readonly string[]).includes(field)) {
|
||||
if (typeof value !== "boolean") {
|
||||
throw new DocumentBridgeError("options 字段非法", 400, "VALIDATION_ERROR", [
|
||||
{ field, reason: "must be boolean" },
|
||||
]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (field === "pageFont") {
|
||||
if (typeof value !== "string" || !PAGE_FONT_VALUES.has(value as PageOptionsState["pageFont"])) {
|
||||
throw new DocumentBridgeError("options 字段非法", 400, "VALIDATION_ERROR", [
|
||||
{ field, reason: "must be one of default/song/kai" },
|
||||
]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (field === "layoutDensity") {
|
||||
if (
|
||||
typeof value !== "string" ||
|
||||
!PAGE_LAYOUT_DENSITY_VALUES.has(value as PageOptionsState["layoutDensity"])
|
||||
) {
|
||||
throw new DocumentBridgeError("options 字段非法", 400, "VALIDATION_ERROR", [
|
||||
{ field, reason: "must be one of compact/normal/spacious" },
|
||||
]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (field === "embedDefaultBlockId" && value !== null && typeof value !== "string") {
|
||||
throw new DocumentBridgeError("options 字段非法", 400, "VALIDATION_ERROR", [
|
||||
{ field, reason: "must be string or null" },
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function documentBridgeErrorResponse(error: unknown) {
|
||||
if (error instanceof DocumentBridgeError) {
|
||||
return apiErrorResponse(error.message, error.status, {
|
||||
code: error.code,
|
||||
details: error.details,
|
||||
});
|
||||
}
|
||||
if (error instanceof HttpError) {
|
||||
return apiErrorResponse(error.message || "未登录", error.status);
|
||||
}
|
||||
return apiErrorResponse(error instanceof Error ? error.message : "服务器错误", 500);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
compareDocumentCanonicalOrder,
|
||||
getCanonicalDocumentByBusinessId,
|
||||
getCanonicalParentDocumentId,
|
||||
pickCanonicalDocumentRecord,
|
||||
} from "../../../convex/_utils/documentRecord";
|
||||
|
||||
describe("pickCanonicalDocumentRecord", () => {
|
||||
it("同一 business id 出现重复记录时优先选择最新未删除记录", () => {
|
||||
const selected = pickCanonicalDocumentRecord([
|
||||
{
|
||||
_id: "doc_old",
|
||||
deleted_at: null,
|
||||
created_at: "2026-04-14T00:00:00.000Z",
|
||||
updated_at: "2026-04-14T00:00:01.000Z",
|
||||
},
|
||||
{
|
||||
_id: "doc_deleted",
|
||||
deleted_at: "2026-04-14T00:00:03.000Z",
|
||||
created_at: "2026-04-14T00:00:02.000Z",
|
||||
updated_at: "2026-04-14T00:00:03.000Z",
|
||||
},
|
||||
{
|
||||
_id: "doc_new",
|
||||
deleted_at: null,
|
||||
created_at: "2026-04-14T00:00:02.000Z",
|
||||
updated_at: "2026-04-14T00:00:04.000Z",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(selected?._id).toBe("doc_new");
|
||||
});
|
||||
|
||||
it("全部已删除时仍稳定选择最新记录,避免 first() 命中漂移", () => {
|
||||
const selected = pickCanonicalDocumentRecord([
|
||||
{
|
||||
_id: "doc_deleted_old",
|
||||
deleted_at: "2026-04-14T00:00:01.000Z",
|
||||
created_at: "2026-04-14T00:00:00.000Z",
|
||||
updated_at: "2026-04-14T00:00:01.000Z",
|
||||
},
|
||||
{
|
||||
_id: "doc_deleted_new",
|
||||
deleted_at: "2026-04-14T00:00:03.000Z",
|
||||
created_at: "2026-04-14T00:00:02.000Z",
|
||||
updated_at: "2026-04-14T00:00:03.000Z",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(selected?._id).toBe("doc_deleted_new");
|
||||
});
|
||||
|
||||
it("时间戳相同时用 _id 稳定打破平手,避免 collect 后结果不稳定", () => {
|
||||
const selected = pickCanonicalDocumentRecord([
|
||||
{
|
||||
_id: "doc_b",
|
||||
deleted_at: null,
|
||||
created_at: "2026-04-14T00:00:00.000Z",
|
||||
updated_at: "2026-04-14T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
_id: "doc_a",
|
||||
deleted_at: null,
|
||||
created_at: "2026-04-14T00:00:00.000Z",
|
||||
updated_at: "2026-04-14T00:00:00.000Z",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(selected?._id).toBe("doc_a");
|
||||
});
|
||||
});
|
||||
|
||||
describe("compareDocumentCanonicalOrder", () => {
|
||||
it("未删除记录始终排在已删除记录前面,供页面权限/内容读链复用", () => {
|
||||
const records = [
|
||||
{
|
||||
_id: "deleted",
|
||||
deleted_at: "2026-04-14T00:00:03.000Z",
|
||||
created_at: "2026-04-14T00:00:02.000Z",
|
||||
updated_at: "2026-04-14T00:00:03.000Z",
|
||||
},
|
||||
{
|
||||
_id: "alive",
|
||||
deleted_at: null,
|
||||
created_at: "2026-04-14T00:00:01.000Z",
|
||||
updated_at: "2026-04-14T00:00:01.000Z",
|
||||
},
|
||||
];
|
||||
|
||||
const sorted = [...records].sort(compareDocumentCanonicalOrder);
|
||||
expect(sorted.map((record) => record._id)).toEqual(["alive", "deleted"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("canonical document helper", () => {
|
||||
const createCtx = (records: Array<Record<string, unknown>>) => ({
|
||||
db: {
|
||||
query: () => ({
|
||||
withIndex: () => ({
|
||||
collect: async () => records,
|
||||
}),
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
it("按 business id 查询时返回 canonical 记录,避免高风险读链命中旧记录", async () => {
|
||||
const ctx = createCtx([
|
||||
{
|
||||
_id: "doc_old",
|
||||
id: "doc_1",
|
||||
parent_id: "parent_old",
|
||||
deleted_at: null,
|
||||
created_at: "2026-04-14T00:00:00.000Z",
|
||||
updated_at: "2026-04-14T00:00:01.000Z",
|
||||
},
|
||||
{
|
||||
_id: "doc_new",
|
||||
id: "doc_1",
|
||||
parent_id: "parent_new",
|
||||
deleted_at: null,
|
||||
created_at: "2026-04-14T00:00:02.000Z",
|
||||
updated_at: "2026-04-14T00:00:03.000Z",
|
||||
},
|
||||
]);
|
||||
|
||||
const doc = await getCanonicalDocumentByBusinessId<any>(ctx, "doc_1");
|
||||
expect(doc?._id).toBe("doc_new");
|
||||
});
|
||||
|
||||
it("父链辅助函数返回 canonical 父页面 id,供共享/评论祖先扫描复用", async () => {
|
||||
const ctx = createCtx([
|
||||
{
|
||||
_id: "doc_old",
|
||||
id: "doc_1",
|
||||
parent_id: "parent_old",
|
||||
deleted_at: null,
|
||||
created_at: "2026-04-14T00:00:00.000Z",
|
||||
updated_at: "2026-04-14T00:00:01.000Z",
|
||||
},
|
||||
{
|
||||
_id: "doc_new",
|
||||
id: "doc_1",
|
||||
parent_id: "parent_new",
|
||||
deleted_at: null,
|
||||
created_at: "2026-04-14T00:00:02.000Z",
|
||||
updated_at: "2026-04-14T00:00:03.000Z",
|
||||
},
|
||||
]);
|
||||
|
||||
const parentId = await getCanonicalParentDocumentId(ctx, "doc_1");
|
||||
expect(parentId).toBe("parent_new");
|
||||
});
|
||||
|
||||
it("父链辅助函数命中已删除旧记录时仍回退到最新未删除父级,供收藏祖先权限复用", async () => {
|
||||
const ctx = createCtx([
|
||||
{
|
||||
_id: "doc_deleted",
|
||||
id: "doc_2",
|
||||
parent_id: "parent_deleted",
|
||||
deleted_at: "2026-04-14T00:00:04.000Z",
|
||||
created_at: "2026-04-14T00:00:00.000Z",
|
||||
updated_at: "2026-04-14T00:00:04.000Z",
|
||||
},
|
||||
{
|
||||
_id: "doc_alive",
|
||||
id: "doc_2",
|
||||
parent_id: "parent_alive",
|
||||
deleted_at: null,
|
||||
created_at: "2026-04-14T00:00:01.000Z",
|
||||
updated_at: "2026-04-14T00:00:03.000Z",
|
||||
},
|
||||
]);
|
||||
|
||||
const parentId = await getCanonicalParentDocumentId(ctx, "doc_2");
|
||||
expect(parentId).toBe("parent_alive");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { api } from "@/lib/convex/api";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import type { CommandEnvelope, BridgeContext } from "@/lib/documents/bridge";
|
||||
import { recordBridgeCommandArtifacts } from "@/lib/documents/bridge-log";
|
||||
import type { PageOptionsState } from "@/types/page-options";
|
||||
|
||||
export type DocumentTitleUpdatePayload = {
|
||||
documentId: string;
|
||||
workspaceId: string | null;
|
||||
title: string;
|
||||
};
|
||||
|
||||
export type DocumentStatsUpdatePayload = {
|
||||
documentId: string;
|
||||
workspaceId: string | null;
|
||||
stats: {
|
||||
wordCount: number;
|
||||
characterCount: number;
|
||||
blockCount: number;
|
||||
todoTotal: number;
|
||||
todoDone: number;
|
||||
};
|
||||
};
|
||||
|
||||
export type DocumentOptionsUpdatePayload = {
|
||||
documentId: string;
|
||||
workspaceId: string | null;
|
||||
options: Partial<PageOptionsState>;
|
||||
};
|
||||
|
||||
export type MetadataCommandExecutionResult = {
|
||||
requestId: string;
|
||||
traceId: string;
|
||||
commandId: string;
|
||||
commandName: string;
|
||||
};
|
||||
|
||||
type MetadataWriteAdapter<TPayload> = {
|
||||
convexMutation: unknown;
|
||||
mapConvexArgs: (payload: TPayload) => Record<string, unknown>;
|
||||
};
|
||||
|
||||
function mapDocumentOptionsToConvexArgs(payload: DocumentOptionsUpdatePayload) {
|
||||
return {
|
||||
id: payload.documentId,
|
||||
options: {
|
||||
wideLayout: payload.options.wideLayout,
|
||||
smallText: payload.options.smallText,
|
||||
showHeadingNumbers: payload.options.showHeadingNumbers,
|
||||
showToc: payload.options.showToc,
|
||||
showStructure: payload.options.showStructure,
|
||||
protectEditing: payload.options.protectEditing,
|
||||
showWordCount: payload.options.showWordCount,
|
||||
collapseBacklinks: payload.options.collapseBacklinks,
|
||||
pageFont: payload.options.pageFont,
|
||||
layoutDensity: payload.options.layoutDensity,
|
||||
hideChildPages: payload.options.hideChildPages,
|
||||
showBlockRefCount: payload.options.showBlockRefCount,
|
||||
embedDefaultBlockId:
|
||||
typeof payload.options.embedDefaultBlockId === "string" ? payload.options.embedDefaultBlockId : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const metadataWriteAdapters: Record<string, MetadataWriteAdapter<unknown>> = {
|
||||
"documents.title.update": {
|
||||
convexMutation: api.documents.updateTitle,
|
||||
mapConvexArgs: (payload: DocumentTitleUpdatePayload) => ({
|
||||
id: payload.documentId,
|
||||
title: payload.title,
|
||||
}),
|
||||
},
|
||||
"documents.stats.update": {
|
||||
convexMutation: api.documents.updateStats,
|
||||
mapConvexArgs: (payload: DocumentStatsUpdatePayload) => ({
|
||||
id: payload.documentId,
|
||||
wordCount: payload.stats.wordCount,
|
||||
characterCount: payload.stats.characterCount,
|
||||
blockCount: payload.stats.blockCount,
|
||||
todoTotal: payload.stats.todoTotal,
|
||||
todoDone: payload.stats.todoDone,
|
||||
}),
|
||||
},
|
||||
"documents.options.update": {
|
||||
convexMutation: api.documents.updateOptions,
|
||||
mapConvexArgs: mapDocumentOptionsToConvexArgs,
|
||||
},
|
||||
};
|
||||
|
||||
function getMetadataWriteAdapter<TPayload>(commandName: string): MetadataWriteAdapter<TPayload> {
|
||||
const adapter = metadataWriteAdapters[commandName];
|
||||
if (!adapter) {
|
||||
throw new Error(`未注册页面元信息命令适配器: ${commandName}`);
|
||||
}
|
||||
return adapter as MetadataWriteAdapter<TPayload>;
|
||||
}
|
||||
|
||||
export async function executeMetadataBridgeCommand<TPayload>(input: {
|
||||
context: BridgeContext;
|
||||
envelope: CommandEnvelope<TPayload>;
|
||||
}): Promise<MetadataCommandExecutionResult> {
|
||||
const adapter = getMetadataWriteAdapter<TPayload>(input.envelope.name);
|
||||
const { client } = await getAuthedConvexClient();
|
||||
|
||||
await client.mutation(
|
||||
adapter.convexMutation as Parameters<typeof client.mutation>[0],
|
||||
adapter.mapConvexArgs(input.envelope.payload) as Parameters<typeof client.mutation>[1],
|
||||
);
|
||||
await recordBridgeCommandArtifacts({
|
||||
context: input.context,
|
||||
envelope: input.envelope,
|
||||
});
|
||||
|
||||
return {
|
||||
requestId: input.context.requestId,
|
||||
traceId: input.context.traceId,
|
||||
commandId: input.envelope.commandId,
|
||||
commandName: input.envelope.name,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { randomUUID } from "crypto";
|
||||
import type { ConvexHttpClient } from "convex/browser";
|
||||
import type { SidebarInitialData } from "@/components/sidebar/types";
|
||||
import type { DocumentRecord } from "@/lib/documents";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import { buildSidebarInitialData } from "@/lib/sidebar-data";
|
||||
import type { WorkspaceSummary } from "@/lib/workspaces";
|
||||
|
||||
type LoadSidebarDataFromConvexInput = {
|
||||
client: ConvexHttpClient;
|
||||
userId: string;
|
||||
fallbackName: string;
|
||||
requestedWorkspaceId?: string | null;
|
||||
};
|
||||
|
||||
type LoadSidebarDataFromConvexResult = {
|
||||
workspaces: WorkspaceSummary[];
|
||||
activeWorkspaceId: string;
|
||||
targetWorkspaceId: string | null;
|
||||
sidebarInitialData: SidebarInitialData | null;
|
||||
documents: DocumentRecord[];
|
||||
};
|
||||
|
||||
export async function loadSidebarDataFromConvex(
|
||||
input: LoadSidebarDataFromConvexInput,
|
||||
): Promise<LoadSidebarDataFromConvexResult> {
|
||||
const bootstrap = await input.client.mutation(api.workspaces.ensureDefaultWorkspace, {
|
||||
fallbackName: input.fallbackName,
|
||||
workspaceIdIfCreate: randomUUID(),
|
||||
});
|
||||
|
||||
const summaries = await input.client.query(api.workspaces.fetchWorkspaceSummaries, {});
|
||||
const workspaces = summaries.workspaces.length > 0 ? summaries.workspaces : bootstrap.workspaces;
|
||||
const activeWorkspaceId = summaries.activeWorkspaceId || bootstrap.activeWorkspaceId;
|
||||
const targetWorkspaceId = input.requestedWorkspaceId?.trim() || activeWorkspaceId || null;
|
||||
|
||||
if (!targetWorkspaceId) {
|
||||
return {
|
||||
workspaces,
|
||||
activeWorkspaceId,
|
||||
targetWorkspaceId: null,
|
||||
sidebarInitialData: null,
|
||||
documents: [],
|
||||
};
|
||||
}
|
||||
|
||||
const [documents, trashedDocuments, mindmaps, mediaAssets, trashedMediaAssets, tables] = await Promise.all([
|
||||
input.client.query(api.documents.listByWorkspace, {
|
||||
workspaceId: targetWorkspaceId,
|
||||
}),
|
||||
input.client.query(api.documents.listTrashedByWorkspace, {
|
||||
workspaceId: targetWorkspaceId,
|
||||
}),
|
||||
input.client.query(api.mindmaps.listByWorkspace, {
|
||||
workspaceId: targetWorkspaceId,
|
||||
includeDeleted: true,
|
||||
}),
|
||||
input.client.query(api.mediaAssets.listByWorkspace, {
|
||||
userId: input.userId,
|
||||
workspaceId: targetWorkspaceId,
|
||||
limit: 200,
|
||||
}),
|
||||
input.client.query(api.mediaAssets.listDeletedByWorkspace, {
|
||||
userId: input.userId,
|
||||
workspaceId: targetWorkspaceId,
|
||||
limit: 2000,
|
||||
}),
|
||||
input.client.query(api.tables.listByWorkspaceForSearch, {
|
||||
userId: input.userId,
|
||||
workspaceId: targetWorkspaceId,
|
||||
includeArchived: true,
|
||||
limit: 3000,
|
||||
}),
|
||||
]);
|
||||
|
||||
const normalizedDocuments = documents as DocumentRecord[];
|
||||
|
||||
return {
|
||||
workspaces,
|
||||
activeWorkspaceId,
|
||||
targetWorkspaceId,
|
||||
sidebarInitialData: buildSidebarInitialData({
|
||||
activeWorkspaceId: targetWorkspaceId,
|
||||
workspaces,
|
||||
documents: normalizedDocuments,
|
||||
trashedDocuments,
|
||||
mindmaps: mindmaps ?? [],
|
||||
mediaAssets: mediaAssets ?? [],
|
||||
trashedMediaAssets: trashedMediaAssets ?? [],
|
||||
tables: tables ?? [],
|
||||
}),
|
||||
documents: normalizedDocuments,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { DocumentRecord } from "@/lib/documents";
|
||||
import type { WorkspaceSummary } from "@/lib/workspaces";
|
||||
import type { SidebarInitialData } from "@/components/sidebar/types";
|
||||
import { buildSidebarInitialData, extractMindmapImageAssetIdsFromData } from "@/lib/sidebar-data";
|
||||
|
||||
describe("extractMindmapImageAssetIdsFromData", () => {
|
||||
it("提取导图节点里的 asset 图片引用并去重", () => {
|
||||
const ids = extractMindmapImageAssetIdsFromData({
|
||||
root: {
|
||||
data: { image: "asset:img_1" },
|
||||
children: [
|
||||
{ image: { url: "asset:img_2" } },
|
||||
{ data: { image: { url: "asset:img_1" } } },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(ids).toEqual(["img_1", "img_2"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildSidebarInitialData", () => {
|
||||
it("统一组装 mindmap/table/media 相关侧边栏数据", () => {
|
||||
const workspaces: WorkspaceSummary[] = [
|
||||
{
|
||||
id: "ws_1",
|
||||
name: "工作区",
|
||||
type: "personal",
|
||||
iconUrl: null,
|
||||
memberCount: 1,
|
||||
isDefault: true,
|
||||
},
|
||||
];
|
||||
|
||||
const documents: DocumentRecord[] = [
|
||||
{
|
||||
id: "doc_1",
|
||||
workspace_id: "ws_1",
|
||||
title: "页面 1",
|
||||
parent_id: null,
|
||||
sort_order: 1,
|
||||
is_starred: false,
|
||||
access_scope: "private",
|
||||
is_template: false,
|
||||
created_at: "2026-04-14T00:00:00Z",
|
||||
updated_at: null,
|
||||
},
|
||||
];
|
||||
|
||||
const trashedDocuments: SidebarInitialData["trashedDocuments"] = [];
|
||||
|
||||
const payload = buildSidebarInitialData({
|
||||
activeWorkspaceId: "ws_1",
|
||||
workspaces,
|
||||
documents,
|
||||
trashedDocuments,
|
||||
mediaAssets: [
|
||||
{
|
||||
id: "asset_file_1",
|
||||
workspace_id: "ws_1",
|
||||
document_id: "doc_1",
|
||||
asset_type: "file",
|
||||
file_url: "/file/1",
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: "a.txt",
|
||||
file_size: null,
|
||||
mime_type: "text/plain",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
signed_url: null,
|
||||
created_at: "2026-04-14T00:00:00Z",
|
||||
updated_at: "2026-04-14T00:00:00Z",
|
||||
},
|
||||
],
|
||||
trashedMediaAssets: [],
|
||||
mindmaps: [
|
||||
{
|
||||
mindmap_id: "mind_1",
|
||||
workspace_id: "ws_1",
|
||||
document_id: "doc_1",
|
||||
data: {
|
||||
root: {
|
||||
data: { image: "asset:img_a" },
|
||||
children: [{ image: { url: "asset:img_b" } }],
|
||||
},
|
||||
},
|
||||
created_at: "2026-04-14T00:00:00Z",
|
||||
updated_at: "2026-04-14T00:00:00Z",
|
||||
deleted_at: null,
|
||||
},
|
||||
{
|
||||
mindmap_id: "mind_2",
|
||||
workspace_id: "ws_1",
|
||||
document_id: "doc_1",
|
||||
data: null,
|
||||
created_at: "2026-04-14T00:00:00Z",
|
||||
updated_at: "2026-04-14T00:00:00Z",
|
||||
deleted_at: "2026-04-14T01:00:00Z",
|
||||
deleted_by: "user_1",
|
||||
},
|
||||
],
|
||||
tables: [
|
||||
{
|
||||
id: "table_1",
|
||||
workspace_id: "ws_1",
|
||||
document_id: "doc_1",
|
||||
title: "预算",
|
||||
created_at: "2026-04-14T00:00:00Z",
|
||||
updated_at: "2026-04-14T00:00:00Z",
|
||||
is_archived: false,
|
||||
},
|
||||
{
|
||||
id: "table_2",
|
||||
workspace_id: "ws_1",
|
||||
document_id: "doc_1",
|
||||
title: "归档表格",
|
||||
created_at: "2026-04-14T00:00:00Z",
|
||||
updated_at: "2026-04-14T00:00:00Z",
|
||||
deleted_at: "2026-04-14T01:00:00Z",
|
||||
deleted_by: "user_1",
|
||||
purged_at: null,
|
||||
is_archived: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(payload.activeWorkspaceId).toBe("ws_1");
|
||||
expect(payload.mindmapDocs).toEqual(["doc_1"]);
|
||||
expect(payload.mindmapAssetChildren).toEqual({
|
||||
mind_1: ["img_a", "img_b"],
|
||||
});
|
||||
expect(payload.mindmapAssets?.map((item) => item.id)).toEqual(["mind_1"]);
|
||||
expect(payload.trashedMindmapAssets?.map((item) => item.id)).toEqual(["mind_2"]);
|
||||
expect(payload.tableAssets?.map((item) => item.file_name)).toEqual(["预算.luckysheet"]);
|
||||
expect(payload.trashedTableAssets?.map((item) => item.id)).toEqual(["table_2"]);
|
||||
expect(payload.mediaAssets?.map((item) => item.id)).toEqual(["asset_file_1"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,189 @@
|
||||
import type { SidebarInitialData } from "@/components/sidebar/types";
|
||||
import type { DocumentRecord } from "@/lib/documents";
|
||||
import type { WorkspaceSummary } from "@/lib/workspaces";
|
||||
import type { MediaAsset } from "@/types/media";
|
||||
|
||||
type MindmapRow = {
|
||||
mindmap_id: string;
|
||||
workspace_id?: string | null;
|
||||
document_id: string;
|
||||
data?: unknown;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
deleted_at?: string | null;
|
||||
deleted_by?: string | null;
|
||||
};
|
||||
|
||||
type TableRow = {
|
||||
id: string;
|
||||
workspace_id?: string | null;
|
||||
document_id: string;
|
||||
title?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
deleted_at?: string | null;
|
||||
deleted_by?: string | null;
|
||||
purged_at?: string | null;
|
||||
is_archived?: boolean | null;
|
||||
};
|
||||
|
||||
type SidebarDatasetInput = {
|
||||
activeWorkspaceId: string;
|
||||
workspaces: WorkspaceSummary[];
|
||||
documents: DocumentRecord[];
|
||||
trashedDocuments: SidebarInitialData["trashedDocuments"];
|
||||
mindmaps: MindmapRow[];
|
||||
mediaAssets?: MediaAsset[] | null;
|
||||
trashedMediaAssets?: MediaAsset[] | null;
|
||||
tables?: TableRow[] | null;
|
||||
};
|
||||
|
||||
function normalizeStringArray(values: Iterable<string>): string[] {
|
||||
return Array.from(new Set(values)).filter((value) => value.trim().length > 0);
|
||||
}
|
||||
|
||||
export function extractMindmapImageAssetIdsFromData(input: unknown): string[] {
|
||||
const root = (() => {
|
||||
if (!input || typeof input !== "object") return input;
|
||||
const record = input as Record<string, unknown>;
|
||||
return record && typeof record === "object" && "root" in record ? record.root : input;
|
||||
})();
|
||||
|
||||
const ids: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
const push = (value: unknown) => {
|
||||
if (typeof value !== "string") return;
|
||||
if (!value.startsWith("asset:")) return;
|
||||
const id = value.slice("asset:".length).trim();
|
||||
if (!id || seen.has(id)) return;
|
||||
seen.add(id);
|
||||
ids.push(id);
|
||||
};
|
||||
|
||||
const get = (obj: unknown, key: string): unknown => {
|
||||
if (!obj || typeof obj !== "object") return undefined;
|
||||
return (obj as Record<string, unknown>)[key];
|
||||
};
|
||||
|
||||
const walk = (node: unknown) => {
|
||||
if (!node || typeof node !== "object") return;
|
||||
|
||||
const data = get(node, "data");
|
||||
const image = get(node, "image");
|
||||
|
||||
push(get(data, "image"));
|
||||
push(image);
|
||||
push(get(image, "url"));
|
||||
push(get(get(data, "image"), "url"));
|
||||
|
||||
const children = get(node, "children");
|
||||
if (Array.isArray(children)) {
|
||||
children.forEach(walk);
|
||||
}
|
||||
};
|
||||
|
||||
walk(root);
|
||||
return ids;
|
||||
}
|
||||
|
||||
function toMindmapAsset(row: MindmapRow, workspaceId: string): MediaAsset {
|
||||
const isLegacy = row.mindmap_id.startsWith("legacy-");
|
||||
return {
|
||||
id: row.mindmap_id,
|
||||
workspace_id: row.workspace_id ?? workspaceId,
|
||||
document_id: row.document_id,
|
||||
asset_type: "mindmap",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: isLegacy ? "mindmap.json" : `mindmap-${row.mindmap_id}.json`,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
signed_url: null,
|
||||
created_at: row.created_at ?? "",
|
||||
updated_at: row.updated_at ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
function toTrashedMindmapAsset(row: MindmapRow, workspaceId: string): MediaAsset {
|
||||
return {
|
||||
...toMindmapAsset(row, workspaceId),
|
||||
deleted_at: row.deleted_at ?? null,
|
||||
deleted_by: row.deleted_by ?? null,
|
||||
purged_at: null,
|
||||
};
|
||||
}
|
||||
|
||||
function toTableAsset(row: TableRow, workspaceId: string): MediaAsset {
|
||||
const base = String(row.title ?? "未命名表格").trim() || "未命名表格";
|
||||
const fileName = base.toLowerCase().endsWith(".luckysheet") ? base : `${base}.luckysheet`;
|
||||
return {
|
||||
id: row.id,
|
||||
workspace_id: row.workspace_id ?? workspaceId,
|
||||
document_id: row.document_id,
|
||||
asset_type: "luckysheet",
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: fileName,
|
||||
file_size: null,
|
||||
mime_type: "application/json",
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
signed_url: null,
|
||||
created_at: row.created_at ?? "",
|
||||
updated_at: row.updated_at ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
function toTrashedTableAsset(row: TableRow, workspaceId: string): MediaAsset {
|
||||
return {
|
||||
...toTableAsset(row, workspaceId),
|
||||
deleted_at: row.deleted_at ?? row.updated_at ?? null,
|
||||
deleted_by: row.deleted_by ?? null,
|
||||
purged_at: row.purged_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildSidebarInitialData(input: SidebarDatasetInput): SidebarInitialData {
|
||||
const activeMindmaps = input.mindmaps.filter((row) => !row.deleted_at);
|
||||
const trashedMindmaps = input.mindmaps.filter((row) => Boolean(row.deleted_at));
|
||||
const activeTables = (input.tables ?? []).filter((row) => !row.is_archived);
|
||||
const trashedTables = (input.tables ?? []).filter((row) => Boolean(row.is_archived));
|
||||
|
||||
const mindmapAssetChildren: Record<string, string[]> = {};
|
||||
activeMindmaps.forEach((row) => {
|
||||
const ids = extractMindmapImageAssetIdsFromData(row.data);
|
||||
if (ids.length > 0) {
|
||||
mindmapAssetChildren[row.mindmap_id] = ids;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
activeWorkspaceId: input.activeWorkspaceId,
|
||||
workspaces: input.workspaces,
|
||||
documents: input.documents,
|
||||
trashedDocuments: input.trashedDocuments,
|
||||
trashedMediaAssets: [...(input.trashedMediaAssets ?? [])],
|
||||
trashedMindmapAssets: trashedMindmaps.map((row) =>
|
||||
toTrashedMindmapAsset(row, input.activeWorkspaceId),
|
||||
),
|
||||
trashedTableAssets: trashedTables.map((row) =>
|
||||
toTrashedTableAsset(row, input.activeWorkspaceId),
|
||||
),
|
||||
mindmapDocs: normalizeStringArray(activeMindmaps.map((row) => row.document_id)),
|
||||
mindmapAssets: activeMindmaps.map((row) => toMindmapAsset(row, input.activeWorkspaceId)),
|
||||
mindmapAssetChildren,
|
||||
tableAssets: activeTables.map((row) => toTableAsset(row, input.activeWorkspaceId)),
|
||||
mediaAssets: [...(input.mediaAssets ?? [])],
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user