cladogram 0.5.5-beta.2 → 0.5.5-beta.4

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.
@@ -0,0 +1,344 @@
1
+ /**
2
+ * 轻量插件市场底座:
3
+ * - 权限风险审计(auditPluginPermissions)
4
+ * - 插件脚手架生成(scaffoldPlugin:支持 ui 能力插件与 executor ACP 执行器插件)
5
+ * - 本地目录安全打包安装与卸载(installPluginFromDirectory / removeWorkspacePlugin)
6
+ * - 轻量 JSON Registry 索引读取与检索(loadRegistryIndex / searchRegistry)
7
+ */
8
+
9
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
10
+ import { extname, join, resolve } from 'node:path';
11
+ import { z } from 'zod/v4';
12
+ import { VERSION } from '../util/version.js';
13
+ import { fail, locked } from '../workspace/storage.js';
14
+ import { inspectWorkspacePlugins, installWorkspacePlugin, isReservedPluginId } from './plugins.js';
15
+
16
+ const registryEntrySchema = z.strictObject({
17
+ id: z.string().regex(/^[a-z0-9][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$/).max(80),
18
+ name: z.string().trim().min(1).max(80),
19
+ version: z.string().min(1).max(64),
20
+ description: z.string().max(400).default(''),
21
+ category: z.enum(['ui', 'executor', 'template', 'view', 'renderer']).default('ui'),
22
+ author: z.string().max(80).default('community'),
23
+ engines: z.strictObject({ clado: z.string().min(1).max(120) }).default({ clado: '^0.5.4' }),
24
+ permissions: z.array(z.string().max(120)).max(64).default([]),
25
+ homepage: z.string().max(512).optional(),
26
+ sourceDir: z.string().max(512).optional(),
27
+ tarballUrl: z.string().max(512).optional(),
28
+ sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),
29
+ });
30
+
31
+ const registrySchema = z.strictObject({
32
+ registryVersion: z.literal(1),
33
+ name: z.string().max(120).default('Clado Plugin Registry'),
34
+ plugins: z.array(registryEntrySchema).max(500),
35
+ });
36
+
37
+ export function auditPluginPermissions(manifestData = {}) {
38
+ const permissions = Array.isArray(manifestData.permissions) ? manifestData.permissions : [];
39
+ const capabilities = Array.isArray(manifestData.contributes?.capabilities) ? manifestData.contributes.capabilities : [];
40
+ const executors = Array.isArray(manifestData.contributes?.executors) ? manifestData.contributes.executors : [];
41
+ const items = [];
42
+ for (const perm of permissions) {
43
+ if (perm.startsWith('ui.mount:')) {
44
+ items.push({ permission: perm, risk: 'low', summary: `界面挂载:在 ${perm.slice('ui.mount:'.length)} 槽位渲染隔离面板` });
45
+ } else if (perm.startsWith('canvas.')) {
46
+ items.push({ permission: perm, risk: 'low', summary: `只读画布上下文:${perm}` });
47
+ } else if (perm.startsWith('capability.call:')) {
48
+ items.push({ permission: perm, risk: 'medium', summary: `跨插件调用:${perm.slice('capability.call:'.length)}` });
49
+ } else {
50
+ items.push({ permission: perm, risk: 'medium', summary: perm });
51
+ }
52
+ }
53
+ for (const cap of capabilities) {
54
+ if (cap?.exposeToAgent) {
55
+ items.push({ permission: `agent.capability:${cap.id}`, risk: 'medium', summary: `向 AI 暴露能力:${cap.id}` });
56
+ }
57
+ }
58
+ for (const exec of executors) {
59
+ items.push({ permission: `acp.executor:${exec.id}`, risk: 'high', summary: `注册本机 ACP 开发执行器:${exec.name || exec.id} (${exec.command})` });
60
+ }
61
+ const highestRisk = items.some(i => i.risk === 'high') ? 'high' : items.some(i => i.risk === 'medium') ? 'medium' : 'low';
62
+ return { highestRisk, items };
63
+ }
64
+
65
+ export function scaffoldPlugin({ dir, id, name, kind = 'ui' }) {
66
+ if (!id || !/^[a-z0-9][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$/.test(id)) {
67
+ fail('插件 ID 必须为反向域名格式(如 acme.review),仅允许小写字母、数字、连字符和点。', 400);
68
+ }
69
+ if (isReservedPluginId(id)) {
70
+ fail(`${id} 使用了 Clado 内置保留命名空间(clado.*),不能作为外部插件 ID。`, 400);
71
+ }
72
+ if (!['ui', 'executor'].includes(kind)) {
73
+ fail('插件脚手架 --kind 仅支持 ui 或 executor。', 400);
74
+ }
75
+ const targetDir = resolve(dir || id);
76
+ if (existsSync(targetDir)) fail(`目标目录已存在:${targetDir}`, 409);
77
+
78
+ const displayName = (name || id.split('.').pop()).trim();
79
+ const baseRange = '^0.5.4';
80
+ const manifest = {
81
+ manifestVersion: 1,
82
+ id,
83
+ name: displayName,
84
+ version: '0.1.0',
85
+ engines: { clado: baseRange },
86
+ protocols: ['1.0'],
87
+ entrypoints: { ui: { path: 'ui/index.html' } },
88
+ permissions: ['ui.mount:sidebar', 'canvas.document.read', 'canvas.selection.read'],
89
+ configuration: {
90
+ schema: {
91
+ type: 'object',
92
+ properties: { enabled: { type: 'boolean' } },
93
+ additionalProperties: false,
94
+ },
95
+ defaults: { enabled: true },
96
+ },
97
+ contributes: {
98
+ mounts: [{ id: 'panel', slot: 'sidebar' }],
99
+ capabilities: [
100
+ {
101
+ id: 'inspect.summary',
102
+ mount: 'panel',
103
+ version: '1.0.0',
104
+ description: `由 ${displayName} 提供的只读画布摘要能力`,
105
+ exposeToAgent: true,
106
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
107
+ outputSchema: {
108
+ type: 'object',
109
+ properties: { title: { type: 'string' }, selectedCount: { type: 'integer' } },
110
+ required: ['title', 'selectedCount'],
111
+ additionalProperties: false,
112
+ },
113
+ },
114
+ ],
115
+ ...(kind === 'executor' ? {
116
+ executors: [
117
+ {
118
+ id: id.replace(/\./g, '-') + '-acp',
119
+ name: `${displayName} 执行器`,
120
+ protocol: 'acp',
121
+ command: 'echo',
122
+ args: ['Replace with your ACP adapter command'],
123
+ capabilities: ['code.implement', 'test.run'],
124
+ description: '将 Clado 画布规格派发给外部 ACP 编码 Agent 的示例执行器',
125
+ },
126
+ ],
127
+ } : {}),
128
+ },
129
+ };
130
+
131
+ const html = `<!doctype html>
132
+ <html lang="zh-CN">
133
+ <head>
134
+ <meta charset="utf-8">
135
+ <title>${displayName}</title>
136
+ <link rel="stylesheet" href="/plugin-ui.css">
137
+ <link rel="stylesheet" href="./style.css">
138
+ </head>
139
+ <body>
140
+ <div class="plugin-card">
141
+ <h3>${displayName}</h3>
142
+ <p id="summary" class="muted">正在连接 Clado 宿主…</p>
143
+ <button id="refresh" type="button" class="clado-ui-button">读取当前画布</button>
144
+ </div>
145
+ <script src="/clado-plugin-sdk.js"></script>
146
+ <script src="./main.js"></script>
147
+ </body>
148
+ </html>
149
+ `;
150
+
151
+ const mainJs = `const plugin = window.CladoPluginSDK.connect();
152
+ const summary = document.getElementById('summary');
153
+
154
+ async function inspect() {
155
+ const ctx = await plugin.getContext(['document', 'selection']);
156
+ const title = ctx.document?.title || '未打开画布';
157
+ const count = Array.isArray(ctx.selection) ? ctx.selection.length : 0;
158
+ summary.textContent = \`当前画布:\${title}(已选 \${count} 个节点)\`;
159
+ return { title, selectedCount: count };
160
+ }
161
+
162
+ plugin.provideCapability('inspect.summary', () => inspect());
163
+ document.getElementById('refresh').onclick = () => inspect();
164
+ inspect().catch(() => { summary.textContent = '就绪'; });
165
+ `;
166
+
167
+ const css = `.plugin-card { padding: 12px; display: flex; flex-direction: column; gap: 8px; font-size: 13px; }
168
+ .plugin-card h3 { margin: 0; font-size: 14px; }
169
+ .plugin-card .muted { margin: 0; color: var(--clado-ui-muted, #667085); }
170
+ `;
171
+
172
+ mkdirSync(join(targetDir, 'ui'), { recursive: true });
173
+ writeFileSync(join(targetDir, 'clado-plugin.json'), JSON.stringify(manifest, null, 2) + '\n');
174
+ writeFileSync(join(targetDir, 'ui', 'index.html'), html);
175
+ writeFileSync(join(targetDir, 'ui', 'main.js'), mainJs);
176
+ writeFileSync(join(targetDir, 'ui', 'style.css'), css);
177
+
178
+ return {
179
+ id,
180
+ name: displayName,
181
+ kind,
182
+ directory: targetDir,
183
+ files: ['clado-plugin.json', 'ui/index.html', 'ui/main.js', 'ui/style.css'],
184
+ audit: auditPluginPermissions(manifest),
185
+ };
186
+ }
187
+
188
+ const allowedAssetExts = new Set(['.html', '.js', '.mjs', '.css', '.json', '.svg', '.png', '.jpg', '.jpeg', '.gif', '.webp', '.woff2']);
189
+
190
+ export function collectPluginDirectoryFiles(sourceDir) {
191
+ const root = resolve(sourceDir);
192
+ if (!existsSync(root) || !lstatSync(root).isDirectory()) {
193
+ fail(`插件目录不存在或不是实体目录:${sourceDir}`, 404);
194
+ }
195
+ const files = [];
196
+ const manifestPath = join(root, 'clado-plugin.json');
197
+ if (!existsSync(manifestPath) || !lstatSync(manifestPath).isFile()) {
198
+ fail('插件目录缺少 clado-plugin.json。', 422);
199
+ }
200
+ const manifestRaw = readFileSync(manifestPath);
201
+ files.push({ path: 'clado-plugin.json', data: manifestRaw.toString('base64') });
202
+
203
+ const uiDir = join(root, 'ui');
204
+ if (existsSync(uiDir) && lstatSync(uiDir).isDirectory()) {
205
+ const walk = (dir, relPrefix) => {
206
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
207
+ if (entry.name.startsWith('.')) continue;
208
+ const full = join(dir, entry.name);
209
+ const info = lstatSync(full);
210
+ if (info.isSymbolicLink()) fail(`插件目录不允许包含符号链接:${relPrefix}/${entry.name}`, 422);
211
+ const rel = `${relPrefix}/${entry.name}`;
212
+ if (info.isDirectory()) walk(full, rel);
213
+ else if (info.isFile()) {
214
+ if (!allowedAssetExts.has(extname(entry.name).toLowerCase())) {
215
+ fail(`插件包不支持的文件类型:${rel}`, 422);
216
+ }
217
+ files.push({ path: rel, data: readFileSync(full).toString('base64') });
218
+ }
219
+ }
220
+ };
221
+ walk(uiDir, 'ui');
222
+ }
223
+ let parsedManifest = {};
224
+ try { parsedManifest = JSON.parse(manifestRaw.toString('utf8')); } catch {}
225
+ return { files, audit: auditPluginPermissions(parsedManifest) };
226
+ }
227
+
228
+ export function installPluginFromDirectory(ctx, sourceDir, runtime = null) {
229
+ const { files, audit } = collectPluginDirectoryFiles(sourceDir);
230
+ const installed = installWorkspacePlugin(ctx, files, runtime);
231
+ return { ...installed, audit };
232
+ }
233
+
234
+ export function removeWorkspacePlugin(ctx, id) {
235
+ if (!id || typeof id !== 'string') fail('缺少要卸载的插件 ID。', 400);
236
+ if (isReservedPluginId(id)) fail(`内置插件 ${id} 受系统保护,不可卸载。`, 403);
237
+ if (!/^[a-z0-9][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$/.test(id)) fail('插件 ID 格式无效。', 400);
238
+ return locked(ctx, () => {
239
+ const dir = join(ctx.state, 'plugins');
240
+ if (!existsSync(dir) || !lstatSync(dir).isDirectory()) fail(`工作区尚未安装插件:${id}`, 404);
241
+ const direct = join(dir, id);
242
+ let target = existsSync(direct) && lstatSync(direct).isDirectory() ? direct : null;
243
+ if (!target) {
244
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
245
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
246
+ const mPath = join(dir, entry.name, 'clado-plugin.json');
247
+ if (!existsSync(mPath)) continue;
248
+ try {
249
+ if (JSON.parse(readFileSync(mPath, 'utf8')).id === id) { target = join(dir, entry.name); break; }
250
+ } catch {}
251
+ }
252
+ }
253
+ if (!target) fail(`找不到已安装的插件:${id}`, 404);
254
+ rmSync(target, { recursive: true, force: true });
255
+ return { removed: true, id };
256
+ });
257
+ }
258
+
259
+ export function listInstalledWorkspacePlugins(stateDir) {
260
+ const basic = inspectWorkspacePlugins(stateDir);
261
+ const pluginsDir = join(stateDir, 'plugins');
262
+ return basic.map(item => {
263
+ let manifestData = {};
264
+ try {
265
+ const mPath = join(pluginsDir, item.id, 'clado-plugin.json');
266
+ if (existsSync(mPath)) manifestData = JSON.parse(readFileSync(mPath, 'utf8'));
267
+ } catch {}
268
+ return {
269
+ ...item,
270
+ permissions: Array.isArray(manifestData.permissions) ? manifestData.permissions : [],
271
+ audit: auditPluginPermissions(manifestData),
272
+ };
273
+ });
274
+ }
275
+
276
+ const DEFAULT_REGISTRY = {
277
+ registryVersion: 1,
278
+ name: 'Clado Built-in Starter Catalog',
279
+ plugins: [
280
+ {
281
+ id: 'starter.review-sidebar',
282
+ name: '画布评审侧栏(官方脚手架示例)',
283
+ version: '0.1.0',
284
+ description: '展示如何读取画布文档与选区并向 AI 暴露结构化能力;可通过 clado plugin create --kind ui 一键生成。',
285
+ category: 'ui',
286
+ author: 'Clado',
287
+ engines: { clado: '^0.5.4' },
288
+ permissions: ['ui.mount:sidebar', 'canvas.document.read', 'canvas.selection.read'],
289
+ },
290
+ {
291
+ id: 'starter.acp-executor',
292
+ name: 'ACP 外包编码执行器(官方脚手架示例)',
293
+ version: '0.1.0',
294
+ description: '将画布设计规格一键派发给外部 ACP 编码 Agent(Codex / Claude Code / Gemini CLI 等);可通过 clado plugin create --kind executor 一键生成。',
295
+ category: 'executor',
296
+ author: 'Clado',
297
+ engines: { clado: '^0.5.4' },
298
+ permissions: ['ui.mount:sidebar', 'canvas.document.read'],
299
+ },
300
+ ],
301
+ };
302
+
303
+ export async function loadRegistryIndex({ registry = '', stateDir = '', fetchImpl = fetch } = {}) {
304
+ const source = registry || process.env.CLADO_PLUGIN_REGISTRY || (stateDir && existsSync(join(stateDir, 'plugin-registry.json')) ? join(stateDir, 'plugin-registry.json') : '');
305
+ let rawData = DEFAULT_REGISTRY;
306
+ let origin = 'builtin';
307
+ if (source) {
308
+ if (/^https?:\/\//i.test(source)) {
309
+ const res = await fetchImpl(source, { headers: { accept: 'application/json' } });
310
+ if (!res.ok) fail(`拉取插件索引失败(HTTP ${res.status}):${source}`, 502);
311
+ rawData = await res.json();
312
+ origin = source;
313
+ } else {
314
+ const filePath = resolve(source.replace(/^file:\/\//, ''));
315
+ if (!existsSync(filePath)) fail(`找不到插件索引文件:${source}`, 404);
316
+ rawData = JSON.parse(readFileSync(filePath, 'utf8'));
317
+ origin = filePath;
318
+ }
319
+ }
320
+ const parsed = registrySchema.safeParse(rawData);
321
+ if (!parsed.success) {
322
+ const issue = parsed.error.issues[0];
323
+ fail(`插件市场索引格式无效(${issue.path.join('.') || 'root'}):${issue.message}`, 422);
324
+ }
325
+ return {
326
+ origin,
327
+ name: parsed.data.name,
328
+ plugins: parsed.data.plugins
329
+ .filter(p => !isReservedPluginId(p.id))
330
+ .map(p => ({ ...p, audit: auditPluginPermissions(p) })),
331
+ };
332
+ }
333
+
334
+ export function searchRegistry(registryData, query = '') {
335
+ const q = String(query || '').trim().toLowerCase();
336
+ const list = Array.isArray(registryData?.plugins) ? registryData.plugins : [];
337
+ if (!q) return list;
338
+ return list.filter(item =>
339
+ item.id.toLowerCase().includes(q)
340
+ || item.name.toLowerCase().includes(q)
341
+ || item.description.toLowerCase().includes(q)
342
+ || item.category.toLowerCase().includes(q)
343
+ );
344
+ }
@@ -106,7 +106,7 @@ function readManifest(root) {
106
106
  }
107
107
  const data = result.data;
108
108
  if (isReservedPluginId(data.id)) throw new Error(data.id + ' 使用了 Clado 保留命名空间(clado.*)。');
109
- if (!semver.validRange(data.engines.clado) || !semver.satisfies(VERSION, data.engines.clado)) {
109
+ if (!semver.validRange(data.engines.clado) || !semver.satisfies(VERSION, data.engines.clado, { includePrerelease: true })) {
110
110
  throw new Error(`插件需要 Clado ${data.engines.clado},当前版本为 ${VERSION}。`);
111
111
  }
112
112
  if (!data.protocols.includes(PLUGIN_PROTOCOL)) throw new Error(`插件需要声明协议 ${PLUGIN_PROTOCOL}。`);
@@ -10,6 +10,7 @@ import { contextFor, discoverWorkspaces, initialize } from '../workspace/storage
10
10
  import { createWorkspaceService } from '../workspace/service.js';
11
11
  import { createMcpHandler } from './mcp.js';
12
12
  import { builtInCapabilities, builtInGrants, inspectWorkspacePlugins, installWorkspacePlugin, loadWorkspacePlugins } from './plugins.js';
13
+ import { loadRegistryIndex, removeWorkspacePlugin, searchRegistry } from './plugin-registry.js';
13
14
  import { createCapabilityRegistry } from './plugin-capabilities.js';
14
15
  import { createPluginSettings } from './plugin-settings.js';
15
16
  import { createWorkspaceEvents, broadcastMcpEvent } from './events.js';
@@ -95,6 +96,12 @@ export function createWorkspaceHandler(directory, options = {}) {
95
96
  return true;
96
97
  }
97
98
  if (options.installPlugin && url.pathname === '/library/install-plugin') {
99
+ if (req.method === 'DELETE' && options.removePlugin) {
100
+ if (req.headers.origin !== 'http://' + host) throw new DocumentError('卸载插件需要在工作区页面操作。', 403);
101
+ const target = resolveTarget(url);
102
+ json(res, 200, options.removePlugin(target.workspace, url.searchParams.get('id')));
103
+ return true;
104
+ }
98
105
  if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
99
106
  throw new DocumentError('插件安装需要在工作区页面操作。', 403);
100
107
  }
@@ -108,6 +115,12 @@ export function createWorkspaceHandler(directory, options = {}) {
108
115
  json(res, 201, options.installPlugin(target.workspace, JSON.parse(Buffer.concat(chunks).toString('utf8'))?.files));
109
116
  return true;
110
117
  }
118
+ if (url.pathname === '/library/plugin-registry' && options.readPluginRegistry) {
119
+ if (req.method !== 'GET') throw new DocumentError('插件市场索引仅支持 GET。', 405);
120
+ const target = resolveTarget(url);
121
+ json(res, 200, await options.readPluginRegistry(target.workspace, url.searchParams.get('q') || ''));
122
+ return true;
123
+ }
111
124
  if (options.capabilities && url.pathname === '/library/plugin-bridge') {
112
125
  const view = z.uuid().safeParse(url.searchParams.get('viewId'));
113
126
  if (!view.success) throw new DocumentError('需要有效的 viewId。', 400);
@@ -321,10 +334,19 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
321
334
  }
322
335
  throw new DocumentError('插件资源不存在。', 404);
323
336
  }
337
+ function removePlugin(targetWorkspace, id) {
338
+ const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
339
+ return removeWorkspacePlugin(rt.ctx, id);
340
+ }
341
+ async function readPluginRegistry(targetWorkspace, query) {
342
+ const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
343
+ const reg = await loadRegistryIndex({ stateDir: rt.ctx.state });
344
+ return { name: reg.name, origin: reg.origin, plugins: searchRegistry(reg, query) };
345
+ }
324
346
  const handle = createWorkspaceHandler(root,{
325
347
  entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,
326
348
  plugins:rootRuntime.plugins,experimentalPlugins,servePluginAsset,
327
- agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,
349
+ agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,removePlugin,readPluginRegistry,
328
350
  resolveWorkspace:resolveWorkspaceParam,
329
351
  listWorkspaces:() => discoverWorkspaces(workspace, root),
330
352
  scopeName:basename(workspace),
@@ -7,7 +7,7 @@ import { ancestorTemplateContexts, contextFor, discoverWorkspaces, initialize, l
7
7
  import { allReferences, linkHref, resolveReference, rewriteReferences } from './references.js';
8
8
  import { editContent, paragraphs, paragraphLocations, contentLocation } from './content.js';
9
9
  import { markdownLinks } from '../core/links.js';
10
- import { blockMedia, mediaLinkLocations, mediaLinkTitle, mediaPointFits, mediaTargetPoint, tableBlock } from '../core/media-links.js';
10
+ import { blockMedia, findTargetLineOffset, formatTargetPoint, mediaBlockByIndex, mediaLinkLocations, mediaLinkTitle, mediaPointFits, mediaTargetPoint } from '../core/media-links.js';
11
11
  import { sortDiagnostics, summarizeDiagnostics } from '../core/diagnostics.js';
12
12
 
13
13
  const copySnapshot = state => ({ ...state, documents: new Map(state.documents), templates: new Map(state.templates) });
@@ -30,9 +30,28 @@ function locatedReferences(documents) {
30
30
  }
31
31
 
32
32
  function targetMediaPoint(record, point) {
33
- const block = tableBlock(record.node.content, point.table);
34
- if (!block || point.row > block.rows) return null;
35
- return publicMediaPoint(record, { ...block, point: { kind: 'table', row: point.row } });
33
+ if (!record || !point) return null;
34
+ if (point.kind === 'line') {
35
+ const found = findTargetLineOffset(record.node.content, point.text);
36
+ if (!found) return null;
37
+ const loc = contentLocation(record.node.content, found.start, found.end, record.node.location.bodyStartLine);
38
+ return { kind: 'line', text: point.text, paragraph: loc.paragraph, documentLine: loc.startLine };
39
+ }
40
+ const index = point.kind === 'table' ? point.table : point.block;
41
+ const block = mediaBlockByIndex(record.node.content, point.kind, index);
42
+ if (!block) return null;
43
+ if (point.kind === 'table') {
44
+ if (point.row > block.media.rows && !point.text) return null;
45
+ return publicMediaPoint(record, { ...block, point: { kind: 'table', row: point.row, ...(point.text ? { text: point.text } : {}) } });
46
+ }
47
+ if (point.kind === 'code') {
48
+ if (point.line > block.media.lines.length && !point.text) return null;
49
+ return publicMediaPoint(record, { ...block, point: { kind: 'code', line: point.line, ...(point.text ? { text: point.text } : {}) } });
50
+ }
51
+ if (point.kind === 'mermaid') {
52
+ return publicMediaPoint(record, { ...block, point: { kind: 'mermaid', nodeId: point.nodeId } });
53
+ }
54
+ return null;
36
55
  }
37
56
 
38
57
  function publicMediaPoint(record, media) {
@@ -63,7 +82,7 @@ function receipt(op, operationIndex, feedback = {}) {
63
82
  }
64
83
 
65
84
  function resolveResults(state, results) {
66
- return results.map(({ contentText, contentRange, contentBodyVersion, mediaLinkOnly, ...result }) => {
85
+ return results.map(({ contentText, contentRange, contentBodyVersion, mediaLinkOnly, hasTargetPoint, ...result }) => {
67
86
  if (result.kind === 'template') return { ...result, deleted: !state.templates.has(result.file), ...(state.templates.has(result.file) ? { version: versionOf(state.templates.get(result.file)) } : {}) };
68
87
  if (result.deleted || !state.documents.has(result.file)) return { ...result, deleted: true };
69
88
  const source = state.documents.get(result.file), tree = treeOf(source, result.file), located = { ...result, version: versionOf(source) };
@@ -79,11 +98,13 @@ function resolveResults(state, results) {
79
98
  else {
80
99
  located.contentLocationStatus = 'exact';
81
100
  located.contentLocation = contentLocation(record.node.content, start, start + contentText.length, record.node.location.bodyStartLine);
82
- if (mediaLinkOnly) {
101
+ if (mediaLinkOnly || hasTargetPoint) {
83
102
  const links = markdownLinks(record.node.content);
84
103
  const link = links.find(ref => ref.start === start);
85
- const point = mediaLinkLocations(record.node.content, links).get(start);
86
- if (point?.valid) located.sourcePoint = publicMediaPoint(record, point);
104
+ if (mediaLinkOnly) {
105
+ const point = mediaLinkLocations(record.node.content, links).get(start);
106
+ if (point?.valid) located.sourcePoint = publicMediaPoint(record, point);
107
+ }
87
108
  const targetPoint = mediaTargetPoint(link?.title), target = link && resolveReference(link.target, result.file, state.documents);
88
109
  if (targetPoint && target?.path) located.targetPoint = targetMediaPoint(findNode(getTree(state, target.file), target.path), targetPoint);
89
110
  }
@@ -195,8 +216,8 @@ function checkWriteBase(state, op, workspaceGuarded) {
195
216
  }
196
217
  if (!workspaceGuarded && type === 'node.move' && op.index !== undefined && op.targetFile && op.targetFile !== file) fail('跨文档按序号移动需要 expectedWorkspaceVersion。', 400, { code: 'WRITE_BASE_REQUIRED' });
197
218
  if (workspaceGuarded || expectedFileVersion !== undefined) return;
198
- const needsFileVersion = type === 'node.create' && op.index !== undefined || type === 'node.move' && op.index !== undefined || type === 'link.connect' && op.targetPoint;
199
- if (needsFileVersion) fail('按同级序号或目标表格行写入,需要 expectedFileVersion。', 400, { code: 'WRITE_BASE_REQUIRED' });
219
+ const needsFileVersion = type === 'node.create' && op.index !== undefined || type === 'node.move' && op.index !== undefined || type === 'link.connect' && op.targetPoint && op.targetPoint.kind !== 'line';
220
+ if (needsFileVersion) fail('按同级序号或目标段落编号写入,需要 expectedFileVersion。', 400, { code: 'WRITE_BASE_REQUIRED' });
200
221
  if (expectedNodeVersion !== undefined) return;
201
222
  const safeWithoutVersion = ['document.create', 'document.copy', 'node.create'].includes(type) ||
202
223
  type === 'node.update' && position?.anchor !== undefined ||
@@ -326,9 +347,8 @@ function applyOperation(ctx, state, op) {
326
347
  const label = op.label || targetPath?.at(-1) || targetTree.doc.title;
327
348
  if (/[\r\n\[\]]/.test(label)) fail('label 需要单行文字,不能含方括号。');
328
349
  let placement = op.position;
329
- if (op.targetPoint && !op.sourcePoint) fail('targetPoint 需要同时指定 sourcePoint。');
350
+ if ((op.sourcePoint || op.targetPoint) && targetFile !== file) fail('精确线端点要连接同一画布内的节点。');
330
351
  if (op.sourcePoint) {
331
- if (targetFile !== file) fail('精确线端点要连接同一画布内的节点。');
332
352
  if (op.position || op.before || op.after) fail('sourcePoint 已经确定位置,独立连线标注不接受 position、before 或 after。');
333
353
  const block = paragraphs(record.node.content)[op.sourcePoint.paragraph - 1];
334
354
  if (!block || !mediaPointFits(blockMedia(block.text), op.sourcePoint)) fail('指定段落中找不到这个代码行、表格行或 Mermaid 节点。', 422, { code: 'INVALID_MEDIA_SOURCE' });
@@ -336,11 +356,28 @@ function applyOperation(ctx, state, op) {
336
356
  }
337
357
  let title = op.sourcePoint ? mediaLinkTitle(op.sourcePoint) : '';
338
358
  if (op.targetPoint) {
339
- const blocks = paragraphs(targetRecord.node.content).slice(0, op.targetPoint.paragraph);
340
- const last = blocks.at(-1);
341
- if (last?.index !== op.targetPoint.paragraph || !mediaPointFits(blockMedia(last.text), op.targetPoint)) fail('目标段落中找不到这个表格数据行。', 422, { code: 'INVALID_MEDIA_TARGET' });
342
- const table = blocks.filter(block => blockMedia(block.text)?.kind === 'table').length;
343
- title += ';to:' + table + ':' + op.targetPoint.row;
359
+ const tp = op.targetPoint;
360
+ let formattedTarget = '';
361
+ if (tp.kind === 'line') {
362
+ if (!findTargetLineOffset(targetRecord.node.content, tp.text)) {
363
+ fail('目标节点正文中找不到指定的行锚点文本:' + tp.text, 422, { code: 'INVALID_MEDIA_TARGET' });
364
+ }
365
+ formattedTarget = formatTargetPoint({ kind: 'line', text: tp.text }, { standalone: !op.sourcePoint });
366
+ } else {
367
+ const blocks = paragraphs(targetRecord.node.content).slice(0, tp.paragraph);
368
+ const last = blocks.at(-1);
369
+ if (last?.index !== tp.paragraph || !mediaPointFits(blockMedia(last.text), tp)) {
370
+ fail('目标段落中找不到指定的代码行、表格行或 Mermaid 节点。', 422, { code: 'INVALID_MEDIA_TARGET' });
371
+ }
372
+ const blockIndex = blocks.filter(block => blockMedia(block.text)?.kind === tp.kind).length;
373
+ const spec = tp.kind === 'table'
374
+ ? { kind: 'table', table: blockIndex, row: tp.row, ...(tp.text ? { text: tp.text } : {}) }
375
+ : tp.kind === 'code'
376
+ ? { kind: 'code', block: blockIndex, line: tp.line, ...(tp.text ? { text: tp.text } : {}) }
377
+ : { kind: 'mermaid', block: blockIndex, nodeId: tp.nodeId };
378
+ formattedTarget = formatTargetPoint(spec, { standalone: !op.sourcePoint });
379
+ }
380
+ title = title ? (title + ';' + formattedTarget) : formattedTarget;
344
381
  }
345
382
  const linkText = '[' + label + '](<' + href + '>' + (title ? ' "' + title + '"' : '') + ')';
346
383
  const text = (op.before || '') + linkText + (op.after || '');
@@ -351,13 +388,13 @@ function applyOperation(ctx, state, op) {
351
388
  if (op.sourcePoint && !mediaLinkLocations(edited.content, links).get(expectedStart)?.valid) fail('无法将链接绑定到指定内容。', 422, { code: 'INVALID_MEDIA_SOURCE' });
352
389
  checkBody(edited.content);
353
390
  state.documents.set(file, replaceNodeBody(tree, record.node, edited.content));
354
- return { contentText: linkText, contentRange: { start: expectedStart, end: expectedStart + linkText.length }, contentBodyVersion: versionOf(edited.content), placement: placement || { mode: 'append' }, mediaLinkOnly: !!op.sourcePoint };
391
+ return { contentText: linkText, contentRange: { start: expectedStart, end: expectedStart + linkText.length }, contentBodyVersion: versionOf(edited.content), placement: placement || { mode: 'append' }, mediaLinkOnly: !!op.sourcePoint, hasTargetPoint: !!op.targetPoint };
355
392
  }
356
393
  if (type === 'link.disconnect') {
357
394
  const matching = locatedReferences(before).filter(r => r.file === file && samePath(r.node, record.path) && (op.linkIndex === undefined || r.linkIndex === op.linkIndex) && (op.linkIndex !== undefined && op.targetFile === undefined && op.targetNode === undefined || r.target.file === (op.targetFile || file) && samePath(r.target.path, op.targetNode || null)));
358
395
  if (!matching.length) fail('找不到这条链接。', 404);
359
396
  let content = record.node.content;
360
- for (const ref of matching.sort((a, b) => b.link.start - a.link.start)) content = content.slice(0, ref.link.start) + (ref.link.title?.startsWith('clado:') ? '' : ref.label) + content.slice(ref.link.end);
397
+ for (const ref of matching.sort((a, b) => b.link.start - a.link.start)) content = content.slice(0, ref.link.start) + (ref.sourcePoint ? '' : ref.label) + content.slice(ref.link.end);
361
398
  state.documents.set(file, replaceNodeBody(tree, record.node, content)); return;
362
399
  }
363
400
  fail('不支持的操作:' + type);