@capyclaw/browser-workbench 0.1.0 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +29 -7
  2. package/contract/browser-contract.json +484 -25
  3. package/demo/form.html +27 -0
  4. package/lib/host.mjs +1 -68
  5. package/node_modules/@capyclaw/asset-service/README.md +48 -0
  6. package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
  7. package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
  8. package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
  9. package/node_modules/@capyclaw/asset-service/package.json +59 -0
  10. package/node_modules/@capyclaw/asset-service/src/index.mjs +304 -0
  11. package/node_modules/@capyclaw/document-workbench/README.md +125 -0
  12. package/node_modules/@capyclaw/document-workbench/package.json +44 -0
  13. package/node_modules/@capyclaw/document-workbench/src/bridge/index.mjs +321 -0
  14. package/node_modules/@capyclaw/document-workbench/src/client/index.mjs +625 -0
  15. package/node_modules/@capyclaw/document-workbench/src/client/screenshot.mjs +98 -0
  16. package/node_modules/@capyclaw/document-workbench/src/index.mjs +9 -0
  17. package/node_modules/@capyclaw/document-workbench/src/model/audit.mjs +101 -0
  18. package/node_modules/@capyclaw/document-workbench/src/model/conformance.mjs +92 -0
  19. package/node_modules/@capyclaw/document-workbench/src/model/ids.mjs +56 -0
  20. package/node_modules/@capyclaw/document-workbench/src/model/index.mjs +18 -0
  21. package/node_modules/@capyclaw/document-workbench/src/model/locate.mjs +118 -0
  22. package/node_modules/@capyclaw/document-workbench/src/model/manifest.mjs +148 -0
  23. package/node_modules/@capyclaw/document-workbench/src/model/ops.mjs +160 -0
  24. package/node_modules/@capyclaw/document-workbench/src/model/validate.mjs +72 -0
  25. package/node_modules/@capyclaw/document-workbench/src/ops/index.mjs +93 -0
  26. package/node_modules/@capyclaw/document-workbench/src/session/context.mjs +103 -0
  27. package/node_modules/@capyclaw/document-workbench/src/session/index.mjs +394 -0
  28. package/node_modules/@capyclaw/document-workbench/src/session/lease.mjs +105 -0
  29. package/node_modules/@capyclaw/document-workbench/src/session/mode.mjs +80 -0
  30. package/node_modules/@capyclaw/document-workbench/src/session/sanitize.mjs +107 -0
  31. package/node_modules/@capyclaw/document-workbench/src/session/state.mjs +159 -0
  32. package/node_modules/@capyclaw/document-workbench/src/session/watch.mjs +63 -0
  33. package/{server/shared/state-service.mjs → node_modules/@capyclaw/document-workbench/src/store/file-backend.mjs} +6 -97
  34. package/node_modules/@capyclaw/document-workbench/src/testing/index.mjs +75 -0
  35. package/node_modules/@capyclaw/foundation/README.md +51 -0
  36. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
  37. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  38. package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
  39. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  40. package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
  41. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  42. package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
  43. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  44. package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
  45. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  46. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  47. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  48. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  49. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  50. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
  51. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  52. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  53. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  54. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  55. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  56. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  57. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  58. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  59. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
  60. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
  61. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
  62. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
  63. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  64. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
  65. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  66. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  67. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  68. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
  69. package/node_modules/@capyclaw/foundation/package.json +53 -0
  70. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  71. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  72. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  73. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  74. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  78. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +58 -0
  79. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  80. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  81. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  82. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  83. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  84. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  85. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  86. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  87. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  88. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  89. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  90. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  91. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  92. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  93. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  94. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  95. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  96. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  97. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  98. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  99. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  100. package/node_modules/@capyclaw/service-host/README.md +86 -0
  101. package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
  102. package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
  103. package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
  104. package/node_modules/@capyclaw/service-host/package.json +60 -0
  105. package/node_modules/@capyclaw/service-host/src/index.mjs +571 -0
  106. package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
  107. package/node_modules/@capyclaw/tool-host/README.md +56 -0
  108. package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
  109. package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
  110. package/node_modules/@capyclaw/tool-host/lib/host.mjs +16 -0
  111. package/node_modules/@capyclaw/tool-host/package.json +59 -0
  112. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
  113. package/node_modules/@capyclaw/tool-host/src/index.mjs +416 -0
  114. package/package.json +28 -12
  115. package/plugin.mjs +1 -0
  116. package/server/contract.mjs +3 -3
  117. package/server/embedded-host.mjs +247 -0
  118. package/server/engine.mjs +1906 -115
  119. package/server/governor.mjs +189 -0
  120. package/server/http-utils.mjs +1 -1
  121. package/server/human.mjs +628 -0
  122. package/server/infra/http.mjs +2 -113
  123. package/server/infra/tuning.mjs +2 -82
  124. package/server/input.mjs +154 -0
  125. package/server/login-vault.mjs +109 -0
  126. package/server/mcp/handler.mjs +1 -1
  127. package/server/mcp/instructions.mjs +5 -2
  128. package/server/orphans.mjs +163 -0
  129. package/server/relay.mjs +160 -188
  130. package/server/routes/api.mjs +126 -13
  131. package/server/routes/assets.mjs +1 -1
  132. package/server/session-engines.mjs +223 -0
  133. package/server/shared/SHARED_MANIFEST.json +47 -24
  134. package/server/shared/asset-service.mjs +2 -217
  135. package/server/shared/editor-host.mjs +2 -125
  136. package/server/shared/kit/editor/lease.mjs +2 -139
  137. package/server/shared/kit/service/api.mjs +2 -45
  138. package/server/shared/kit/service/http.mjs +2 -113
  139. package/server/shared/kit/service/mcp-http.mjs +2 -142
  140. package/server/shared/kit/tools/validate.mjs +2 -115
  141. package/server/shared/kit/tuning.mjs +2 -82
  142. package/server/shared/kit/util/fs-lock.mjs +2 -132
  143. package/server/shared/service-host.mjs +2 -511
  144. package/server/shared/tool-host.mjs +2 -341
  145. package/server/shared/tuning.mjs +2 -63
  146. package/server/tools/capabilities/contract.mjs +25 -5
  147. package/server/tools/capabilities/interaction.mjs +113 -9
  148. package/server/tools/capabilities/navigation.mjs +5 -2
  149. package/server/tools/capabilities/screenshot.mjs +25 -8
  150. package/server/tools/capabilities/session.mjs +13 -7
  151. package/server/tools/capabilities/snapshot.mjs +1 -1
  152. package/server/tools/capabilities/tabs.mjs +2 -2
  153. package/server/tools/kernel/define.mjs +1 -1
  154. package/server/tools/kernel/output.mjs +8 -0
  155. package/server/tools/kernel/ports.mjs +12 -7
  156. package/server/tools/kernel/registry.mjs +1 -1
  157. package/server/workbench-framework.mjs +305 -0
  158. package/ui/app.js +409 -119
  159. package/ui/index.html +29 -39
  160. package/ui/style.css +131 -63
  161. package/cordis.patch.yml +0 -25
@@ -0,0 +1,125 @@
1
+ # @capyclaw/document-workbench
2
+
3
+ 通用文档工作台框架。它把「文档会话协议」从具体文档插件里抽出来,供 PPT、Canvas、DOCX、XLSX 等编辑器插件复用。
4
+
5
+ 它是**纯库**,不是运行时插件:不提供 `ctx.*`,不监听端口,也不生成 service row。HTTP 宿主、工具注册、资产、编辑器托管仍由 `@capyclaw/service-host` / `@capyclaw/tool-host` / `@capyclaw/asset-service` / `@capyclaw/editor-host` 提供;状态持久化(journal/checkpoint/file backend)由本包 `store/file-backend` 承担(原 `@capyclaw/state-service` 已于 2026-11-15 退役)。
6
+
7
+ ## 分层
8
+
9
+ | 子路径 | 位置 | 职责 |
10
+ |---|---|---|
11
+ | `@capyclaw/document-workbench/session` | Node | `DocumentSession`:seq/命令队列/ack/state/ui/shot/owner lease/checkpoint/recover |
12
+ | `@capyclaw/document-workbench/ops` | Node | `defineOp` / `createOpRegistry`:op 元数据、snapshot 策略、未知指令 |
13
+ | `@capyclaw/document-workbench/bridge` | Node | `createDocumentBridge`:标准 HTTP 端点族 |
14
+ | `@capyclaw/document-workbench/client` | Browser | `createEditorClient`:claim/心跳/长轮询/镜像/应用/截图请求 |
15
+ | `@capyclaw/document-workbench/screenshot` | Browser | `composeContactSheet` / `composeTiles` |
16
+ | `@capyclaw/document-workbench/testing` | Node | 内存 backend、fake adapter,供一致性测试 |
17
+
18
+ 浏览器侧只能从 `./client` 与 `./screenshot` 导入;这两个入口不依赖 `node:*`。
19
+
20
+ ## 最小接入
21
+
22
+ 服务端:
23
+
24
+ ```js
25
+ import { DocumentSession } from '@capyclaw/document-workbench/session'
26
+ import { createDocumentBridge } from '@capyclaw/document-workbench/bridge'
27
+ import { createOpRegistry } from '@capyclaw/document-workbench/ops'
28
+ import { createMemoryBackend } from '@capyclaw/document-workbench/testing'
29
+
30
+ const session = new DocumentSession({
31
+ backend,
32
+ initialDoc: { document: { value: 0 } },
33
+ documentKey: 'document',
34
+ summary: (doc) => ({ value: doc.document?.value }),
35
+ })
36
+
37
+ const ops = createOpRegistry({
38
+ modules: { counter: { inc: { run: (doc, cmd) => { doc.document.value += cmd.by || 1 } } } },
39
+ snapshot: (doc) => { /* 可选:mutating op 前拍快照 */ },
40
+ })
41
+
42
+ const bridge = createDocumentBridge({
43
+ session,
44
+ basePath: '/api/my-doc',
45
+ documentKey: 'document',
46
+ documentPath: '/document',
47
+ apply: (cmd) => ops.apply(session.getDocument(), cmd),
48
+ projectStatus: (doc) => ({ value: doc.document?.value }),
49
+ })
50
+
51
+ for (const route of bridge.routes) app.use(route)
52
+ ```
53
+
54
+ 浏览器侧:
55
+
56
+ ```js
57
+ import { createEditorClient } from '@capyclaw/document-workbench/client'
58
+
59
+ const client = createEditorClient({
60
+ api,
61
+ clientId: 'tab-1',
62
+ documentKey: 'document',
63
+ documentPath: '/document',
64
+ adapter: {
65
+ isMounted: () => !!editor.mounted,
66
+ load: (doc) => editor.load(doc),
67
+ dump: () => editor.dump(),
68
+ apply: (cmds) => editor.apply(cmds),
69
+ applyUi: (cmds) => editor.applyView(cmds),
70
+ onChange: (fn) => editor.on('change', fn),
71
+ renderScreenshot: () => editor.renderContactSheet(),
72
+ },
73
+ })
74
+
75
+ await client.ensureLinked()
76
+ await client.restore()
77
+ await client.activate()
78
+ client.claimLoop()
79
+ ```
80
+
81
+ ## 协议字段
82
+
83
+ 标准信封:
84
+
85
+ ```text
86
+ seq, cmds, title, applied_seq, applied, error, updated,
87
+ state_seq, ui_seq, ui, shot_req, shot { req, data }, owner
88
+ ```
89
+
90
+ - `seq`:服务端批次号,push 时自增。
91
+ - `applied_seq` / `applied`:当前批次已应用数与回执。
92
+ - `state_seq`:编辑器镜像对应的批次号;旧镜像不会覆盖新文档。
93
+ - `ui_seq` / `ui`:页面级命令(present/select 等),不写文档。
94
+ - `shot_req` / `shot`:截图请求与结果,旧结果会被丢弃。
95
+ - `owner`:文档 owner 租约,默认 TTL 10s。
96
+
97
+ ## 实时性与传输(0.2.0)
98
+
99
+ - **变更订阅**:`DocumentSession#subscribe(fn)` / `#waitForChange(timeoutMs)`——
100
+ push/ack/state/ui/shot 的每次状态迁移都会即时唤醒订阅方;长轮询
101
+ `GET /watch` 与工具侧等待不再受轮询粒度影响(`watch.pollMs` 保留为兜底)。
102
+ - **响应轻量化**:`GET /watch` 只回协议字段(`seq/applied_seq/state_seq/error/
103
+ title/shot_req/ui_seq/cmds/ui`),不回领域文档与截图 base64;`POST`(push/
104
+ ack/state/shot-*)响应同理只回回执字段。领域文档只在 `GET` 主端点(编辑器
105
+ restore)与 `GET /doc|/deck` 出全量。
106
+
107
+ ## 两种权威模式
108
+
109
+ - `authority: 'server'`:服务端执行命令,编辑器只拉镜像;PPT 使用这种模式。
110
+ - `authority: 'editor'`:服务端只 push,编辑器应用命令后 `POST /ack`;适合 Canvas 这类编辑器权威的模型。
111
+
112
+ ## 边界
113
+
114
+ - **不要**把 deck/slide/布局/审计等 PPT 领域逻辑放进本包。
115
+ - **不要**把本包做成 service plugin;它是被功能插件 import 的框架库。
116
+ - `@capyclaw/editor-host` 的 lease 是「浏览器标签页租约」;本包的 `owner` 是「文档归属租约」,两者不要混用。
117
+ - checkpoint 的领域载荷放在 `documentKey` 下(PPT 是 `deck`)。
118
+
119
+ ## 测试
120
+
121
+ ```bash
122
+ npm test
123
+ ```
124
+
125
+ 测试覆盖 session 状态迁移、串行批次、checkpoint/recover、owner lease、watch、sanitizer、op registry、bridge 端点、浏览器客户端以及编辑器权威模式。
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@capyclaw/document-workbench",
3
+ "version": "0.2.2",
4
+ "description": "通用文档工作台框架:版本化文档会话、命令注册、桥路由、浏览器编辑器客户端与截图协议。",
5
+ "type": "module",
6
+ "main": "./src/index.mjs",
7
+ "exports": {
8
+ ".": "./src/index.mjs",
9
+ "./session": "./src/session/index.mjs",
10
+ "./session-context": "./src/session/context.mjs",
11
+ "./session-mode": "./src/session/mode.mjs",
12
+ "./model": "./src/model/index.mjs",
13
+ "./ops": "./src/ops/index.mjs",
14
+ "./bridge": "./src/bridge/index.mjs",
15
+ "./client": "./src/client/index.mjs",
16
+ "./screenshot": "./src/client/screenshot.mjs",
17
+ "./testing": "./src/testing/index.mjs",
18
+ "./package.json": "./package.json",
19
+ "./store/file-backend": "./src/store/file-backend.mjs"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "dependencies": {
25
+ "@capyclaw/plugin-kit": "^0.2.0"
26
+ },
27
+ "files": [
28
+ "src/",
29
+ "README.md"
30
+ ],
31
+ "license": "MIT",
32
+ "scripts": {
33
+ "test": "node --test test/*.test.mjs"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/Maple496/capyclaw.git",
38
+ "directory": "C/packages/capyclaw-document-workbench"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/Maple496/capyclaw/issues"
42
+ },
43
+ "homepage": "https://github.com/Maple496/capyclaw/tree/main/C/packages/capyclaw-document-workbench#readme"
44
+ }
@@ -0,0 +1,321 @@
1
+ /**
2
+ * 文档桥路由:把 DocumentSession 暴露成与 PPT/Canvas 桥一致的 HTTP 端点。
3
+ * 业务语义仍由 session 的 apply 与调用方的 projection 承担。
4
+ */
5
+ import { intQ, readBody, send } from '@capyclaw/plugin-kit/service/http'
6
+ import { createSessionSanitizers } from '../session/sanitize.mjs'
7
+ import { ownerStatus } from '../session/lease.mjs'
8
+ import { watchSession } from '../session/watch.mjs'
9
+
10
+ /** 未回执批次年龄(秒):超过 pendingTtl 的批次会在下次 claim 时作废。 */
11
+ function pendingAgeOf(doc, now = Date.now() / 1000) {
12
+ if ((doc.seq | 0) <= (doc.applied_seq | 0)) return 0
13
+ const since = doc.pending_since || doc.updated || 0
14
+ return since ? Math.max(0, Math.round(now - since)) : 0
15
+ }
16
+
17
+ function normalizeBase(basePath) {
18
+ const value = String(basePath || '')
19
+ if (!value || value === '/') return ''
20
+ return value.replace(/\/+$/, '')
21
+ }
22
+
23
+ function errorStatus(error) {
24
+ return error && error.code === 'BODY_TOO_LARGE' ? 413 : 400
25
+ }
26
+
27
+ export function createDocumentBridge({
28
+ session,
29
+ basePath = '',
30
+ bridgeName = 'document-workbench',
31
+ documentKey = null,
32
+ documentPath = '/document',
33
+ authority = 'server',
34
+ apply = null,
35
+ isViewOp = () => false,
36
+ sanitizers = null,
37
+ bodyLimitBytes = 10 * 1024 * 1024,
38
+ watch = {},
39
+ projectStatus = () => ({}),
40
+ projectDocument = null,
41
+ projectTaskStatus = null,
42
+ /* E:通用镜像校验钩子(可选)。宿主注入自己的规则(如会话一致性),
43
+ * 返回 {ok:false,error} 即响亮拒绝(409)。桥本身不写死任何业务规则。 */
44
+ validateState = null,
45
+ /* F:通用认领校验钩子(可选)。宿主注入会话模式锁等规则,/claim 前调用,
46
+ * 返回 {ok:false,error} 即响亮拒绝(409)。桥本身不写死任何业务规则。 */
47
+ validateClaim = null,
48
+ } = {}) {
49
+ if (!session) throw new Error('createDocumentBridge 需要 session')
50
+ if (authority !== 'server' && authority !== 'editor') {
51
+ throw new Error('authority 只能是 server 或 editor')
52
+ }
53
+ if (authority === 'server' && typeof apply !== 'function') {
54
+ throw new Error('server authority 需要 apply(cmd)')
55
+ }
56
+
57
+ const prefix = normalizeBase(basePath)
58
+ const key = documentKey || session.documentKey || 'document'
59
+ const sanitize = sanitizers || createSessionSanitizers({ documentKey: key })
60
+ const documentEndpoint = documentPath || '/document'
61
+
62
+ async function readJson(req, res) {
63
+ try {
64
+ return { ok: true, body: await readBody(req, bodyLimitBytes) }
65
+ } catch (error) {
66
+ send(req, res, errorStatus(error), { error: String(error.message || error) })
67
+ return { ok: false }
68
+ }
69
+ }
70
+
71
+ function statusBody(doc) {
72
+ const owner = ownerStatus(doc)
73
+ return {
74
+ seq: doc.seq | 0,
75
+ applied_seq: doc.applied_seq | 0,
76
+ applied: doc.applied | 0,
77
+ error: doc.error || '',
78
+ shot_req: doc.shot_req | 0,
79
+ shot: { req: (doc.shot && doc.shot.req) || 0 },
80
+ shot_opts: doc.shot_opts || null,
81
+ state_seq: doc.state_seq | 0,
82
+ ui_seq: doc.ui_seq | 0,
83
+ owner,
84
+ /* 标准状态机:unclaimed / live / stale。健康检查与工具都读这两字段,
85
+ * 不再让调用方自己从 applied_seq 猜“桥断没断”。 */
86
+ editor_state: owner ? owner.state : 'unclaimed',
87
+ pending_age: pendingAgeOf(doc),
88
+ updated: doc.updated || 0,
89
+ ...(projectStatus(doc) || {}),
90
+ }
91
+ }
92
+
93
+ /** 长轮询轻量体:编辑器 pump 只消费这些字段。
94
+ * 旧实现回整个信封——大镜像/截图 base64 每次拾取都白白传一轮。 */
95
+ function watchBody(doc) {
96
+ return {
97
+ seq: doc.seq | 0,
98
+ applied_seq: doc.applied_seq | 0,
99
+ applied: doc.applied | 0,
100
+ state_seq: doc.state_seq | 0,
101
+ error: doc.error || '',
102
+ title: doc.title || '',
103
+ shot_req: doc.shot_req | 0,
104
+ /* 截图选项要跟 shot_req 同一轮送达:编辑器据此只渲染指定页。 */
105
+ shot_opts: doc.shot_opts || null,
106
+ ui_seq: doc.ui_seq | 0,
107
+ cmds: Array.isArray(doc.cmds) ? doc.cmds : [],
108
+ ui: Array.isArray(doc.ui) ? doc.ui : [],
109
+ }
110
+ }
111
+
112
+ /** push 回执轻量体:调用方只用 seq/回执字段,不需要镜像。 */
113
+ function pushBody(doc) {
114
+ return {
115
+ seq: doc.seq | 0,
116
+ applied_seq: doc.applied_seq | 0,
117
+ applied: doc.applied | 0,
118
+ error: doc.error || '',
119
+ }
120
+ }
121
+
122
+ function documentBody(doc) {
123
+ if (projectDocument) return projectDocument(doc)
124
+ return {
125
+ [key]: doc[key] || {},
126
+ state_seq: doc.state_seq | 0,
127
+ applied_seq: doc.applied_seq | 0,
128
+ }
129
+ }
130
+
131
+ const route = async (req, res, u) => {
132
+ const pathname = u.pathname
133
+ if (prefix && pathname !== prefix && !pathname.startsWith(prefix + '/')) return false
134
+ const sub = prefix ? pathname.slice(prefix.length) : pathname
135
+
136
+ /* 主端点:push / read */
137
+ if (sub === '' || sub === '/') {
138
+ if (req.method === 'POST') {
139
+ const parsed = await readJson(req, res)
140
+ if (!parsed.ok) return true
141
+ const data = sanitize.sanitizePush(parsed.body)
142
+ if (!data) {
143
+ send(req, res, 400, { error: `${bridgeName} 数据不合法` })
144
+ return true
145
+ }
146
+ const doc = authority === 'editor'
147
+ ? await session.enqueue(() => session.push(data.cmds, data.title))
148
+ : await session.runBatch({ cmds: data.cmds, title: data.title, apply, isViewOp })
149
+ send(req, res, 200, pushBody(doc))
150
+ return true
151
+ }
152
+ /* GET 全量信封:编辑器 restore(镜像恢复)专用。 */
153
+ send(req, res, 200, session.get())
154
+ return true
155
+ }
156
+
157
+ if (sub === '/ui' && (req.method === 'GET' || req.method === 'HEAD')) {
158
+ const doc = session.get()
159
+ send(req, res, 200, { ui_seq: doc.ui_seq | 0, ui: Array.isArray(doc.ui) ? doc.ui : [] })
160
+ return true
161
+ }
162
+
163
+ if (sub === '/task/status' && (req.method === 'GET' || req.method === 'HEAD')) {
164
+ send(req, res, 200, projectTaskStatus ? projectTaskStatus(session.get()) : session.taskStatus())
165
+ return true
166
+ }
167
+ if (sub === '/task/checkpoints' && (req.method === 'GET' || req.method === 'HEAD')) {
168
+ send(req, res, 200, { checkpoints: session.listCheckpoints() })
169
+ return true
170
+ }
171
+ if (sub === '/task/checkpoint' && (req.method === 'GET' || req.method === 'HEAD')) {
172
+ const name = u.searchParams.get('name')
173
+ if (!name) {
174
+ send(req, res, 400, { error: '缺少 checkpoint name' })
175
+ return true
176
+ }
177
+ try { send(req, res, 200, session.readCheckpoint(name)) }
178
+ catch (error) { send(req, res, 404, { error: String(error.message || error) }) }
179
+ return true
180
+ }
181
+ if (sub === '/task/checkpoint' && req.method === 'POST') {
182
+ const parsed = await readJson(req, res)
183
+ if (!parsed.ok) return true
184
+ const body = parsed.body
185
+ if (!body || typeof body.name !== 'string' || !body.name) {
186
+ send(req, res, 400, { error: '缺少 checkpoint name' })
187
+ return true
188
+ }
189
+ try {
190
+ const payload = await session.enqueue(() => session.checkpoint(body.name, body.meta || {}))
191
+ send(req, res, 200, payload)
192
+ } catch (error) {
193
+ send(req, res, 409, { error: String(error.message || error) })
194
+ }
195
+ return true
196
+ }
197
+
198
+ if (sub === '/watch' && (req.method === 'GET' || req.method === 'HEAD')) {
199
+ let aborted = false
200
+ req.on('close', () => { aborted = true })
201
+ const doc = await watchSession(session, {
202
+ seq: intQ(u, 'seq'),
203
+ shot: intQ(u, 'shot'),
204
+ ui: intQ(u, 'ui'),
205
+ timeoutS: u.searchParams.get('timeout'),
206
+ isAborted: () => aborted,
207
+ ...watch,
208
+ })
209
+ if (aborted || res.writableEnded || res.destroyed) return true
210
+ send(req, res, 200, watchBody(doc))
211
+ return true
212
+ }
213
+
214
+ if (sub === '/status' && (req.method === 'GET' || req.method === 'HEAD')) {
215
+ send(req, res, 200, statusBody(session.get()))
216
+ return true
217
+ }
218
+ if (sub === '/shot' && (req.method === 'GET' || req.method === 'HEAD')) {
219
+ const doc = session.get()
220
+ send(req, res, 200, {
221
+ req: (doc.shot && doc.shot.req) || 0,
222
+ data: (doc.shot && doc.shot.data) || '',
223
+ })
224
+ return true
225
+ }
226
+ if (sub === documentEndpoint && (req.method === 'GET' || req.method === 'HEAD')) {
227
+ send(req, res, 200, documentBody(session.get()))
228
+ return true
229
+ }
230
+
231
+ if (req.method !== 'POST') {
232
+ send(req, res, 404, { error: 'not found' })
233
+ return true
234
+ }
235
+ const parsed = await readJson(req, res)
236
+ if (!parsed.ok) return true
237
+
238
+ if (sub === '/claim') {
239
+ const data = sanitize.sanitizeClaim(parsed.body)
240
+ if (!data) {
241
+ send(req, res, 400, { error: `${bridgeName} 所有权声明不合法` })
242
+ return true
243
+ }
244
+ if (typeof validateClaim === 'function') {
245
+ const verdict = validateClaim({ sessionId: String(req.sessionId || ''), id: data.id, meta: data.meta })
246
+ if (verdict && verdict.ok === false) {
247
+ send(req, res, 409, { error: String(verdict.error || '认领被拒绝') })
248
+ return true
249
+ }
250
+ }
251
+ send(req, res, 200, session.claim(data.id, data.force, data.meta))
252
+ return true
253
+ }
254
+ if (sub === '/release') {
255
+ const data = sanitize.sanitizeClaim(parsed.body)
256
+ if (!data) {
257
+ send(req, res, 400, { error: `${bridgeName} 所有权声明不合法` })
258
+ return true
259
+ }
260
+ send(req, res, 200, session.release(data.id))
261
+ return true
262
+ }
263
+ if (sub === '/ack') {
264
+ const data = sanitize.sanitizeAck(parsed.body)
265
+ if (!data) {
266
+ send(req, res, 400, { error: `${bridgeName} 回执不合法` })
267
+ return true
268
+ }
269
+ await session.enqueue(() => session.ack(data.seq, data.applied, data.error, data.epoch))
270
+ send(req, res, 200, { ok: true })
271
+ return true
272
+ }
273
+ if (sub === '/state') {
274
+ const data = sanitize.sanitizeState(parsed.body)
275
+ if (!data) {
276
+ send(req, res, 400, { error: `${bridgeName} 状态不合法` })
277
+ return true
278
+ }
279
+ const value = data.value !== undefined ? data.value : data[key]
280
+ /* E:宿主校验钩子——异会话/非法镜像在这里被响亮拒绝(409),
281
+ * 而不是静默落库。req.sessionId 由会话分发层设置(无会话机制的宿主为空)。 */
282
+ if (typeof validateState === 'function') {
283
+ const verdict = validateState(value, {
284
+ clientId: data.clientId || '',
285
+ sessionId: data.sessionId || '',
286
+ seq: data.seq,
287
+ requestSessionId: String(req.sessionId || ''),
288
+ })
289
+ if (verdict && verdict.ok === false) {
290
+ send(req, res, 409, { error: verdict.error || `${bridgeName} 状态镜像被拒绝` })
291
+ return true
292
+ }
293
+ }
294
+ await session.enqueue(() => session.state(value, data.seq, { clientId: data.clientId, origin: 'editor-mirror' }))
295
+ /* 编辑器刚上传完全量镜像,不能再把整份回传给它——轻量确认即可。 */
296
+ send(req, res, 200, { ok: true, state_seq: session.get().state_seq | 0 })
297
+ return true
298
+ }
299
+ if (sub === '/shot-request') {
300
+ /* body 可选:老客户端 POST {} / 空体都按「整份拼图」处理。 */
301
+ session.shotRequest(parsed.body)
302
+ send(req, res, 200, { ok: true, shot_req: session.get().shot_req | 0 })
303
+ return true
304
+ }
305
+ if (sub === '/shot-result') {
306
+ const data = sanitize.sanitizeShotResult(parsed.body)
307
+ if (!data) {
308
+ send(req, res, 400, { error: `${bridgeName} 截图回传不合法` })
309
+ return true
310
+ }
311
+ session.shotResult(data.req, data.data)
312
+ send(req, res, 200, { ok: true })
313
+ return true
314
+ }
315
+
316
+ send(req, res, 404, { error: 'not found' })
317
+ return true
318
+ }
319
+
320
+ return { routes: [route], handle: route, documentKey: key, basePath: prefix }
321
+ }