An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support end-to-end typed contracts for kernel APIs https://github.com/siyuan-note/siyuan/issues/19378
Daniel0627dd6a2a5b
diff --git a/.github/workflows/api-contracts.yml b/.github/workflows/api-contracts.ymlnew file mode 100644index 0000000000..5806066ce2--- /dev/null+++ b/.github/workflows/api-contracts.yml@@ -0,0 +1,50 @@+name: API contracts++on:+ pull_request:+ push:+ branches: [dev, master]++permissions:+ contents: read++jobs:+ contracts:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v6+ with:+ fetch-depth: 0+ - uses: actions/setup-go@v6+ with:+ go-version-file: kernel/go.mod+ cache-dependency-path: kernel/go.sum+ - uses: actions/setup-node@v6+ with:+ node-version: 24+ - name: Install repository pnpm version+ run: node -e "require('node:child_process').execFileSync('npm', ['install', '--global', require('./app/package.json').packageManager], {stdio:'inherit'});"+ - name: Install frontend dependencies+ run: pnpm install --frozen-lockfile+ working-directory: app+ - name: Check generated contracts and route coverage+ run: pnpm run api:check+ working-directory: app+ - name: Check legacy coverage does not grow+ if: github.event_name == 'pull_request' || github.event.before != '0000000000000000000000000000000000000000'+ run: pnpm run api:check --base "$API_CONTRACT_BASE"+ working-directory: app+ env:+ API_CONTRACT_BASE: ${{ github.event.pull_request.base.sha || github.event.before }}+ - name: Check application and strict contract types+ run: pnpm run typecheck+ working-directory: app+ - name: Test request and response contracts+ run: go test ./apicontract/...+ working-directory: kernel+ - name: Test actual API responses and compatibility+ run: go test -tags "fts5 sqlcipher" ./api -run "TestAPIContract|TestBlockAttrsRespectPublishAccess|TestGetBlockInfoRecovery|TestGetBlockInfoPublishAccess|TestListNotebooksSortsBySubDocCount" -count=1+ working-directory: kernel+ - name: Test frontend transport behavior+ run: pnpm exec tsx --test src/util/fetch.test.ts src/util/fetchTimeout.test.ts+ working-directory: appdiff --git a/app/package.json b/app/package.jsonindex 852f68c18a..c813b02b54 100644--- a/app/package.json+++ b/app/package.json@@ -8,7 +8,9 @@"packageManager": "[email protected]","scripts": {"lint": "pnpm run typecheck && eslint . --fix --cache",- "typecheck": "tsc -p tsconfig.typecheck.json",+ "typecheck": "tsc -p tsconfig.typecheck.json && tsc -p tsconfig.api.json",+ "api:generate": "node scripts/api-contracts.mjs",+ "api:check": "node scripts/api-contracts.mjs --check","test": "node --import tsx --test","dev": "webpack --mode development","dev:mobile": "webpack --mode development --config webpack.mobile.js",diff --git a/app/scripts/api-contracts.mjs b/app/scripts/api-contracts.mjsnew file mode 100644index 0000000000..0242858c96--- /dev/null+++ b/app/scripts/api-contracts.mjs@@ -0,0 +1,12 @@+import {spawnSync} from "node:child_process";+import {fileURLToPath} from "node:url";++const kernel = fileURLToPath(new URL("../../kernel/", import.meta.url));+const result = spawnSync("go", ["run", "./apicontract/cmd/apigen", ...process.argv.slice(2)], {+ cwd: kernel,+ stdio: "inherit",+});+if (result.error) {+ console.error(result.error.message);+}+process.exit(result.status ?? 1);diff --git a/app/src/boot/globalEvent/command/global.ts b/app/src/boot/globalEvent/command/global.tsindex 54961822d2..a6eaf3dd58 100644--- a/app/src/boot/globalEvent/command/global.ts+++ b/app/src/boot/globalEvent/command/global.ts@@ -216,6 +216,9 @@ export const globalCommand = (command: string, app: App, range?: Range) => {return true;}fetchPost("/api/block/getBlockInfo", {id: childData.rootId || childData.blockId}, (infoResponse) => {+ if (infoResponse.code !== 0) {+ return;+ }if (infoResponse.data.rootID === (childData.rootId || childData.blockId)) {if (childData.instance === "Editor") {openFile({diff --git a/app/src/editor/util.ts b/app/src/editor/util.tsindex ddf126203d..e2b23b857a 100644--- a/app/src/editor/util.ts+++ b/app/src/editor/util.ts@@ -85,6 +85,9 @@ export const openFileById = async (options: {showMessage(response.msg);return;}+ if (response.code !== 0) {+ return;+ }const zoomIn = options.zoomIn === true && options.id !== response.data.rootID;return openFile({diff --git a/app/src/history/doc.ts b/app/src/history/doc.tsindex 41eeac320a..1287b5f06d 100644--- a/app/src/history/doc.ts+++ b/app/src/history/doc.ts@@ -59,13 +59,14 @@ const renderDoc = (element: HTMLElement, currentPage: number, id: string) => {const pageInfoElement = nextElement.nextElementSibling.nextElementSibling;pageInfoElement.classList.remove("fn__none");pageInfoElement.textContent = window.siyuan.languages.pageCountAndHistoryCount.replace("${x}", response.data.pageCount).replace("${y}", response.data.totalCount);- if (response.data.histories.length === 0) {+ const histories = response.data.histories || [];+ if (histories.length === 0) {listElement.innerHTML = `${genCurrentVersionItem()}<li class="b3-list--empty">${window.siyuan.languages.emptyContent}</li>`;element.dispatchEvent(new CustomEvent("versionListRendered"));return;}let logsHTML = genCurrentVersionItem();- response.data.histories.forEach((item: string) => {+ histories.forEach((item: string) => {logsHTML += `<li class="b3-list-item b3-list-item--hide-action" data-created="${item}"><span class="b3-list-item__text">${dayjs(parseInt(item) * 1000).format("YYYY-MM-DD HH:mm:ss")}</span><span class="fn__space"></span>diff --git a/app/src/history/history.ts b/app/src/history/history.tsindex 7f5629ee20..5b575af7c2 100644--- a/app/src/history/history.ts+++ b/app/src/history/history.ts@@ -96,12 +96,13 @@ const renderDoc = (element: HTMLElement, currentPage: number) => {const pageElement = nextElement.nextElementSibling.nextElementSibling;pageElement.textContent = `${window.siyuan.languages.pageCountAndHistoryCount.replace("${x}", response.data.pageCount).replace("${y}", response.data.totalCount || 1)}`;pageElement.classList.remove("fn__none");- if (response.data.histories.length === 0) {+ const histories = response.data.histories || [];+ if (histories.length === 0) {listElement.innerHTML = `<li class="b3-list--empty">${window.siyuan.languages.emptyContent}</li>`;return;}let logsHTML = "";- response.data.histories.forEach((item: string) => {+ histories.forEach((item: string) => {logsHTML += `<li class="b3-list-item" data-type="toggle" data-created="${item}"><span class="b3-list-item__toggle b3-list-item__toggle--hl"><svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg></span><span style="padding-left: 4px" class="b3-list-item__text">${dayjs(parseInt(item) * 1000).format("YYYY-MM-DD HH:mm:ss")}</span>@@ -377,7 +378,8 @@ const renderRepo = (element: Element, currentPage: number) => {previousElement.setAttribute("disabled", "disabled");}nextElement.setAttribute("disabled", "disabled");- fetchPost(`/api/repo/${selectValue}`, {page: currentPage}, (response) => {+ const snapshotURL: string = `/api/repo/${selectValue}`;+ fetchPost(snapshotURL, {page: currentPage}, (response) => {selectElement.disabled = false;if (currentPage < response.data.pageCount) {nextElement.removeAttribute("disabled");diff --git a/app/src/menus/util.ts b/app/src/menus/util.tsindex 75df173780..a1461fb8c1 100644--- a/app/src/menus/util.ts+++ b/app/src/menus/util.ts@@ -197,6 +197,9 @@ export const openEditorTab = (app: App, ids: string[], notebookId?: string, path} else {ids.forEach((id) => {fetchPost("/api/block/getBlockInfo", {id}, (response) => {+ if (response.code !== 0 || response.data.publishAccessRequired) {+ return;+ }useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, response.data.box, response.data.path));});});diff --git a/app/src/mobile/editor.ts b/app/src/mobile/editor.tsindex bc9091f306..0c6041436c 100644--- a/app/src/mobile/editor.ts+++ b/app/src/mobile/editor.ts@@ -152,7 +152,7 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[}const targetNotebookId = notebookId || window.siyuan.mobile.editor?.protyle?.notebookId;- const blockInfoParam: IObject = {id};+ const blockInfoParam: {id: string; notebook?: string} = {id};if (isEncryptedBox(targetNotebookId)) {blockInfoParam.notebook = targetNotebookId;}diff --git a/app/src/mobile/tabs/MobileTabs.ts b/app/src/mobile/tabs/MobileTabs.tsindex 718d7d4876..0374b2bb23 100644--- a/app/src/mobile/tabs/MobileTabs.ts+++ b/app/src/mobile/tabs/MobileTabs.ts@@ -324,9 +324,9 @@ export class MobileTabs {}private resolveRoot(id: string, notebookId?: string, signal?: AbortSignal) {- return new Promise<{rootID: string; box: string}>((resolve, reject) => {+ return new Promise<{rootID: string; box?: string}>((resolve, reject) => {signal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), {once: true});- const data: IObject = {id};+ const data: {id: string; notebook?: string} = {id};if (notebookId) {data.notebook = notebookId;}@@ -353,7 +353,7 @@ export class MobileTabs {const abortController = new AbortController();this.abortController = abortController;const epoch = ++this.navigationEpoch;- let info: {rootID: string; box: string};+ let info: {rootID: string; box?: string};try {info = await this.resolveRoot(id, options.notebookId, abortController.signal);} catch (error) {diff --git a/app/src/plugin/API.ts b/app/src/plugin/API.tsindex c7b718e927..d4fef76814 100644--- a/app/src/plugin/API.ts+++ b/app/src/plugin/API.ts@@ -307,7 +307,7 @@ export const expandDocTree = async (options: {liElement = file.element.querySelector(`.b3-list[data-url="${options.id}"]`)?.firstElementChild as HTMLElement;} else {const response = await fetchSyncPost("/api/block/getBlockInfo", {id: options.id});- if (response.code === -1) {+ if (response.code !== 0 || response.data.publishAccessRequired) {return;}notebookId = response.data.box;diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.tsindex f0850dafb0..ef844c22fb 100644--- a/app/src/protyle/util/editorCommonEvent.ts+++ b/app/src/protyle/util/editorCommonEvent.ts@@ -177,7 +177,7 @@ const getDragSourceParentID = async (protyle: IProtyle, element: Element) => {id: element.getAttribute("data-node-id"),notebook: dragSourceElement?.getAttribute(DRAG_SOURCE_NOTEBOOK_ID) || "",});- return response?.data?.rootID || "";+ return response.code === 0 ? response.data.rootID : "";};const cancelDetachedSourceSB = async (nodeElement: Element, excludedChildIDs: Set<string>) => {diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsnew file mode 100644index 0000000000..a9c8379704--- /dev/null+++ b/app/src/types/api/index.d.ts@@ -0,0 +1,774 @@+// 此文件由内核契约生成,请运行 pnpm run api:generate 更新。++export type BlockIDRequestInput = { "id": string; };++export type BlockInfoData = (FullBlockInfo & { "publishAccessRequired"?: never; }) | (PublishedBlockInfo & { "box"?: never; "path"?: never; "rootChildID"?: never; });++export type BlockInfoRequestInput = { "id": string; "ids"?: Array<string> | null; "notebook"?: string | null; };++export type EmptyRequestInput = Record<string, never>;++export type FullBlockInfo = { "box": string; "path": string; "rootChildID": string; "rootID": string; "rootIcon": string; "rootTitle": string; "rootTitleEmpty": boolean; };++export type ListNotebooksData = { "boxDocEnabled": boolean; "notebooks": Array<Notebook | null> | null; };++export type ListNotebooksRequestInput = { "flashcard"?: boolean | null; };++export type Notebook = { "closed": boolean; "dueFlashcardCount": number; "encrypted": boolean; "flashcardCount": number; "icon": string; "id": string; "name": string; "newFlashcardCount": number; "sort": number; "sortMode": number; "state"?: "Locked" | "Unlocking" | "Unlocked" | "Locking" | "Error"; "subFileCount": number; "unlocked": boolean; };++export type PublishedBlockInfo = { "publishAccessRequired": true; "rootID": string; "rootIcon": string; "rootTitle": string; "rootTitleEmpty": boolean; };++export type SearchHistoryData = { "histories": Array<string> | null; "pageCount": number; "totalCount": number; };++export type SearchHistoryRequestInput = { "notebook"?: string | null; "op"?: string | null; "page"?: number | null; "query"?: string | null; "type"?: number | null; };++export type SearchTagData = { "k": string; "tags": Array<string>; };++export type SearchTagRequestInput = { "k": string; };++export type SetBlockAttrsRequestInput = { "attrs": Record<string, string | null>; "id": string; };++export type APILegacyGETPath =+ "/api/ai/mcp/oauth/callback/:flowID" |+ "/api/icon/getDynamicIcon" |+ "/api/network/echo" |+ "/api/network/echo/*path" |+ "/api/network/proxy" |+ "/api/plugin" |+ "/api/plugin/rpc" |+ "/api/plugin/rpc/:name" |+ "/api/system/bootProgress" |+ "/api/system/bootProgressSSE" |+ "/api/system/getBootAppearance" |+ "/api/system/getCaptcha" |+ "/api/system/oidc/callback" |+ "/es/broadcast/subscribe" |+ "/es/network/proxy" |+ "/plugin/private/:name/*path" |+ "/ws/broadcast" |+ "/ws/network/proxy" |+ "/ws/plugin/rpc" |+ "/ws/plugin/rpc/:name";++export interface APIGETRoutes {+ "/api/system/version": {+ request: EmptyRequestInput;+ response: { "code": 0; "data": string; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "none";+ };+}++export type APILegacyPOSTPath =+ "/api/account/checkActivationcode" |+ "/api/account/deactivate" |+ "/api/account/login" |+ "/api/account/startFreeTrial" |+ "/api/account/useActivationcode" |+ "/api/ai/agent/browserCapabilityResult" |+ "/api/ai/agent/chat" |+ "/api/ai/agent/confirm" |+ "/api/ai/agent/getSession" |+ "/api/ai/agent/getSkill" |+ "/api/ai/agent/lsSessions" |+ "/api/ai/agent/lsSkills" |+ "/api/ai/agent/lsUserSkills" |+ "/api/ai/agent/question" |+ "/api/ai/agent/removeSession" |+ "/api/ai/agent/removeSkill" |+ "/api/ai/agent/renameSkill" |+ "/api/ai/agent/saveSession" |+ "/api/ai/agent/saveSkill" |+ "/api/ai/agent/setPermission" |+ "/api/ai/agent/title" |+ "/api/ai/chatGPT" |+ "/api/ai/chatGPTWithAction" |+ "/api/ai/editor/chat" |+ "/api/ai/editor/lsActions" |+ "/api/ai/editor/removeAction" |+ "/api/ai/editor/saveAction" |+ "/api/ai/embeddingStat" |+ "/api/ai/listModels" |+ "/api/ai/lsCapabilities" |+ "/api/ai/mcpEnvironmentVariables" |+ "/api/ai/mcpOAuthAuthorize" |+ "/api/ai/mcpOAuthDisconnect" |+ "/api/ai/mcpStatus" |+ "/api/ai/reindexEmbedding" |+ "/api/ai/retryFailedEmbedding" |+ "/api/ai/testEmbeddingModel" |+ "/api/ai/testModel" |+ "/api/ai/testRerankModel" |+ "/api/archive/unzip" |+ "/api/archive/zip" |+ "/api/asset/fullReindexAssetContent" |+ "/api/asset/getDocAssets" |+ "/api/asset/getDocImageAssets" |+ "/api/asset/getFileAnnotation" |+ "/api/asset/getImageOCRText" |+ "/api/asset/getMissingAssets" |+ "/api/asset/getUnusedAssets" |+ "/api/asset/insertCover" |+ "/api/asset/insertLocalAssets" |+ "/api/asset/ocr" |+ "/api/asset/removeUnusedAsset" |+ "/api/asset/removeUnusedAssets" |+ "/api/asset/renameAsset" |+ "/api/asset/resolveAssetPath" |+ "/api/asset/setFileAnnotation" |+ "/api/asset/setImageOCRText" |+ "/api/asset/statAsset" |+ "/api/asset/upload" |+ "/api/asset/uploadCloud" |+ "/api/asset/uploadCloudByAssetsPaths" |+ "/api/attr/batchGetBlockAttrs" |+ "/api/attr/batchSetBlockAttrs" |+ "/api/attr/getBookmarkLabels" |+ "/api/attr/resetBlockAttrs" |+ "/api/av/addAttributeViewBlocks" |+ "/api/av/addAttributeViewKey" |+ "/api/av/appendAttributeViewDetachedBlocksWithValues" |+ "/api/av/batchReplaceAttributeViewBlocks" |+ "/api/av/batchSetAttributeViewBlockAttrs" |+ "/api/av/changeAttrViewLayout" |+ "/api/av/createAttributeViewItem" |+ "/api/av/createAttributeViewItemDocs" |+ "/api/av/createAttributeViewItemWithMarkdown" |+ "/api/av/duplicateAttributeViewBlock" |+ "/api/av/getAttributeView" |+ "/api/av/getAttributeViewAddingBlockDefaultValues" |+ "/api/av/getAttributeViewBacklinks" |+ "/api/av/getAttributeViewBoundBlockIDsByItemIDs" |+ "/api/av/getAttributeViewFieldViews" |+ "/api/av/getAttributeViewFilterSort" |+ "/api/av/getAttributeViewItemIDsByBoundIDs" |+ "/api/av/getAttributeViewItemStatuses" |+ "/api/av/getAttributeViewKeys" |+ "/api/av/getAttributeViewKeysByAvID" |+ "/api/av/getAttributeViewKeysByID" |+ "/api/av/getAttributeViewPasteRows" |+ "/api/av/getAttributeViewPrimaryKeyValues" |+ "/api/av/getAttributeViewRelationCandidates" |+ "/api/av/getAttributeViewRowSort" |+ "/api/av/getAttributeViewSearchTarget" |+ "/api/av/getCurrentAttrViewImages" |+ "/api/av/getMirrorDatabaseBlocks" |+ "/api/av/getUnusedAttributeViews" |+ "/api/av/removeAttributeViewBlocks" |+ "/api/av/removeAttributeViewKey" |+ "/api/av/removeUnusedAttributeView" |+ "/api/av/removeUnusedAttributeViews" |+ "/api/av/renderAttributeView" |+ "/api/av/renderHistoryAttributeView" |+ "/api/av/renderSnapshotAttributeView" |+ "/api/av/searchAttributeView" |+ "/api/av/searchAttributeViewNonRelationKey" |+ "/api/av/searchAttributeViewRelationKey" |+ "/api/av/searchAttributeViewRollupDestKeys" |+ "/api/av/setAttrViewContextFilter" |+ "/api/av/setAttrViewFilters" |+ "/api/av/setAttrViewGroup" |+ "/api/av/setAttrViewSorts" |+ "/api/av/setAttributeViewBlockAttr" |+ "/api/av/setDatabaseBlockView" |+ "/api/av/sortAttributeViewKey" |+ "/api/av/sortAttributeViewViewKey" |+ "/api/bazaar/batchUpdatePackage" |+ "/api/bazaar/getBazaarIcon" |+ "/api/bazaar/getBazaarPackage" |+ "/api/bazaar/getBazaarPackageREADME" |+ "/api/bazaar/getBazaarPackageRating" |+ "/api/bazaar/getBazaarPackageRatings" |+ "/api/bazaar/getBazaarPackageUserRatings" |+ "/api/bazaar/getBazaarPlugin" |+ "/api/bazaar/getBazaarTemplate" |+ "/api/bazaar/getBazaarTheme" |+ "/api/bazaar/getBazaarWidget" |+ "/api/bazaar/getInstalledIcon" |+ "/api/bazaar/getInstalledPackageSize" |+ "/api/bazaar/getInstalledPlugin" |+ "/api/bazaar/getInstalledTemplate" |+ "/api/bazaar/getInstalledTheme" |+ "/api/bazaar/getInstalledWidget" |+ "/api/bazaar/getUpdatedPackage" |+ "/api/bazaar/installBazaarIcon" |+ "/api/bazaar/installBazaarPlugin" |+ "/api/bazaar/installBazaarTemplate" |+ "/api/bazaar/installBazaarTheme" |+ "/api/bazaar/installBazaarWidget" |+ "/api/bazaar/installLocalBazaarPackage" |+ "/api/bazaar/setBazaarPackageRating" |+ "/api/bazaar/uninstallBazaarIcon" |+ "/api/bazaar/uninstallBazaarPlugin" |+ "/api/bazaar/uninstallBazaarTemplate" |+ "/api/bazaar/uninstallBazaarTheme" |+ "/api/bazaar/uninstallBazaarWidget" |+ "/api/bazaar/updateBazaarPackage" |+ "/api/block/appendBlock" |+ "/api/block/appendDailyNoteBlock" |+ "/api/block/appendHeadingChildren" |+ "/api/block/batchAppendBlock" |+ "/api/block/batchInsertBlock" |+ "/api/block/batchPrependBlock" |+ "/api/block/batchUpdateBlock" |+ "/api/block/batchUpdateTaskListItemMarker" |+ "/api/block/checkBlockExist" |+ "/api/block/checkBlockFold" |+ "/api/block/checkBlockRef" |+ "/api/block/checkBlocksExist" |+ "/api/block/deleteBlock" |+ "/api/block/foldBlock" |+ "/api/block/getBlockBreadcrumb" |+ "/api/block/getBlockBreadcrumbChildren" |+ "/api/block/getBlockDOM" |+ "/api/block/getBlockDOMWithEmbed" |+ "/api/block/getBlockDOMs" |+ "/api/block/getBlockDOMsWithEmbed" |+ "/api/block/getBlockDefIDsByRefText" |+ "/api/block/getBlockIndex" |+ "/api/block/getBlockKramdown" |+ "/api/block/getBlockKramdowns" |+ "/api/block/getBlockRelevantIDs" |+ "/api/block/getBlockSiblingID" |+ "/api/block/getBlockTreeInfos" |+ "/api/block/getBlocksIndexes" |+ "/api/block/getBlocksWordCount" |+ "/api/block/getChildBlocks" |+ "/api/block/getContentWordCount" |+ "/api/block/getDOMText" |+ "/api/block/getDocBlocksOrders" |+ "/api/block/getDocHeadingLevelTransaction" |+ "/api/block/getDocInfo" |+ "/api/block/getDocsInfo" |+ "/api/block/getHeadingChildrenDOM" |+ "/api/block/getHeadingChildrenIDs" |+ "/api/block/getHeadingDeleteTransaction" |+ "/api/block/getHeadingFoldTransaction" |+ "/api/block/getHeadingInsertTransaction" |+ "/api/block/getHeadingLevelTransaction" |+ "/api/block/getOrderedListContinueStart" |+ "/api/block/getRecentUpdatedBlocks" |+ "/api/block/getRefIDs" |+ "/api/block/getRefIDsByFileAnnotationID" |+ "/api/block/getRefText" |+ "/api/block/getTailChildBlocks" |+ "/api/block/getTreeStat" |+ "/api/block/getUnfoldedParentID" |+ "/api/block/insertBlock" |+ "/api/block/moveBlock" |+ "/api/block/moveOutlineHeading" |+ "/api/block/prependBlock" |+ "/api/block/prependDailyNoteBlock" |+ "/api/block/setBlockReminder" |+ "/api/block/swapBlockRef" |+ "/api/block/transferBlockRef" |+ "/api/block/unfoldBlock" |+ "/api/block/updateBlock" |+ "/api/block/updateTaskListItemMarker" |+ "/api/bookmark/getBookmark" |+ "/api/bookmark/removeBookmark" |+ "/api/bookmark/renameBookmark" |+ "/api/broadcast/getChannelInfo" |+ "/api/broadcast/getChannels" |+ "/api/broadcast/postMessage" |+ "/api/broadcast/publish" |+ "/api/clipboard/cleanupRichText" |+ "/api/clipboard/prepareRichText" |+ "/api/clipboard/readFilePaths" |+ "/api/clipboard/writeFilePath" |+ "/api/cloud/getCloudSpace" |+ "/api/cloud/setCloudReminder" |+ "/api/convert/pandoc" |+ "/api/export/copyExportFile" |+ "/api/export/export2Liandi" |+ "/api/export/exportAsFile" |+ "/api/export/exportAsciiDoc" |+ "/api/export/exportAttributeView" |+ "/api/export/exportBrowserHTML" |+ "/api/export/exportCodeBlock" |+ "/api/export/exportData" |+ "/api/export/exportDataInFolder" |+ "/api/export/exportDocx" |+ "/api/export/exportEPUB" |+ "/api/export/exportHTML" |+ "/api/export/exportMd" |+ "/api/export/exportMdContent" |+ "/api/export/exportMdHTML" |+ "/api/export/exportMds" |+ "/api/export/exportMediaWiki" |+ "/api/export/exportNotebookMd" |+ "/api/export/exportNotebookSY" |+ "/api/export/exportNotebooksMd" |+ "/api/export/exportNotebooksSY" |+ "/api/export/exportODT" |+ "/api/export/exportOPML" |+ "/api/export/exportOrgMode" |+ "/api/export/exportPreviewHTML" |+ "/api/export/exportRTF" |+ "/api/export/exportReStructuredText" |+ "/api/export/exportResources" |+ "/api/export/exportSY" |+ "/api/export/exportSYs" |+ "/api/export/exportTempContent" |+ "/api/export/exportTextile" |+ "/api/export/preview" |+ "/api/export/processPDF" |+ "/api/extension/copy" |+ "/api/file/copyFile" |+ "/api/file/getFile" |+ "/api/file/getUniqueFilename" |+ "/api/file/globalCopyFiles" |+ "/api/file/putFile" |+ "/api/file/readDir" |+ "/api/file/removeFile" |+ "/api/file/renameFile" |+ "/api/file/workspaceCopyFiles" |+ "/api/filetree/authFilePublishAccess" |+ "/api/filetree/changeSort" |+ "/api/filetree/createDailyNote" |+ "/api/filetree/createDoc" |+ "/api/filetree/createDocWithMd" |+ "/api/filetree/doc2Heading" |+ "/api/filetree/duplicateDoc" |+ "/api/filetree/getDoc" |+ "/api/filetree/getDocCreateSavePath" |+ "/api/filetree/getFullHPathByID" |+ "/api/filetree/getHPathByID" |+ "/api/filetree/getHPathByPath" |+ "/api/filetree/getHPathsByPaths" |+ "/api/filetree/getIDsByHPath" |+ "/api/filetree/getPathByID" |+ "/api/filetree/getPublishAccess" |+ "/api/filetree/getRefCreateSavePath" |+ "/api/filetree/getShorthandSavePath" |+ "/api/filetree/heading2Doc" |+ "/api/filetree/li2Doc" |+ "/api/filetree/listDocTree" |+ "/api/filetree/listDocsByPath" |+ "/api/filetree/moveDocs" |+ "/api/filetree/moveDocsByID" |+ "/api/filetree/moveLocalShorthands" |+ "/api/filetree/removeDoc" |+ "/api/filetree/removeDocByID" |+ "/api/filetree/removeDocs" |+ "/api/filetree/removeIndexes" |+ "/api/filetree/renameDoc" |+ "/api/filetree/renameDocByID" |+ "/api/filetree/reorderDocs" |+ "/api/filetree/searchDocs" |+ "/api/filetree/setDocSortMode" |+ "/api/filetree/setPublishAccess" |+ "/api/filetree/setSort" |+ "/api/filetree/upsertIndexes" |+ "/api/format/autoSpace" |+ "/api/format/netAssets2LocalAssets" |+ "/api/format/netImg2LocalAssets" |+ "/api/graph/getGraph" |+ "/api/graph/getLocalGraph" |+ "/api/graph/resetGraph" |+ "/api/graph/resetLocalGraph" |+ "/api/graph/setGraphConf" |+ "/api/history/clearWorkspaceHistory" |+ "/api/history/createAssetHistory" |+ "/api/history/createDocHistory" |+ "/api/history/diffDocVersions" |+ "/api/history/getDocHistoryContent" |+ "/api/history/getHistoryItems" |+ "/api/history/getNotebookHistory" |+ "/api/history/reindexHistory" |+ "/api/history/rollbackAssetsHistory" |+ "/api/history/rollbackAttributeViewHistory" |+ "/api/history/rollbackDocHistory" |+ "/api/history/rollbackNotebookHistory" |+ "/api/import/cancelImportSY" |+ "/api/import/cancelObsidianVaultTask" |+ "/api/import/continueImportSY" |+ "/api/import/getObsidianVaultTask" |+ "/api/import/importData" |+ "/api/import/importSY" |+ "/api/import/importSYAuto" |+ "/api/import/importSYNotebook" |+ "/api/import/importStdMd" |+ "/api/import/importZipMd" |+ "/api/import/startObsidianVaultAnalysis" |+ "/api/import/startObsidianVaultImport" |+ "/api/inbox/getShorthand" |+ "/api/inbox/getShorthands" |+ "/api/inbox/removeShorthands" |+ "/api/lute/copyStdMarkdown" |+ "/api/lute/html2BlockDOM" |+ "/api/lute/md2html" |+ "/api/lute/spinBlockDOM" |+ "/api/lute/wpsPresentation2BlockDOM" |+ "/api/network/echo" |+ "/api/network/echo/*path" |+ "/api/network/forwardProxy" |+ "/api/network/proxy" |+ "/api/notebook/changeMasterPassword" |+ "/api/notebook/changeSortNotebook" |+ "/api/notebook/closeNotebook" |+ "/api/notebook/createEncryptedNotebook" |+ "/api/notebook/createNotebook" |+ "/api/notebook/disableEncryptedNotebooks" |+ "/api/notebook/enableEncryptedNotebooks" |+ "/api/notebook/exportNotebookCryptoBackup" |+ "/api/notebook/getEncryptedNotebookStatus" |+ "/api/notebook/getNotebookConf" |+ "/api/notebook/getNotebookInfo" |+ "/api/notebook/importNotebookCryptoBackup" |+ "/api/notebook/lockNotebook" |+ "/api/notebook/openNotebook" |+ "/api/notebook/removeNotebook" |+ "/api/notebook/renameNotebook" |+ "/api/notebook/reorder" |+ "/api/notebook/setNotebookConf" |+ "/api/notebook/setNotebookCryptoAutoLock" |+ "/api/notebook/setNotebookIcon" |+ "/api/notebook/touchEncryptedNotebooks" |+ "/api/notebook/unlockAndOpenNotebook" |+ "/api/notebook/unlockNotebook" |+ "/api/notification/pushErrMsg" |+ "/api/notification/pushMsg" |+ "/api/outline/getDocHeadingNumbers" |+ "/api/outline/getDocOutline" |+ "/api/petal/loadPetals" |+ "/api/petal/setPetalEnabled" |+ "/api/petal/setPetalPublishEnabled" |+ "/api/plugin/getLoadedPlugin" |+ "/api/plugin/listLoadedPlugins" |+ "/api/plugin/rpc" |+ "/api/plugin/rpc/:name" |+ "/api/query/sql" |+ "/api/ref/getBacklink2" |+ "/api/ref/getBacklinkDoc" |+ "/api/ref/getBackmentionDoc" |+ "/api/ref/refreshBacklink" |+ "/api/repo/checkoutRepo" |+ "/api/repo/createSnapshot" |+ "/api/repo/diffRepoSnapshots" |+ "/api/repo/downloadCloudSnapshot" |+ "/api/repo/exportRepoFile" |+ "/api/repo/getCloudRepoSnapshots" |+ "/api/repo/getCloudRepoTagSnapshots" |+ "/api/repo/getRepoDocHistory" |+ "/api/repo/getRepoFile" |+ "/api/repo/getRepoSnapshots" |+ "/api/repo/getRepoTagSnapshots" |+ "/api/repo/importRepoKey" |+ "/api/repo/initRepoKey" |+ "/api/repo/initRepoKeyFromPassphrase" |+ "/api/repo/openRepoSnapshotFile" |+ "/api/repo/purgeCloudRepo" |+ "/api/repo/purgeRepo" |+ "/api/repo/removeCloudRepoTagSnapshot" |+ "/api/repo/removeRepoTagSnapshot" |+ "/api/repo/resetRepo" |+ "/api/repo/rollbackRepoSnapshotFile" |+ "/api/repo/searchRepoFile" |+ "/api/repo/setRepoIndexRetentionDays" |+ "/api/repo/setRetentionIndexesDaily" |+ "/api/repo/tagSnapshot" |+ "/api/repo/uploadCloudSnapshot" |+ "/api/riff/addRiffCards" |+ "/api/riff/batchSetRiffCardsDueTime" |+ "/api/riff/createRiffDeck" |+ "/api/riff/getNotebookRiffCards" |+ "/api/riff/getNotebookRiffDueCards" |+ "/api/riff/getRiffCards" |+ "/api/riff/getRiffCardsByBlockIDs" |+ "/api/riff/getRiffDecks" |+ "/api/riff/getRiffDueCards" |+ "/api/riff/getTreeRiffCards" |+ "/api/riff/getTreeRiffDueCards" |+ "/api/riff/removeRiffCards" |+ "/api/riff/removeRiffDeck" |+ "/api/riff/renameRiffDeck" |+ "/api/riff/resetRiffCards" |+ "/api/riff/reviewRiffCard" |+ "/api/riff/skipReviewRiffCard" |+ "/api/search/findReplace" |+ "/api/search/fullTextSearchAssetContent" |+ "/api/search/fullTextSearchBlock" |+ "/api/search/getAssetContent" |+ "/api/search/getAssetContentByPath" |+ "/api/search/getEmbedBlock" |+ "/api/search/listInvalidBlockRefs" |+ "/api/search/removeTemplate" |+ "/api/search/searchAsset" |+ "/api/search/searchEmbedBlock" |+ "/api/search/searchRefBlock" |+ "/api/search/searchTemplate" |+ "/api/search/searchWidget" |+ "/api/search/semanticSearchBlock" |+ "/api/search/updateEmbedBlock" |+ "/api/setting/addVirtualBlockRefExclude" |+ "/api/setting/addVirtualBlockRefInclude" |+ "/api/setting/getBootAppearances" |+ "/api/setting/getCloudUser" |+ "/api/setting/getPandocBin" |+ "/api/setting/getPublish" |+ "/api/setting/login2faCloudUser" |+ "/api/setting/logoutCloudUser" |+ "/api/setting/refreshVirtualBlockRef" |+ "/api/setting/setAI" |+ "/api/setting/setAppearance" |+ "/api/setting/setBazaar" |+ "/api/setting/setBazaarPetalDisabled" |+ "/api/setting/setBootAppearance" |+ "/api/setting/setEditor" |+ "/api/setting/setEditorReadOnly" |+ "/api/setting/setEmoji" |+ "/api/setting/setEntryVisibility" |+ "/api/setting/setExport" |+ "/api/setting/setFiletree" |+ "/api/setting/setFlashcard" |+ "/api/setting/setIcon" |+ "/api/setting/setKeymap" |+ "/api/setting/setPublish" |+ "/api/setting/setSearch" |+ "/api/setting/setSecrets" |+ "/api/setting/setSnippet" |+ "/api/setting/setTheme" |+ "/api/setting/setVariables" |+ "/api/snippet/getSnippet" |+ "/api/snippet/removeSnippet" |+ "/api/snippet/setSnippet" |+ "/api/sqlite/flushTransaction" |+ "/api/storage/batchUpdateRecentDocCloseTime" |+ "/api/storage/getCriteria" |+ "/api/storage/getInlineStyles" |+ "/api/storage/getLocalStorage" |+ "/api/storage/getLocalStorageVal" |+ "/api/storage/getLocalStorageVals" |+ "/api/storage/getOutlineStorage" |+ "/api/storage/getRecentDocs" |+ "/api/storage/getViewState" |+ "/api/storage/patchViewState" |+ "/api/storage/removeCriterion" |+ "/api/storage/removeLocalStorageVal" |+ "/api/storage/removeLocalStorageVals" |+ "/api/storage/removeOutlineStorage" |+ "/api/storage/removeViewState" |+ "/api/storage/setCriterion" |+ "/api/storage/setInlineStyles" |+ "/api/storage/setLocalStorage" |+ "/api/storage/setLocalStorageVal" |+ "/api/storage/setLocalStorageVals" |+ "/api/storage/setOutlineStorage" |+ "/api/storage/setWorkspaceAVPalette" |+ "/api/storage/updateRecentDocCloseTime" |+ "/api/storage/updateRecentDocOpenTime" |+ "/api/storage/updateRecentDocViewTime" |+ "/api/sync/createCloudSyncDir" |+ "/api/sync/exportSyncProviderS3" |+ "/api/sync/exportSyncProviderWebDAV" |+ "/api/sync/getBootSync" |+ "/api/sync/getSyncInfo" |+ "/api/sync/getSyncLANStatus" |+ "/api/sync/importSyncProviderS3" |+ "/api/sync/importSyncProviderWebDAV" |+ "/api/sync/listCloudSyncDir" |+ "/api/sync/performBootSync" |+ "/api/sync/performSync" |+ "/api/sync/removeCloudSyncDir" |+ "/api/sync/setCloudSyncDir" |+ "/api/sync/setSyncAssetDownloadMode" |+ "/api/sync/setSyncEnable" |+ "/api/sync/setSyncGenerateConflictDoc" |+ "/api/sync/setSyncInterval" |+ "/api/sync/setSyncLAN" |+ "/api/sync/setSyncMode" |+ "/api/sync/setSyncPerception" |+ "/api/sync/setSyncProvider" |+ "/api/sync/setSyncProviderLocal" |+ "/api/sync/setSyncProviderS3" |+ "/api/sync/setSyncProviderWebDAV" |+ "/api/system/addCustomEmoji" |+ "/api/system/addMicrosoftDefenderExclusion" |+ "/api/system/bootProgress" |+ "/api/system/checkUpdate" |+ "/api/system/checkWorkspaceDir" |+ "/api/system/clearTempFiles" |+ "/api/system/createWorkspaceDir" |+ "/api/system/currentTime" |+ "/api/system/dismissOnboarding" |+ "/api/system/ensureOnboarding" |+ "/api/system/exit" |+ "/api/system/exportConf" |+ "/api/system/exportLog" |+ "/api/system/exportTLSCABundle" |+ "/api/system/exportTLSCACert" |+ "/api/system/getChangelog" |+ "/api/system/getConf" |+ "/api/system/getCustomFonts" |+ "/api/system/getEmojiConf" |+ "/api/system/getMobileWorkspaces" |+ "/api/system/getNetwork" |+ "/api/system/getSysFonts" |+ "/api/system/getWorkspaceInfo" |+ "/api/system/getWorkspaces" |+ "/api/system/ignoreAddMicrosoftDefenderExclusion" |+ "/api/system/importConf" |+ "/api/system/importCustomFont" |+ "/api/system/importTLSCABundle" |+ "/api/system/loginAuth" |+ "/api/system/logoutAuth" |+ "/api/system/oidc/mobileCallback" |+ "/api/system/oidc/poll" |+ "/api/system/oidc/start" |+ "/api/system/oidc/validate" |+ "/api/system/oidc/validateActivate" |+ "/api/system/oidc/validateCancel" |+ "/api/system/oidc/validatePoll" |+ "/api/system/rebuildDataIndex" |+ "/api/system/reloadUI" |+ "/api/system/removeCustomFont" |+ "/api/system/removeWorkspaceDir" |+ "/api/system/removeWorkspaceDirPhysically" |+ "/api/system/setAPIToken" |+ "/api/system/setAccessAuthCode" |+ "/api/system/setAppearanceMode" |+ "/api/system/setAutoLaunch" |+ "/api/system/setDownloadInstallPkg" |+ "/api/system/setFollowSystemLockScreen" |+ "/api/system/setNetworkProxy" |+ "/api/system/setNetworkServe" |+ "/api/system/setNetworkServeTLS" |+ "/api/system/setOIDC" |+ "/api/system/setUILayout" |+ "/api/system/setUpdateChannel" |+ "/api/system/setWorkspaceDir" |+ "/api/system/uiproc" |+ "/api/system/vacuumDataIndex" |+ "/api/tag/getTag" |+ "/api/tag/removeTag" |+ "/api/tag/renameTag" |+ "/api/template/docSaveAsTemplate" |+ "/api/template/getDocSaveAsTemplateInfo" |+ "/api/template/manage" |+ "/api/template/render" |+ "/api/template/renderSprig" |+ "/api/transactions" |+ "/api/transactions/clearHistory" |+ "/api/transactions/redo" |+ "/api/transactions/undo" |+ "/api/transactions/undoState" |+ "/api/ui/reloadAttributeView" |+ "/api/ui/reloadFiletree" |+ "/api/ui/reloadIcon" |+ "/api/ui/reloadProtyle" |+ "/api/ui/reloadTag" |+ "/api/ui/reloadTheme" |+ "/api/ui/reloadUI" |+ "/plugin/private/:name/*path";++export interface APIPOSTRoutes {+ "/api/attr/getBlockAttrs": {+ request: BlockIDRequestInput;+ response: { "code": 0; "data": Record<string, string>; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/attr/setBlockAttrs": {+ request: SetBlockAttrsRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/block/getBlockInfo": {+ request: BlockInfoRequestInput;+ response: { "code": 0; "data": BlockInfoData; "msg": string; } | { "code": -1 | 3; "data": { "closeTimeout": number; } | null | string; "msg": string; };+ body: "json";+ };+ "/api/history/searchHistory": {+ request: SearchHistoryRequestInput;+ response: { "code": 0; "data": SearchHistoryData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/notebook/lsNotebooks": {+ request: ListNotebooksRequestInput;+ response: { "code": 0; "data": ListNotebooksData | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "legacyOptional";+ };+ "/api/search/searchTag": {+ request: SearchTagRequestInput;+ response: { "code": 0; "data": SearchTagData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/system/version": {+ request: EmptyRequestInput;+ response: { "code": 0; "data": string; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "none";+ };+}++// 传输层合成的错误独立于业务错误;普通回调只接收消息处理后保留的非负错误码。+export interface APITransportError {+ code: -401 | -403 | -404;+ msg: string;+ data: null;+}++export interface APIFetchFailure {+ code: number;+ msg: string;+ data: null;+}++export interface APILegacyResponse {+ code: number;+ msg: string;+ data?: any;+ cmd?: string;+ callback?: string;+ sid?: string;+ context?: any;+}++type APIContract = {request: unknown; response: unknown; body: string};+type APIRequestArgs<C extends APIContract> = C["body"] extends "json"+ ? [data: C["request"]]+ : [data?: C["request"] | null];+type NonNegative<C extends number> = C extends C ? `${C}` extends `-${string}` ? never : C : never;+export type APICallbackResponse<R> = R extends {code: infer C extends number}+ ? NonNegative<C> extends never ? never : R & {code: NonNegative<C>}+ : never;++type APIPostTail<C extends APIContract> = [+ cb?: (response: APICallbackResponse<C["response"]>) => void,+ headers?: Record<string, string>,+ failCallback?: (response: APIFetchFailure) => void,+ signal?: AbortSignal,+ timeout?: number+];+type LegacyPostArgs<Legacy> = [+ data?: any,+ cb?: (response: Legacy) => void,+ headers?: Record<string, string>,+ failCallback?: (response: Legacy) => void,+ signal?: AbortSignal,+ timeout?: number+];+type APISyncTail = [headers?: Record<string, string>, process?: boolean, signal?: AbortSignal];++// 路径只从首参推导,已知路径不能因请求参数不匹配而选择宽松重载。+export type FetchPost<Legacy = APILegacyResponse> = <Path extends string>(+ url: Path,+ ...args: Path extends keyof APIPOSTRoutes+ ? [...APIRequestArgs<APIPOSTRoutes[Path]>, ...APIPostTail<APIPOSTRoutes[Path]>]+ : Path extends APILegacyPOSTPath ? LegacyPostArgs<Legacy>+ : string extends Path ? LegacyPostArgs<Legacy> : never+) => Promise<void>;++export type FetchSyncPost<Legacy = APILegacyResponse> = <Path extends string>(+ url: Path,+ ...args: Path extends keyof APIPOSTRoutes+ ? [...APIRequestArgs<APIPOSTRoutes[Path]>, ...APISyncTail]+ : Path extends APILegacyPOSTPath ? [data?: any, ...tail: APISyncTail]+ : string extends Path ? [data?: any, ...tail: APISyncTail] : never+) => Promise<Path extends keyof APIPOSTRoutes ? APIPOSTRoutes[Path]["response"] | APITransportError : Legacy>;++export type FetchGet<Legacy = APILegacyResponse | string> = <Path extends string>(+ url: Path,+ ...args: Path extends keyof APIGETRoutes+ ? [cb: (response: APIGETRoutes[Path]["response"]) => void]+ : Path extends keyof APIPOSTRoutes ? never+ : [cb: (response: Legacy) => void]+) => void;diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex 86ac2cb129..f21186cd10 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -656,9 +656,9 @@ interface INotebook {icon: string;sort: number;subFileCount: number;- dueFlashcardCount?: string;- newFlashcardCount?: string;- flashcardCount?: string;+ dueFlashcardCount?: number;+ newFlashcardCount?: number;+ flashcardCount?: number;sortMode: number;encrypted?: boolean;unlocked?: boolean;diff --git a/app/src/util/backForward.ts b/app/src/util/backForward.tsindex 87719aa7d7..ddfae9074b 100644--- a/app/src/util/backForward.ts+++ b/app/src/util/backForward.ts@@ -40,7 +40,7 @@ const focusStack = async (app: App, stack: IBackStack) => {wnd = getWndByLayout(window.siyuan.layout.centerLayout);}if (wnd) {- const blockInfoParam: IObject = {id: stack.id};+ const blockInfoParam: {id: string; notebook?: string} = {id: stack.id};if (isEncryptedBox(stack.protyle.notebookId)) {blockInfoParam.notebook = stack.protyle.notebookId;}@@ -49,6 +49,9 @@ const focusStack = async (app: App, stack: IBackStack) => {showMessage(info.msg);return;}+ if (info.code !== 0) {+ return;+ }const tab = new Tab({title: info.data.rootTitle,docIcon: info.data.rootIcon,diff --git a/app/src/util/fetch.test.ts b/app/src/util/fetch.test.tsindex abe27290b6..0efa4acd47 100644--- a/app/src/util/fetch.test.ts+++ b/app/src/util/fetch.test.ts@@ -6,10 +6,14 @@ import {runInNewContext} from "node:vm";import * as ts from "typescript";import {withFetchTimeout} from "./fetchTimeout";-const loadFetchPost = () => {+const loadFetchPost = (fetchImplementation: typeof fetch = () => new Promise(() => {}),+ processResponse: (response: IWebSocketData) => boolean = () => true) => {const sends: unknown[][] = [];const timeouts: number[] = [];- const exports: {fetchPost?: (...args: any[]) => Promise<void>} = {};+ const exports: {+ fetchPost?: (...args: any[]) => Promise<void>;+ fetchSyncPost?: (...args: any[]) => Promise<IWebSocketData>;+ } = {};const source = ts.transpileModule(readFileSync(join(__dirname, "fetch.ts"), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},}).outputText;@@ -19,7 +23,7 @@ const loadFetchPost = () => {switch (name) {case "../constants": return {Constants: {SIYUAN_QUIT: "quit"}};case "electron": return {ipcRenderer: {send: (...args: unknown[]) => sends.push(args)}};- case "./processMessage": return {processMessage: () => true};+ case "./processMessage": return {processMessage: processResponse};case "./kernelFault": return {kernelError: () => assert.fail("unexpected kernel error")};case "./fetchTimeout": return {withFetchTimeout: (request: (signal?: AbortSignal) => Promise<unknown>, signal: AbortSignal, timeout: number) => {@@ -30,12 +34,12 @@ const loadFetchPost = () => {default: throw new Error(name);}},- fetch: () => new Promise(() => {}),+ fetch: fetchImplementation,FormData,location: {port: "6806"},console: {warn: () => {}},});- return {fetchPost: exports.fetchPost, sends, timeouts};+ return {fetchPost: exports.fetchPost, fetchSyncPost: exports.fetchSyncPost, sends, timeouts};};it("invokes the failure callback once when a request stalls", async () => {@@ -50,6 +54,58 @@ it("invokes the failure callback once when a request stalls", async () => {assert.equal(sends.length, 0);});+it("keeps positive business errors in the callback and filters negative errors", async () => {+ for (const code of [-1, 0, 3]) {+ const payload = {code, msg: "message", data: code === 0 ? {rootID: "id"} : "indexing"};+ const {fetchPost} = loadFetchPost(async () => new Response(JSON.stringify(payload), {+ headers: {"Content-Type": "application/json"},+ }), response => response.code >= 0);+ const received: IWebSocketData[] = [];+ await fetchPost("/api/block/getBlockInfo", {id: "id"}, (response: IWebSocketData) => received.push(response));+ assert.deepEqual(received, code < 0 ? [] : [payload]);+ }+});++it("keeps asynchronous error responses and the process option", async () => {+ const payload = {code: -1, msg: "readonly", data: {closeTimeout: 5000}};+ let processed = 0;+ const {fetchSyncPost} = loadFetchPost(async () => new Response(JSON.stringify(payload)), () => {+ processed++;+ return false;+ });+ assert.deepEqual(await fetchSyncPost("/api/attr/setBlockAttrs", {id: "id", attrs: {}}), payload);+ assert.equal(processed, 1);+ assert.deepEqual(await fetchSyncPost("/api/attr/setBlockAttrs", {id: "id", attrs: {}}, undefined, false), payload);+ assert.equal(processed, 1);+});++it("preserves raw file text and routes HTTP 202 file errors to the failure callback", async () => {+ const text = "file content";+ const raw = loadFetchPost(async () => new Response(text, {headers: {"Content-Type": "text/plain"}}));+ let received: unknown;+ await raw.fetchPost("/api/file/getFile", {path: "file.txt"}, (response: unknown) => received = response);+ assert.equal(received, text);++ const failure: IWebSocketData = {code: -1, msg: "missing file", data: null};+ const missing = loadFetchPost(async () => new Response(JSON.stringify(failure), {+ status: 202,+ headers: {"Content-Type": "application/json"},+ }));+ await missing.fetchPost("/api/file/getFile", {path: "missing"}, () => assert.fail("unexpected success"), undefined,+ (response: unknown) => received = response);+ assert.deepEqual(received, failure);+});++it("preserves FormData request bodies for unmigrated upload endpoints", async () => {+ const body = new FormData();+ body.append("path", "file.txt");+ const {fetchPost} = loadFetchPost(async (_url, options) => {+ assert.equal(options.body, body);+ return new Response(JSON.stringify({code: 0, msg: "", data: null}), {headers: {"Content-Type": "application/json"}});+ });+ await fetchPost("/api/file/putFile", body);+});+it("falls back to desktop quit when exit or closing layout requests stall", async () => {for (const url of ["/api/system/exit", "/api/system/setUILayout", "/api/system/setWorkspaceDir"]) {const {fetchPost, sends, timeouts} = loadFetchPost();diff --git a/app/src/util/fetch.ts b/app/src/util/fetch.tsindex 66635dfeae..fecdf92267 100644--- a/app/src/util/fetch.ts+++ b/app/src/util/fetch.ts@@ -5,8 +5,9 @@ import {ipcRenderer} from "electron";import {processMessage} from "./processMessage";import {kernelError} from "./kernelFault";import {withFetchTimeout} from "./fetchTimeout";+import type {FetchGet, FetchPost, FetchSyncPost} from "../types/api";-export const fetchPost = (+export const fetchPost = ((url: string,data?: any,cb?: (response: IWebSocketData) => void,@@ -122,9 +123,9 @@ export const fetchPost = (}/// #endif});-};+}) as FetchPost<IWebSocketData>;-export const fetchSyncPost = async (url: string, data?: any, headers?: Record<string, string>, process = true,+export const fetchSyncPost = (async (url: string, data?: any, headers?: Record<string, string>, process = true,signal?: AbortSignal) => {const init: RequestInit = {method: "POST",@@ -146,9 +147,9 @@ export const fetchSyncPost = async (url: string, data?: any, headers?: Record<stprocessMessage(res2);}return res2;-};+}) as FetchSyncPost<IWebSocketData>;-export const fetchGet = (url: string, cb: (response: IWebSocketData | IObject | string) => void) => {+export const fetchGet = ((url: string, cb: (response: IWebSocketData | IObject | string) => void) => {fetch(url, {cache: "no-store"}).then((response) => {if (response.headers.get("content-type")?.indexOf("application/json") > -1) {return response.json();@@ -158,4 +159,4 @@ export const fetchGet = (url: string, cb: (response: IWebSocketData | IObject |}).then((response) => {cb(response);});-};+}) as FetchGet<IWebSocketData | IObject | string>;diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.tsindex 7169ad2416..8d401af8f8 100644--- a/app/src/util/pathName.ts+++ b/app/src/util/pathName.ts@@ -816,6 +816,9 @@ export const setNoteBook = (cb?: (notebook: INotebook[]) => void, flashcard = fareturn fetchPost("/api/notebook/lsNotebooks", {flashcard}, (response) => {+ if (!response.data?.notebooks) {+ return;+ }if (!flashcard) {window.siyuan.notebooks = response.data.notebooks;if (window.siyuan.config?.fileTree) {diff --git a/app/src/window/openNewWindow.ts b/app/src/window/openNewWindow.tsindex 38e0b544e5..2b00b2a78b 100644--- a/app/src/window/openNewWindow.ts+++ b/app/src/window/openNewWindow.ts@@ -55,6 +55,9 @@ export const openNewWindowById = async (id: string | string[], options: windowOpshowMessage(response.msg);return;}+ if (response.code !== 0) {+ return;+ }json.push({title: response.data.rootTitle,docIcon: response.data.rootIcon,diff --git a/app/tests/api-contract.types.ts b/app/tests/api-contract.types.tsnew file mode 100644index 0000000000..a571b8921d--- /dev/null+++ b/app/tests/api-contract.types.ts@@ -0,0 +1,90 @@+import type {APIPOSTRoutes, FetchGet, FetchPost, FetchSyncPost} from "../src/types/api";++declare const fetchPost: FetchPost;+declare const fetchGet: FetchGet;+declare const fetchSyncPost: FetchSyncPost;+declare const dynamicURL: string;++fetchPost("/api/system/version");+fetchPost("/api/notebook/lsNotebooks");+fetchPost("/api/notebook/lsNotebooks", {flashcard: null});+fetchPost("/api/attr/setBlockAttrs", {id: "id", attrs: {"custom-value": null}});+fetchPost("/api/history/searchHistory", {page: 1.5, type: null});+fetchPost(dynamicURL, {legacy: true});+fetchPost("/api/system/currentTime", {});++// @ts-expect-error 路径拼写错误不能被误认为存量接口。+fetchPost("/api/attr/getBlockAtrrs", {id: "id"});+// @ts-expect-error 已迁移的 POST 接口不能通过 GET 调用。+fetchGet("/api/attr/getBlockAttrs", () => {});++// @ts-expect-error 已知接口不能省略必填请求体。+fetchPost("/api/attr/getBlockAttrs");+// @ts-expect-error 缺少必填字段时不能回退到存量签名。+fetchPost("/api/attr/getBlockAttrs", {});+// @ts-expect-error 请求字段类型错误时不能回退到存量签名。+fetchPost("/api/attr/getBlockAttrs", {id: 123});+// @ts-expect-error 显式声明的错误回调类型也不能触发宽松重载。+fetchPost("/api/search/searchTag", {k: ""}, (response: {data: number}) => response.data);+// @ts-expect-error 属性值支持字符串和 null,不支持数字。+fetchPost("/api/attr/setBlockAttrs", {id: "id", attrs: {key: 1}});+// @ts-expect-error 异步接口同样要求请求体。+fetchSyncPost("/api/attr/getBlockAttrs");+// @ts-expect-error 数字字符串不属于历史分页请求的数字类型。+fetchSyncPost("/api/history/searchHistory", {page: "2"});++fetchPost("/api/search/searchTag", {k: ""}, response => {+ const code: 0 = response.code;+ const tags: string[] = response.data.tags;+ // @ts-expect-error 拼错响应字段会报错。+ void response.data.tagz;+ // @ts-expect-error 回调数据不能退化为 any。+ const incorrect: number = response.data.k;+ void [code, tags, incorrect];+});++fetchPost("/api/block/getBlockInfo", {id: "id"}, response => {+ // @ts-expect-error 普通回调也可能收到正数错误码,不能假设必定成功。+ void response.data.rootID;+ if (response.code === 0) {+ const title: string = response.data.rootTitle;+ if (response.data.publishAccessRequired) {+ // @ts-expect-error 发布密码提示响应没有笔记本 ID。+ const box: string = response.data.box;+ void box;+ } else {+ const box: string = response.data.box;+ void box;+ }+ void title;+ }+});++fetchGet("/api/system/version", response => {+ if (response.code === 0) {+ const version: string = response.data;+ // @ts-expect-error 版本接口返回字符串。+ void response.data.version;+ void version;+ }+});++async function checkAsyncResult() {+ const response = await fetchSyncPost("/api/notebook/lsNotebooks", {});+ // @ts-expect-error 异步返回值包含失败响应,不能直接访问成功字段。+ void response.data.notebooks;+ if (response.code === 0 && response.data?.notebooks) {+ const notebook = response.data.notebooks[0];+ if (notebook) {+ const count: number = notebook.flashcardCount;+ void count;+ }+ }+}+void checkAsyncResult;++declare const notebooks: APIPOSTRoutes["/api/notebook/lsNotebooks"]["response"];+if (notebooks.code === 0) {+ // @ts-expect-error 成功码下的空数据也必须在严格模式下被检查。+ void notebooks.data.notebooks;+}diff --git a/app/tsconfig.api.json b/app/tsconfig.api.jsonnew file mode 100644index 0000000000..30060ca6ad--- /dev/null+++ b/app/tsconfig.api.json@@ -0,0 +1,13 @@+{+ "compilerOptions": {+ "strict": true,+ "noEmit": true,+ "skipLibCheck": false,+ "target": "ES2021",+ "module": "commonjs",+ "moduleResolution": "node",+ "lib": ["ES2021", "DOM"],+ "types": []+ },+ "files": ["src/types/api/index.d.ts", "tests/api-contract.types.ts"]+}diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.mdnew file mode 100644index 0000000000..287477cc09--- /dev/null+++ b/docs/API-CONTRACTS.md@@ -0,0 +1,62 @@+# 内核接口类型契约++首批覆盖 `/api/system/version`、`/api/attr/getBlockAttrs`、`/api/attr/setBlockAttrs`、`/api/search/searchTag`、`/api/notebook/lsNotebooks`、`/api/history/searchHistory` 和 `/api/block/getBlockInfo`。版本接口同时支持 GET 和 POST,因此共登记 8 个方法与路径组合。++## 契约与实现++`kernel/apicontract/contracts.go` 定义请求、响应和端点。契约包独立于内核启动、数据库和持久化模型,生成器可以单独运行。API 入口通过 `contractHandler` 绑定端点,请求参数和成功返回值受到 Go 泛型签名约束;响应载荷通过构造函数设置,不能直接给通用 `ret.Data` 赋值。业务校验继续使用现有辅助函数,`contractFailure` 保留其错误码、消息和已支持的错误载荷。++生成器从同一组 Go 类型生成 `app/src/types/api/index.d.ts` 和 `kernel/apicontract/schema.json`。后者包含共享的 `$defs` 和每个端点的请求、响应 schema,测试使用同一套 schema 检查实际 HTTP 响应。类型声明不会在运行时验证 JSON,CI 中的处理函数测试负责验证序列化结果。++输入和输出分别处理。`json` tag 控制线协议字段名;请求字段默认必填,`api:"optional"` 表示可缺省,`nullable` 表示接受 `null`,指针保留可空语义。输出字段的 `omitempty` 只控制输出省略,不推导请求必填性。嵌入结构体展平,递归类型通过引用表示;接口联合、常量字段和自定义编解码需要显式建模。未支持的类型、字段冲突和未知 JSON tag 会使生成失败,不会降级为 `any`。++`Notebook` 是接口载荷,业务模型通过显式转换映射到该载荷,回归测试比较完整 JSON,包括各个加密状态。修改契约不会改变 `.sy`、数据库、历史、同步或加密格式。++## 保留的兼容行为++| 接口 | 兼容边界 |+|---|---|+| `version` | 不要求请求体,响应数据是字符串 |+| `getBlockAttrs` | 必须有 ID,成功时始终返回属性字典,没有属性时保持 `{}` |+| `setBlockAttrs` | 属性值为字符串或 `null`;`null` 删除属性,成功时数据为 `null` |+| `searchTag` | 允许空关键词,空结果保持 `[]` |+| `lsNotebooks` | 保留空请求体、`null` 和旧解析失败时的默认分支;合法对象中的错误布尔类型返回错误;保留业务失败时原有的成功码与空数据 |+| `searchHistory` | 数字先按 JSON 浮点值解码,再沿用原有整数转换;缺省或 `null` 保留默认值,数字字符串不作为数字接受 |+| `getBlockInfo` | 保留 ID 去空白、可选笔记本参数和附带 ID 的租约检查;分别声明完整信息、发布密码提示和错误响应 |++`ignoretype` 和 `filterstrings` 仅用于声明过的旧参数兼容行为。生成的请求类型描述规范调用形式;兼容解码可能接受并忽略更宽的旧输入,兼容测试明确覆盖这些例外。不存在全局“绑定失败后回退旧解析”的开关。++只读中间件仍可返回带 `closeTimeout` 的提示对象。`fetchPost` 的普通回调只接收消息处理后保留的非负错误码,块信息接口的 `3` 仍须处理;`fetchSyncPost` 和 `fetchGet` 保留完整响应。动态 URL 保留存量签名;静态 POST 路径必须来自契约或存量路由,错误参数不能通过重载回退。拼接出开放范围的模板 URL 时使用显式 `string` 变量。++## 新增与迁移++1. 在契约包中定义传输类型与端点,并明确请求体、错误码、空值、默认值和历史输入兼容规则+2. 用 `contractHandler` 接入业务入口,保持路由中间件顺序、授权和租约范围+3. 已有接口迁移完成后,从 `legacy_routes.json` 删除对应记录;新接口不能加入该清单+4. 更新实际响应、兼容输入和严格类型测试,运行生成器,再修正编译器指出的调用问题+5. 同步 `petal` 的生成声明和相关公共声明;已公开接口同步更新接口文档++`legacy_routes.json` 记录尚未迁移的路由,包括非 JSON、动态路径和 `ANY` 注册。生成检查读取实际路由与处理函数声明,验证方法、路径、处理函数和契约适配器的对应关系。CI 对照合入前的清单阻止增加存量记录。++## 生成与验证++在 `app/` 下运行:++```text+pnpm run api:generate+pnpm run api:generate --petal ../../petal+pnpm run api:check --petal ../../petal+pnpm run lint+pnpm exec tsx --test src/util/fetch.test.ts src/util/fetchTimeout.test.ts+```++`--petal` 路径相对于生成器的工作目录 `kernel/`,示例对应同级仓库。CI 只检查本仓库产物,本地跨仓库同步须使用该参数核对插件声明。++在 `kernel/` 下运行:++```text+go test ./apicontract/...+go test -tags "fts5 sqlcipher" ./api -run "TestAPIContract|TestBlockAttrsRespectPublishAccess|TestGetBlockInfoRecovery|TestGetBlockInfoPublishAccess|TestListNotebooksSortsBySubDocCount" -count=1+```++`tsconfig.api.json` 单独启用严格检查并检查声明文件,覆盖参数错误、字段拼写、必填请求体、成功与失败分支、可空值和方法不匹配。主应用继续沿用现有配置,因此存量调用的严格空值检查并未全量开启。处理函数测试使用临时工作区和独立测试进程,不启动或重启运行中的内核。diff --git a/docs/API.md b/docs/API.mdindex 91484d136a..69153ba2f5 100644--- a/docs/API.md+++ b/docs/API.md@@ -4,6 +4,7 @@* [Specification](#Specification)* [Parameters and return values](#Parameters-and-return-values)+ * [TypeScript contracts](#TypeScript-contracts)* [Behavior semantics](#Behavior-semantics)* [Authentication](#Authentication)* [Notebooks](#Notebooks)@@ -118,6 +119,21 @@* `msg`: an empty string under normal circumstances, an error text will be returned under abnormal conditions* `data`: may be `{}`, `[]` or `NULL`, depending on the interface+### TypeScript contracts++The plugin `fetchPost`, `fetchSyncPost`, and `fetchGet` declarations infer request and response types for migrated API paths from generated kernel contracts. The initial coverage includes version, block attributes, tag search, notebook listing, history search, and block information. Existing untyped endpoints and dynamic URLs remain supported. Check the response code before reading successful data from asynchronous calls, and handle nullable fields explicitly.++```typescript+import {fetchSyncPost} from "siyuan";++const response = await fetchSyncPost("/api/attr/getBlockAttrs", {id: blockID});+if (response.code === 0 && response.data) {+ const value = response.data["custom-value"];+}+```++See the [generated route declarations](../app/src/types/api/index.d.ts) for exact coverage and the [contract maintenance guide](API-CONTRACTS.md) for generation and compatibility rules. Type declarations do not perform runtime JSON validation.+### Behavior semantics* Only interfaces with dedicated interface sections in this document are public APIs. Other kernel routes and `/api/transactions` operations are internal implementations and provide no compatibility or behavioral stability guarantees unless otherwise stateddiff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.mdindex f3a61d01fc..b3074c67be 100644--- a/docs/API.zh-CN.md+++ b/docs/API.zh-CN.md@@ -4,6 +4,7 @@* [规范](#规范)* [参数和返回值](#参数和返回值)+ * [TypeScript 类型契约](#typescript-类型契约)* [行为语义](#行为语义)* [鉴权](#鉴权)* [笔记本](#笔记本)@@ -118,6 +119,21 @@* `msg`:正常情况下是空字符串,异常情况下会返回错误文案* `data`:可能为 `{}`、`[]` 或者 `NULL`,根据不同接口而不同+### TypeScript 类型契约++插件的 `fetchPost`、`fetchSyncPost` 和 `fetchGet` 声明会根据已迁移的接口路径,从内核生成的契约推导请求与响应类型。首批覆盖版本、块属性、标签搜索、笔记本列表、历史搜索和块信息。存量未迁移接口及动态 URL 继续支持。读取异步返回值中的成功数据前须检查响应码,并显式处理可空字段。++```typescript+import {fetchSyncPost} from "siyuan";++const response = await fetchSyncPost("/api/attr/getBlockAttrs", {id: blockID});+if (response.code === 0 && response.data) {+ const value = response.data["custom-value"];+}+```++准确覆盖范围见[生成的路由声明](../app/src/types/api/index.d.ts),生成与兼容规则见[契约维护说明](API-CONTRACTS.md)。类型声明本身不执行运行时 JSON 校验。+### 行为语义* 只有在本文档中设有独立接口说明的接口属于公开 API。其他内核路由和 `/api/transactions` 操作属于内部实现,除非另有说明,否则不承诺兼容性和行为稳定性diff --git a/kernel/api/attr.go b/kernel/api/attr.goindex 697b56ab38..07567235f9 100644--- a/kernel/api/attr.go+++ b/kernel/api/attr.go@@ -22,6 +22,7 @@ import ("github.com/88250/gulu""github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/sql""github.com/siyuan-note/siyuan/kernel/treenode"@@ -58,45 +59,35 @@ func batchGetBlockAttrs(c *gin.Context) {ret.Data = sql.BatchGetBlockAttrs(idList)}-func getBlockAttrs(c *gin.Context) {+var getBlockAttrs = contractHandler(apicontract.GetBlockAttrs, func(c *gin.Context, request apicontract.BlockIDRequest) apicontract.Response[map[string]string] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }- id := arg["id"].(string)+ id := request.IDif util.InvalidIDPattern(id, ret) {- return+ return contractFailure[map[string]string](ret)}if !checkBlockPublishAccess(c, id, ret) {- return+ return contractFailure[map[string]string](ret)}- ret.Data = sql.GetBlockAttrs(id)-}+ return apicontract.Success(sql.GetBlockAttrs(id))+})-func setBlockAttrs(c *gin.Context) {+var setBlockAttrs = contractHandler(apicontract.SetBlockAttrs, func(c *gin.Context, request apicontract.SetBlockAttrsRequest) apicontract.Response[apicontract.Null] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }-- id := arg["id"].(string)+ id := request.IDif util.InvalidIDPattern(id, ret) {- return+ return contractFailure[apicontract.Null](ret)}- attrs := arg["attrs"].(map[string]any)- if 1 == len(attrs) && "" != attrs["scroll"] {+ attrs := request.Attrs+ scroll := attrs["scroll"]+ if 1 == len(attrs) && (scroll == nil || *scroll != "") {// 不记录用户指南滚动位置if b := treenode.GetBlockTree(id); nil != b && (model.IsUserGuide(b.BoxID)) {- attrs["scroll"] = ""+ empty := ""+ attrs["scroll"] = &empty}}@@ -105,22 +96,17 @@ func setBlockAttrs(c *gin.Context) {if nil == value { // API `setBlockAttrs` 中如果存在属性值设置为 `null` 时移除该属性 https://github.com/siyuan-note/siyuan/issues/5577nameValues[name] = ""} else {- strValue, ok := value.(string)- if !ok {- ret.Code = -1- ret.Msg = fmt.Sprintf("the value of attr [%s] must be a string", name)- return- }- nameValues[name] = strValue+ nameValues[name] = *value}}err := model.SetBlockAttrs(id, nameValues)if err != nil {ret.Code = -1ret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}-}+ return apicontract.Success(apicontract.Null{})+})func batchSetBlockAttrs(c *gin.Context) {ret := gulu.Ret.NewResult()diff --git a/kernel/api/attr_test.go b/kernel/api/attr_test.goindex b8e0944f64..a7e16d85e0 100644--- a/kernel/api/attr_test.go+++ b/kernel/api/attr_test.go@@ -156,6 +156,9 @@ func postBlockAttrs(t *testing.T, role model.Role, path, body string, handler girequest := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))request.Header.Set("Content-Type", "application/json")engine.ServeHTTP(recorder, request)+ if path == "/api/attr/getBlockAttrs" {+ requireAPIContract(t, http.MethodPost, path, recorder)+ }response := &blockAttrsResponse{}if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {diff --git a/kernel/api/block.go b/kernel/api/block.goindex e425ac193c..21b4af3c89 100644--- a/kernel/api/block.go+++ b/kernel/api/block.go@@ -28,6 +28,7 @@ import ("github.com/88250/lute/parse""github.com/gin-gonic/gin""github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/filesys""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/treenode"@@ -1181,47 +1182,39 @@ func getDocBlocksOrders(c *gin.Context) {ret.Data = orders}-func getBlockInfo(c *gin.Context) {+var getBlockInfo = contractHandler(apicontract.GetBlockInfo, func(c *gin.Context, request apicontract.BlockInfoRequest) apicontract.Response[apicontract.BlockInfoData] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }- var id string- if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {- return- }+ id := request.IDif util.InvalidIDPattern(id, ret) {- return+ return contractFailure[apicontract.BlockInfoData](ret)+ }+ boxID := ""+ if request.Notebook != "" && model.IsEncryptedBox(request.Notebook) {+ boxID = request.Notebook}- boxID := encryptedNotebookFromArg(arg)// 普通文档的索引可能尚未就绪,先恢复索引,再按实际归属取得响应租约。if boxID == "" && !model.IsReadOnlyRoleContext(c) && treenode.GetBlockTree(id) == nil {if err := model.ReindexMissingNormalBlock(id); setGetBlockInfoError(ret, id, err) {- return+ return contractFailure[apicontract.BlockInfoData](ret)}}- if !holdBlockRequest(c, ret, boxID, arg) {- return+ ids := append([]string{id}, request.IDs...)+ if err := holdEncryptedBlockRequests(c, boxID, ids, false); err != nil {+ ret.Code, ret.Msg = -1, err.Error()+ return contractFailure[apicontract.BlockInfoData](ret)}blockTree, publishAccessRequired, publishMetadataVisible, publishAccessible := getBlockInfoPublishAccess(c, id, boxID)if !publishAccessible {ret.Code = -1ret.Msg = fmt.Sprintf(model.Conf.Language(15), id)- return+ return contractFailure[apicontract.BlockInfoData](ret)}if publishAccessRequired && !publishMetadataVisible {- ret.Data = map[string]any{- "rootID": blockTree.RootID,- "rootTitle": "",- "rootTitleEmpty": true,- "rootIcon": "",- "publishAccessRequired": true,- }- return+ return apicontract.Success[apicontract.BlockInfoData](apicontract.PublishedBlockInfo{+ BlockInfoCommon: apicontract.BlockInfoCommon{RootID: blockTree.RootID, RootTitleEmpty: true},+ PublishAccessRequired: true,+ })}// 仅在此处使用带重建索引的加载函数,其他地方不要使用@@ -1233,34 +1226,30 @@ func getBlockInfo(c *gin.Context) {tree, err = model.LoadTreeByBlockIDWithReindex(id)}if setGetBlockInfoError(ret, id, err) {- return+ return contractFailure[apicontract.BlockInfoData](ret)}block, _ := model.GetBlock(id, tree)if nil == block {ret.Code = -1ret.Msg = fmt.Sprintf(model.Conf.Language(15), id)- return+ return contractFailure[apicontract.BlockInfoData](ret)}root, err := model.GetBlock(block.RootID, tree)if errors.Is(err, model.ErrIndexing) {- ret.Code = 3- ret.Data = model.Conf.Language(56)- return+ return apicontract.FailureWithText[apicontract.BlockInfoData](3, ret.Msg, model.Conf.Language(56))}rootTitle := root.IAL["title"]rootTitle = html.UnescapeString(rootTitle)icon := html.UnescapeString(root.IAL["icon"])if publishAccessRequired {- ret.Data = map[string]any{- "rootID": block.RootID,- "rootTitle": rootTitle,- "rootTitleEmpty": root.IAL[model.NodeAttrTitleEmpty] == "true",- "rootIcon": icon,- "publishAccessRequired": true,- }- return+ return apicontract.Success[apicontract.BlockInfoData](apicontract.PublishedBlockInfo{+ BlockInfoCommon: apicontract.BlockInfoCommon{+ RootID: block.RootID, RootTitle: rootTitle, RootTitleEmpty: root.IAL[model.NodeAttrTitleEmpty] == "true", RootIcon: icon,+ },+ PublishAccessRequired: true,+ })}var rootChildID string@@ -1277,16 +1266,13 @@ func getBlockInfo(c *gin.Context) {}}- ret.Data = map[string]any{- "box": block.Box,- "path": block.Path,- "rootID": block.RootID,- "rootTitle": rootTitle,- "rootTitleEmpty": root.IAL[model.NodeAttrTitleEmpty] == "true",- "rootChildID": rootChildID,- "rootIcon": icon,- }-}+ return apicontract.Success[apicontract.BlockInfoData](apicontract.FullBlockInfo{+ BlockInfoCommon: apicontract.BlockInfoCommon{+ RootID: block.RootID, RootTitle: rootTitle, RootTitleEmpty: root.IAL[model.NodeAttrTitleEmpty] == "true", RootIcon: icon,+ },+ Box: block.Box, Path: block.Path, RootChildID: rootChildID,+ })+})func setGetBlockInfoError(ret *gulu.Result, id string, err error) bool {if err == nil {diff --git a/kernel/api/block_test.go b/kernel/api/block_test.goindex 8684df1e56..034983a51f 100644--- a/kernel/api/block_test.go+++ b/kernel/api/block_test.go@@ -129,6 +129,7 @@ func testGetBlockInfoRecovery(t *testing.T, name string) {request := httptest.NewRequest(http.MethodPost, "/api/block/getBlockInfo", strings.NewReader(string(body)))request.Header.Set("Content-Type", "application/json")engine.ServeHTTP(recorder, request)+ requireAPIContract(t, http.MethodPost, "/api/block/getBlockInfo", recorder)var response struct {Code int `json:"code"`Data struct {diff --git a/kernel/api/contract.go b/kernel/api/contract.gonew file mode 100644index 0000000000..b772144590--- /dev/null+++ b/kernel/api/contract.go@@ -0,0 +1,48 @@+package api++import (+ "fmt"+ "net/http"++ "github.com/88250/gulu"+ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/model"+)++// contractHandler 将请求绑定和响应类型与注册契约关联,业务入口继续使用现有中间件。+func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, Data],+ handler func(*gin.Context, Request) apicontract.Response[Data]) gin.HandlerFunc {+ return func(c *gin.Context) {+ request, err := endpoint.Decode(c.Request.Body)+ if err != nil {+ c.JSON(http.StatusOK, apicontract.Failure[Data](-1, err.Error()))+ return+ }+ c.JSON(http.StatusOK, handler(c, request))+ }+}++// contractFailure 保留既有业务校验的错误码和消息,并限制其错误载荷形态。+func contractFailure[Data any](result *gulu.Result) apicontract.Response[Data] {+ switch data := result.Data.(type) {+ case nil:+ return apicontract.Failure[Data](result.Code, result.Msg)+ case string:+ return apicontract.FailureWithText[Data](result.Code, result.Msg, data)+ default:+ panic(fmt.Sprintf("unsupported API error data %T", result.Data))+ }+}++func notebookContract(box *model.Box) *apicontract.Notebook {+ if box == nil {+ return nil+ }+ return &apicontract.Notebook{+ ID: box.ID, Name: box.Name, Icon: box.Icon, Sort: box.Sort, SortMode: box.SortMode,+ Closed: box.Closed, SubFileCount: box.SubFileCount, NewFlashcardCount: box.NewFlashcardCount,+ DueFlashcardCount: box.DueFlashcardCount, FlashcardCount: box.FlashcardCount,+ Encrypted: box.Encrypted, Unlocked: box.Unlocked, State: string(box.State),+ }+}diff --git a/kernel/api/contract_test.go b/kernel/api/contract_test.gonew file mode 100644index 0000000000..ee1e3f8485--- /dev/null+++ b/kernel/api/contract_test.go@@ -0,0 +1,243 @@+package api++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "reflect"+ "strings"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func requireAPIContract(t *testing.T, method, path string, recorder *httptest.ResponseRecorder) {+ t.Helper()+ if recorder.Code != http.StatusOK || !strings.HasPrefix(recorder.Header().Get("Content-Type"), "application/json") {+ t.Fatalf("unexpected transport response for %s: %d %v", path, recorder.Code, recorder.Header())+ }+ bundle, err := apicontract.BuildBundle()+ if err != nil {+ t.Fatal(err)+ }+ if err := bundle.ValidateResponse(method, path, recorder.Body.Bytes()); err != nil {+ t.Fatalf("response violates %s: %v\n%s", path, err, recorder.Body.String())+ }+}++func TestAPIContractNotebookConversion(t *testing.T) {+ for _, state := range []model.EncryptedBoxState{"", model.EncryptedBoxStateLocked, model.EncryptedBoxStateUnlocking,+ model.EncryptedBoxStateUnlocked, model.EncryptedBoxStateLocking, model.EncryptedBoxStateError} {+ box := &model.Box{ID: "box", Name: "Notebook", Icon: "icon", Sort: 2, SortMode: 3, Closed: true,+ SubFileCount: 4, NewFlashcardCount: 5, DueFlashcardCount: 6, FlashcardCount: 7,+ Encrypted: state != "", Unlocked: state == model.EncryptedBoxStateUnlocked, State: state}+ before, _ := json.Marshal(box)+ after, _ := json.Marshal(notebookContract(box))+ if string(before) != string(after) {+ t.Fatalf("notebook JSON changed:\n%s\n%s", before, after)+ }+ bundle, err := apicontract.BuildBundle()+ if err != nil {+ t.Fatal(err)+ }+ payload, _ := json.Marshal(apicontract.Success(&apicontract.ListNotebooksData{Notebooks: []*apicontract.Notebook{notebookContract(box)}}))+ if err := bundle.ValidateResponse("POST", "/api/notebook/lsNotebooks", payload); err != nil {+ t.Fatal(err)+ }+ }+ if notebookContract(nil) != nil {+ t.Fatal("nil notebook changed")+ }+}++func TestAPIContractRouterCoverage(t *testing.T) {+ gin.SetMode(gin.TestMode)+ engine := gin.New()+ ServeAPI(engine)+ data, err := os.ReadFile("../apicontract/legacy_routes.json")+ if err != nil {+ t.Fatal(err)+ }+ var legacy []apicontract.Route+ if err := json.Unmarshal(data, &legacy); err != nil {+ t.Fatal(err)+ }+ expected := map[string]bool{}+ for _, route := range legacy {+ methods := []string{route.Method}+ if route.Method == "ANY" {+ methods = []string{"GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS", "DELETE", "CONNECT", "TRACE"}+ }+ for _, method := range methods {+ expected[method+" "+route.Path] = true+ }+ }+ for _, definition := range apicontract.Definitions() {+ for _, method := range definition.Methods {+ expected[method+" "+definition.Path] = true+ }+ }+ for _, route := range engine.Routes() {+ key := route.Method + " " + route.Path+ if !expected[key] {+ t.Fatalf("actual router exposes an undeclared endpoint: %s", key)+ }+ delete(expected, key)+ }+ if len(expected) > 0 {+ t.Fatalf("declared routes are absent from the actual router: %v", expected)+ }+}++func TestAPIContractHandlers(t *testing.T) {+ if os.Getenv("SIYUAN_TEST_API_CONTRACT_HANDLERS") != "1" {+ // 数据库和缓存带有进程级状态,使用独立测试进程避免污染其他测试。+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ defer cancel()+ command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestAPIContractHandlers$", "-test.v")+ command.Env = append(os.Environ(), "SIYUAN_TEST_API_CONTRACT_HANDLERS=1")+ if output, err := command.CombinedOutput(); err != nil {+ t.Fatalf("contract subprocess failed: %v\n%s", err, output)+ }+ return+ }+ root := t.TempDir()+ util.DataDir, util.TempDir, util.ConfDir = filepath.Join(root, "data"), root, root+ util.QueueDir = filepath.Join(root, "queue")+ util.DBPath, util.HistoryDBPath = filepath.Join(root, "siyuan.db"), filepath.Join(root, "history.db")+ util.AssetContentDBPath, util.BlockTreeDBPath = filepath.Join(root, "asset_content.db"), filepath.Join(root, "blocktree.db")+ model.Conf = model.NewAppConf()+ model.Conf.Lang = "en"+ util.TimeLangs["en"] = map[string]any{}+ for _, key := range []string{"albl", "blbl", "now", "1s", "xs", "1m", "xm", "1h", "xh", "1d", "xd", "1w", "xw", "1M", "xM", "1y", "2y", "xy", "max"} {+ util.TimeLangs["en"][key] = "time"+ }+ model.Conf.FileTree, model.Conf.Sync = conf.NewFileTree(), conf.NewSync()+ model.Conf.Search, model.Conf.Editor, model.Conf.Export = conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ model.Conf.NotebookCrypto = conf.NewNotebookCrypto()+ const boxID, docID = "20260912000000-boxapi1", "20260912000001-docapi1"+ box := &model.Box{ID: boxID}+ boxConf := conf.NewBoxConf()+ boxConf.Name, boxConf.Closed = "Contracts", false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ sql.InitDatabase(true)+ sql.InitHistoryDatabase(true)+ sql.InitAssetContentDatabase(true)+ defer sql.CloseDatabase()+ tree := treenode.NewTree(boxID, "/"+docID+".sy", "/Contract", "Contract")+ tree.Root.SetIALAttr("custom-value", "before")+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }++ gin.SetMode(gin.TestMode)+ request := func(method, path, body string, role model.Role, handlers ...gin.HandlerFunc) map[string]any {+ t.Helper()+ engine := gin.New()+ engine.Use(boxLeaseMiddleware, func(c *gin.Context) { c.Set(model.RoleContextKey, role); c.Next() })+ engine.Handle(method, path, handlers...)+ recorder := httptest.NewRecorder()+ req := httptest.NewRequest(method, path, strings.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, req)+ requireAPIContract(t, method, path, recorder)+ var response map[string]any+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ return response+ }+ admin := model.RoleAdministrator+ for _, method := range []string{"GET", "POST"} {+ response := request(method, "/api/system/version", "", admin, version)+ if response["data"] != util.Ver {+ t.Fatal("version payload changed")+ }+ }+ info := request("POST", "/api/block/getBlockInfo", `{"id":"`+docID+`"}`, admin, getBlockInfo)+ if info["code"] != float64(0) || info["data"].(map[string]any)["rootID"] != docID {+ t.Fatalf("block info failed: %+v", info)+ }+ attrs := request("POST", "/api/attr/getBlockAttrs", `{"id":"`+docID+`"}`, admin, getBlockAttrs)+ if attrs["data"].(map[string]any)["custom-value"] != "before" {+ t.Fatal("attribute fixture was not read")+ }+ changed := request("POST", "/api/attr/setBlockAttrs", `{"id":"`+docID+`","attrs":{"custom-value":null,"custom-other":"after"}}`, admin, setBlockAttrs)+ if changed["code"] != float64(0) || changed["data"] != nil {+ t.Fatalf("attribute update failed: %+v", changed)+ }+ attrs = request("POST", "/api/attr/getBlockAttrs", `{"id":"`+docID+`"}`, admin, getBlockAttrs)+ values := attrs["data"].(map[string]any)+ if _, exists := values["custom-value"]; exists {+ t.Fatal("null did not remove the attribute")+ }+ if values["custom-other"] != "after" {+ t.Fatal("attribute update was not preserved")+ }+ tags := request("POST", "/api/search/searchTag", `{"k":""}`, admin, searchTag)+ if !reflect.DeepEqual(tags["data"].(map[string]any)["tags"], []any{}) {+ t.Fatalf("empty tag response changed: %+v", tags)+ }+ for _, body := range []string{`{}`, `{"page":null}`, `{"page":1.9,"type":0.9}`} {+ response := request("POST", "/api/history/searchHistory", body, admin, searchHistory)+ if response["code"] != float64(0) {+ t.Fatalf("history request failed: %+v", response)+ }+ }+ for _, body := range []string{"", "{}", "null", "invalid", `{"flashcard":false}`} {+ response := request("POST", "/api/notebook/lsNotebooks", body, admin, lsNotebooks)+ if response["code"] != float64(0) || len(response["data"].(map[string]any)["notebooks"].([]any)) != 1 {+ t.Fatalf("legacy notebook request changed: %+v", response)+ }+ }+ for _, entry := range []struct {+ path, body string+ handler gin.HandlerFunc+ }{+ {"/api/attr/getBlockAttrs", `{}`, getBlockAttrs},+ {"/api/attr/setBlockAttrs", `{"id":"` + docID + `","attrs":{"x":1}}`, setBlockAttrs},+ {"/api/search/searchTag", `{"k":1}`, searchTag},+ {"/api/history/searchHistory", `{"page":"1"}`, searchHistory},+ {"/api/notebook/lsNotebooks", `{"flashcard":1}`, lsNotebooks},+ {"/api/block/getBlockInfo", `{"id":" "}`, getBlockInfo},+ } {+ response := request("POST", entry.path, entry.body, admin, entry.handler)+ if response["code"] != float64(-1) {+ t.Fatalf("invalid request did not return an error: %+v", response)+ }+ }+ readonly := request("POST", "/api/attr/setBlockAttrs", `{"id":"`+docID+`","attrs":{}}`, model.RoleReader, model.CheckReadonly, setBlockAttrs)+ if readonly["code"] != float64(-1) {+ t.Fatal("readonly middleware did not reject the write")+ }+ for _, visible := range []bool{false, true} {+ if err := model.SetPublishAccess(model.PublishAccess{{ID: docID, Visible: visible, Password: "password"}}); err != nil {+ t.Fatal(err)+ }+ response := request("POST", "/api/block/getBlockInfo", `{"id":"`+docID+`"}`, model.RoleReader, getBlockInfo)+ data := response["data"].(map[string]any)+ if data["publishAccessRequired"] != true {+ t.Fatalf("publish gate changed: %+v", response)+ }+ if _, exists := data["box"]; exists {+ t.Fatal("publish gate exposed full block information")+ }+ if !visible && data["rootTitle"] != "" {+ t.Fatal("private document title was exposed")+ }+ }+}diff --git a/kernel/api/history.go b/kernel/api/history.goindex 173b2e0bc7..55fb8a3fec 100644--- a/kernel/api/history.go+++ b/kernel/api/history.go@@ -24,50 +24,23 @@ import ("github.com/88250/gulu""github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/util")-func searchHistory(c *gin.Context) {- ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }-- var notebook, query, op string- if !util.ParseJsonArgs(arg, ret,- util.BindJsonArg("notebook", ¬ebook, false, false),- util.BindJsonArg("query", &query, false, false),- util.BindJsonArg("op", &op, false, false),- ) {- return- }+var searchHistory = contractHandler(apicontract.SearchHistory, func(c *gin.Context, request apicontract.SearchHistoryRequest) apicontract.Response[apicontract.SearchHistoryData] {typ := model.HistoryTypeDoc- if nil != arg["type"] {- typeVal, ok := util.ParseJsonArg[float64]("type", arg, ret, true, false)- if !ok {- return- }- typ = int(typeVal)+ if request.Type != nil {+ typ = int(*request.Type)}page := 1- if nil != arg["page"] {- pageVal, ok := util.ParseJsonArg[float64]("page", arg, ret, true, false)- if !ok {- return- }- page = int(pageVal)+ if request.Page != nil {+ page = int(*request.Page)}- histories, pageCount, totalCount := model.FullTextSearchHistory(query, notebook, op, typ, page)- ret.Data = map[string]any{- "histories": histories,- "pageCount": pageCount,- "totalCount": totalCount,- }-}+ histories, pageCount, totalCount := model.FullTextSearchHistory(request.Query, request.Notebook, request.Op, typ, page)+ return apicontract.Success(apicontract.SearchHistoryData{Histories: histories, PageCount: pageCount, TotalCount: totalCount})+})func getHistoryItems(c *gin.Context) {ret := gulu.Ret.NewResult()diff --git a/kernel/api/notebook.go b/kernel/api/notebook.goindex 89f0c56192..f29b9334af 100644--- a/kernel/api/notebook.go+++ b/kernel/api/notebook.go@@ -26,6 +26,7 @@ import ("github.com/88250/gulu""github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util"@@ -495,19 +496,10 @@ func setNotebookConf(c *gin.Context) {ret.Data = boxConf}-func lsNotebooks(c *gin.Context) {+var lsNotebooks = contractHandler(apicontract.ListNotebooks, func(c *gin.Context, request apicontract.ListNotebooksRequest) apicontract.Response[*apicontract.ListNotebooksData] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)- flashcard := false-- // 兼容旧版接口,不能直接使用 util.JsonArg()- arg := map[string]any{}- if err := c.ShouldBindJSON(&arg); err == nil {- if arg["flashcard"] != nil {- flashcard = arg["flashcard"].(bool)- }- }+ flashcard := request.Flashcardvar notebooks []*model.Boxvar publishAccess model.PublishAccess@@ -522,13 +514,13 @@ func lsNotebooks(c *gin.Context) {if err := holdEncryptedBoxRequest(c, boxID); err != nil {ret.Code = -1ret.Msg = model.Conf.Language(314)- return+ return contractFailure[*apicontract.ListNotebooksData](ret)}}var err errornotebooks, err = model.ListNotebooks()if err != nil {- return+ return apicontract.Success[*apicontract.ListNotebooksData](nil)}if isReadOnlyRole {publishAccess = model.GetPublishAccess()@@ -557,11 +549,15 @@ func lsNotebooks(c *gin.Context) {sortNotebooksBySubFileCount(notebooks, model.Conf.FileTree.Sort)}- ret.Data = map[string]any{- "notebooks": notebooks,- "boxDocEnabled": boxDocEnabled,+ var values []*apicontract.Notebook+ if notebooks != nil {+ values = make([]*apicontract.Notebook, 0, len(notebooks))+ for _, notebook := range notebooks {+ values = append(values, notebookContract(notebook))+ }}-}+ return apicontract.Success(&apicontract.ListNotebooksData{Notebooks: values, BoxDocEnabled: boxDocEnabled})+})func sortNotebooksBySubFileCount(notebooks []*model.Box, sortMode int) {switch sortMode {diff --git a/kernel/api/search.go b/kernel/api/search.goindex ca7a7aad66..a81cad55ec 100644--- a/kernel/api/search.go+++ b/kernel/api/search.go@@ -23,6 +23,7 @@ import ("github.com/88250/gulu""github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/sql""github.com/siyuan-note/siyuan/kernel/util"@@ -249,25 +250,15 @@ func searchAsset(c *gin.Context) {return}-func searchTag(c *gin.Context) {- ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)+var searchTag = contractHandler(apicontract.SearchTag, func(c *gin.Context, request apicontract.SearchTagRequest) apicontract.Response[apicontract.SearchTagData] {- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }-- k := arg["k"].(string)+ k := request.Ktags := model.SearchTags(k)if 1 > len(tags) {tags = []string{}}- ret.Data = map[string]any{- "tags": tags,- "k": k,- }-}+ return apicontract.Success(apicontract.SearchTagData{Tags: tags, K: k})+})func searchWidget(c *gin.Context) {ret := gulu.Ret.NewResult()diff --git a/kernel/api/system.go b/kernel/api/system.goindex 5bb2992519..3f54ba7c17 100644--- a/kernel/api/system.go+++ b/kernel/api/system.go@@ -38,6 +38,7 @@ import ("github.com/gin-gonic/gin""github.com/siyuan-note/filelock""github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/util"@@ -1227,12 +1228,9 @@ func removeCustomFont(c *gin.Context) {}}-func version(c *gin.Context) {- ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- ret.Data = util.Ver-}+var version = contractHandler(apicontract.Version, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[string] {+ return apicontract.Success(util.Ver)+})func currentTime(c *gin.Context) {ret := gulu.Ret.NewResult()diff --git a/kernel/apicontract/cmd/apigen/main.go b/kernel/apicontract/cmd/apigen/main.gonew file mode 100644index 0000000000..fff9bf1277--- /dev/null+++ b/kernel/apicontract/cmd/apigen/main.go@@ -0,0 +1,113 @@+package main++import (+ "bytes"+ "encoding/json"+ "flag"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "sort"++ "github.com/siyuan-note/siyuan/kernel/apicontract"+)++func main() {+ check := flag.Bool("check", false, "check generated artifacts without writing")+ root := flag.String("root", "..", "repository root")+ petal := flag.String("petal", "", "optional petal repository to synchronize or check")+ base := flag.String("base", "", "base git revision for the legacy coverage ratchet")+ flag.Parse()+ if err := run(*root, *petal, *base, *check); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+}++func run(root, petal, base string, check bool) error {+ bundle, err := apicontract.BuildBundle()+ if err != nil {+ return err+ }+ routes, bindings, err := apicontract.ReadRoutes(filepath.Join(root, "kernel", "api"))+ if err != nil {+ return err+ }+ legacyPath := filepath.Join(root, "kernel", "apicontract", "legacy_routes.json")+ data, err := os.ReadFile(legacyPath)+ if err != nil {+ return err+ }+ var legacy []apicontract.Route+ if err = json.Unmarshal(data, &legacy); err != nil {+ return err+ }+ if err = apicontract.CheckRoutes(routes, bindings, legacy); err != nil {+ return err+ }+ if base != "" {+ command := exec.Command("git", "show", base+":kernel/apicontract/legacy_routes.json")+ command.Dir = root+ previous, readErr := command.Output()+ if readErr != nil {+ // 首次建立契约时基线文件尚不存在;其他 git 错误仍然中止校验。+ probe := exec.Command("git", "ls-tree", base, "kernel/apicontract/legacy_routes.json")+ probe.Dir = root+ listing, probeErr := probe.Output()+ if probeErr != nil || len(listing) != 0 {+ return fmt.Errorf("cannot read legacy coverage baseline: %w", readErr)+ }+ } else {+ var baseline []apicontract.Route+ if err = json.Unmarshal(previous, &baseline); err != nil {+ return err+ }+ allowed := map[string]bool{}+ for _, route := range baseline {+ allowed[route.Key()] = true+ }+ for _, route := range legacy {+ if !allowed[route.Key()] {+ return fmt.Errorf("legacy coverage may not grow: %s", route.Key())+ }+ }+ }+ }+ jsonData, err := json.MarshalIndent(bundle, "", " ")+ if err != nil {+ return err+ }+ artifacts := map[string][]byte{+ filepath.Join(root, "app", "src", "types", "api", "index.d.ts"): bundle.TypeScript(legacy),+ filepath.Join(root, "kernel", "apicontract", "schema.json"): append(jsonData, '\n'),+ }+ if petal != "" {+ artifacts[filepath.Join(petal, "types", "api", "index.d.ts")] = bundle.TypeScript(legacy)+ }+ var paths []string+ for path := range artifacts {+ paths = append(paths, path)+ }+ sort.Strings(paths)+ for _, path := range paths {+ if check {+ current, err := os.ReadFile(path)+ if err != nil {+ return err+ }+ if !bytes.Equal(bytes.ReplaceAll(current, []byte("\r\n"), []byte("\n")), artifacts[path]) {+ return fmt.Errorf("generated API contract is out of date: %s", path)+ }+ } else {+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ return err+ }+ if err := os.WriteFile(path, artifacts[path], 0644); err != nil {+ return err+ }+ }+ }+ fmt.Printf("API contracts: %d typed method/path pairs checked\n", len(bundle.Endpoints))+ return nil+}diff --git a/kernel/apicontract/contract_test.go b/kernel/apicontract/contract_test.gonew file mode 100644index 0000000000..e9315635f8--- /dev/null+++ b/kernel/apicontract/contract_test.go@@ -0,0 +1,229 @@+package apicontract++import (+ "encoding/json"+ "os"+ "reflect"+ "strings"+ "testing"+)++func TestRequestCompatibility(t *testing.T) {+ for _, body := range []string{"", "null", "{}", "[]", "invalid", `{"flashcard":`, `{"flashcard":null}`} {+ request, err := ListNotebooks.Decode(strings.NewReader(body))+ if err != nil || request.Flashcard {+ t.Fatalf("legacy notebook request %q: %+v, %v", body, request, err)+ }+ }+ request, err := ListNotebooks.Decode(strings.NewReader(`{"flashcard":true}`))+ if err != nil || !request.Flashcard {+ t.Fatalf("flashcard request: %+v, %v", request, err)+ }+ if _, err := ListNotebooks.Decode(strings.NewReader(`{"flashcard":1}`)); err == nil {+ t.Fatal("invalid boolean must return an error")+ }+ for _, body := range []string{`{}`, `{"page":null,"type":null}`} {+ request, err := SearchHistory.Decode(strings.NewReader(body))+ if err != nil || request.Page != nil || request.Type != nil {+ t.Fatalf("history defaults %q: %+v, %v", body, request, err)+ }+ }+ for _, number := range []string{"0", "1.9", "-1.9", "1e2"} {+ request, err := SearchHistory.Decode(strings.NewReader(`{"page":` + number + `,"type":` + number + `}`))+ var legacy map[string]any+ _ = json.Unmarshal([]byte(`{"page":`+number+`}`), &legacy)+ if err != nil || request.Page == nil || int(*request.Page) != int(legacy["page"].(float64)) || *request.Type != *request.Page {+ t.Fatalf("numeric conversion %q changed: %+v, %v", number, request, err)+ }+ }+ for _, body := range []string{`{"page":"2"}`, `{"page":true}`, `{"query":2}`} {+ if _, err := SearchHistory.Decode(strings.NewReader(body)); err == nil {+ t.Fatalf("invalid history request accepted: %s", body)+ }+ }+ attrs, err := SetBlockAttrs.Decode(strings.NewReader(`{"id":"id","attrs":{"custom-value":null,"name":"value"}}`))+ if err != nil || attrs.Attrs["custom-value"] != nil || *attrs.Attrs["name"] != "value" {+ t.Fatalf("nullable attribute values changed: %+v, %v", attrs, err)+ }+ for _, body := range []string{"", "null", "{}", `{"ID":"id"}`, `{"id":null}`, `{"id":1}`} {+ if _, err := GetBlockAttrs.Decode(strings.NewReader(body)); err == nil {+ t.Fatalf("invalid ID request accepted: %q", body)+ }+ }+ for _, body := range []string{`{"id":"id"}`, `{"id":"id","attrs":null}`, `{"id":"id","attrs":{"x":1}}`} {+ if _, err := SetBlockAttrs.Decode(strings.NewReader(body)); err == nil {+ t.Fatalf("invalid attributes accepted: %s", body)+ }+ }+ info, err := GetBlockInfo.Decode(strings.NewReader(`{"id":" id ","notebook":12,"ids":["a",null,12,"b"],"ignored":true}`))+ if err != nil || info.ID != "id" || info.Notebook != "" || !reflect.DeepEqual(info.IDs, []string{"a", "b"}) {+ t.Fatalf("block request compatibility changed: %+v, %v", info, err)+ }+ if _, err := GetBlockInfo.Decode(strings.NewReader(`{"id":" "}`)); err == nil {+ t.Fatal("whitespace-only ID accepted")+ }+ tag, err := SearchTag.Decode(strings.NewReader(`{"k":"","ignored":true}`))+ if err != nil || tag.K != "" {+ t.Fatalf("empty keyword changed: %+v, %v", tag, err)+ }+}++func TestResponseContracts(t *testing.T) {+ bundle, err := BuildBundle()+ if err != nil {+ t.Fatal(err)+ }+ for _, test := range []struct {+ path, payload string+ valid bool+ }{+ {"/api/system/version", `{"code":0,"msg":"","data":"3.8.4"}`, true},+ {"/api/system/version", `{"code":0,"msg":"","data":1}`, false},+ {"/api/attr/setBlockAttrs", `{"code":0,"msg":"","data":null}`, true},+ {"/api/attr/getBlockAttrs", `{"code":0,"msg":"","data":{"custom-x":"value"}}`, true},+ {"/api/attr/getBlockAttrs", `{"code":0,"msg":"","data":{"custom-x":1}}`, false},+ {"/api/search/searchTag", `{"code":0,"msg":"","data":{"tags":[],"k":""}}`, true},+ {"/api/search/searchTag", `{"code":0,"msg":"","data":{"tags":null,"k":""}}`, false},+ {"/api/search/searchTag", `{"code":0,"msg":"","data":{"tagz":[],"k":""}}`, false},+ {"/api/search/searchTag", `{"code":-1,"msg":"readonly","data":{"closeTimeout":5000},"cmd":"","reqId":0}`, true},+ {"/api/notebook/lsNotebooks", `{"code":0,"msg":"","data":null}`, true},+ {"/api/history/searchHistory", `{"code":0,"msg":"","data":{"histories":null,"pageCount":0,"totalCount":0}}`, true},+ {"/api/history/searchHistory", `{"code":0,"msg":"","data":{"histories":[123],"pageCount":1,"totalCount":1}}`, false},+ {"/api/block/getBlockInfo", `{"code":3,"msg":"indexing","data":"indexing"}`, true},+ {"/api/block/getBlockInfo", `{"code":0,"msg":"","data":{"rootID":"id","rootTitle":"","rootIcon":"","rootTitleEmpty":true,"publishAccessRequired":true}}`, true},+ {"/api/block/getBlockInfo", `{"code":0,"msg":"","data":{"rootID":"id","rootTitle":"","rootIcon":"","rootTitleEmpty":true,"publishAccessRequired":false}}`, false},+ {"/api/block/getBlockInfo", `{"code":0,"msg":"","data":{"rootID":"id","rootTitle":"","rootIcon":"","rootTitleEmpty":true,"publishAccessRequired":true,"box":"secret"}}`, false},+ } {+ err := bundle.ValidateResponse("POST", test.path, []byte(test.payload))+ if (err == nil) != test.valid {+ t.Errorf("%s %s: valid=%v, error=%v", test.path, test.payload, test.valid, err)+ }+ }+}++type recursiveFixture struct {+ ID string `json:"id"`+ Children []*recursiveFixture `json:"children"`+ Flag *bool `json:"flag,omitempty"`+ Ignored string `json:"-"`+}++type codecFixture string++func (codecFixture) MarshalJSON() ([]byte, error) { return []byte(`{}`), nil }++type embeddedRequestFixture struct {+ Mode string `json:"mode" api:"enum=a|b"`+}++type constrainedRequestFixture struct {+ embeddedRequestFixture+ Enabled bool `json:"enabled" api:"const=true"`+ Ignored string `json:"-"`+}++func TestEmbeddedRequestConstraints(t *testing.T) {+ endpoint := Endpoint[constrainedRequestFixture, Null]{definition: Definition{Path: "/test", Body: JSONBody}}+ request, err := endpoint.Decode(strings.NewReader(`{"mode":"a","enabled":true,"Ignored":"secret"}`))+ if err != nil || request.Mode != "a" || !request.Enabled || request.Ignored != "" {+ t.Fatalf("embedded request failed: %+v, %v", request, err)+ }+ for _, body := range []string{`{"mode":"c","enabled":true}`, `{"mode":"a","enabled":false}`, `{"enabled":true}`} {+ if _, err := endpoint.Decode(strings.NewReader(body)); err == nil {+ t.Fatalf("request constraints bypassed: %s", body)+ }+ }+ builder := &schemaBuilder{definitions: map[string]*Schema{}, owners: map[string]reflect.Type{}}+ schema, err := builder.schema(reflect.TypeFor[constrainedRequestFixture](), true)+ if err != nil {+ t.Fatal(err)+ }+ bundle := &Bundle{Definitions: builder.definitions}+ if err := bundle.validate(schema, map[string]any{"mode": "a", "enabled": true}, "$"); err != nil {+ t.Fatal(err)+ }+ if err := bundle.validate(&Schema{AnyOf: []*Schema{{Type: "string"}, {Type: "null"}}, Enum: []any{"a"}}, "b", "$"); err == nil {+ t.Fatal("union bypassed enum constraint")+ }+}++func TestGeneratorRejectsUnsupportedTypes(t *testing.T) {+ builder := &schemaBuilder{definitions: map[string]*Schema{}, owners: map[string]reflect.Type{}}+ if _, err := builder.schema(reflect.TypeFor[recursiveFixture](), false); err != nil {+ t.Fatal(err)+ }+ if _, err := builder.schema(reflect.TypeFor[recursiveFixture](), true); err != nil {+ t.Fatal(err)+ }+ output := builder.definitions["recursiveFixture"]+ input := builder.definitions["recursiveFixtureInput"]+ if _, exists := output.Properties["Ignored"]; exists {+ t.Fatal("ignored JSON field was generated")+ }+ if output.Properties["flag"].Type != "boolean" || input.Properties["flag"].AnyOf == nil {+ t.Fatal("input and output nullability were conflated")+ }+ for _, typ := range []reflect.Type{reflect.TypeFor[any](), reflect.TypeFor[codecFixture](), reflect.TypeFor[[]byte](), reflect.TypeFor[map[int]string]()} {+ if _, err := builder.schema(typ, false); err == nil {+ t.Fatalf("unsupported type silently accepted: %s", typ)+ }+ }+}++func TestRouteCoverage(t *testing.T) {+ routes, bindings, err := ReadRoutes("../api")+ if err != nil {+ t.Fatal(err)+ }+ data, err := os.ReadFile("legacy_routes.json")+ if err != nil {+ t.Fatal(err)+ }+ var legacy []Route+ if err := json.Unmarshal(data, &legacy); err != nil {+ t.Fatal(err)+ }+ if err := CheckRoutes(routes, bindings, legacy); err != nil {+ t.Fatal(err)+ }+ if err := CheckRoutes(append(routes, Route{"POST", "/api/new/untyped", "newHandler"}), bindings, legacy); err == nil {+ t.Fatal("new untyped route was accepted")+ }+ bindings["getBlockAttrs"] = "setBlockAttrs"+ if err := CheckRoutes(routes, bindings, legacy); err == nil {+ t.Fatal("handler bound to the wrong contract was accepted")+ }+}++func TestGeneratedArtifacts(t *testing.T) {+ bundle, err := BuildBundle()+ if err != nil {+ t.Fatal(err)+ }+ declaration, err := os.ReadFile("../../app/src/types/api/index.d.ts")+ if err != nil {+ t.Fatal(err)+ }+ legacyJSON, err := os.ReadFile("legacy_routes.json")+ if err != nil {+ t.Fatal(err)+ }+ var legacy []Route+ if err := json.Unmarshal(legacyJSON, &legacy); err != nil {+ t.Fatal(err)+ }+ if strings.ReplaceAll(string(declaration), "\r\n", "\n") != string(bundle.TypeScript(legacy)) {+ t.Fatal("TypeScript contracts are out of date")+ }+ schema, err := os.ReadFile("schema.json")+ if err != nil {+ t.Fatal(err)+ }+ want, err := json.MarshalIndent(bundle, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ if strings.TrimSpace(strings.ReplaceAll(string(schema), "\r\n", "\n")) != string(want) {+ t.Fatal("JSON schemas are out of date")+ }+}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.gonew file mode 100644index 0000000000..17f494d697--- /dev/null+++ b/kernel/apicontract/contracts.go@@ -0,0 +1,150 @@+// 包 apicontract 定义 HTTP 接口的线协议,不依赖内核启动或持久化模型。+package apicontract++import "reflect"++type BodyMode string++const (+ JSONBody BodyMode = "json"+ NoBody BodyMode = "none"+ LegacyOptionalBody BodyMode = "legacyOptional"+)++type Definition struct {+ Name string+ Path string+ Methods []string+ Body BodyMode+ Request reflect.Type+ Data reflect.Type+ ErrorCodes []int+ ErrorText bool+ DataNonNullable bool+}++type Endpoint[Request, Data any] struct {+ definition Definition+}++type ResponseOptions struct {+ AdditionalCodes []int+ Text bool+ NonNullable bool+}++var definitions []Definition++func define[Request, Data any](name, path string, body BodyMode, response ResponseOptions, methods ...string) Endpoint[Request, Data] {+ d := Definition{Name: name, Path: path, Methods: methods, Body: body,+ Request: reflect.TypeFor[Request](), Data: reflect.TypeFor[Data](),+ ErrorCodes: append([]int{-1}, response.AdditionalCodes...), ErrorText: response.Text, DataNonNullable: response.NonNullable}+ definitions = append(definitions, d)+ return Endpoint[Request, Data]{definition: d}+}++func (e Endpoint[Request, Data]) Definition() Definition { return e.definition }++func Definitions() []Definition { return append([]Definition(nil), definitions...) }++var (+ Version = define[EmptyRequest, string]("version", "/api/system/version", NoBody, ResponseOptions{}, "GET", "POST")+ GetBlockAttrs = define[BlockIDRequest, map[string]string]("getBlockAttrs", "/api/attr/getBlockAttrs", JSONBody, ResponseOptions{NonNullable: true}, "POST")+ SetBlockAttrs = define[SetBlockAttrsRequest, Null]("setBlockAttrs", "/api/attr/setBlockAttrs", JSONBody, ResponseOptions{}, "POST")+ SearchTag = define[SearchTagRequest, SearchTagData]("searchTag", "/api/search/searchTag", JSONBody, ResponseOptions{}, "POST")+ ListNotebooks = define[ListNotebooksRequest, *ListNotebooksData]("lsNotebooks", "/api/notebook/lsNotebooks", LegacyOptionalBody, ResponseOptions{}, "POST")+ SearchHistory = define[SearchHistoryRequest, SearchHistoryData]("searchHistory", "/api/history/searchHistory", JSONBody, ResponseOptions{}, "POST")+ GetBlockInfo = define[BlockInfoRequest, BlockInfoData]("getBlockInfo", "/api/block/getBlockInfo", JSONBody, ResponseOptions{AdditionalCodes: []int{3}, Text: true}, "POST")+)++type EmptyRequest struct{}++type BlockIDRequest struct {+ ID string `json:"id"`+}++type SetBlockAttrsRequest struct {+ ID string `json:"id"`+ Attrs map[string]*string `json:"attrs"`+}++type SearchTagRequest struct {+ K string `json:"k"`+}++type SearchTagData struct {+ Tags []string `json:"tags" api:"nonnullable"`+ K string `json:"k"`+}++type ListNotebooksRequest struct {+ Flashcard bool `json:"flashcard" api:"optional,nullable"`+}++// Notebook 仅承载接口公开的笔记本信息;转换测试校验其与现有序列化结果一致。+type Notebook struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Icon string `json:"icon"`+ Sort int `json:"sort"`+ SortMode int `json:"sortMode"`+ Closed bool `json:"closed"`+ SubFileCount int `json:"subFileCount"`+ NewFlashcardCount int `json:"newFlashcardCount"`+ DueFlashcardCount int `json:"dueFlashcardCount"`+ FlashcardCount int `json:"flashcardCount"`+ Encrypted bool `json:"encrypted"`+ Unlocked bool `json:"unlocked"`+ State string `json:"state,omitempty" api:"enum=Locked|Unlocking|Unlocked|Locking|Error"`+}++type ListNotebooksData struct {+ Notebooks []*Notebook `json:"notebooks"`+ BoxDocEnabled bool `json:"boxDocEnabled"`+}++// 数字保留 JSON 浮点语义,由业务入口沿用既有的整数转换及缺省值。+type SearchHistoryRequest struct {+ Notebook string `json:"notebook" api:"optional,nullable"`+ Query string `json:"query" api:"optional,nullable"`+ Op string `json:"op" api:"optional,nullable"`+ Type *float64 `json:"type" api:"optional"`+ Page *float64 `json:"page" api:"optional"`+}++type SearchHistoryData struct {+ Histories []string `json:"histories"`+ PageCount int `json:"pageCount"`+ TotalCount int `json:"totalCount"`+}++type BlockInfoRequest struct {+ ID string `json:"id" api:"trim"`+ Notebook string `json:"notebook" api:"optional,nullable,ignoretype"`+ // 附带的 ID 仍参与租约检查,保留旧入口对非字符串元素的忽略行为。+ IDs []string `json:"ids" api:"optional,filterstrings"`+}++type BlockInfoData interface{ blockInfoData() }++type BlockInfoCommon struct {+ RootID string `json:"rootID"`+ RootTitle string `json:"rootTitle"`+ RootTitleEmpty bool `json:"rootTitleEmpty"`+ RootIcon string `json:"rootIcon"`+}++type FullBlockInfo struct {+ BlockInfoCommon+ Box string `json:"box"`+ Path string `json:"path"`+ RootChildID string `json:"rootChildID"`+}++type PublishedBlockInfo struct {+ BlockInfoCommon+ PublishAccessRequired bool `json:"publishAccessRequired" api:"const=true"`+}++func (FullBlockInfo) blockInfoData() {}+func (PublishedBlockInfo) blockInfoData() {}diff --git a/kernel/apicontract/decode.go b/kernel/apicontract/decode.gonew file mode 100644index 0000000000..46b4e87912--- /dev/null+++ b/kernel/apicontract/decode.go@@ -0,0 +1,131 @@+package apicontract++import (+ "bytes"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "reflect"+ "strings"+)++// Decode 按精确的 JSON 字段名绑定请求,缺失、null 和兼容转换由字段声明控制。+func (e Endpoint[Request, Data]) Decode(reader io.Reader) (request Request, err error) {+ if e.definition.Body == NoBody {+ return+ }+ if reader == nil {+ reader = bytes.NewReader(nil)+ }+ var fields map[string]json.RawMessage+ err = json.NewDecoder(reader).Decode(&fields)+ if err != nil {+ if e.definition.Body == LegacyOptionalBody {+ return request, nil+ }+ if errors.Is(err, io.EOF) {+ err = errors.New("the request body is empty or truncated (EOF)")+ }+ return request, fmt.Errorf("Parses request [%s] failed: %s", e.definition.Path, err)+ }+ value := reflect.ValueOf(&request).Elem()+ if value.Kind() != reflect.Struct {+ return request, fmt.Errorf("request contract must be a struct")+ }+ err = decodeRequestFields(value, fields)+ return request, err+}++func decodeRequestFields(value reflect.Value, fields map[string]json.RawMessage) error {+ for i := 0; i < value.NumField(); i++ {+ field := value.Type().Field(i)+ name := strings.Split(field.Tag.Get("json"), ",")[0]+ if (!field.IsExported() && !field.Anonymous) || name == "-" {+ continue+ }+ if field.Anonymous && name == "" {+ if field.Type.Kind() != reflect.Struct {+ return fmt.Errorf("unsupported embedded request field: %s", field.Name)+ }+ if err := decodeRequestFields(value.Field(i), fields); err != nil {+ return err+ }+ continue+ }+ options := "," + field.Tag.Get("api") + ","+ has := func(option string) bool { return strings.Contains(options, ","+option+",") }+ raw, present := fields[name]+ if !present {+ if has("optional") {+ continue+ }+ return fmt.Errorf("Field [%s] is required", name)+ }+ isNull := bytes.Equal(bytes.TrimSpace(raw), []byte("null"))+ if isNull && !has("nullable") && field.Type.Kind() != reflect.Pointer && !has("filterstrings") {+ return fmt.Errorf("Field [%s] must not be null", name)+ }+ if has("filterstrings") {+ var entries []json.RawMessage+ if json.Unmarshal(raw, &entries) == nil {+ var ids []string+ for _, entry := range entries {+ var id string+ if !bytes.Equal(bytes.TrimSpace(entry), []byte("null")) && json.Unmarshal(entry, &id) == nil {+ ids = append(ids, id)+ }+ }+ value.Field(i).Set(reflect.ValueOf(ids))+ }+ continue+ }+ if err := json.Unmarshal(raw, value.Field(i).Addr().Interface()); err != nil {+ if has("ignoretype") {+ continue+ }+ return fmt.Errorf("Field [%s] has an invalid type: %w", name, err)+ }+ if has("trim") {+ trimmed := strings.TrimSpace(value.Field(i).String())+ if trimmed == "" {+ return fmt.Errorf("Field [%s] must not be empty", name)+ }+ value.Field(i).SetString(trimmed)+ }+ for _, option := range strings.Split(field.Tag.Get("api"), ",") {+ if strings.HasPrefix(option, "enum=") {+ if field.Type.Kind() != reflect.String {+ return fmt.Errorf("unsupported enum field: %s", name)+ }+ found := false+ for _, choice := range strings.Split(strings.TrimPrefix(option, "enum="), "|") {+ if value.Field(i).String() == choice {+ found = true+ break+ }+ }+ if !found {+ return fmt.Errorf("Field [%s] has an invalid value", name)+ }+ }+ if strings.HasPrefix(option, "const=") {+ var expected, actual any+ if err := json.Unmarshal([]byte(strings.TrimPrefix(option, "const=")), &expected); err != nil {+ return err+ }+ data, err := json.Marshal(value.Field(i).Interface())+ if err != nil {+ return err+ }+ if err := json.Unmarshal(data, &actual); err != nil {+ return err+ }+ if !reflect.DeepEqual(expected, actual) {+ return fmt.Errorf("Field [%s] has an invalid constant", name)+ }+ }+ }+ }+ return nil+}diff --git a/kernel/apicontract/legacy_routes.json b/kernel/apicontract/legacy_routes.jsonnew file mode 100644index 0000000000..df548bc9f2--- /dev/null+++ b/kernel/apicontract/legacy_routes.json@@ -0,0 +1,619 @@+[+ {"method":"ANY","path":"/api/network/echo","handler":"echo"},+ {"method":"ANY","path":"/api/network/echo/*path","handler":"echo"},+ {"method":"ANY","path":"/api/network/proxy","handler":"httpProxy"},+ {"method":"ANY","path":"/plugin/private/:name/*path","handler":"pluginPrivateWebServer"},+ {"method":"GET","path":"/api/ai/mcp/oauth/callback/:flowID","handler":"mcpOAuthCallback"},+ {"method":"GET","path":"/api/icon/getDynamicIcon","handler":"getDynamicIcon"},+ {"method":"GET","path":"/api/plugin","handler":"listLoadedPlugins"},+ {"method":"GET","path":"/api/plugin/rpc","handler":"getLoadedPlugin"},+ {"method":"GET","path":"/api/plugin/rpc/:name","handler":"getLoadedPlugin"},+ {"method":"GET","path":"/api/system/bootProgress","handler":"bootProgress"},+ {"method":"GET","path":"/api/system/bootProgressSSE","handler":"bootProgressSSE"},+ {"method":"GET","path":"/api/system/getBootAppearance","handler":"getBootAppearance"},+ {"method":"GET","path":"/api/system/getCaptcha","handler":"model.GetCaptcha"},+ {"method":"GET","path":"/api/system/oidc/callback","handler":"model.OIDCCallback"},+ {"method":"GET","path":"/es/broadcast/subscribe","handler":"broadcastSubscribe"},+ {"method":"GET","path":"/es/network/proxy","handler":"esProxy"},+ {"method":"GET","path":"/ws/broadcast","handler":"broadcast"},+ {"method":"GET","path":"/ws/network/proxy","handler":"wsProxy"},+ {"method":"GET","path":"/ws/plugin/rpc","handler":"pluginJsonRpcWebSocket"},+ {"method":"GET","path":"/ws/plugin/rpc/:name","handler":"pluginJsonRpcWebSocket"},+ {"method":"POST","path":"/api/account/checkActivationcode","handler":"checkActivationcode"},+ {"method":"POST","path":"/api/account/deactivate","handler":"deactivateUser"},+ {"method":"POST","path":"/api/account/login","handler":"login"},+ {"method":"POST","path":"/api/account/startFreeTrial","handler":"startFreeTrial"},+ {"method":"POST","path":"/api/account/useActivationcode","handler":"useActivationcode"},+ {"method":"POST","path":"/api/ai/agent/browserCapabilityResult","handler":"agentChatBrowserCapabilityResult"},+ {"method":"POST","path":"/api/ai/agent/chat","handler":"agentChat"},+ {"method":"POST","path":"/api/ai/agent/confirm","handler":"agentChatConfirm"},+ {"method":"POST","path":"/api/ai/agent/getSession","handler":"getSession"},+ {"method":"POST","path":"/api/ai/agent/getSkill","handler":"getSkill"},+ {"method":"POST","path":"/api/ai/agent/lsSessions","handler":"lsSessions"},+ {"method":"POST","path":"/api/ai/agent/lsSkills","handler":"lsSkills"},+ {"method":"POST","path":"/api/ai/agent/lsUserSkills","handler":"lsUserSkills"},+ {"method":"POST","path":"/api/ai/agent/question","handler":"agentChatQuestion"},+ {"method":"POST","path":"/api/ai/agent/removeSession","handler":"removeSession"},+ {"method":"POST","path":"/api/ai/agent/removeSkill","handler":"removeSkill"},+ {"method":"POST","path":"/api/ai/agent/renameSkill","handler":"renameSkill"},+ {"method":"POST","path":"/api/ai/agent/saveSession","handler":"saveSession"},+ {"method":"POST","path":"/api/ai/agent/saveSkill","handler":"saveSkill"},+ {"method":"POST","path":"/api/ai/agent/setPermission","handler":"setAgentSessionPermission"},+ {"method":"POST","path":"/api/ai/agent/title","handler":"agentChatTitle"},+ {"method":"POST","path":"/api/ai/chatGPT","handler":"chatGPT"},+ {"method":"POST","path":"/api/ai/chatGPTWithAction","handler":"chatGPTWithAction"},+ {"method":"POST","path":"/api/ai/editor/chat","handler":"aiEditorChat"},+ {"method":"POST","path":"/api/ai/editor/lsActions","handler":"lsAIEditorActions"},+ {"method":"POST","path":"/api/ai/editor/removeAction","handler":"removeAIEditorAction"},+ {"method":"POST","path":"/api/ai/editor/saveAction","handler":"saveAIEditorAction"},+ {"method":"POST","path":"/api/ai/embeddingStat","handler":"embeddingStat"},+ {"method":"POST","path":"/api/ai/listModels","handler":"listModels"},+ {"method":"POST","path":"/api/ai/lsCapabilities","handler":"lsCapabilities"},+ {"method":"POST","path":"/api/ai/mcpEnvironmentVariables","handler":"mcpEnvironmentVariables"},+ {"method":"POST","path":"/api/ai/mcpOAuthAuthorize","handler":"mcpOAuthAuthorize"},+ {"method":"POST","path":"/api/ai/mcpOAuthDisconnect","handler":"mcpOAuthDisconnect"},+ {"method":"POST","path":"/api/ai/mcpStatus","handler":"mcpStatus"},+ {"method":"POST","path":"/api/ai/reindexEmbedding","handler":"reindexEmbedding"},+ {"method":"POST","path":"/api/ai/retryFailedEmbedding","handler":"retryFailedEmbedding"},+ {"method":"POST","path":"/api/ai/testEmbeddingModel","handler":"testEmbeddingModel"},+ {"method":"POST","path":"/api/ai/testModel","handler":"testModel"},+ {"method":"POST","path":"/api/ai/testRerankModel","handler":"testRerankModel"},+ {"method":"POST","path":"/api/archive/unzip","handler":"unzip"},+ {"method":"POST","path":"/api/archive/zip","handler":"zip"},+ {"method":"POST","path":"/api/asset/fullReindexAssetContent","handler":"fullReindexAssetContent"},+ {"method":"POST","path":"/api/asset/getDocAssets","handler":"getDocAssets"},+ {"method":"POST","path":"/api/asset/getDocImageAssets","handler":"getDocImageAssets"},+ {"method":"POST","path":"/api/asset/getFileAnnotation","handler":"getFileAnnotation"},+ {"method":"POST","path":"/api/asset/getImageOCRText","handler":"getImageOCRText"},+ {"method":"POST","path":"/api/asset/getMissingAssets","handler":"getMissingAssets"},+ {"method":"POST","path":"/api/asset/getUnusedAssets","handler":"getUnusedAssets"},+ {"method":"POST","path":"/api/asset/insertCover","handler":"insertCover"},+ {"method":"POST","path":"/api/asset/insertLocalAssets","handler":"insertLocalAssets"},+ {"method":"POST","path":"/api/asset/ocr","handler":"ocr"},+ {"method":"POST","path":"/api/asset/removeUnusedAsset","handler":"removeUnusedAsset"},+ {"method":"POST","path":"/api/asset/removeUnusedAssets","handler":"removeUnusedAssets"},+ {"method":"POST","path":"/api/asset/renameAsset","handler":"renameAsset"},+ {"method":"POST","path":"/api/asset/resolveAssetPath","handler":"resolveAssetPath"},+ {"method":"POST","path":"/api/asset/setFileAnnotation","handler":"setFileAnnotation"},+ {"method":"POST","path":"/api/asset/setImageOCRText","handler":"setImageOCRText"},+ {"method":"POST","path":"/api/asset/statAsset","handler":"statAsset"},+ {"method":"POST","path":"/api/asset/upload","handler":"model.Upload"},+ {"method":"POST","path":"/api/asset/uploadCloud","handler":"uploadCloud"},+ {"method":"POST","path":"/api/asset/uploadCloudByAssetsPaths","handler":"uploadCloudByAssetsPaths"},+ {"method":"POST","path":"/api/attr/batchGetBlockAttrs","handler":"batchGetBlockAttrs"},+ {"method":"POST","path":"/api/attr/batchSetBlockAttrs","handler":"batchSetBlockAttrs"},+ {"method":"POST","path":"/api/attr/getBookmarkLabels","handler":"getBookmarkLabels"},+ {"method":"POST","path":"/api/attr/resetBlockAttrs","handler":"deprecated"},+ {"method":"POST","path":"/api/av/addAttributeViewBlocks","handler":"addAttributeViewBlocks"},+ {"method":"POST","path":"/api/av/addAttributeViewKey","handler":"addAttributeViewKey"},+ {"method":"POST","path":"/api/av/appendAttributeViewDetachedBlocksWithValues","handler":"appendAttributeViewDetachedBlocksWithValues"},+ {"method":"POST","path":"/api/av/batchReplaceAttributeViewBlocks","handler":"batchReplaceAttributeViewBlocks"},+ {"method":"POST","path":"/api/av/batchSetAttributeViewBlockAttrs","handler":"batchSetAttributeViewBlockAttrs"},+ {"method":"POST","path":"/api/av/changeAttrViewLayout","handler":"changeAttrViewLayout"},+ {"method":"POST","path":"/api/av/createAttributeViewItem","handler":"createAttributeViewItem"},+ {"method":"POST","path":"/api/av/createAttributeViewItemDocs","handler":"createAttributeViewItemDocs"},+ {"method":"POST","path":"/api/av/createAttributeViewItemWithMarkdown","handler":"createAttributeViewItemWithMarkdown"},+ {"method":"POST","path":"/api/av/duplicateAttributeViewBlock","handler":"duplicateAttributeViewBlock"},+ {"method":"POST","path":"/api/av/getAttributeView","handler":"getAttributeView"},+ {"method":"POST","path":"/api/av/getAttributeViewAddingBlockDefaultValues","handler":"getAttributeViewAddingBlockDefaultValues"},+ {"method":"POST","path":"/api/av/getAttributeViewBacklinks","handler":"getAttributeViewBacklinks"},+ {"method":"POST","path":"/api/av/getAttributeViewBoundBlockIDsByItemIDs","handler":"getAttributeViewBoundBlockIDsByItemIDs"},+ {"method":"POST","path":"/api/av/getAttributeViewFieldViews","handler":"getAttributeViewFieldViews"},+ {"method":"POST","path":"/api/av/getAttributeViewFilterSort","handler":"getAttributeViewFilterSort"},+ {"method":"POST","path":"/api/av/getAttributeViewItemIDsByBoundIDs","handler":"getAttributeViewItemIDsByBoundIDs"},+ {"method":"POST","path":"/api/av/getAttributeViewItemStatuses","handler":"getAttributeViewItemStatuses"},+ {"method":"POST","path":"/api/av/getAttributeViewKeys","handler":"getAttributeViewKeys"},+ {"method":"POST","path":"/api/av/getAttributeViewKeysByAvID","handler":"getAttributeViewKeysByAvID"},+ {"method":"POST","path":"/api/av/getAttributeViewKeysByID","handler":"getAttributeViewKeysByID"},+ {"method":"POST","path":"/api/av/getAttributeViewPasteRows","handler":"getAttributeViewPasteRows"},+ {"method":"POST","path":"/api/av/getAttributeViewPrimaryKeyValues","handler":"getAttributeViewPrimaryKeyValues"},+ {"method":"POST","path":"/api/av/getAttributeViewRelationCandidates","handler":"getAttributeViewRelationCandidates"},+ {"method":"POST","path":"/api/av/getAttributeViewRowSort","handler":"getAttributeViewRowSort"},+ {"method":"POST","path":"/api/av/getAttributeViewSearchTarget","handler":"getAttributeViewSearchTarget"},+ {"method":"POST","path":"/api/av/getCurrentAttrViewImages","handler":"getCurrentAttrViewImages"},+ {"method":"POST","path":"/api/av/getMirrorDatabaseBlocks","handler":"getMirrorDatabaseBlocks"},+ {"method":"POST","path":"/api/av/getUnusedAttributeViews","handler":"getUnusedAttributeViews"},+ {"method":"POST","path":"/api/av/removeAttributeViewBlocks","handler":"removeAttributeViewBlocks"},+ {"method":"POST","path":"/api/av/removeAttributeViewKey","handler":"removeAttributeViewKey"},+ {"method":"POST","path":"/api/av/removeUnusedAttributeView","handler":"removeUnusedAttributeView"},+ {"method":"POST","path":"/api/av/removeUnusedAttributeViews","handler":"removeUnusedAttributeViews"},+ {"method":"POST","path":"/api/av/renderAttributeView","handler":"renderAttributeView"},+ {"method":"POST","path":"/api/av/renderHistoryAttributeView","handler":"renderHistoryAttributeView"},+ {"method":"POST","path":"/api/av/renderSnapshotAttributeView","handler":"renderSnapshotAttributeView"},+ {"method":"POST","path":"/api/av/searchAttributeView","handler":"searchAttributeView"},+ {"method":"POST","path":"/api/av/searchAttributeViewNonRelationKey","handler":"deprecated"},+ {"method":"POST","path":"/api/av/searchAttributeViewRelationKey","handler":"searchAttributeViewRelationKey"},+ {"method":"POST","path":"/api/av/searchAttributeViewRollupDestKeys","handler":"searchAttributeViewRollupDestKeys"},+ {"method":"POST","path":"/api/av/setAttrViewContextFilter","handler":"setAttrViewContextFilter"},+ {"method":"POST","path":"/api/av/setAttrViewFilters","handler":"setAttrViewFilters"},+ {"method":"POST","path":"/api/av/setAttrViewGroup","handler":"setAttrViewGroup"},+ {"method":"POST","path":"/api/av/setAttrViewSorts","handler":"setAttrViewSorts"},+ {"method":"POST","path":"/api/av/setAttributeViewBlockAttr","handler":"setAttributeViewBlockAttr"},+ {"method":"POST","path":"/api/av/setDatabaseBlockView","handler":"setDatabaseBlockView"},+ {"method":"POST","path":"/api/av/sortAttributeViewKey","handler":"sortAttributeViewKey"},+ {"method":"POST","path":"/api/av/sortAttributeViewViewKey","handler":"sortAttributeViewViewKey"},+ {"method":"POST","path":"/api/bazaar/batchUpdatePackage","handler":"batchUpdatePackage"},+ {"method":"POST","path":"/api/bazaar/getBazaarIcon","handler":"getBazaarIcon"},+ {"method":"POST","path":"/api/bazaar/getBazaarPackage","handler":"getBazaarPackage"},+ {"method":"POST","path":"/api/bazaar/getBazaarPackageREADME","handler":"getBazaarPackageREADME"},+ {"method":"POST","path":"/api/bazaar/getBazaarPackageRating","handler":"getBazaarPackageRating"},+ {"method":"POST","path":"/api/bazaar/getBazaarPackageRatings","handler":"getBazaarPackageRatings"},+ {"method":"POST","path":"/api/bazaar/getBazaarPackageUserRatings","handler":"getBazaarPackageUserRatings"},+ {"method":"POST","path":"/api/bazaar/getBazaarPlugin","handler":"getBazaarPlugin"},+ {"method":"POST","path":"/api/bazaar/getBazaarTemplate","handler":"getBazaarTemplate"},+ {"method":"POST","path":"/api/bazaar/getBazaarTheme","handler":"getBazaarTheme"},+ {"method":"POST","path":"/api/bazaar/getBazaarWidget","handler":"getBazaarWidget"},+ {"method":"POST","path":"/api/bazaar/getInstalledIcon","handler":"getInstalledIcon"},+ {"method":"POST","path":"/api/bazaar/getInstalledPackageSize","handler":"getInstalledPackageSize"},+ {"method":"POST","path":"/api/bazaar/getInstalledPlugin","handler":"getInstalledPlugin"},+ {"method":"POST","path":"/api/bazaar/getInstalledTemplate","handler":"getInstalledTemplate"},+ {"method":"POST","path":"/api/bazaar/getInstalledTheme","handler":"getInstalledTheme"},+ {"method":"POST","path":"/api/bazaar/getInstalledWidget","handler":"getInstalledWidget"},+ {"method":"POST","path":"/api/bazaar/getUpdatedPackage","handler":"getUpdatedPackage"},+ {"method":"POST","path":"/api/bazaar/installBazaarIcon","handler":"installBazaarIcon"},+ {"method":"POST","path":"/api/bazaar/installBazaarPlugin","handler":"installBazaarPlugin"},+ {"method":"POST","path":"/api/bazaar/installBazaarTemplate","handler":"installBazaarTemplate"},+ {"method":"POST","path":"/api/bazaar/installBazaarTheme","handler":"installBazaarTheme"},+ {"method":"POST","path":"/api/bazaar/installBazaarWidget","handler":"installBazaarWidget"},+ {"method":"POST","path":"/api/bazaar/installLocalBazaarPackage","handler":"installLocalBazaarPackage"},+ {"method":"POST","path":"/api/bazaar/setBazaarPackageRating","handler":"setBazaarPackageRating"},+ {"method":"POST","path":"/api/bazaar/uninstallBazaarIcon","handler":"uninstallBazaarIcon"},+ {"method":"POST","path":"/api/bazaar/uninstallBazaarPlugin","handler":"uninstallBazaarPlugin"},+ {"method":"POST","path":"/api/bazaar/uninstallBazaarTemplate","handler":"uninstallBazaarTemplate"},+ {"method":"POST","path":"/api/bazaar/uninstallBazaarTheme","handler":"uninstallBazaarTheme"},+ {"method":"POST","path":"/api/bazaar/uninstallBazaarWidget","handler":"uninstallBazaarWidget"},+ {"method":"POST","path":"/api/bazaar/updateBazaarPackage","handler":"updateBazaarPackage"},+ {"method":"POST","path":"/api/block/appendBlock","handler":"appendBlock"},+ {"method":"POST","path":"/api/block/appendDailyNoteBlock","handler":"appendDailyNoteBlock"},+ {"method":"POST","path":"/api/block/appendHeadingChildren","handler":"appendHeadingChildren"},+ {"method":"POST","path":"/api/block/batchAppendBlock","handler":"batchAppendBlock"},+ {"method":"POST","path":"/api/block/batchInsertBlock","handler":"batchInsertBlock"},+ {"method":"POST","path":"/api/block/batchPrependBlock","handler":"batchPrependBlock"},+ {"method":"POST","path":"/api/block/batchUpdateBlock","handler":"batchUpdateBlock"},+ {"method":"POST","path":"/api/block/batchUpdateTaskListItemMarker","handler":"batchUpdateTaskListItemMarker"},+ {"method":"POST","path":"/api/block/checkBlockExist","handler":"checkBlockExist"},+ {"method":"POST","path":"/api/block/checkBlockFold","handler":"checkBlockFold"},+ {"method":"POST","path":"/api/block/checkBlockRef","handler":"checkBlockRef"},+ {"method":"POST","path":"/api/block/checkBlocksExist","handler":"checkBlocksExist"},+ {"method":"POST","path":"/api/block/deleteBlock","handler":"deleteBlock"},+ {"method":"POST","path":"/api/block/foldBlock","handler":"foldBlock"},+ {"method":"POST","path":"/api/block/getBlockBreadcrumb","handler":"getBlockBreadcrumb"},+ {"method":"POST","path":"/api/block/getBlockBreadcrumbChildren","handler":"getBlockBreadcrumbChildren"},+ {"method":"POST","path":"/api/block/getBlockDOM","handler":"getBlockDOM"},+ {"method":"POST","path":"/api/block/getBlockDOMWithEmbed","handler":"getBlockDOMWithEmbed"},+ {"method":"POST","path":"/api/block/getBlockDOMs","handler":"getBlockDOMs"},+ {"method":"POST","path":"/api/block/getBlockDOMsWithEmbed","handler":"getBlockDOMsWithEmbed"},+ {"method":"POST","path":"/api/block/getBlockDefIDsByRefText","handler":"getBlockDefIDsByRefText"},+ {"method":"POST","path":"/api/block/getBlockIndex","handler":"getBlockIndex"},+ {"method":"POST","path":"/api/block/getBlockKramdown","handler":"getBlockKramdown"},+ {"method":"POST","path":"/api/block/getBlockKramdowns","handler":"getBlockKramdowns"},+ {"method":"POST","path":"/api/block/getBlockRelevantIDs","handler":"getBlockRelevantIDs"},+ {"method":"POST","path":"/api/block/getBlockSiblingID","handler":"getBlockSiblingID"},+ {"method":"POST","path":"/api/block/getBlockTreeInfos","handler":"getBlockTreeInfos"},+ {"method":"POST","path":"/api/block/getBlocksIndexes","handler":"getBlocksIndexes"},+ {"method":"POST","path":"/api/block/getBlocksWordCount","handler":"getBlocksWordCount"},+ {"method":"POST","path":"/api/block/getChildBlocks","handler":"getChildBlocks"},+ {"method":"POST","path":"/api/block/getContentWordCount","handler":"getContentWordCount"},+ {"method":"POST","path":"/api/block/getDOMText","handler":"getDOMText"},+ {"method":"POST","path":"/api/block/getDocBlocksOrders","handler":"getDocBlocksOrders"},+ {"method":"POST","path":"/api/block/getDocHeadingLevelTransaction","handler":"getDocHeadingLevelTransaction"},+ {"method":"POST","path":"/api/block/getDocInfo","handler":"getDocInfo"},+ {"method":"POST","path":"/api/block/getDocsInfo","handler":"getDocsInfo"},+ {"method":"POST","path":"/api/block/getHeadingChildrenDOM","handler":"getHeadingChildrenDOM"},+ {"method":"POST","path":"/api/block/getHeadingChildrenIDs","handler":"getHeadingChildrenIDs"},+ {"method":"POST","path":"/api/block/getHeadingDeleteTransaction","handler":"getHeadingDeleteTransaction"},+ {"method":"POST","path":"/api/block/getHeadingFoldTransaction","handler":"getHeadingFoldTransaction"},+ {"method":"POST","path":"/api/block/getHeadingInsertTransaction","handler":"getHeadingInsertTransaction"},+ {"method":"POST","path":"/api/block/getHeadingLevelTransaction","handler":"getHeadingLevelTransaction"},+ {"method":"POST","path":"/api/block/getOrderedListContinueStart","handler":"getOrderedListContinueStart"},+ {"method":"POST","path":"/api/block/getRecentUpdatedBlocks","handler":"getRecentUpdatedBlocks"},+ {"method":"POST","path":"/api/block/getRefIDs","handler":"getRefIDs"},+ {"method":"POST","path":"/api/block/getRefIDsByFileAnnotationID","handler":"getRefIDsByFileAnnotationID"},+ {"method":"POST","path":"/api/block/getRefText","handler":"getRefText"},+ {"method":"POST","path":"/api/block/getTailChildBlocks","handler":"getTailChildBlocks"},+ {"method":"POST","path":"/api/block/getTreeStat","handler":"getTreeStat"},+ {"method":"POST","path":"/api/block/getUnfoldedParentID","handler":"getUnfoldedParentID"},+ {"method":"POST","path":"/api/block/insertBlock","handler":"insertBlock"},+ {"method":"POST","path":"/api/block/moveBlock","handler":"moveBlock"},+ {"method":"POST","path":"/api/block/moveOutlineHeading","handler":"moveOutlineHeading"},+ {"method":"POST","path":"/api/block/prependBlock","handler":"prependBlock"},+ {"method":"POST","path":"/api/block/prependDailyNoteBlock","handler":"prependDailyNoteBlock"},+ {"method":"POST","path":"/api/block/setBlockReminder","handler":"setBlockReminder"},+ {"method":"POST","path":"/api/block/swapBlockRef","handler":"swapBlockRef"},+ {"method":"POST","path":"/api/block/transferBlockRef","handler":"transferBlockRef"},+ {"method":"POST","path":"/api/block/unfoldBlock","handler":"unfoldBlock"},+ {"method":"POST","path":"/api/block/updateBlock","handler":"updateBlock"},+ {"method":"POST","path":"/api/block/updateTaskListItemMarker","handler":"updateTaskListItemMarker"},+ {"method":"POST","path":"/api/bookmark/getBookmark","handler":"getBookmark"},+ {"method":"POST","path":"/api/bookmark/removeBookmark","handler":"removeBookmark"},+ {"method":"POST","path":"/api/bookmark/renameBookmark","handler":"renameBookmark"},+ {"method":"POST","path":"/api/broadcast/getChannelInfo","handler":"getChannelInfo"},+ {"method":"POST","path":"/api/broadcast/getChannels","handler":"getChannels"},+ {"method":"POST","path":"/api/broadcast/postMessage","handler":"postMessage"},+ {"method":"POST","path":"/api/broadcast/publish","handler":"broadcastPublish"},+ {"method":"POST","path":"/api/clipboard/cleanupRichText","handler":"cleanupRichText"},+ {"method":"POST","path":"/api/clipboard/prepareRichText","handler":"prepareRichText"},+ {"method":"POST","path":"/api/clipboard/readFilePaths","handler":"readFilePaths"},+ {"method":"POST","path":"/api/clipboard/writeFilePath","handler":"writeFilePath"},+ {"method":"POST","path":"/api/cloud/getCloudSpace","handler":"getCloudSpace"},+ {"method":"POST","path":"/api/cloud/setCloudReminder","handler":"setCloudReminder"},+ {"method":"POST","path":"/api/convert/pandoc","handler":"pandoc"},+ {"method":"POST","path":"/api/export/copyExportFile","handler":"copyExportFile"},+ {"method":"POST","path":"/api/export/export2Liandi","handler":"export2Liandi"},+ {"method":"POST","path":"/api/export/exportAsFile","handler":"exportAsFile"},+ {"method":"POST","path":"/api/export/exportAsciiDoc","handler":"exportAsciiDoc"},+ {"method":"POST","path":"/api/export/exportAttributeView","handler":"exportAttributeView"},+ {"method":"POST","path":"/api/export/exportBrowserHTML","handler":"exportBrowserHTML"},+ {"method":"POST","path":"/api/export/exportCodeBlock","handler":"exportCodeBlock"},+ {"method":"POST","path":"/api/export/exportData","handler":"exportData"},+ {"method":"POST","path":"/api/export/exportDataInFolder","handler":"exportDataInFolder"},+ {"method":"POST","path":"/api/export/exportDocx","handler":"exportDocx"},+ {"method":"POST","path":"/api/export/exportEPUB","handler":"exportEPUB"},+ {"method":"POST","path":"/api/export/exportHTML","handler":"exportHTML"},+ {"method":"POST","path":"/api/export/exportMd","handler":"exportMd"},+ {"method":"POST","path":"/api/export/exportMdContent","handler":"exportMdContent"},+ {"method":"POST","path":"/api/export/exportMdHTML","handler":"exportMdHTML"},+ {"method":"POST","path":"/api/export/exportMds","handler":"exportMds"},+ {"method":"POST","path":"/api/export/exportMediaWiki","handler":"exportMediaWiki"},+ {"method":"POST","path":"/api/export/exportNotebookMd","handler":"exportNotebookMd"},+ {"method":"POST","path":"/api/export/exportNotebookSY","handler":"exportNotebookSY"},+ {"method":"POST","path":"/api/export/exportNotebooksMd","handler":"exportNotebooksMd"},+ {"method":"POST","path":"/api/export/exportNotebooksSY","handler":"exportNotebooksSY"},+ {"method":"POST","path":"/api/export/exportODT","handler":"exportODT"},+ {"method":"POST","path":"/api/export/exportOPML","handler":"exportOPML"},+ {"method":"POST","path":"/api/export/exportOrgMode","handler":"exportOrgMode"},+ {"method":"POST","path":"/api/export/exportPreviewHTML","handler":"exportPreviewHTML"},+ {"method":"POST","path":"/api/export/exportRTF","handler":"exportRTF"},+ {"method":"POST","path":"/api/export/exportReStructuredText","handler":"exportReStructuredText"},+ {"method":"POST","path":"/api/export/exportResources","handler":"exportResources"},+ {"method":"POST","path":"/api/export/exportSY","handler":"exportSY"},+ {"method":"POST","path":"/api/export/exportSYs","handler":"exportSYs"},+ {"method":"POST","path":"/api/export/exportTempContent","handler":"exportTempContent"},+ {"method":"POST","path":"/api/export/exportTextile","handler":"exportTextile"},+ {"method":"POST","path":"/api/export/preview","handler":"exportPreview"},+ {"method":"POST","path":"/api/export/processPDF","handler":"processPDF"},+ {"method":"POST","path":"/api/extension/copy","handler":"extensionCopy"},+ {"method":"POST","path":"/api/file/copyFile","handler":"copyFile"},+ {"method":"POST","path":"/api/file/getFile","handler":"getFile"},+ {"method":"POST","path":"/api/file/getUniqueFilename","handler":"getUniqueFilename"},+ {"method":"POST","path":"/api/file/globalCopyFiles","handler":"globalCopyFiles"},+ {"method":"POST","path":"/api/file/putFile","handler":"putFile"},+ {"method":"POST","path":"/api/file/readDir","handler":"readDir"},+ {"method":"POST","path":"/api/file/removeFile","handler":"removeFile"},+ {"method":"POST","path":"/api/file/renameFile","handler":"renameFile"},+ {"method":"POST","path":"/api/file/workspaceCopyFiles","handler":"workspaceCopyFiles"},+ {"method":"POST","path":"/api/filetree/authFilePublishAccess","handler":"authFilePublishAccess"},+ {"method":"POST","path":"/api/filetree/changeSort","handler":"changeSort"},+ {"method":"POST","path":"/api/filetree/createDailyNote","handler":"createDailyNote"},+ {"method":"POST","path":"/api/filetree/createDoc","handler":"createDoc"},+ {"method":"POST","path":"/api/filetree/createDocWithMd","handler":"createDocWithMd"},+ {"method":"POST","path":"/api/filetree/doc2Heading","handler":"doc2Heading"},+ {"method":"POST","path":"/api/filetree/duplicateDoc","handler":"duplicateDoc"},+ {"method":"POST","path":"/api/filetree/getDoc","handler":"getDoc"},+ {"method":"POST","path":"/api/filetree/getDocCreateSavePath","handler":"getDocCreateSavePath"},+ {"method":"POST","path":"/api/filetree/getFullHPathByID","handler":"getFullHPathByID"},+ {"method":"POST","path":"/api/filetree/getHPathByID","handler":"getHPathByID"},+ {"method":"POST","path":"/api/filetree/getHPathByPath","handler":"getHPathByPath"},+ {"method":"POST","path":"/api/filetree/getHPathsByPaths","handler":"getHPathsByPaths"},+ {"method":"POST","path":"/api/filetree/getIDsByHPath","handler":"getIDsByHPath"},+ {"method":"POST","path":"/api/filetree/getPathByID","handler":"getPathByID"},+ {"method":"POST","path":"/api/filetree/getPublishAccess","handler":"getPublishAccess"},+ {"method":"POST","path":"/api/filetree/getRefCreateSavePath","handler":"getRefCreateSavePath"},+ {"method":"POST","path":"/api/filetree/getShorthandSavePath","handler":"getShorthandSavePath"},+ {"method":"POST","path":"/api/filetree/heading2Doc","handler":"heading2Doc"},+ {"method":"POST","path":"/api/filetree/li2Doc","handler":"li2Doc"},+ {"method":"POST","path":"/api/filetree/listDocTree","handler":"listDocTree"},+ {"method":"POST","path":"/api/filetree/listDocsByPath","handler":"listDocsByPath"},+ {"method":"POST","path":"/api/filetree/moveDocs","handler":"moveDocs"},+ {"method":"POST","path":"/api/filetree/moveDocsByID","handler":"moveDocsByID"},+ {"method":"POST","path":"/api/filetree/moveLocalShorthands","handler":"moveLocalShorthands"},+ {"method":"POST","path":"/api/filetree/removeDoc","handler":"removeDoc"},+ {"method":"POST","path":"/api/filetree/removeDocByID","handler":"removeDocByID"},+ {"method":"POST","path":"/api/filetree/removeDocs","handler":"removeDocs"},+ {"method":"POST","path":"/api/filetree/removeIndexes","handler":"removeIndexes"},+ {"method":"POST","path":"/api/filetree/renameDoc","handler":"renameDoc"},+ {"method":"POST","path":"/api/filetree/renameDocByID","handler":"renameDocByID"},+ {"method":"POST","path":"/api/filetree/reorderDocs","handler":"reorderDocs"},+ {"method":"POST","path":"/api/filetree/searchDocs","handler":"searchDocs"},+ {"method":"POST","path":"/api/filetree/setDocSortMode","handler":"setDocSortMode"},+ {"method":"POST","path":"/api/filetree/setPublishAccess","handler":"setPublishAccess"},+ {"method":"POST","path":"/api/filetree/setSort","handler":"setSort"},+ {"method":"POST","path":"/api/filetree/upsertIndexes","handler":"upsertIndexes"},+ {"method":"POST","path":"/api/format/autoSpace","handler":"autoSpace"},+ {"method":"POST","path":"/api/format/netAssets2LocalAssets","handler":"netAssets2LocalAssets"},+ {"method":"POST","path":"/api/format/netImg2LocalAssets","handler":"netImg2LocalAssets"},+ {"method":"POST","path":"/api/graph/getGraph","handler":"getGraph"},+ {"method":"POST","path":"/api/graph/getLocalGraph","handler":"getLocalGraph"},+ {"method":"POST","path":"/api/graph/resetGraph","handler":"resetGraph"},+ {"method":"POST","path":"/api/graph/resetLocalGraph","handler":"resetLocalGraph"},+ {"method":"POST","path":"/api/graph/setGraphConf","handler":"setGraphConf"},+ {"method":"POST","path":"/api/history/clearWorkspaceHistory","handler":"clearWorkspaceHistory"},+ {"method":"POST","path":"/api/history/createAssetHistory","handler":"createAssetHistory"},+ {"method":"POST","path":"/api/history/createDocHistory","handler":"createDocHistory"},+ {"method":"POST","path":"/api/history/diffDocVersions","handler":"diffDocVersions"},+ {"method":"POST","path":"/api/history/getDocHistoryContent","handler":"getDocHistoryContent"},+ {"method":"POST","path":"/api/history/getHistoryItems","handler":"getHistoryItems"},+ {"method":"POST","path":"/api/history/getNotebookHistory","handler":"getNotebookHistory"},+ {"method":"POST","path":"/api/history/reindexHistory","handler":"reindexHistory"},+ {"method":"POST","path":"/api/history/rollbackAssetsHistory","handler":"rollbackAssetsHistory"},+ {"method":"POST","path":"/api/history/rollbackAttributeViewHistory","handler":"rollbackAttributeViewHistory"},+ {"method":"POST","path":"/api/history/rollbackDocHistory","handler":"rollbackDocHistory"},+ {"method":"POST","path":"/api/history/rollbackNotebookHistory","handler":"rollbackNotebookHistory"},+ {"method":"POST","path":"/api/import/cancelImportSY","handler":"cancelImportSY"},+ {"method":"POST","path":"/api/import/cancelObsidianVaultTask","handler":"cancelObsidianVaultTask"},+ {"method":"POST","path":"/api/import/continueImportSY","handler":"continueImportSY"},+ {"method":"POST","path":"/api/import/getObsidianVaultTask","handler":"getObsidianVaultTask"},+ {"method":"POST","path":"/api/import/importData","handler":"importData"},+ {"method":"POST","path":"/api/import/importSY","handler":"importSY"},+ {"method":"POST","path":"/api/import/importSYAuto","handler":"importSYAuto"},+ {"method":"POST","path":"/api/import/importSYNotebook","handler":"importSYNotebook"},+ {"method":"POST","path":"/api/import/importStdMd","handler":"importStdMd"},+ {"method":"POST","path":"/api/import/importZipMd","handler":"importZipMd"},+ {"method":"POST","path":"/api/import/startObsidianVaultAnalysis","handler":"startObsidianVaultAnalysis"},+ {"method":"POST","path":"/api/import/startObsidianVaultImport","handler":"startObsidianVaultImport"},+ {"method":"POST","path":"/api/inbox/getShorthand","handler":"getShorthand"},+ {"method":"POST","path":"/api/inbox/getShorthands","handler":"getShorthands"},+ {"method":"POST","path":"/api/inbox/removeShorthands","handler":"removeShorthands"},+ {"method":"POST","path":"/api/lute/copyStdMarkdown","handler":"copyStdMarkdown"},+ {"method":"POST","path":"/api/lute/html2BlockDOM","handler":"html2BlockDOM"},+ {"method":"POST","path":"/api/lute/md2html","handler":"md2HTML"},+ {"method":"POST","path":"/api/lute/spinBlockDOM","handler":"spinBlockDOM"},+ {"method":"POST","path":"/api/lute/wpsPresentation2BlockDOM","handler":"wpsPresentation2BlockDOM"},+ {"method":"POST","path":"/api/network/forwardProxy","handler":"forwardProxy"},+ {"method":"POST","path":"/api/notebook/changeMasterPassword","handler":"changeMasterPassword"},+ {"method":"POST","path":"/api/notebook/changeSortNotebook","handler":"changeSortNotebook"},+ {"method":"POST","path":"/api/notebook/closeNotebook","handler":"closeNotebook"},+ {"method":"POST","path":"/api/notebook/createEncryptedNotebook","handler":"createEncryptedNotebook"},+ {"method":"POST","path":"/api/notebook/createNotebook","handler":"createNotebook"},+ {"method":"POST","path":"/api/notebook/disableEncryptedNotebooks","handler":"disableEncryptedNotebooks"},+ {"method":"POST","path":"/api/notebook/enableEncryptedNotebooks","handler":"enableEncryptedNotebooks"},+ {"method":"POST","path":"/api/notebook/exportNotebookCryptoBackup","handler":"exportNotebookCryptoBackup"},+ {"method":"POST","path":"/api/notebook/getEncryptedNotebookStatus","handler":"getEncryptedNotebookStatus"},+ {"method":"POST","path":"/api/notebook/getNotebookConf","handler":"getNotebookConf"},+ {"method":"POST","path":"/api/notebook/getNotebookInfo","handler":"getNotebookInfo"},+ {"method":"POST","path":"/api/notebook/importNotebookCryptoBackup","handler":"importNotebookCryptoBackup"},+ {"method":"POST","path":"/api/notebook/lockNotebook","handler":"lockNotebook"},+ {"method":"POST","path":"/api/notebook/openNotebook","handler":"openNotebook"},+ {"method":"POST","path":"/api/notebook/removeNotebook","handler":"removeNotebook"},+ {"method":"POST","path":"/api/notebook/renameNotebook","handler":"renameNotebook"},+ {"method":"POST","path":"/api/notebook/reorder","handler":"reorderNotebooks"},+ {"method":"POST","path":"/api/notebook/setNotebookConf","handler":"setNotebookConf"},+ {"method":"POST","path":"/api/notebook/setNotebookCryptoAutoLock","handler":"setNotebookCryptoAutoLock"},+ {"method":"POST","path":"/api/notebook/setNotebookIcon","handler":"setNotebookIcon"},+ {"method":"POST","path":"/api/notebook/touchEncryptedNotebooks","handler":"touchEncryptedNotebooks"},+ {"method":"POST","path":"/api/notebook/unlockAndOpenNotebook","handler":"unlockAndOpenNotebook"},+ {"method":"POST","path":"/api/notebook/unlockNotebook","handler":"unlockNotebook"},+ {"method":"POST","path":"/api/notification/pushErrMsg","handler":"pushErrMsg"},+ {"method":"POST","path":"/api/notification/pushMsg","handler":"pushMsg"},+ {"method":"POST","path":"/api/outline/getDocHeadingNumbers","handler":"getDocHeadingNumbers"},+ {"method":"POST","path":"/api/outline/getDocOutline","handler":"getDocOutline"},+ {"method":"POST","path":"/api/petal/loadPetals","handler":"loadPetals"},+ {"method":"POST","path":"/api/petal/setPetalEnabled","handler":"setPetalEnabled"},+ {"method":"POST","path":"/api/petal/setPetalPublishEnabled","handler":"setPetalPublishEnabled"},+ {"method":"POST","path":"/api/plugin/getLoadedPlugin","handler":"getLoadedPlugin"},+ {"method":"POST","path":"/api/plugin/listLoadedPlugins","handler":"listLoadedPlugins"},+ {"method":"POST","path":"/api/plugin/rpc","handler":"pluginJsonRpcHttp"},+ {"method":"POST","path":"/api/plugin/rpc/:name","handler":"pluginJsonRpcHttp"},+ {"method":"POST","path":"/api/query/sql","handler":"SQL"},+ {"method":"POST","path":"/api/ref/getBacklink2","handler":"getBacklink2"},+ {"method":"POST","path":"/api/ref/getBacklinkDoc","handler":"getBacklinkDoc"},+ {"method":"POST","path":"/api/ref/getBackmentionDoc","handler":"getBackmentionDoc"},+ {"method":"POST","path":"/api/ref/refreshBacklink","handler":"refreshBacklink"},+ {"method":"POST","path":"/api/repo/checkoutRepo","handler":"checkoutRepo"},+ {"method":"POST","path":"/api/repo/createSnapshot","handler":"createSnapshot"},+ {"method":"POST","path":"/api/repo/diffRepoSnapshots","handler":"diffRepoSnapshots"},+ {"method":"POST","path":"/api/repo/downloadCloudSnapshot","handler":"downloadCloudSnapshot"},+ {"method":"POST","path":"/api/repo/exportRepoFile","handler":"exportRepoFile"},+ {"method":"POST","path":"/api/repo/getCloudRepoSnapshots","handler":"getCloudRepoSnapshots"},+ {"method":"POST","path":"/api/repo/getCloudRepoTagSnapshots","handler":"getCloudRepoTagSnapshots"},+ {"method":"POST","path":"/api/repo/getRepoDocHistory","handler":"getRepoDocHistory"},+ {"method":"POST","path":"/api/repo/getRepoFile","handler":"getRepoFile"},+ {"method":"POST","path":"/api/repo/getRepoSnapshots","handler":"getRepoSnapshots"},+ {"method":"POST","path":"/api/repo/getRepoTagSnapshots","handler":"getRepoTagSnapshots"},+ {"method":"POST","path":"/api/repo/importRepoKey","handler":"importRepoKey"},+ {"method":"POST","path":"/api/repo/initRepoKey","handler":"initRepoKey"},+ {"method":"POST","path":"/api/repo/initRepoKeyFromPassphrase","handler":"initRepoKeyFromPassphrase"},+ {"method":"POST","path":"/api/repo/openRepoSnapshotFile","handler":"openRepoSnapshotFile"},+ {"method":"POST","path":"/api/repo/purgeCloudRepo","handler":"purgeCloudRepo"},+ {"method":"POST","path":"/api/repo/purgeRepo","handler":"purgeRepo"},+ {"method":"POST","path":"/api/repo/removeCloudRepoTagSnapshot","handler":"removeCloudRepoTagSnapshot"},+ {"method":"POST","path":"/api/repo/removeRepoTagSnapshot","handler":"removeRepoTagSnapshot"},+ {"method":"POST","path":"/api/repo/resetRepo","handler":"resetRepo"},+ {"method":"POST","path":"/api/repo/rollbackRepoSnapshotFile","handler":"rollbackRepoSnapshotFile"},+ {"method":"POST","path":"/api/repo/searchRepoFile","handler":"searchRepoFile"},+ {"method":"POST","path":"/api/repo/setRepoIndexRetentionDays","handler":"setRepoIndexRetentionDays"},+ {"method":"POST","path":"/api/repo/setRetentionIndexesDaily","handler":"setRetentionIndexesDaily"},+ {"method":"POST","path":"/api/repo/tagSnapshot","handler":"tagSnapshot"},+ {"method":"POST","path":"/api/repo/uploadCloudSnapshot","handler":"uploadCloudSnapshot"},+ {"method":"POST","path":"/api/riff/addRiffCards","handler":"addRiffCards"},+ {"method":"POST","path":"/api/riff/batchSetRiffCardsDueTime","handler":"batchSetRiffCardsDueTime"},+ {"method":"POST","path":"/api/riff/createRiffDeck","handler":"createRiffDeck"},+ {"method":"POST","path":"/api/riff/getNotebookRiffCards","handler":"getNotebookRiffCards"},+ {"method":"POST","path":"/api/riff/getNotebookRiffDueCards","handler":"getNotebookRiffDueCards"},+ {"method":"POST","path":"/api/riff/getRiffCards","handler":"getRiffCards"},+ {"method":"POST","path":"/api/riff/getRiffCardsByBlockIDs","handler":"getRiffCardsByBlockIDs"},+ {"method":"POST","path":"/api/riff/getRiffDecks","handler":"getRiffDecks"},+ {"method":"POST","path":"/api/riff/getRiffDueCards","handler":"getRiffDueCards"},+ {"method":"POST","path":"/api/riff/getTreeRiffCards","handler":"getTreeRiffCards"},+ {"method":"POST","path":"/api/riff/getTreeRiffDueCards","handler":"getTreeRiffDueCards"},+ {"method":"POST","path":"/api/riff/removeRiffCards","handler":"removeRiffCards"},+ {"method":"POST","path":"/api/riff/removeRiffDeck","handler":"removeRiffDeck"},+ {"method":"POST","path":"/api/riff/renameRiffDeck","handler":"renameRiffDeck"},+ {"method":"POST","path":"/api/riff/resetRiffCards","handler":"resetRiffCards"},+ {"method":"POST","path":"/api/riff/reviewRiffCard","handler":"reviewRiffCard"},+ {"method":"POST","path":"/api/riff/skipReviewRiffCard","handler":"skipReviewRiffCard"},+ {"method":"POST","path":"/api/search/findReplace","handler":"findReplace"},+ {"method":"POST","path":"/api/search/fullTextSearchAssetContent","handler":"fullTextSearchAssetContent"},+ {"method":"POST","path":"/api/search/fullTextSearchBlock","handler":"fullTextSearchBlock"},+ {"method":"POST","path":"/api/search/getAssetContent","handler":"getAssetContent"},+ {"method":"POST","path":"/api/search/getAssetContentByPath","handler":"getAssetContentByPath"},+ {"method":"POST","path":"/api/search/getEmbedBlock","handler":"getEmbedBlock"},+ {"method":"POST","path":"/api/search/listInvalidBlockRefs","handler":"listInvalidBlockRefs"},+ {"method":"POST","path":"/api/search/removeTemplate","handler":"removeTemplate"},+ {"method":"POST","path":"/api/search/searchAsset","handler":"searchAsset"},+ {"method":"POST","path":"/api/search/searchEmbedBlock","handler":"searchEmbedBlock"},+ {"method":"POST","path":"/api/search/searchRefBlock","handler":"searchRefBlock"},+ {"method":"POST","path":"/api/search/searchTemplate","handler":"searchTemplate"},+ {"method":"POST","path":"/api/search/searchWidget","handler":"searchWidget"},+ {"method":"POST","path":"/api/search/semanticSearchBlock","handler":"semanticSearchBlock"},+ {"method":"POST","path":"/api/search/updateEmbedBlock","handler":"updateEmbedBlock"},+ {"method":"POST","path":"/api/setting/addVirtualBlockRefExclude","handler":"addVirtualBlockRefExclude"},+ {"method":"POST","path":"/api/setting/addVirtualBlockRefInclude","handler":"addVirtualBlockRefInclude"},+ {"method":"POST","path":"/api/setting/getBootAppearances","handler":"getBootAppearances"},+ {"method":"POST","path":"/api/setting/getCloudUser","handler":"getCloudUser"},+ {"method":"POST","path":"/api/setting/getPandocBin","handler":"getPandocBin"},+ {"method":"POST","path":"/api/setting/getPublish","handler":"getPublish"},+ {"method":"POST","path":"/api/setting/login2faCloudUser","handler":"login2faCloudUser"},+ {"method":"POST","path":"/api/setting/logoutCloudUser","handler":"logoutCloudUser"},+ {"method":"POST","path":"/api/setting/refreshVirtualBlockRef","handler":"refreshVirtualBlockRef"},+ {"method":"POST","path":"/api/setting/setAI","handler":"setAI"},+ {"method":"POST","path":"/api/setting/setAppearance","handler":"setAppearance"},+ {"method":"POST","path":"/api/setting/setBazaar","handler":"setBazaar"},+ {"method":"POST","path":"/api/setting/setBazaarPetalDisabled","handler":"setBazaarPetalDisabled"},+ {"method":"POST","path":"/api/setting/setBootAppearance","handler":"setBootAppearance"},+ {"method":"POST","path":"/api/setting/setEditor","handler":"setEditor"},+ {"method":"POST","path":"/api/setting/setEditorReadOnly","handler":"setEditorReadOnly"},+ {"method":"POST","path":"/api/setting/setEmoji","handler":"setEmoji"},+ {"method":"POST","path":"/api/setting/setEntryVisibility","handler":"setEntryVisibility"},+ {"method":"POST","path":"/api/setting/setExport","handler":"setExport"},+ {"method":"POST","path":"/api/setting/setFiletree","handler":"setFiletree"},+ {"method":"POST","path":"/api/setting/setFlashcard","handler":"setFlashcard"},+ {"method":"POST","path":"/api/setting/setIcon","handler":"setIcon"},+ {"method":"POST","path":"/api/setting/setKeymap","handler":"setKeymap"},+ {"method":"POST","path":"/api/setting/setPublish","handler":"setPublish"},+ {"method":"POST","path":"/api/setting/setSearch","handler":"setSearch"},+ {"method":"POST","path":"/api/setting/setSecrets","handler":"setSecrets"},+ {"method":"POST","path":"/api/setting/setSnippet","handler":"setConfSnippet"},+ {"method":"POST","path":"/api/setting/setTheme","handler":"setTheme"},+ {"method":"POST","path":"/api/setting/setVariables","handler":"setVariables"},+ {"method":"POST","path":"/api/snippet/getSnippet","handler":"getSnippet"},+ {"method":"POST","path":"/api/snippet/removeSnippet","handler":"removeSnippet"},+ {"method":"POST","path":"/api/snippet/setSnippet","handler":"setSnippet"},+ {"method":"POST","path":"/api/sqlite/flushTransaction","handler":"flushTransaction"},+ {"method":"POST","path":"/api/storage/batchUpdateRecentDocCloseTime","handler":"batchUpdateRecentDocCloseTime"},+ {"method":"POST","path":"/api/storage/getCriteria","handler":"getCriteria"},+ {"method":"POST","path":"/api/storage/getInlineStyles","handler":"getInlineStyles"},+ {"method":"POST","path":"/api/storage/getLocalStorage","handler":"getLocalStorage"},+ {"method":"POST","path":"/api/storage/getLocalStorageVal","handler":"getLocalStorageVal"},+ {"method":"POST","path":"/api/storage/getLocalStorageVals","handler":"getLocalStorageVals"},+ {"method":"POST","path":"/api/storage/getOutlineStorage","handler":"getOutlineStorage"},+ {"method":"POST","path":"/api/storage/getRecentDocs","handler":"getRecentDocs"},+ {"method":"POST","path":"/api/storage/getViewState","handler":"getViewState"},+ {"method":"POST","path":"/api/storage/patchViewState","handler":"patchViewState"},+ {"method":"POST","path":"/api/storage/removeCriterion","handler":"removeCriterion"},+ {"method":"POST","path":"/api/storage/removeLocalStorageVal","handler":"removeLocalStorageVal"},+ {"method":"POST","path":"/api/storage/removeLocalStorageVals","handler":"removeLocalStorageVals"},+ {"method":"POST","path":"/api/storage/removeOutlineStorage","handler":"removeOutlineStorage"},+ {"method":"POST","path":"/api/storage/removeViewState","handler":"removeViewState"},+ {"method":"POST","path":"/api/storage/setCriterion","handler":"setCriterion"},+ {"method":"POST","path":"/api/storage/setInlineStyles","handler":"setInlineStyles"},+ {"method":"POST","path":"/api/storage/setLocalStorage","handler":"deprecated"},+ {"method":"POST","path":"/api/storage/setLocalStorageVal","handler":"setLocalStorageVal"},+ {"method":"POST","path":"/api/storage/setLocalStorageVals","handler":"setLocalStorageVals"},+ {"method":"POST","path":"/api/storage/setOutlineStorage","handler":"setOutlineStorage"},+ {"method":"POST","path":"/api/storage/setWorkspaceAVPalette","handler":"setWorkspaceAVPalette"},+ {"method":"POST","path":"/api/storage/updateRecentDocCloseTime","handler":"updateRecentDocCloseTime"},+ {"method":"POST","path":"/api/storage/updateRecentDocOpenTime","handler":"updateRecentDocOpenTime"},+ {"method":"POST","path":"/api/storage/updateRecentDocViewTime","handler":"updateRecentDocViewTime"},+ {"method":"POST","path":"/api/sync/createCloudSyncDir","handler":"createCloudSyncDir"},+ {"method":"POST","path":"/api/sync/exportSyncProviderS3","handler":"exportSyncProviderS3"},+ {"method":"POST","path":"/api/sync/exportSyncProviderWebDAV","handler":"exportSyncProviderWebDAV"},+ {"method":"POST","path":"/api/sync/getBootSync","handler":"getBootSync"},+ {"method":"POST","path":"/api/sync/getSyncInfo","handler":"getSyncInfo"},+ {"method":"POST","path":"/api/sync/getSyncLANStatus","handler":"getSyncLANStatus"},+ {"method":"POST","path":"/api/sync/importSyncProviderS3","handler":"importSyncProviderS3"},+ {"method":"POST","path":"/api/sync/importSyncProviderWebDAV","handler":"importSyncProviderWebDAV"},+ {"method":"POST","path":"/api/sync/listCloudSyncDir","handler":"listCloudSyncDir"},+ {"method":"POST","path":"/api/sync/performBootSync","handler":"performBootSync"},+ {"method":"POST","path":"/api/sync/performSync","handler":"performSync"},+ {"method":"POST","path":"/api/sync/removeCloudSyncDir","handler":"removeCloudSyncDir"},+ {"method":"POST","path":"/api/sync/setCloudSyncDir","handler":"setCloudSyncDir"},+ {"method":"POST","path":"/api/sync/setSyncAssetDownloadMode","handler":"setSyncAssetDownloadMode"},+ {"method":"POST","path":"/api/sync/setSyncEnable","handler":"setSyncEnable"},+ {"method":"POST","path":"/api/sync/setSyncGenerateConflictDoc","handler":"setSyncGenerateConflictDoc"},+ {"method":"POST","path":"/api/sync/setSyncInterval","handler":"setSyncInterval"},+ {"method":"POST","path":"/api/sync/setSyncLAN","handler":"setSyncLAN"},+ {"method":"POST","path":"/api/sync/setSyncMode","handler":"setSyncMode"},+ {"method":"POST","path":"/api/sync/setSyncPerception","handler":"setSyncPerception"},+ {"method":"POST","path":"/api/sync/setSyncProvider","handler":"setSyncProvider"},+ {"method":"POST","path":"/api/sync/setSyncProviderLocal","handler":"setSyncProviderLocal"},+ {"method":"POST","path":"/api/sync/setSyncProviderS3","handler":"setSyncProviderS3"},+ {"method":"POST","path":"/api/sync/setSyncProviderWebDAV","handler":"setSyncProviderWebDAV"},+ {"method":"POST","path":"/api/system/addCustomEmoji","handler":"addCustomEmoji"},+ {"method":"POST","path":"/api/system/addMicrosoftDefenderExclusion","handler":"addMicrosoftDefenderExclusion"},+ {"method":"POST","path":"/api/system/bootProgress","handler":"bootProgress"},+ {"method":"POST","path":"/api/system/checkUpdate","handler":"checkUpdate"},+ {"method":"POST","path":"/api/system/checkWorkspaceDir","handler":"checkWorkspaceDir"},+ {"method":"POST","path":"/api/system/clearTempFiles","handler":"clearTempFiles"},+ {"method":"POST","path":"/api/system/createWorkspaceDir","handler":"createWorkspaceDir"},+ {"method":"POST","path":"/api/system/currentTime","handler":"currentTime"},+ {"method":"POST","path":"/api/system/dismissOnboarding","handler":"dismissOnboarding"},+ {"method":"POST","path":"/api/system/ensureOnboarding","handler":"ensureOnboarding"},+ {"method":"POST","path":"/api/system/exit","handler":"exit"},+ {"method":"POST","path":"/api/system/exportConf","handler":"exportConf"},+ {"method":"POST","path":"/api/system/exportLog","handler":"exportLog"},+ {"method":"POST","path":"/api/system/exportTLSCABundle","handler":"exportTLSCABundle"},+ {"method":"POST","path":"/api/system/exportTLSCACert","handler":"exportTLSCACert"},+ {"method":"POST","path":"/api/system/getChangelog","handler":"getChangelog"},+ {"method":"POST","path":"/api/system/getConf","handler":"getConf"},+ {"method":"POST","path":"/api/system/getCustomFonts","handler":"getCustomFonts"},+ {"method":"POST","path":"/api/system/getEmojiConf","handler":"getEmojiConf"},+ {"method":"POST","path":"/api/system/getMobileWorkspaces","handler":"getMobileWorkspaces"},+ {"method":"POST","path":"/api/system/getNetwork","handler":"getNetwork"},+ {"method":"POST","path":"/api/system/getSysFonts","handler":"getSysFonts"},+ {"method":"POST","path":"/api/system/getWorkspaceInfo","handler":"getWorkspaceInfo"},+ {"method":"POST","path":"/api/system/getWorkspaces","handler":"getWorkspaces"},+ {"method":"POST","path":"/api/system/ignoreAddMicrosoftDefenderExclusion","handler":"ignoreAddMicrosoftDefenderExclusion"},+ {"method":"POST","path":"/api/system/importConf","handler":"importConf"},+ {"method":"POST","path":"/api/system/importCustomFont","handler":"importCustomFont"},+ {"method":"POST","path":"/api/system/importTLSCABundle","handler":"importTLSCABundle"},+ {"method":"POST","path":"/api/system/loginAuth","handler":"model.LoginAuth"},+ {"method":"POST","path":"/api/system/logoutAuth","handler":"model.LogoutAuth"},+ {"method":"POST","path":"/api/system/oidc/mobileCallback","handler":"model.OIDCMobileCallback"},+ {"method":"POST","path":"/api/system/oidc/poll","handler":"model.OIDCPoll"},+ {"method":"POST","path":"/api/system/oidc/start","handler":"model.OIDCStart"},+ {"method":"POST","path":"/api/system/oidc/validate","handler":"model.OIDCValidateStart"},+ {"method":"POST","path":"/api/system/oidc/validateActivate","handler":"model.OIDCValidateActivate"},+ {"method":"POST","path":"/api/system/oidc/validateCancel","handler":"model.OIDCValidateCancel"},+ {"method":"POST","path":"/api/system/oidc/validatePoll","handler":"model.OIDCValidatePoll"},+ {"method":"POST","path":"/api/system/rebuildDataIndex","handler":"rebuildDataIndex"},+ {"method":"POST","path":"/api/system/reloadUI","handler":"deprecated"},+ {"method":"POST","path":"/api/system/removeCustomFont","handler":"removeCustomFont"},+ {"method":"POST","path":"/api/system/removeWorkspaceDir","handler":"removeWorkspaceDir"},+ {"method":"POST","path":"/api/system/removeWorkspaceDirPhysically","handler":"removeWorkspaceDirPhysically"},+ {"method":"POST","path":"/api/system/setAPIToken","handler":"setAPIToken"},+ {"method":"POST","path":"/api/system/setAccessAuthCode","handler":"setAccessAuthCode"},+ {"method":"POST","path":"/api/system/setAppearanceMode","handler":"setAppearanceMode"},+ {"method":"POST","path":"/api/system/setAutoLaunch","handler":"setAutoLaunch"},+ {"method":"POST","path":"/api/system/setDownloadInstallPkg","handler":"setDownloadInstallPkg"},+ {"method":"POST","path":"/api/system/setFollowSystemLockScreen","handler":"setFollowSystemLockScreen"},+ {"method":"POST","path":"/api/system/setNetworkProxy","handler":"setNetworkProxy"},+ {"method":"POST","path":"/api/system/setNetworkServe","handler":"setNetworkServe"},+ {"method":"POST","path":"/api/system/setNetworkServeTLS","handler":"setNetworkServeTLS"},+ {"method":"POST","path":"/api/system/setOIDC","handler":"setOIDC"},+ {"method":"POST","path":"/api/system/setUILayout","handler":"setUILayout"},+ {"method":"POST","path":"/api/system/setUpdateChannel","handler":"setUpdateChannel"},+ {"method":"POST","path":"/api/system/setWorkspaceDir","handler":"setWorkspaceDir"},+ {"method":"POST","path":"/api/system/uiproc","handler":"addUIProcess"},+ {"method":"POST","path":"/api/system/vacuumDataIndex","handler":"vacuumDataIndex"},+ {"method":"POST","path":"/api/tag/getTag","handler":"getTag"},+ {"method":"POST","path":"/api/tag/removeTag","handler":"removeTag"},+ {"method":"POST","path":"/api/tag/renameTag","handler":"renameTag"},+ {"method":"POST","path":"/api/template/docSaveAsTemplate","handler":"docSaveAsTemplate"},+ {"method":"POST","path":"/api/template/getDocSaveAsTemplateInfo","handler":"getDocSaveAsTemplateInfo"},+ {"method":"POST","path":"/api/template/manage","handler":"manageTemplateFiles"},+ {"method":"POST","path":"/api/template/render","handler":"renderTemplate"},+ {"method":"POST","path":"/api/template/renderSprig","handler":"renderSprig"},+ {"method":"POST","path":"/api/transactions","handler":"performTransactions"},+ {"method":"POST","path":"/api/transactions/clearHistory","handler":"clearHistory"},+ {"method":"POST","path":"/api/transactions/redo","handler":"performRedo"},+ {"method":"POST","path":"/api/transactions/undo","handler":"performUndo"},+ {"method":"POST","path":"/api/transactions/undoState","handler":"undoState"},+ {"method":"POST","path":"/api/ui/reloadAttributeView","handler":"reloadAttributeView"},+ {"method":"POST","path":"/api/ui/reloadFiletree","handler":"reloadFiletree"},+ {"method":"POST","path":"/api/ui/reloadIcon","handler":"reloadIcon"},+ {"method":"POST","path":"/api/ui/reloadProtyle","handler":"reloadProtyle"},+ {"method":"POST","path":"/api/ui/reloadTag","handler":"reloadTag"},+ {"method":"POST","path":"/api/ui/reloadTheme","handler":"reloadTheme"},+ {"method":"POST","path":"/api/ui/reloadUI","handler":"reloadUI"}+]diff --git a/kernel/apicontract/response.go b/kernel/apicontract/response.gonew file mode 100644index 0000000000..ae64c28efe--- /dev/null+++ b/kernel/apicontract/response.go@@ -0,0 +1,33 @@+package apicontract++import "encoding/json"++// Null 表示成功但没有数据,线协议始终写出 null。+type Null struct{}++func (Null) MarshalJSON() ([]byte, error) { return []byte("null"), nil }++// Response 的载荷仅能通过有类型的成功构造函数或明确的错误构造函数设置。+type Response[Data any] struct {+ code int+ msg string+ data any+}++func Success[Data any](data Data) Response[Data] { return Response[Data]{data: data} }++func Failure[Data any](code int, msg string) Response[Data] {+ return Response[Data]{code: code, msg: msg}+}++func FailureWithText[Data any](code int, msg, data string) Response[Data] {+ return Response[Data]{code: code, msg: msg, data: data}+}++func (r Response[Data]) MarshalJSON() ([]byte, error) {+ return json.Marshal(struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data any `json:"data"`+ }{r.code, r.msg, r.data})+}diff --git a/kernel/apicontract/routes.go b/kernel/apicontract/routes.gonew file mode 100644index 0000000000..c3a189705f--- /dev/null+++ b/kernel/apicontract/routes.go@@ -0,0 +1,200 @@+package apicontract++import (+ "fmt"+ "go/ast"+ "go/parser"+ "go/token"+ "os"+ "path/filepath"+ "sort"+ "strconv"+ "strings"+)++type Route struct {+ Method string `json:"method"`+ Path string `json:"path"`+ Handler string `json:"handler"`+}++func (r Route) Key() string { return r.Method + " " + r.Path }++// ReadRoutes 读取实际路由及处理函数声明,防止契约与独立登记表各自漂移。+func ReadRoutes(apiDir string) ([]Route, map[string]string, error) {+ var routes []Route+ bindings := map[string]string{}+ endpointNames, err := readEndpointNames(filepath.Join(apiDir, "..", "apicontract", "contracts.go"))+ if err != nil {+ return nil, nil, err+ }+ entries, err := os.ReadDir(apiDir)+ if err != nil {+ return nil, nil, err+ }+ for _, entry := range entries {+ if filepath.Ext(entry.Name()) != ".go" || len(entry.Name()) > 8 && entry.Name()[len(entry.Name())-8:] == "_test.go" {+ continue+ }+ file, parseErr := parser.ParseFile(token.NewFileSet(), filepath.Join(apiDir, entry.Name()), nil, 0)+ if parseErr != nil {+ return nil, nil, parseErr+ }+ ast.Inspect(file, func(node ast.Node) bool {+ if spec, ok := node.(*ast.ValueSpec); ok && len(spec.Names) == 1 && len(spec.Values) == 1 {+ if call, ok := spec.Values[0].(*ast.CallExpr); ok && len(call.Args) == 2 {+ if fun, ok := call.Fun.(*ast.Ident); ok && fun.Name == "contractHandler" {+ if endpoint, ok := call.Args[0].(*ast.SelectorExpr); ok {+ bindings[spec.Names[0].Name] = endpointNames[endpoint.Sel.Name]+ }+ }+ }+ }+ if entry.Name() != "router.go" {+ return true+ }+ call, ok := node.(*ast.CallExpr)+ if !ok {+ return true+ }+ fun, ok := call.Fun.(*ast.SelectorExpr)+ if !ok {+ return true+ }+ server, ok := fun.X.(*ast.Ident)+ if !ok || server.Name != "ginServer" || fun.Sel.Name == "Use" {+ return true+ }+ methodValue := strings.ToUpper(fun.Sel.Name)+ pathIndex := 0+ if fun.Sel.Name == "Handle" {+ if len(call.Args) < 3 {+ err = fmt.Errorf("invalid Handle registration")+ return false+ }+ method, ok := call.Args[0].(*ast.BasicLit)+ if !ok {+ err = fmt.Errorf("API method must be literal")+ return false+ }+ methodValue, _ = strconv.Unquote(method.Value)+ pathIndex = 1+ } else if !strings.Contains("|GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|CONNECT|TRACE|ANY|", "|"+methodValue+"|") {+ err = fmt.Errorf("unsupported router declaration: %s", fun.Sel.Name)+ return false+ }+ if len(call.Args) < pathIndex+2 {+ err = fmt.Errorf("invalid route registration")+ return false+ }+ path, pathOK := call.Args[pathIndex].(*ast.BasicLit)+ if !pathOK {+ err = fmt.Errorf("API route must use literal method and path")+ return false+ }+ pathValue, _ := strconv.Unquote(path.Value)+ handler := ""+ switch value := call.Args[len(call.Args)-1].(type) {+ case *ast.Ident:+ handler = value.Name+ case *ast.SelectorExpr:+ if pkg, ok := value.X.(*ast.Ident); ok {+ handler = pkg.Name + "." + value.Sel.Name+ }+ case *ast.FuncLit:+ handler = "inline"+ default:+ err = fmt.Errorf("unsupported API route handler: %s", pathValue)+ }+ routes = append(routes, Route{methodValue, pathValue, handler})+ return true+ })+ }+ sort.Slice(routes, func(i, j int) bool {+ if routes[i].Key() == routes[j].Key() {+ return routes[i].Handler < routes[j].Handler+ }+ return routes[i].Key() < routes[j].Key()+ })+ return routes, bindings, err+}++// CheckRoutes 要求每个实际路由都有契约或存量记录,已迁移路由必须绑定对应的类型适配器。+func CheckRoutes(routes []Route, bindings map[string]string, legacy []Route) error {+ typed := map[string]Definition{}+ for _, definition := range Definitions() {+ for _, method := range definition.Methods {+ typed[method+" "+definition.Path] = definition+ }+ }+ legacySet := map[string]Route{}+ for _, route := range legacy {+ if _, exists := legacySet[route.Key()]; exists {+ return fmt.Errorf("duplicate legacy route: %s", route.Key())+ }+ legacySet[route.Key()] = route+ }+ seen := map[string]bool{}+ for _, route := range routes {+ if definition, exists := typed[route.Key()]; exists {+ if seen[route.Key()] {+ return fmt.Errorf("duplicate typed route: %s", route.Key())+ }+ seen[route.Key()] = true+ if route.Handler != definition.Name || bindings[route.Handler] != definition.Name {+ return fmt.Errorf("typed handler missing or mismatched: %s", route.Key())+ }+ if _, exists := legacySet[route.Key()]; exists {+ return fmt.Errorf("migrated route remains in legacy list: %s", route.Key())+ }+ } else {+ previous, exists := legacySet[route.Key()]+ if !exists || previous.Handler != route.Handler {+ return fmt.Errorf("route needs a typed contract: %s (%s)", route.Key(), route.Handler)+ }+ seen[route.Key()] = true+ }+ }+ for key := range typed {+ if !seen[key] {+ return fmt.Errorf("contract has no route: %s", key)+ }+ }+ for key := range legacySet {+ if !seen[key] {+ return fmt.Errorf("removed route remains in legacy list: %s", key)+ }+ }+ return nil+}++func readEndpointNames(path string) (map[string]string, error) {+ file, err := parser.ParseFile(token.NewFileSet(), path, nil, 0)+ if err != nil {+ return nil, err+ }+ names := map[string]string{}+ ast.Inspect(file, func(node ast.Node) bool {+ spec, ok := node.(*ast.ValueSpec)+ if !ok || len(spec.Names) != 1 || len(spec.Values) != 1 {+ return true+ }+ call, ok := spec.Values[0].(*ast.CallExpr)+ if !ok || len(call.Args) == 0 {+ return true+ }+ generic, ok := call.Fun.(*ast.IndexListExpr)+ if !ok {+ return true+ }+ function, ok := generic.X.(*ast.Ident)+ if !ok || function.Name != "define" {+ return true+ }+ if name, ok := call.Args[0].(*ast.BasicLit); ok {+ names[spec.Names[0].Name], _ = strconv.Unquote(name.Value)+ }+ return true+ })+ return names, nil+}diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.gonew file mode 100644index 0000000000..f39deb3e0f--- /dev/null+++ b/kernel/apicontract/schema.go@@ -0,0 +1,388 @@+package apicontract++import (+ "encoding/json"+ "fmt"+ "math"+ "reflect"+ "sort"+ "strings"+)++// Schema 是生成器和响应验证共用的 JSON Schema 子集;不支持的 Go 类型直接报错。+type Schema struct {+ Ref string `json:"$ref,omitempty"`+ Type string `json:"type,omitempty"`+ Enum []any `json:"enum,omitempty"`+ AnyOf []*Schema `json:"anyOf,omitempty"`+ Properties map[string]*Schema `json:"properties,omitempty"`+ Required []string `json:"required,omitempty"`+ Items *Schema `json:"items,omitempty"`+ AdditionalProperties any `json:"additionalProperties,omitempty"`+}++type EndpointSchema struct {+ Method string `json:"method"`+ Path string `json:"path"`+ Handler string `json:"handler"`+ Body BodyMode `json:"body"`+ Request *Schema `json:"request"`+ Response *Schema `json:"response"`+}++type Bundle struct {+ Dialect string `json:"$schema"`+ Definitions map[string]*Schema `json:"$defs"`+ Endpoints []EndpointSchema `json:"endpoints"`+}++type schemaBuilder struct {+ definitions map[string]*Schema+ owners map[string]reflect.Type+}++func nullable(schema *Schema) *Schema {+ if schema.Type == "null" {+ return schema+ }+ for _, option := range schema.AnyOf {+ if option.Type == "null" {+ return schema+ }+ }+ return &Schema{AnyOf: []*Schema{schema, {Type: "null"}}}+}++func nonnullable(schema *Schema) *Schema {+ if len(schema.AnyOf) == 0 {+ return schema+ }+ var options []*Schema+ for _, option := range schema.AnyOf {+ if option.Type != "null" {+ options = append(options, option)+ }+ }+ if len(options) == 1 {+ return options[0]+ }+ return &Schema{AnyOf: options}+}++func (b *schemaBuilder) schema(t reflect.Type, input bool) (*Schema, error) {+ if t == reflect.TypeFor[Null]() {+ return &Schema{Type: "null"}, nil+ }+ if t == reflect.TypeFor[json.Number]() {+ return nil, fmt.Errorf("JSON number requires an explicit schema: %s", t)+ }+ if t == reflect.TypeFor[BlockInfoData]() {+ var variants []*Schema+ for _, member := range []reflect.Type{reflect.TypeFor[FullBlockInfo](), reflect.TypeFor[PublishedBlockInfo]()} {+ schema, err := b.schema(member, input)+ if err != nil {+ return nil, err+ }+ variants = append(variants, schema)+ }+ b.definitions["BlockInfoData"] = &Schema{AnyOf: variants}+ return &Schema{Ref: "#/$defs/BlockInfoData"}, nil+ }+ marshaler := reflect.TypeFor[json.Marshaler]()+ unmarshaler := reflect.TypeFor[json.Unmarshaler]()+ if t.Implements(marshaler) || reflect.PointerTo(t).Implements(marshaler) ||+ (input && (t.Implements(unmarshaler) || reflect.PointerTo(t).Implements(unmarshaler))) {+ return nil, fmt.Errorf("custom JSON codec requires an explicit schema: %s", t)+ }+ switch t.Kind() {+ case reflect.Pointer:+ child, err := b.schema(t.Elem(), input)+ if err != nil {+ return nil, err+ }+ return nullable(child), nil+ case reflect.String:+ return &Schema{Type: "string"}, nil+ case reflect.Bool:+ return &Schema{Type: "boolean"}, nil+ case reflect.Float32, reflect.Float64:+ return &Schema{Type: "number"}, nil+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,+ reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:+ return &Schema{Type: "integer"}, nil+ case reflect.Slice:+ if t.Elem().Kind() == reflect.Uint8 {+ return nil, fmt.Errorf("byte encoding requires an explicit schema: %s", t)+ }+ child, err := b.schema(t.Elem(), input)+ if err != nil {+ return nil, err+ }+ return nullable(&Schema{Type: "array", Items: child}), nil+ case reflect.Map:+ if t.Key().Kind() != reflect.String {+ return nil, fmt.Errorf("unsupported JSON map key: %s", t)+ }+ child, err := b.schema(t.Elem(), input)+ if err != nil {+ return nil, err+ }+ return nullable(&Schema{Type: "object", AdditionalProperties: child}), nil+ case reflect.Struct:+ name := t.Name()+ if name == "" {+ return nil, fmt.Errorf("anonymous contract type: %s", t)+ }+ if input {+ name += "Input"+ }+ if owner, exists := b.owners[name]; exists {+ if owner != t {+ return nil, fmt.Errorf("duplicate contract type name: %s", name)+ }+ return &Schema{Ref: "#/$defs/" + name}, nil+ }+ b.owners[name] = t+ object := &Schema{Type: "object", Properties: map[string]*Schema{}, AdditionalProperties: false}+ b.definitions[name] = object+ if err := b.fields(object, t, input); err != nil {+ return nil, err+ }+ sort.Strings(object.Required)+ return &Schema{Ref: "#/$defs/" + name}, nil+ default:+ return nil, fmt.Errorf("unsupported contract type: %s", t)+ }+}++func (b *schemaBuilder) fields(object *Schema, t reflect.Type, input bool) error {+ for i := 0; i < t.NumField(); i++ {+ field := t.Field(i)+ if !field.IsExported() && !field.Anonymous {+ continue+ }+ tag := strings.Split(field.Tag.Get("json"), ",")+ if tag[0] == "-" {+ continue+ }+ if field.Anonymous && tag[0] == "" {+ if field.Type.Kind() != reflect.Struct {+ return fmt.Errorf("embedded pointer requires an explicit schema: %s", field.Name)+ }+ if err := b.fields(object, field.Type, input); err != nil {+ return err+ }+ continue+ }+ name := tag[0]+ if name == "" {+ return fmt.Errorf("missing JSON field name: %s.%s", t, field.Name)+ }+ if _, exists := object.Properties[name]; exists {+ return fmt.Errorf("ambiguous JSON field: %s.%s", t, name)+ }+ for _, option := range tag[1:] {+ if option != "omitempty" {+ return fmt.Errorf("unsupported JSON tag: %s.%s", t, name)+ }+ }+ child, err := b.schema(field.Type, input)+ if err != nil {+ return err+ }+ options := "," + field.Tag.Get("api") + ","+ has := func(option string) bool { return strings.Contains(options, ","+option+",") }+ for _, option := range strings.Split(field.Tag.Get("api"), ",") {+ switch {+ case option == "", option == "optional", option == "nullable", option == "nonnullable":+ case option == "trim", option == "ignoretype", strings.HasPrefix(option, "enum="):+ if field.Type.Kind() != reflect.String {+ return fmt.Errorf("API option %s requires a string: %s.%s", option, t, name)+ }+ case option == "filterstrings":+ if field.Type != reflect.TypeFor[[]string]() {+ return fmt.Errorf("filterstrings requires []string: %s.%s", t, name)+ }+ case strings.HasPrefix(option, "const="):+ default:+ return fmt.Errorf("unknown API option %s: %s.%s", option, t, name)+ }+ }+ optional := input && has("optional")+ if input {+ if has("nullable") {+ child = nullable(child)+ }+ if !has("nullable") && field.Type.Kind() != reflect.Pointer && !has("filterstrings") {+ child = nonnullable(child)+ }+ } else if len(tag) > 1 && tag[1] == "omitempty" {+ optional = true+ child = nonnullable(child)+ }+ if has("nonnullable") {+ child = nonnullable(child)+ }+ for _, option := range strings.Split(field.Tag.Get("api"), ",") {+ if strings.HasPrefix(option, "enum=") {+ child.Enum = nil+ for _, value := range strings.Split(strings.TrimPrefix(option, "enum="), "|") {+ child.Enum = append(child.Enum, value)+ }+ }+ if strings.HasPrefix(option, "const=") {+ var constant any+ if err := json.Unmarshal([]byte(strings.TrimPrefix(option, "const=")), &constant); err != nil {+ return err+ }+ child.Enum = []any{constant}+ }+ }+ object.Properties[name] = child+ if !optional {+ object.Required = append(object.Required, name)+ }+ }+ return nil+}++func object(properties map[string]*Schema, required ...string) *Schema {+ return &Schema{Type: "object", Properties: properties, Required: required, AdditionalProperties: false}+}++func BuildBundle() (*Bundle, error) {+ b := &schemaBuilder{definitions: map[string]*Schema{}, owners: map[string]reflect.Type{}}+ bundle := &Bundle{Dialect: "https://json-schema.org/draft/2020-12/schema", Definitions: b.definitions}+ for _, definition := range Definitions() {+ if definition.Request.Kind() != reflect.Struct {+ return nil, fmt.Errorf("request contract must be a struct: %s", definition.Name)+ }+ request, err := b.schema(definition.Request, true)+ if err != nil {+ return nil, err+ }+ data, err := b.schema(definition.Data, false)+ if err != nil {+ return nil, err+ }+ if definition.DataNonNullable {+ data = nonnullable(data)+ }+ success := object(map[string]*Schema{"code": {Type: "integer", Enum: []any{0}}, "msg": {Type: "string"}, "data": data}, "code", "msg", "data")+ var codes []any+ for _, code := range definition.ErrorCodes {+ codes = append(codes, code)+ }+ // 只读中间件使用提示对象;其余业务错误没有数据,块信息还允许索引提示文本。+ errorData := nullable(object(map[string]*Schema{"closeTimeout": {Type: "number"}}, "closeTimeout"))+ if definition.ErrorText {+ errorData.AnyOf = append(errorData.AnyOf, &Schema{Type: "string"})+ }+ failure := object(map[string]*Schema{"code": {Type: "integer", Enum: codes}, "msg": {Type: "string"}, "data": errorData}, "code", "msg", "data")+ // 中间件可能使用带命令元数据的统一信封,保留这些额外的顶层字段。+ failure.AdditionalProperties = true+ response := &Schema{AnyOf: []*Schema{success, failure}}+ for _, method := range definition.Methods {+ bundle.Endpoints = append(bundle.Endpoints, EndpointSchema{method, definition.Path, definition.Name, definition.Body, request, response})+ }+ }+ sort.Slice(bundle.Endpoints, func(i, j int) bool {+ return bundle.Endpoints[i].Method+bundle.Endpoints[i].Path < bundle.Endpoints[j].Method+bundle.Endpoints[j].Path+ })+ return bundle, nil+}++func (b *Bundle) ValidateResponse(method, path string, payload []byte) error {+ var value any+ if err := json.Unmarshal(payload, &value); err != nil {+ return err+ }+ for _, endpoint := range b.Endpoints {+ if endpoint.Method == method && endpoint.Path == path {+ return b.validate(endpoint.Response, value, "$")+ }+ }+ return fmt.Errorf("unregistered API contract: %s %s", method, path)+}++func (b *Bundle) validate(schema *Schema, value any, path string) error {+ if len(schema.Enum) > 0 {+ matched := false+ actual, _ := json.Marshal(value)+ for _, option := range schema.Enum {+ expected, _ := json.Marshal(option)+ if string(actual) == string(expected) {+ matched = true+ break+ }+ }+ if !matched {+ return fmt.Errorf("%s has an unexpected value", path)+ }+ }+ if schema.Ref != "" {+ target, ok := b.Definitions[strings.TrimPrefix(schema.Ref, "#/$defs/")]+ if !ok {+ return fmt.Errorf("unknown schema reference: %s", schema.Ref)+ }+ return b.validate(target, value, path)+ }+ if len(schema.AnyOf) > 0 {+ for _, option := range schema.AnyOf {+ if b.validate(option, value, path) == nil {+ return nil+ }+ }+ return fmt.Errorf("%s does not match any response variant", path)+ }+ valid := false+ switch schema.Type {+ case "null":+ valid = value == nil+ case "string":+ _, valid = value.(string)+ case "boolean":+ _, valid = value.(bool)+ case "number", "integer":+ number, ok := value.(float64)+ valid = ok && (schema.Type != "integer" || math.Trunc(number) == number)+ case "array":+ array, ok := value.([]any)+ valid = ok+ if ok {+ for i, element := range array {+ if err := b.validate(schema.Items, element, fmt.Sprintf("%s[%d]", path, i)); err != nil {+ return err+ }+ }+ }+ case "object":+ fields, ok := value.(map[string]any)+ valid = ok+ if !ok {+ break+ }+ for _, key := range schema.Required {+ if _, exists := fields[key]; !exists {+ return fmt.Errorf("%s.%s is required", path, key)+ }+ }+ for key, child := range fields {+ if childSchema, exists := schema.Properties[key]; exists {+ if err := b.validate(childSchema, child, path+"."+key); err != nil {+ return err+ }+ } else if additional, ok := schema.AdditionalProperties.(*Schema); ok {+ if err := b.validate(additional, child, path+"."+key); err != nil {+ return err+ }+ } else if schema.AdditionalProperties != true {+ return fmt.Errorf("%s.%s is not declared", path, key)+ }+ }+ }+ if !valid {+ return fmt.Errorf("%s must be %s", path, schema.Type)+ }+ return nil+}diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonnew file mode 100644index 0000000000..f3b264b841--- /dev/null+++ b/kernel/apicontract/schema.json@@ -0,0 +1,1007 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$defs": {+ "BlockIDRequestInput": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ },+ "BlockInfoData": {+ "anyOf": [+ {+ "$ref": "#/$defs/FullBlockInfo"+ },+ {+ "$ref": "#/$defs/PublishedBlockInfo"+ }+ ]+ },+ "BlockInfoRequestInput": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "ids": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "notebook": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ },+ "EmptyRequestInput": {+ "type": "object",+ "additionalProperties": false+ },+ "FullBlockInfo": {+ "type": "object",+ "properties": {+ "box": {+ "type": "string"+ },+ "path": {+ "type": "string"+ },+ "rootChildID": {+ "type": "string"+ },+ "rootID": {+ "type": "string"+ },+ "rootIcon": {+ "type": "string"+ },+ "rootTitle": {+ "type": "string"+ },+ "rootTitleEmpty": {+ "type": "boolean"+ }+ },+ "required": [+ "box",+ "path",+ "rootChildID",+ "rootID",+ "rootIcon",+ "rootTitle",+ "rootTitleEmpty"+ ],+ "additionalProperties": false+ },+ "ListNotebooksData": {+ "type": "object",+ "properties": {+ "boxDocEnabled": {+ "type": "boolean"+ },+ "notebooks": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/Notebook"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "boxDocEnabled",+ "notebooks"+ ],+ "additionalProperties": false+ },+ "ListNotebooksRequestInput": {+ "type": "object",+ "properties": {+ "flashcard": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "additionalProperties": false+ },+ "Notebook": {+ "type": "object",+ "properties": {+ "closed": {+ "type": "boolean"+ },+ "dueFlashcardCount": {+ "type": "integer"+ },+ "encrypted": {+ "type": "boolean"+ },+ "flashcardCount": {+ "type": "integer"+ },+ "icon": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "newFlashcardCount": {+ "type": "integer"+ },+ "sort": {+ "type": "integer"+ },+ "sortMode": {+ "type": "integer"+ },+ "state": {+ "type": "string",+ "enum": [+ "Locked",+ "Unlocking",+ "Unlocked",+ "Locking",+ "Error"+ ]+ },+ "subFileCount": {+ "type": "integer"+ },+ "unlocked": {+ "type": "boolean"+ }+ },+ "required": [+ "closed",+ "dueFlashcardCount",+ "encrypted",+ "flashcardCount",+ "icon",+ "id",+ "name",+ "newFlashcardCount",+ "sort",+ "sortMode",+ "subFileCount",+ "unlocked"+ ],+ "additionalProperties": false+ },+ "PublishedBlockInfo": {+ "type": "object",+ "properties": {+ "publishAccessRequired": {+ "type": "boolean",+ "enum": [+ true+ ]+ },+ "rootID": {+ "type": "string"+ },+ "rootIcon": {+ "type": "string"+ },+ "rootTitle": {+ "type": "string"+ },+ "rootTitleEmpty": {+ "type": "boolean"+ }+ },+ "required": [+ "publishAccessRequired",+ "rootID",+ "rootIcon",+ "rootTitle",+ "rootTitleEmpty"+ ],+ "additionalProperties": false+ },+ "SearchHistoryData": {+ "type": "object",+ "properties": {+ "histories": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "pageCount": {+ "type": "integer"+ },+ "totalCount": {+ "type": "integer"+ }+ },+ "required": [+ "histories",+ "pageCount",+ "totalCount"+ ],+ "additionalProperties": false+ },+ "SearchHistoryRequestInput": {+ "type": "object",+ "properties": {+ "notebook": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "op": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "page": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "query": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "type": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "additionalProperties": false+ },+ "SearchTagData": {+ "type": "object",+ "properties": {+ "k": {+ "type": "string"+ },+ "tags": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "k",+ "tags"+ ],+ "additionalProperties": false+ },+ "SearchTagRequestInput": {+ "type": "object",+ "properties": {+ "k": {+ "type": "string"+ }+ },+ "required": [+ "k"+ ],+ "additionalProperties": false+ },+ "SetBlockAttrsRequestInput": {+ "type": "object",+ "properties": {+ "attrs": {+ "type": "object",+ "additionalProperties": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "id": {+ "type": "string"+ }+ },+ "required": [+ "attrs",+ "id"+ ],+ "additionalProperties": false+ }+ },+ "endpoints": [+ {+ "method": "GET",+ "path": "/api/system/version",+ "handler": "version",+ "body": "none",+ "request": {+ "$ref": "#/$defs/EmptyRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "string"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/attr/getBlockAttrs",+ "handler": "getBlockAttrs",+ "body": "json",+ "request": {+ "$ref": "#/$defs/BlockIDRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/attr/setBlockAttrs",+ "handler": "setBlockAttrs",+ "body": "json",+ "request": {+ "$ref": "#/$defs/SetBlockAttrsRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/block/getBlockInfo",+ "handler": "getBlockInfo",+ "body": "json",+ "request": {+ "$ref": "#/$defs/BlockInfoRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/BlockInfoData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ 3+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ },+ {+ "type": "string"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/history/searchHistory",+ "handler": "searchHistory",+ "body": "json",+ "request": {+ "$ref": "#/$defs/SearchHistoryRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/SearchHistoryData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/notebook/lsNotebooks",+ "handler": "lsNotebooks",+ "body": "legacyOptional",+ "request": {+ "$ref": "#/$defs/ListNotebooksRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "anyOf": [+ {+ "$ref": "#/$defs/ListNotebooksData"+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/search/searchTag",+ "handler": "searchTag",+ "body": "json",+ "request": {+ "$ref": "#/$defs/SearchTagRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/SearchTagData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/system/version",+ "handler": "version",+ "body": "none",+ "request": {+ "$ref": "#/$defs/EmptyRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "string"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ }+ ]+}diff --git a/kernel/apicontract/typescript.go b/kernel/apicontract/typescript.gonew file mode 100644index 0000000000..520b528e81--- /dev/null+++ b/kernel/apicontract/typescript.go@@ -0,0 +1,214 @@+package apicontract++import (+ "encoding/json"+ "fmt"+ "sort"+ "strings"+)++func sortedKeys[V any](values map[string]V) []string {+ keys := make([]string, 0, len(values))+ for key := range values {+ keys = append(keys, key)+ }+ sort.Strings(keys)+ return keys+}++func quote(value string) string { data, _ := json.Marshal(value); return string(data) }++func (b *Bundle) typeScript(schema *Schema) string {+ if schema.Ref != "" {+ return strings.TrimPrefix(schema.Ref, "#/$defs/")+ }+ if len(schema.Enum) > 0 {+ var values []string+ for _, value := range schema.Enum {+ data, _ := json.Marshal(value)+ values = append(values, string(data))+ }+ return strings.Join(values, " | ")+ }+ if len(schema.AnyOf) > 0 {+ var variants []string+ // 联合成员缺少的字段标记为可选 never,保留精确的属性存在性和判别能力。+ allProperties := map[string]bool{}+ objects := make([]*Schema, len(schema.AnyOf))+ allObjects := true+ for i, option := range schema.AnyOf {+ target := option+ if option.Ref != "" {+ target = b.Definitions[strings.TrimPrefix(option.Ref, "#/$defs/")]+ }+ if target == nil || target.Type != "object" {+ allObjects = false+ break+ }+ objects[i] = target+ for key := range target.Properties {+ allProperties[key] = true+ }+ }+ for i, option := range schema.AnyOf {+ variant := b.typeScript(option)+ if allObjects {+ var absent []string+ for _, key := range sortedKeys(allProperties) {+ if _, exists := objects[i].Properties[key]; !exists {+ absent = append(absent, quote(key)+"?: never;")+ }+ }+ if len(absent) > 0 {+ variant = "(" + variant + " & { " + strings.Join(absent, " ") + " })"+ }+ }+ variants = append(variants, variant)+ }+ return strings.Join(variants, " | ")+ }+ switch schema.Type {+ case "integer", "number":+ return "number"+ case "null", "string", "boolean":+ return schema.Type+ case "array":+ return "Array<" + b.typeScript(schema.Items) + ">"+ case "object":+ if additional, ok := schema.AdditionalProperties.(*Schema); ok {+ return "Record<string, " + b.typeScript(additional) + ">"+ }+ if len(schema.Properties) == 0 {+ return "Record<string, never>"+ }+ required := map[string]bool{}+ for _, key := range schema.Required {+ required[key] = true+ }+ var fields []string+ for _, key := range sortedKeys(schema.Properties) {+ optional := ""+ if !required[key] {+ optional = "?"+ }+ fields = append(fields, quote(key)+optional+": "+b.typeScript(schema.Properties[key])+";")+ }+ return "{ " + strings.Join(fields, " ") + " }"+ default:+ panic("unsupported TypeScript schema: " + schema.Type)+ }+}++func (b *Bundle) TypeScript(legacy []Route) []byte {+ var output strings.Builder+ output.WriteString("// 此文件由内核契约生成,请运行 pnpm run api:generate 更新。\n\n")+ for _, name := range sortedKeys(b.Definitions) {+ fmt.Fprintf(&output, "export type %s = %s;\n\n", name, b.typeScript(b.Definitions[name]))+ }+ for _, method := range []string{"GET", "POST"} {+ legacyPaths := map[string]bool{}+ for _, route := range legacy {+ if route.Method == method || route.Method == "ANY" {+ legacyPaths[route.Path] = true+ }+ }+ fmt.Fprintf(&output, "export type APILegacy%sPath =\n", method)+ for i, path := range sortedKeys(legacyPaths) {+ separator := " |"+ if i == len(legacyPaths)-1 {+ separator = ";"+ }+ fmt.Fprintf(&output, " %s%s\n", quote(path), separator)+ }+ if len(legacyPaths) == 0 {+ output.WriteString(" never;\n")+ }+ output.WriteString("\n")+ fmt.Fprintf(&output, "export interface API%sRoutes {\n", method)+ for _, endpoint := range b.Endpoints {+ if endpoint.Method != method {+ continue+ }+ fmt.Fprintf(&output, " %s: {\n request: %s;\n response: %s;\n body: %s;\n };\n",+ quote(endpoint.Path), b.typeScript(endpoint.Request), b.typeScript(endpoint.Response), quote(string(endpoint.Body)))+ }+ output.WriteString("}\n\n")+ }+ output.WriteString(fetchDeclarations)+ return []byte(output.String())+}++const fetchDeclarations = `// 传输层合成的错误独立于业务错误;普通回调只接收消息处理后保留的非负错误码。+export interface APITransportError {+ code: -401 | -403 | -404;+ msg: string;+ data: null;+}++export interface APIFetchFailure {+ code: number;+ msg: string;+ data: null;+}++export interface APILegacyResponse {+ code: number;+ msg: string;+ data?: any;+ cmd?: string;+ callback?: string;+ sid?: string;+ context?: any;+}++type APIContract = {request: unknown; response: unknown; body: string};+type APIRequestArgs<C extends APIContract> = C["body"] extends "json"+ ? [data: C["request"]]+ : [data?: C["request"] | null];+type NonNegative<C extends number> = C extends C ? ` + "`${C}` extends `-${string}`" + ` ? never : C : never;+export type APICallbackResponse<R> = R extends {code: infer C extends number}+ ? NonNegative<C> extends never ? never : R & {code: NonNegative<C>}+ : never;++type APIPostTail<C extends APIContract> = [+ cb?: (response: APICallbackResponse<C["response"]>) => void,+ headers?: Record<string, string>,+ failCallback?: (response: APIFetchFailure) => void,+ signal?: AbortSignal,+ timeout?: number+];+type LegacyPostArgs<Legacy> = [+ data?: any,+ cb?: (response: Legacy) => void,+ headers?: Record<string, string>,+ failCallback?: (response: Legacy) => void,+ signal?: AbortSignal,+ timeout?: number+];+type APISyncTail = [headers?: Record<string, string>, process?: boolean, signal?: AbortSignal];++// 路径只从首参推导,已知路径不能因请求参数不匹配而选择宽松重载。+export type FetchPost<Legacy = APILegacyResponse> = <Path extends string>(+ url: Path,+ ...args: Path extends keyof APIPOSTRoutes+ ? [...APIRequestArgs<APIPOSTRoutes[Path]>, ...APIPostTail<APIPOSTRoutes[Path]>]+ : Path extends APILegacyPOSTPath ? LegacyPostArgs<Legacy>+ : string extends Path ? LegacyPostArgs<Legacy> : never+) => Promise<void>;++export type FetchSyncPost<Legacy = APILegacyResponse> = <Path extends string>(+ url: Path,+ ...args: Path extends keyof APIPOSTRoutes+ ? [...APIRequestArgs<APIPOSTRoutes[Path]>, ...APISyncTail]+ : Path extends APILegacyPOSTPath ? [data?: any, ...tail: APISyncTail]+ : string extends Path ? [data?: any, ...tail: APISyncTail] : never+) => Promise<Path extends keyof APIPOSTRoutes ? APIPOSTRoutes[Path]["response"] | APITransportError : Legacy>;++export type FetchGet<Legacy = APILegacyResponse | string> = <Path extends string>(+ url: Path,+ ...args: Path extends keyof APIGETRoutes+ ? [cb: (response: APIGETRoutes[Path]["response"]) => void]+ : Path extends keyof APIPOSTRoutes ? never+ : [cb: (response: Legacy) => void]+) => void;+`