cladogram 0.5.5-beta.3 → 0.5.5-beta.5

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),
@@ -1,10 +1,22 @@
1
1
  import { posix } from 'node:path';
2
2
  import { markdownLinks } from '../core/links.js';
3
3
  import { mediaLinkLocations } from '../core/media-links.js';
4
+ import { extractTagsFromBody } from '../core/tags.js';
4
5
  import { treeOf, records, samePath, insidePath, serializeTree } from './tree.js';
5
6
  import { fail } from './storage.js';
6
7
 
7
8
  const decode = value => { try { return decodeURIComponent(value); } catch { return value; } };
9
+ function findTagOwners(all, tagId, scopeOwners = null) {
10
+ const hits = [];
11
+ for (const r of all) {
12
+ if (scopeOwners && !scopeOwners.some(o => insidePath(r.path, o.path))) continue;
13
+ const tags = extractTagsFromBody(r.node.content || '');
14
+ for (const tag of tags) {
15
+ if (tag.id && tag.id === tagId) hits.push({ record: r, tag });
16
+ }
17
+ }
18
+ return hits;
19
+ }
8
20
  export function resolveReference(target, sourceFile, documents) {
9
21
  if (/^(?:[a-z][a-z0-9+.-]*:|\/\/|\/)/i.test(target)) return null;
10
22
  let file = sourceFile, wanted = target;
@@ -24,12 +36,28 @@ export function resolveReference(target, sourceFile, documents) {
24
36
  const owners = all.filter(r => r.node.title === head || r.path.join('.') === head);
25
37
  if (!owners.length) continue;
26
38
  hits = all.filter(r => owners.some(o => insidePath(r.path, o.path) && r.path.length > o.path.length) && (r.node.title === tail || r.path.slice(1).join('.') === tail));
39
+ if (!hits.length) {
40
+ const tagHits = findTagOwners(all, tail, owners);
41
+ if (tagHits.length === 1) return { file, path: tagHits[0].record.path, tagId: tagHits[0].tag.id };
42
+ if (tagHits.length > 1) return { file, path: null, missing: true, ambiguous: true };
43
+ }
27
44
  break;
28
45
  }
29
46
  }
47
+ if (!hits.length) {
48
+ const tagHits = findTagOwners(all, wanted);
49
+ if (tagHits.length === 1) return { file, path: tagHits[0].record.path, tagId: tagHits[0].tag.id };
50
+ if (tagHits.length > 1) return { file, path: null, missing: true, ambiguous: true };
51
+ }
30
52
  return hits.length === 1 ? { file, path: hits[0].path } : { file, path: null, missing: true, ambiguous: hits.length > 1 };
31
53
  }
32
- export function linkHref(sourceFile, targetFile, targetPath) {
54
+ export function linkHref(sourceFile, targetFile, targetPath, tagId = '') {
55
+ if (tagId) {
56
+ const encodedTag = encodeURIComponent(tagId).replace(/[!'()*]/g, ch => '%' + ch.charCodeAt(0).toString(16).toUpperCase());
57
+ if (sourceFile === targetFile) return '#' + encodedTag;
58
+ const file = posix.relative(posix.dirname(sourceFile), targetFile).split('/').map(encodeURIComponent).join('/');
59
+ return file + '#' + encodedTag;
60
+ }
33
61
  const path = targetPath?.join('.') || '';
34
62
  const encoded = encodeURIComponent(path).replace(/[!'()*]/g, ch => '%' + ch.charCodeAt(0).toString(16).toUpperCase());
35
63
  if (sourceFile === targetFile && path) return encoded;
@@ -64,12 +92,12 @@ export function rewriteReferences(before, after, mapping, unlink = false) {
64
92
  const source = map(ref.file, ref.node), target = map(ref.target.file, ref.target.path);
65
93
  if (!source) continue;
66
94
  if (!target && !unlink) fail('目标仍被引用;先断开引用,或显式使用 unlink。', 409, { code: 'REFERENCED', references: [{ file: ref.file, node: ref.node, label: ref.label }] });
67
- if (target && source.file === ref.file && target.file === ref.target.file && samePath(target.path, ref.target.path)) continue;
95
+ if (target && source.file === ref.file && target.file === ref.target.file && (ref.target.tagId || samePath(target.path, ref.target.path))) continue;
68
96
  const key = JSON.stringify(source);
69
97
  if (!patches.has(key)) patches.set(key, { ...source, edits: [] });
70
- const label = target?.path && ref.target.path && ref.label === ref.target.path.at(-1) ? target.path.at(-1) : ref.label;
98
+ const label = !ref.target.tagId && target?.path && ref.target.path && ref.label === ref.target.path.at(-1) ? target.path.at(-1) : ref.label;
71
99
  const title = ref.link.title?.startsWith('clado:') ? ' "' + ref.link.title + '"' : '';
72
- patches.get(key).edits.push({ start: ref.link.start, end: ref.link.end, text: target ? '[' + label + '](<' + linkHref(source.file, target.file, target.path) + '>' + title + ')' : ref.media ? '' : ref.label });
100
+ patches.get(key).edits.push({ start: ref.link.start, end: ref.link.end, text: target ? '[' + label + '](<' + linkHref(source.file, target.file, target.path, ref.target.tagId) + '>' + title + ')' : ref.media ? '' : ref.label });
73
101
  }
74
102
  // 文件或子树跨目录后,图片、附件及原本未解析的文件链接也保持原目标。
75
103
  for (const [file, text] of before) for (const record of records(treeOf(text, file))) {