0.6 rust重构01

This commit is contained in:
lix-2026
2026-04-14 13:22:29 +08:00
parent 71fb1aee7e
commit 84a8454fa9
401 changed files with 5841 additions and 1512 deletions
@@ -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");
});
});
+345
View File
@@ -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,
};
}