Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:memo: Document complete API contract coverage https://github.com/siyuan-note/siyuan/issues/19378

Danielcdd44863dd87
diff --git a/app/tests/api-contract.types.ts b/app/tests/api-contract.types.ts
index 9d5864d95f..00d243f9e7 100644
--- a/app/tests/api-contract.types.ts
+++ b/app/tests/api-contract.types.ts
@@ -483,3 +483,83 @@ fetchPost("/plugin/private/:name/*path", {extension: [true, null, 1]}, response
const code: number = response.code;
void code;
});
+
+fetchPost("/api/system/exit", {execInstallPkg: 2.9, setCurrentWorkspace: null});
+fetchPost("/api/system/setOIDC", {enabled: false, scopes: null, claimRules: [{claim: "group", values: null}]});
+fetchPost("/api/system/setUILayout", {layout: {extension: [null, false, 1]}});
+fetchPost("/api/system/importConf", new ContractFormData({file: [new Blob(["config"])]}));
+// @ts-expect-error 配置导入使用文件列表。
+fetchPost("/api/system/importConf", new ContractFormData({file: new Blob(["config"])}));
+// @ts-expect-error 系统请求的数值标志不能使用字符串。
+fetchPost("/api/system/exit", {execInstallPkg: "2"});
+fetchPost("/api/system/getConf", {}, response => {
+ if (response.code === 0 && response.data.conf) {
+ const enabled: boolean | undefined = response.data.conf.notebookCrypto?.enabled;
+ const layout: JSONValue | undefined = response.data.conf.uiLayout?.layout;
+ void enabled;
+ void layout;
+ // @ts-expect-error 配置声明不包含未定义字段。
+ const unmodeled = response.data.conf.unmodeled;
+ void unmodeled;
+ }
+});
+fetchPost("/api/system/oidc/poll", {pollToken: "token"}, response => {
+ if (response.code === 0 && response.data.status === "completed") {
+ const to: string = response.data.to;
+ void to;
+ }
+});
+fetchPost("/api/system/oidc/mobileCallback", {callbackURL: "siyuan:/oidc-callback"}, response => {
+ if (response.code === 0) {
+ if (response.data.validation === true) {
+ const validated: true = response.data.validation;
+ void validated;
+ } else {
+ const to: string = response.data.to;
+ void to;
+ }
+ }
+});
+
+const transactionContractRequest: APIPOSTRoutes["/api/transactions"]["request"] = {
+ reqId: 1,
+ transactions: [{doOperations: [{action: "setAttrViewPageSize", data: 50}, {action: "updateAttrViewCell", data: {text: null}}]}],
+};
+void transactionContractRequest;
+
+const invalidTransactionContractRequest: APIPOSTRoutes["/api/transactions"]["request"] = {
+ reqId: 1,
+ transactions: [{doOperations: [
+ // @ts-expect-error 已知数值操作不能借用未知操作的兼容分支传入字符串。
+ {action: "setAttrViewPageSize", data: "50"},
+ ]}],
+};
+void invalidTransactionContractRequest;
+
+const invalidUnknownTransactionRequest: APIPOSTRoutes["/api/transactions"]["request"] = {
+ reqId: 1,
+ transactions: [{doOperations: [
+ // @ts-expect-error 未注册操作必须使用显式的兼容操作类型。
+ {action: "unregistered-plugin-operation", data: {plugin: true}},
+ ]}],
+};
+void invalidUnknownTransactionRequest;
+
+const broadcastFrame: APIGETRoutes["/ws/broadcast"]["websocket"]["outgoing"] = new Blob([new Uint8Array([0, 255])]);
+const broadcastDataEncoding: APIGETRoutes["/es/broadcast/subscribe"]["sse"]["raw"]["dataEncoding"] = "raw";
+void [broadcastFrame, broadcastDataEncoding];
+// @ts-expect-error 广播原始帧不能当作 JSON 对象。
+const invalidBroadcastFrame: APIGETRoutes["/ws/broadcast"]["websocket"]["outgoing"] = {message: "text"};
+void invalidBroadcastFrame;
+
+fetchPost("/api/extension/copy", new ContractFormData({dom: "<p>clip</p>", "https://example.com/image.png": new Blob(["image"])}), response => {
+ if (response.code === 0 && response.data) {
+ const markdown: string = response.data.md;
+ const withMath: boolean = response.data.withMath;
+ void [markdown, withMath];
+ }
+});
+// @ts-expect-error 剪藏请求必须携带 DOM 文本。
+fetchPost("/api/extension/copy", new ContractFormData({notebook: "notebook"}));
+const iconOutput: APIGETRoutes["/api/icon/getDynamicIcon"]["output"] = "binary";
+void iconOutput;
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index 37793c2dea..1f55b4266a 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -4,7 +4,7 @@
## Scope
-This document defines type declarations, compatibility requirements, generated artifacts, and verification for kernel HTTP APIs. Endpoint definitions are maintained in `kernel/apicontract/contracts.go`. `kernel/apicontract/legacy_routes.json` records routes that use existing handling, including non-JSON responses, dynamic paths, and `ANY` registrations. New endpoints must define type contracts and must not be added to the legacy list.
+This document defines type declarations, compatibility requirements, generated artifacts, and verification for kernel HTTP APIs. Endpoint definitions are maintained in `kernel/apicontract/contracts.go`. The migration is complete and `kernel/apicontract/legacy_routes.json` is empty. New endpoints must define type contracts and must not be added to the legacy list.
## Contracts and implementation
@@ -24,6 +24,14 @@ Encrypted notebook lifecycle endpoints use typed requests and responses while re
## Compatibility requirements
+All 629 method/path registrations in `kernel/api/router.go` are contracted, and the legacy list is empty. The four `ANY` registrations expand to 661 concrete method/path pairs in generated metadata. Static resources, the main application WebSocket, and other transport services registered by `kernel/server/serve.go` are outside this API route inventory.
+
+System contracts retain complete configuration, workspace management, uploads, authentication, OIDC response variants, boot streams, and empty or binary responses. Persisted layout and shortcut values are narrowed where the frontend consumes them, preserving existing default repair, obsolete-key cleanup, and binding filtering. Configuration export, import, and shutdown keep their existing lifecycle and encryption behavior.
+
+Transaction contracts discriminate all 97 known operation actions and exclude those names from the explicit unknown-action compatibility branch. The frontend uses the same finite operation union. Private raw input preserves historical fields, ignored values, asynchronous model errors, and echoed payloads; schema declarations do not move model validation into HTTP admission. Undo, redo, heading operations, response leases, and transaction persistence formats retain their existing behavior.
+
+Extension clipping retains first-value multipart handling, dynamically named uploaded files, partial results, original messages, and encrypted-notebook admission. Dynamic icons retain SVG bytes, security and cache headers, and empty failure responses. Broadcast streams declare raw SSE bytes with dynamic event names, IDs, and retry values, and raw WebSocket frames with their upgrade errors; payloads are not converted to JSON or Base64, and channel cleanup retains its original scope.
+
Plugin private services declare their existing serialization modes, raw files, redirects, proxy responses, SSE events, and WebSocket frames. Plugin-defined payloads remain protocol extension data; branch-specific validation distinguishes serialized formats from arbitrary bytes. Request bodies, explicit response headers, admission failures, and cancellation retain the plugin service lifecycle.
Network contracts retain request bytes, multipart fields, headers, URL and TLS diagnostics, including complete certificate public-key structures and large integers. Forward proxy options preserve validation order, numeric truncation, response encodings, and protocol-defined JSON payloads. HTTP, EventSource, and WebSocket proxies retain upstream statuses and bytes, repeated-header behavior, security headers, stream cancellation, and connection cleanup. Echo wildcard paths bind their own adapter while sharing the same handler behavior.
@@ -48,7 +56,7 @@ Sync contracts retain numeric truncation, conditional direction validation in ma
Marketplace contracts retain required-field ordering, whitespace handling, theme mode dependencies, rating availability and rate-limit payloads, and local-package upload errors. Package and appearance responses declare their complete nested structures, including the fixed five-element rating distribution. Upload requests keep first-file selection and overwrite parsing. Installation, removal, authentication, and publish restrictions remain in the existing business handlers and middleware.
-Plugin information queries retain path, query-string, and JSON-body name precedence, including whitespace and business error codes 1 through 4. URL parameters bypass body decoding, and list queries ignore the body. Plugin and RPC-method lists retain nullable arrays and entries. HTTP JSON-RPC has a separate contract for single and batch requests, success and error replies, and notification-only HTTP 204 responses. Plugin admission occurs before body reads, batch errors retain their order, and arbitrary JSON is limited to RPC parameters, results, and error details. RPC WebSocket routes declare HTTP 101 upgrades, HTTP 404 plugin admission errors, HTTP 400 text rejections, and separate incoming calls and outgoing replies or notifications. Origin authorization and connection cleanup remain in the existing upgrade lifecycle. Plugin HTTP services remain a separate protocol migration.
+Plugin information queries retain path, query-string, and JSON-body name precedence, including whitespace and business error codes 1 through 4. URL parameters bypass body decoding, and list queries ignore the body. Plugin and RPC-method lists retain nullable arrays and entries. HTTP JSON-RPC has a separate contract for single and batch requests, success and error replies, and notification-only HTTP 204 responses. Plugin admission occurs before body reads, batch errors retain their order, and arbitrary JSON is limited to RPC parameters, results, and error details. RPC WebSocket routes declare HTTP 101 upgrades, HTTP 404 plugin admission errors, HTTP 400 text rejections, and separate incoming calls and outgoing replies or notifications. Origin authorization and connection cleanup remain in the existing upgrade lifecycle.
Search contracts retain pagination defaults and numeric truncation, path validation and deduplication, ignored historical subtype filters, and null versus empty arrays. Reference search distinguishes correlation-only responses from block results and retains notebook admission before deferred parameter validation. SQL search authorization, publish filtering, encrypted notebook leases, cancellation responses, and read-only embed-update no-ops remain in their original order. Desktop and mobile callers share generated request types.
@@ -86,7 +94,7 @@ Notebook configuration updates use a typed partial object. The `legacyobject` fi
`JSONValue` is reserved for fields whose wire protocol explicitly accepts arbitrary JSON, such as an echoed correlation ID. Its schema is a recursive union of null, booleans, numbers, strings, arrays, and objects; it does not stand in for a structured request or response. Word-count results retain their fixed statistics fields independently of the correlation value.
-Heading transaction queries return `BlockTransaction` with typed operations and preserve empty, null, and undo-operation payloads. `BlockOperationResult` declares the finite union of text, block ID arrays, and null. Conversion from the model's polymorphic fields rejects unsupported types; attribute-view operations require their own payload contracts. The editor's operation type also accepts the empty column-type field returned by non-attribute-view operations.
+Heading transaction queries return `BlockTransaction` with typed operations and preserve empty, null, and undo-operation payloads. `BlockOperationResult` declares the finite union of text, block ID arrays, and null. Conversion from the model's polymorphic fields rejects unsupported types; attribute-view operation payloads use their action-specific contracts. The editor's operation type also accepts the empty column-type field returned by non-attribute-view operations.
All `/api/block/` routes use contracts. Heading-level queries retain batch-ID precedence, deduplication, fractional-level truncation, document struct binding, and message display durations. Document conversion results include the six heading counts and typed transactions. Reference checks validate only the fields used by the selected scope, preserve ignored fields and notebook trimming rules, and retain boolean error payloads, publish filtering, and notebook leases through response serialization. These exceptional input rules use private, endpoint-specific typed decoders; ordinary endpoints continue to use field declarations. Recent-update results use a recursive `SearchBlock` payload, including nullable references, children, and card metadata.
@@ -96,7 +104,9 @@ Storage contracts keep arbitrary JSON limited to storage values; keys, recent do
## Multipart requests
-SSE endpoints declare each event name and payload with `SSEOptions` and `SSEEvent`. `StreamSSE` executes the existing stream lifecycle within the request; cancellation and cleanup remain inside that lifecycle. HTTP validation distinguishes `text/event-stream` from the declared pre-stream JSON failures, while `ValidateSSEEvent` checks each JSON event payload separately. Generated metadata exposes the event types. `fetchPost` and `fetchGet` buffer streams as text; `fetchSyncPost` continues to parse JSON and is not a stream reader.
+`RawSSEOptions` and `RawWebSocketOptions` declare byte-oriented broadcast protocols. Use `ValidateRawSSEEvent` and `ValidateRawWebSocketFrame` to check their event and frame metadata independently; JSON event and RPC message declarations retain their existing validation. Raw WebSocket failures are written by the upgrader rather than `RejectWebSocket`.
+
+JSON SSE endpoints declare each event name and payload with `SSEOptions` and `SSEEvent`. `StreamSSE` executes the existing stream lifecycle within the request; cancellation and cleanup remain inside that lifecycle. HTTP validation distinguishes `text/event-stream` from the declared pre-stream JSON failures, while `ValidateSSEEvent` checks each JSON event payload separately. Generated metadata exposes the event types. `fetchPost` and `fetchGet` buffer streams as text; `fetchSyncPost` continues to parse JSON and is not a stream reader.
Endpoints with an empty HTTP response list its permitted statuses in `EmptyResponseStatuses` and return `EmptyHTTPResponse`; other responses retain their own declared shapes. `RedirectHTTPContent` preserves the standard redirect status, Location header, and escaped HTML body. `RawBody` leaves the original request stream unread for protocol handlers. `ProxyOptions` distinguishes HTTP bytes, EventSource bytes, and WebSocket frames, preserving upstream statuses instead of treating them as kernel business codes. Proxy admission errors and middleware envelopes are validated separately. `ANY` registrations remain one coverage record and expand to the router's nine HTTP methods in generated metadata. Response validation preserves JSON number precision, including certificate integers outside the floating-point range; it does not change request numeric conversion.
diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.md
index e18b02ed37..710d7c076e 100644
--- a/docs/API-CONTRACTS.zh-CN.md
+++ b/docs/API-CONTRACTS.zh-CN.md
@@ -4,7 +4,7 @@
## 适用范围
-本文规定内核 HTTP 接口的类型定义、兼容要求、生成产物和验证流程。端点定义以 `kernel/apicontract/contracts.go` 为准;`kernel/apicontract/legacy_routes.json` 登记使用既有处理方式的路由,包括非 JSON、动态路径和 `ANY` 注册。新增接口必须定义类型契约,不得加入存量清单。
+本文规定内核 HTTP 接口的类型定义、兼容要求、生成产物和验证流程。端点定义以 `kernel/apicontract/contracts.go` 为准;迁移已完成,`kernel/apicontract/legacy_routes.json` 清单为空。新增接口必须定义类型契约,不得加入该清单。
## 契约与实现
@@ -24,6 +24,14 @@
## 兼容要求
+`kernel/api/router.go` 中的 629 条方法和路径注册均已接入契约,旧路由清单为空。其中 4 条 `ANY` 注册在生成声明中展开为 661 条具体方法和路径。由 `kernel/server/serve.go` 注册的静态资源、应用主 WebSocket 和其他传输服务不属于这份 API 路由清单。
+
+系统契约保留完整配置、工作空间管理、上传、认证、OIDC 响应分支、启动事件流以及空响应和二进制响应。前端在读取持久化布局和快捷键的位置收窄类型,保留原有默认值修复、废弃键清理和绑定过滤逻辑。配置导入、导出和退出保持原有生命周期及加密行为。
+
+事务契约按动作区分全部 97 个已知操作,并在显式未知操作兼容分支中排除这些名称。前端使用同一组有限操作联合。私有原始输入保留历史字段、被忽略的值、模型异步错误和回传载荷,类型声明不把模型校验提前到 HTTP 准入阶段。撤销、重做、标题操作、响应租约及事务持久化格式保持原有行为。
+
+扩展剪藏保留多段表单首值处理、动态名称上传文件、部分结果、原有消息及加密笔记本准入。动态图标保留 SVG 字节、安全和缓存响应头以及空错误响应。广播流声明原始 SSE 字节、动态事件名、ID 和重试值,以及原始 WebSocket 帧和升级错误;载荷不转换为 JSON 或 Base64,频道清理保持原有作用范围。
+
插件私有服务声明现有序列化模式、原始文件、重定向、代理响应、SSE 事件和 WebSocket 帧。插件自行定义的载荷保留为协议扩展数据,并按实际分支分别校验序列化格式与任意字节。请求体、显式响应头、准入错误和取消处理保持插件服务原有生命周期。
网络契约保留请求字节、表单字段、请求头、URL 和 TLS 诊断信息,包括完整证书公钥结构与大整数。转发代理选项保留校验顺序、数字截断、响应编码及协议定义的 JSON 载荷。HTTP、EventSource 和 WebSocket 代理保留上游状态与字节、重复请求头行为、安全响应头、流取消和连接清理。回显通配路径绑定独立适配器,并共用相同业务处理。
@@ -48,7 +56,7 @@ AI 契约保留供应商配置、模型发现与匹配、确认结果、会话
集市契约保留必填字段的校验顺序、空白处理、主题模式联动、评分可用性和限流载荷,以及本地包上传错误。包和外观响应声明完整嵌套结构,包括固定五项的评分分布。上传请求保留首文件选择及覆盖参数解析。安装、卸载、鉴权和发布限制仍由既有业务处理函数及中间件执行。
-插件信息查询保留路径参数、查询参数和 JSON 请求体中名称的优先级,包括空白及业务错误码 1 至 4。命中 URL 参数时不解析请求体,列表查询忽略请求体。插件列表与 RPC 方法列表保留数组及数组元素的空值语义。HTTP JSON-RPC 使用独立契约描述单次与批量请求、成功与错误回复,以及纯通知请求的 HTTP 204 响应。插件准入先于请求体读取,批量错误保留原有顺序,任意 JSON 仅用于 RPC 参数、返回值和错误详情。RPC WebSocket 路由声明 HTTP 101 升级、HTTP 404 插件准入错误、HTTP 400 文本拒绝,以及独立的入站调用和出站回复或通知。Origin 授权与连接清理保留在既有升级生命周期中。插件 HTTP 服务仍需单独迁移。
+插件信息查询保留路径参数、查询参数和 JSON 请求体中名称的优先级,包括空白及业务错误码 1 至 4。命中 URL 参数时不解析请求体,列表查询忽略请求体。插件列表与 RPC 方法列表保留数组及数组元素的空值语义。HTTP JSON-RPC 使用独立契约描述单次与批量请求、成功与错误回复,以及纯通知请求的 HTTP 204 响应。插件准入先于请求体读取,批量错误保留原有顺序,任意 JSON 仅用于 RPC 参数、返回值和错误详情。RPC WebSocket 路由声明 HTTP 101 升级、HTTP 404 插件准入错误、HTTP 400 文本拒绝,以及独立的入站调用和出站回复或通知。Origin 授权与连接清理保留在既有升级生命周期中。
搜索契约保留分页默认值与小数截断、路径校验与去重、历史子类型筛选的忽略规则,以及空值与空数组的区别。引用搜索区分仅回传请求标识和完整块结果,保留笔记本准入先于延迟参数校验的顺序。SQL 搜索权限、发布过滤、加密笔记本租约、取消请求的响应和只读嵌入块更新的空操作保持原有顺序。桌面端与移动端调用使用生成的请求类型。
@@ -86,7 +94,7 @@ SQL 查询契约保留成功信封顶层的 `limit` 和 `truncated`。`SuccessSQ
`JSONValue` 仅用于线协议明确接受任意 JSON 的字段,例如原样返回的请求标识。其 schema 是 null、布尔、数字、字符串、数组和对象的递归联合,不可代替应有明确结构的请求或响应。字数统计结果的固定字段与请求标识分别建模。
-标题事务查询使用 `BlockTransaction` 返回有类型的操作,保留空数组、空值和撤销操作载荷。`BlockOperationResult` 明确声明文本、块 ID 数组和空值的有限联合类型。业务模型中的多态字段转换时拒绝不支持的类型,属性视图操作需要单独声明其载荷契约。编辑器操作类型同时接受非属性视图操作返回的空列类型字段。
+标题事务查询使用 `BlockTransaction` 返回有类型的操作,保留空数组、空值和撤销操作载荷。`BlockOperationResult` 明确声明文本、块 ID 数组和空值的有限联合类型。业务模型中的多态字段转换时拒绝不支持的类型,属性视图操作载荷使用各动作对应的契约。编辑器操作类型同时接受非属性视图操作返回的空列类型字段。
全部 `/api/block/` 路由已使用契约。标题级别查询保留批量 ID 优先、去重、小数级别截断、文档结构体绑定和消息展示时长。文档转换结果包含六级标题计数和有类型的事务。引用检查仅校验所选范围使用的字段,保留忽略字段及笔记本参数去空白规则,并保留布尔错误载荷、发布过滤和持续到响应序列化完成的笔记本租约。这些特殊输入规则使用私有的入口专用类型解码函数,普通接口继续通过字段声明解码。最近更新结果使用递归的 `SearchBlock` 载荷,包含可为空的引用、子块和卡片元数据。
@@ -98,7 +106,9 @@ SQL 查询契约保留成功信封顶层的 `limit` 和 `truncated`。`SuccessSQ
## 文件上传请求
-SSE 接口通过 `SSEOptions` 和 `SSEEvent` 声明各事件名称及载荷。`StreamSSE` 在请求上下文内执行原有流生命周期,取消与清理仍在该生命周期内完成。HTTP 校验区分 `text/event-stream` 与声明过的流建立前 JSON 错误,`ValidateSSEEvent` 单独校验各事件的 JSON 载荷。生成声明包含事件类型。`fetchPost` 和 `fetchGet` 将完整流缓冲为文本,`fetchSyncPost` 仍解析 JSON,不用于读取事件流。
+`RawSSEOptions` 和 `RawWebSocketOptions` 声明以字节为载荷的广播协议,通过 `ValidateRawSSEEvent` 和 `ValidateRawWebSocketFrame` 单独校验事件及帧元数据;JSON 事件与 RPC 消息保留各自既有校验。原始 WebSocket 的错误由升级器写出,不使用 `RejectWebSocket`。
+
+JSON SSE 接口通过 `SSEOptions` 和 `SSEEvent` 声明各事件名称及载荷。`StreamSSE` 在请求上下文内执行原有流生命周期,取消与清理仍在该生命周期内完成。HTTP 校验区分 `text/event-stream` 与声明过的流建立前 JSON 错误,`ValidateSSEEvent` 单独校验各事件的 JSON 载荷。生成声明包含事件类型。`fetchPost` 和 `fetchGet` 将完整流缓冲为文本,`fetchSyncPost` 仍解析 JSON,不用于读取事件流。
允许空 HTTP 响应的端点通过 `EmptyResponseStatuses` 列出允许状态,并返回 `EmptyHTTPResponse`;其他响应继续使用各自声明的结构。`RedirectHTTPContent` 保留标准重定向状态、Location 响应头和转义后的 HTML 正文。`RawBody` 将未读取的原始请求流留给协议处理函数。`ProxyOptions` 区分 HTTP 字节、EventSource 字节和 WebSocket 帧,保留上游状态,不将其解释为内核业务错误码。代理准入错误与中间件信封分别校验。`ANY` 注册仍按一条记录检查覆盖率,生成元数据时展开为路由器的九种 HTTP 方法。响应校验保留 JSON 数字精度,包括超过浮点范围的证书整数,不改变请求侧的数字转换。