@tokenroll/llmdoc 3.5.1 → 3.5.2

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,471 @@
1
+ import { buildDocumentGraph, buildTopicGraph, STATUS_COLOR } from "./viewer-model.js";
2
+
3
+ const SVG_NS = "http://www.w3.org/2000/svg";
4
+ const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
5
+
6
+ export function layoutGraph(graph, width, height, mode) {
7
+ const nodes = graph.nodes.map((node) => ({ ...node, x: 0, y: 0, vx: 0, vy: 0 }));
8
+ const edges = graph.edges.map((edge) => ({ ...edge }));
9
+ if (!nodes.length) return { nodes, edges };
10
+
11
+ const margin = 54;
12
+ const usableWidth = Math.max(160, width - margin * 2);
13
+ const usableHeight = Math.max(160, height - margin * 2);
14
+ const centerX = width / 2;
15
+ const centerY = height / 2;
16
+ const byId = new Map(nodes.map((node) => [node.id, node]));
17
+ const indexById = new Map(nodes.map((node, index) => [node.id, index]));
18
+
19
+ if (mode === "docs") initializeDocumentClusters(nodes, centerX, centerY, usableWidth, usableHeight);
20
+ else initializeRadial(nodes, centerX, centerY, Math.min(usableWidth, usableHeight) * .43);
21
+
22
+ const iterations = nodes.length > 500 ? 22 : nodes.length > 200 ? 30 : nodes.length > 80 ? 42 : 64;
23
+ const cellSize = Math.max(56, Math.min(110, Math.min(usableWidth, usableHeight) / 5));
24
+ const clusterCenters = buildClusterCenters(nodes, centerX, centerY, usableWidth, usableHeight);
25
+
26
+ for (let iteration = 0; iteration < iterations; iteration += 1) {
27
+ const cells = new Map();
28
+ for (const node of nodes) {
29
+ const key = cellKey(node.x, node.y, cellSize);
30
+ const bucket = cells.get(key) ?? [];
31
+ bucket.push(node);
32
+ cells.set(key, bucket);
33
+ }
34
+
35
+ for (const node of nodes) {
36
+ const cellX = Math.floor(node.x / cellSize);
37
+ const cellY = Math.floor(node.y / cellSize);
38
+ for (let offsetX = -1; offsetX <= 1; offsetX += 1) {
39
+ for (let offsetY = -1; offsetY <= 1; offsetY += 1) {
40
+ const bucket = cells.get(`${cellX + offsetX}:${cellY + offsetY}`) ?? [];
41
+ for (const other of bucket) {
42
+ if ((indexById.get(other.id) ?? 0) <= (indexById.get(node.id) ?? 0)) continue;
43
+ pushApart(node, other, cellSize);
44
+ }
45
+ }
46
+ }
47
+ }
48
+
49
+ for (const edge of edges) {
50
+ const source = byId.get(edge.from);
51
+ const target = byId.get(edge.to);
52
+ if (!source || !target) continue;
53
+ const dx = target.x - source.x;
54
+ const dy = target.y - source.y;
55
+ const distance = Math.hypot(dx, dy) || 1;
56
+ const desired = source.radius + target.radius + (mode === "topics" ? 110 : 68);
57
+ const pull = (distance - desired) * (mode === "topics" ? .008 : .0055);
58
+ const fx = dx / distance * pull;
59
+ const fy = dy / distance * pull;
60
+ source.vx += fx;
61
+ source.vy += fy;
62
+ target.vx -= fx;
63
+ target.vy -= fy;
64
+ }
65
+
66
+ for (const node of nodes) {
67
+ const clusterCenter = node.cluster ? clusterCenters.get(node.cluster) : null;
68
+ const gravityX = clusterCenter?.x ?? centerX;
69
+ const gravityY = clusterCenter?.y ?? centerY;
70
+ const gravity = node.cluster ? .009 : .0035;
71
+ node.vx += (gravityX - node.x) * gravity;
72
+ node.vy += (gravityY - node.y) * gravity;
73
+ node.x += node.vx *= .74;
74
+ node.y += node.vy *= .74;
75
+ node.x = Math.min(width - margin, Math.max(margin, node.x));
76
+ node.y = Math.min(height - margin, Math.max(margin, node.y));
77
+ }
78
+ }
79
+
80
+ return { nodes, edges };
81
+ }
82
+
83
+ function initializeRadial(nodes, centerX, centerY, spread) {
84
+ const ordered = [...nodes].sort((left, right) => left.id.localeCompare(right.id));
85
+ ordered.forEach((node, index) => {
86
+ const radius = spread * Math.sqrt((index + .65) / ordered.length);
87
+ const angle = index * GOLDEN_ANGLE + stableUnit(node.id) * .35;
88
+ node.x = centerX + Math.cos(angle) * radius;
89
+ node.y = centerY + Math.sin(angle) * radius;
90
+ });
91
+ }
92
+
93
+ function initializeDocumentClusters(nodes, centerX, centerY, width, height) {
94
+ const groups = new Map();
95
+ for (const node of nodes) {
96
+ const bucket = groups.get(node.cluster) ?? [];
97
+ bucket.push(node);
98
+ groups.set(node.cluster, bucket);
99
+ }
100
+ const clusterCenters = ellipseCenters([...groups.keys()].sort(), centerX, centerY, width, height);
101
+ for (const [cluster, groupedNodes] of groups) {
102
+ const center = clusterCenters.get(cluster);
103
+ [...groupedNodes].sort((left, right) => left.id.localeCompare(right.id)).forEach((node, index) => {
104
+ const radius = 18 + 23 * Math.sqrt(index);
105
+ const angle = index * GOLDEN_ANGLE + stableUnit(node.id) * .4;
106
+ node.x = center.x + Math.cos(angle) * radius;
107
+ node.y = center.y + Math.sin(angle) * radius;
108
+ });
109
+ }
110
+ }
111
+
112
+ function buildClusterCenters(nodes, centerX, centerY, width, height) {
113
+ const clusters = [...new Set(nodes.map((node) => node.cluster).filter(Boolean))].sort();
114
+ return ellipseCenters(clusters, centerX, centerY, width, height);
115
+ }
116
+
117
+ function ellipseCenters(clusters, centerX, centerY, width, height) {
118
+ const result = new Map();
119
+ clusters.forEach((cluster, index) => {
120
+ if (clusters.length === 1) {
121
+ result.set(cluster, { x: centerX, y: centerY });
122
+ return;
123
+ }
124
+ const angle = index / clusters.length * Math.PI * 2 - Math.PI / 2;
125
+ result.set(cluster, {
126
+ x: centerX + Math.cos(angle) * width * .31,
127
+ y: centerY + Math.sin(angle) * height * .31
128
+ });
129
+ });
130
+ return result;
131
+ }
132
+
133
+ function pushApart(left, right, cellSize) {
134
+ let dx = right.x - left.x;
135
+ let dy = right.y - left.y;
136
+ let distance = Math.hypot(dx, dy);
137
+ if (distance === 0) {
138
+ const angle = stableUnit(`${left.id}:${right.id}`) * Math.PI * 2;
139
+ dx = Math.cos(angle);
140
+ dy = Math.sin(angle);
141
+ distance = 1;
142
+ }
143
+ const desired = Math.min(cellSize * .92, left.radius + right.radius + 28);
144
+ if (distance >= desired) return;
145
+ const force = Math.min(5, (desired - distance) * .055);
146
+ const fx = dx / distance * force;
147
+ const fy = dy / distance * force;
148
+ left.vx -= fx;
149
+ left.vy -= fy;
150
+ right.vx += fx;
151
+ right.vy += fy;
152
+ }
153
+
154
+ function cellKey(x, y, cellSize) {
155
+ return `${Math.floor(x / cellSize)}:${Math.floor(y / cellSize)}`;
156
+ }
157
+
158
+ function stableUnit(value) {
159
+ let hash = 2166136261;
160
+ for (let index = 0; index < value.length; index += 1) {
161
+ hash ^= value.charCodeAt(index);
162
+ hash = Math.imul(hash, 16777619);
163
+ }
164
+ return (hash >>> 0) / 4294967295;
165
+ }
166
+
167
+ export function createGraphController(options) {
168
+ const { svg, hint, legend, empty, onSelectTopic, onSelectDocument } = options;
169
+ let current = null;
170
+ let view = { x: 0, y: 0, scale: 1 };
171
+ let interaction = null;
172
+ let highlightedId = null;
173
+
174
+ const onWheel = (event) => {
175
+ event.preventDefault();
176
+ zoomBy(event.deltaY < 0 ? 1.12 : .9, event.offsetX, event.offsetY);
177
+ };
178
+
179
+ const onPointerDown = (event) => {
180
+ if (event.button !== 0 || !current) return;
181
+ const nodeElement = event.target.closest?.(".node");
182
+ const node = nodeElement ? current.nodesById.get(nodeElement.dataset.nodeId) : null;
183
+ interaction = node
184
+ ? { type: "node", node, nodeElement, startX: event.clientX, startY: event.clientY, nodeX: node.x, nodeY: node.y, moved: false }
185
+ : { type: "pan", startX: event.clientX, startY: event.clientY, viewX: view.x, viewY: view.y, moved: false };
186
+ svg.classList.add("dragging");
187
+ svg.setPointerCapture(event.pointerId);
188
+ };
189
+
190
+ const onPointerMove = (event) => {
191
+ if (!interaction || !current) return;
192
+ const dx = event.clientX - interaction.startX;
193
+ const dy = event.clientY - interaction.startY;
194
+ interaction.moved ||= Math.hypot(dx, dy) > 3;
195
+ if (interaction.type === "node") {
196
+ interaction.node.x = interaction.nodeX + dx / view.scale;
197
+ interaction.node.y = interaction.nodeY + dy / view.scale;
198
+ current.position();
199
+ } else {
200
+ view.x = interaction.viewX + dx;
201
+ view.y = interaction.viewY + dy;
202
+ applyView();
203
+ }
204
+ };
205
+
206
+ const onPointerUp = (event) => {
207
+ if (!interaction) return;
208
+ if (!interaction.moved) {
209
+ if (interaction.type === "node") selectTarget(interaction.node.target);
210
+ else highlight(null);
211
+ }
212
+ interaction = null;
213
+ svg.classList.remove("dragging");
214
+ if (svg.hasPointerCapture(event.pointerId)) svg.releasePointerCapture(event.pointerId);
215
+ };
216
+
217
+ const onKeyDown = (event) => {
218
+ const nodeElement = event.target.closest?.(".node");
219
+ if (nodeElement && (event.key === "Enter" || event.key === " ")) {
220
+ event.preventDefault();
221
+ const node = current?.nodesById.get(nodeElement.dataset.nodeId);
222
+ if (node) selectTarget(node.target);
223
+ return;
224
+ }
225
+ if (event.key === "0") {
226
+ event.preventDefault();
227
+ resetView();
228
+ } else if (event.key === "+" || event.key === "=") {
229
+ event.preventDefault();
230
+ zoomBy(1.15);
231
+ } else if (event.key === "-") {
232
+ event.preventDefault();
233
+ zoomBy(.87);
234
+ }
235
+ };
236
+
237
+ svg.addEventListener("wheel", onWheel, { passive: false });
238
+ svg.addEventListener("pointerdown", onPointerDown);
239
+ svg.addEventListener("pointermove", onPointerMove);
240
+ svg.addEventListener("pointerup", onPointerUp);
241
+ svg.addEventListener("pointercancel", onPointerUp);
242
+ svg.addEventListener("keydown", onKeyDown);
243
+
244
+ function render(input) {
245
+ const bounds = svg.getBoundingClientRect();
246
+ const width = Math.max(240, bounds.width);
247
+ const height = Math.max(240, bounds.height);
248
+ const source = input.mode === "topics"
249
+ ? buildTopicGraph(input.state, input.topicColors)
250
+ : buildDocumentGraph(input.state, input.topicColors);
251
+ const graph = layoutGraph(source, width, height, input.mode);
252
+ svg.replaceChildren();
253
+ empty.hidden = graph.nodes.length > 0;
254
+ setGraphChrome(input.mode);
255
+
256
+ const defs = svgElement("defs");
257
+ defs.append(createArrowMarker(), createShadowFilter());
258
+ const root = svgElement("g");
259
+ svg.append(defs, root);
260
+
261
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
262
+ const edgeElements = graph.edges.map((edge) => {
263
+ const path = svgElement("path");
264
+ path.setAttribute("class", "edge-path");
265
+ path.setAttribute("stroke", edge.style === "link" ? "#c8cfd8" : "#9aa4b2");
266
+ path.setAttribute("stroke-width", String(edge.width ?? (edge.style === "link" ? 1 : 1.7)));
267
+ path.setAttribute("stroke-linecap", "round");
268
+ path.setAttribute("stroke-opacity", edge.style === "link" ? ".75" : ".85");
269
+ if (edge.style === "related") path.setAttribute("stroke-dasharray", "5 5");
270
+ if (edge.style === "requires") path.setAttribute("marker-end", "url(#arrow)");
271
+ root.append(path);
272
+ return { edge, element: path };
273
+ });
274
+
275
+ const nodeElements = graph.nodes.map((node) => {
276
+ const group = svgElement("g");
277
+ group.setAttribute("class", "node");
278
+ group.setAttribute("data-node-id", node.id);
279
+ group.setAttribute("tabindex", "0");
280
+ group.setAttribute("role", "button");
281
+ group.setAttribute("aria-label", node.tooltip.replace(/\n/g, ","));
282
+ const circle = svgElement("circle");
283
+ circle.setAttribute("r", String(node.radius));
284
+ circle.setAttribute("fill", node.fill);
285
+ circle.setAttribute("fill-opacity", node.isTopic ? ".92" : ".88");
286
+ circle.setAttribute("stroke", node.status === "fresh" ? "#ffffff" : STATUS_COLOR[node.status]);
287
+ circle.setAttribute("stroke-width", node.status === "fresh" ? "2" : "3.5");
288
+ circle.setAttribute("filter", "url(#soft)");
289
+ group.append(circle);
290
+ if (node.isTopic) {
291
+ group.append(
292
+ textElement(node.label, 0, 4, 12.5, 700, "#ffffff"),
293
+ textElement(node.subLabel, 0, node.radius + 15, 10.5, 500, null, "sub")
294
+ );
295
+ } else {
296
+ group.append(textElement(node.label, 0, node.radius + 13, 10, 500));
297
+ }
298
+ const title = svgElement("title");
299
+ title.textContent = node.tooltip;
300
+ group.append(title);
301
+ root.append(group);
302
+ return { node, element: group };
303
+ });
304
+
305
+ const position = () => {
306
+ for (const { edge, element } of edgeElements) {
307
+ const sourceNode = nodesById.get(edge.from);
308
+ const targetNode = nodesById.get(edge.to);
309
+ if (!sourceNode || !targetNode) continue;
310
+ element.setAttribute("d", edgePath(sourceNode, targetNode, edge.style));
311
+ }
312
+ for (const { node, element } of nodeElements) {
313
+ element.setAttribute("transform", `translate(${node.x},${node.y})`);
314
+ }
315
+ };
316
+
317
+ current = { root, graph, nodesById, nodeElements, edgeElements, position };
318
+ view = { x: 0, y: 0, scale: 1 };
319
+ position();
320
+ applyView();
321
+ highlight(input.mode === "docs" ? input.selected : highlightedId);
322
+ }
323
+
324
+ function resize(input) {
325
+ render(input);
326
+ }
327
+
328
+ function selectTarget(target) {
329
+ if (target.type === "topic") onSelectTopic(target.value);
330
+ else onSelectDocument(target.value);
331
+ }
332
+
333
+ function setGraphChrome(mode) {
334
+ hint.textContent = mode === "topics"
335
+ ? "Topic 拓扑 · 边粗细表示跨域引用数 · 点击下钻"
336
+ : "文档全图 · 点击查看详情 · 拖动画布 / 滚轮缩放";
337
+ legend.replaceChildren();
338
+ const edgeItems = mode === "topics"
339
+ ? [["", "跨域引用"]]
340
+ : [["", "requires"], ["related", "related"], ["link", "link"]];
341
+ for (const [className, label] of edgeItems) {
342
+ const item = document.createElement("span");
343
+ const sample = document.createElement("i");
344
+ if (className) sample.className = className;
345
+ item.append(sample, label);
346
+ legend.append(item);
347
+ }
348
+ for (const [status, label] of [["dirty", "dirty"], ["impacted", "impacted"], ["needs-review", "review"]]) {
349
+ const item = document.createElement("span");
350
+ const bullet = document.createElement("b");
351
+ bullet.textContent = "●";
352
+ bullet.style.color = STATUS_COLOR[status];
353
+ item.append(bullet, ` ${label}`);
354
+ legend.append(item);
355
+ }
356
+ }
357
+
358
+ function highlight(id) {
359
+ highlightedId = id;
360
+ if (!current) return;
361
+ const neighbors = new Set();
362
+ if (id) {
363
+ neighbors.add(id);
364
+ for (const edge of current.graph.edges) {
365
+ if (edge.from === id) neighbors.add(edge.to);
366
+ if (edge.to === id) neighbors.add(edge.from);
367
+ }
368
+ }
369
+ for (const { node, element } of current.nodeElements) {
370
+ element.setAttribute("class", `node${id && !neighbors.has(node.id) ? " dim" : ""}`);
371
+ }
372
+ for (const { edge, element } of current.edgeElements) {
373
+ element.setAttribute("class", `edge-path${id && edge.from !== id && edge.to !== id ? " dim" : ""}`);
374
+ }
375
+ }
376
+
377
+ function zoomBy(factor, anchorX, anchorY) {
378
+ const bounds = svg.getBoundingClientRect();
379
+ const x = anchorX ?? bounds.width / 2;
380
+ const y = anchorY ?? bounds.height / 2;
381
+ const next = Math.min(4, Math.max(.3, view.scale * factor));
382
+ view.x = x - (x - view.x) / view.scale * next;
383
+ view.y = y - (y - view.y) / view.scale * next;
384
+ view.scale = next;
385
+ applyView();
386
+ }
387
+
388
+ function resetView() {
389
+ view = { x: 0, y: 0, scale: 1 };
390
+ applyView();
391
+ }
392
+
393
+ function applyView() {
394
+ current?.root.setAttribute("transform", `translate(${view.x},${view.y}) scale(${view.scale})`);
395
+ }
396
+
397
+ function destroy() {
398
+ svg.removeEventListener("wheel", onWheel);
399
+ svg.removeEventListener("pointerdown", onPointerDown);
400
+ svg.removeEventListener("pointermove", onPointerMove);
401
+ svg.removeEventListener("pointerup", onPointerUp);
402
+ svg.removeEventListener("pointercancel", onPointerUp);
403
+ svg.removeEventListener("keydown", onKeyDown);
404
+ }
405
+
406
+ return { render, resize, highlight, zoomBy, resetView, destroy };
407
+ }
408
+
409
+ function edgePath(source, target, style) {
410
+ const dx = target.x - source.x;
411
+ const dy = target.y - source.y;
412
+ const distance = Math.hypot(dx, dy) || 1;
413
+ const sourceX = source.x + dx / distance * source.radius;
414
+ const sourceY = source.y + dy / distance * source.radius;
415
+ const arrowPadding = style === "requires" ? 4 : 0;
416
+ const targetX = target.x - dx / distance * (target.radius + arrowPadding);
417
+ const targetY = target.y - dy / distance * (target.radius + arrowPadding);
418
+ const middleX = (sourceX + targetX) / 2 - dy / distance * distance * .09;
419
+ const middleY = (sourceY + targetY) / 2 + dx / distance * distance * .09;
420
+ return `M ${sourceX} ${sourceY} Q ${middleX} ${middleY} ${targetX} ${targetY}`;
421
+ }
422
+
423
+ function svgElement(name) {
424
+ return document.createElementNS(SVG_NS, name);
425
+ }
426
+
427
+ function textElement(content, x, y, size, weight, fill, className) {
428
+ const element = svgElement("text");
429
+ element.setAttribute("text-anchor", "middle");
430
+ element.setAttribute("x", String(x));
431
+ element.setAttribute("y", String(y));
432
+ element.setAttribute("font-size", String(size));
433
+ element.setAttribute("font-weight", String(weight));
434
+ if (fill) element.style.fill = fill;
435
+ if (className) element.setAttribute("class", className);
436
+ element.textContent = content;
437
+ return element;
438
+ }
439
+
440
+ function createArrowMarker() {
441
+ const marker = svgElement("marker");
442
+ marker.setAttribute("id", "arrow");
443
+ marker.setAttribute("viewBox", "0 0 8 8");
444
+ marker.setAttribute("refX", "7.5");
445
+ marker.setAttribute("refY", "4");
446
+ marker.setAttribute("markerWidth", "5.5");
447
+ marker.setAttribute("markerHeight", "5.5");
448
+ marker.setAttribute("orient", "auto");
449
+ const path = svgElement("path");
450
+ path.setAttribute("d", "M0 .8 L8 4 L0 7.2 z");
451
+ path.setAttribute("fill", "#9aa4b2");
452
+ marker.append(path);
453
+ return marker;
454
+ }
455
+
456
+ function createShadowFilter() {
457
+ const filter = svgElement("filter");
458
+ filter.setAttribute("id", "soft");
459
+ filter.setAttribute("x", "-40%");
460
+ filter.setAttribute("y", "-40%");
461
+ filter.setAttribute("width", "180%");
462
+ filter.setAttribute("height", "180%");
463
+ const shadow = svgElement("feDropShadow");
464
+ shadow.setAttribute("dx", "0");
465
+ shadow.setAttribute("dy", "1.5");
466
+ shadow.setAttribute("stdDeviation", "2.5");
467
+ shadow.setAttribute("flood-color", "#101828");
468
+ shadow.setAttribute("flood-opacity", ".18");
469
+ filter.append(shadow);
470
+ return filter;
471
+ }
@@ -0,0 +1,127 @@
1
+ export const PALETTE = ["#4c5fd5", "#0e8f6f", "#c26a12", "#7a4bc9", "#0d84ab", "#b13d72", "#5f8016", "#96591f"];
2
+
3
+ export const STATUS_COLOR = {
4
+ fresh: "#aab2bd",
5
+ impacted: "#e8890c",
6
+ dirty: "#d6453d",
7
+ "needs-review": "#c9a227"
8
+ };
9
+
10
+ const STATUS_RANK = { fresh: 0, "needs-review": 1, impacted: 2, dirty: 3 };
11
+
12
+ export function createTopicColors(nodes) {
13
+ const topics = [...new Set(nodes.map((node) => node.topic).filter(Boolean))].sort();
14
+ return new Map(topics.map((topic, index) => [topic, PALETTE[index % PALETTE.length]]));
15
+ }
16
+
17
+ export function colorOf(topicColors, topic) {
18
+ return topic ? topicColors.get(topic) ?? PALETTE[0] : "#3c4657";
19
+ }
20
+
21
+ export function worstStatus(nodes) {
22
+ return nodes.reduce(
23
+ (worst, node) => (STATUS_RANK[node.status] > STATUS_RANK[worst] ? node.status : worst),
24
+ "fresh"
25
+ );
26
+ }
27
+
28
+ export function documentName(path) {
29
+ return path.split("/").pop()?.replace(/\.mdx$/, "") ?? path;
30
+ }
31
+
32
+ export function compactLabel(label, limit = 24) {
33
+ return label.length > limit ? `${label.slice(0, limit - 1)}…` : label;
34
+ }
35
+
36
+ export function matchesSearch(node, rawQuery) {
37
+ const query = rawQuery.trim().toLocaleLowerCase();
38
+ if (!query) return true;
39
+ return [node.path, node.title, node.description, node.kind, node.topic]
40
+ .filter(Boolean)
41
+ .some((value) => String(value).toLocaleLowerCase().includes(query));
42
+ }
43
+
44
+ export function buildTopicGraph(state, topicColors) {
45
+ const topics = [...new Set(state.nodes.map((node) => node.topic).filter(Boolean))].sort();
46
+ const nodes = [];
47
+
48
+ for (const topic of topics) {
49
+ const documents = state.nodes.filter((node) => node.topic === topic);
50
+ const tokens = documents.reduce((sum, node) => sum + node.estimatedTokens, 0);
51
+ nodes.push({
52
+ id: `topic:${topic}`,
53
+ isTopic: true,
54
+ topic,
55
+ label: compactLabel(topic),
56
+ subLabel: `${documents.length} docs · ~${tokens} tk`,
57
+ radius: 26 + Math.min(26, Math.sqrt(tokens)),
58
+ fill: colorOf(topicColors, topic),
59
+ status: worstStatus(documents),
60
+ tooltip: `${topic}/\n${documents.map((document) => `· ${documentName(document.path)}`).join("\n")}`,
61
+ target: { type: "topic", value: topic }
62
+ });
63
+ }
64
+
65
+ for (const node of state.nodes.filter((item) => !item.topic)) {
66
+ nodes.push({
67
+ id: `doc:${node.path}`,
68
+ isTopic: false,
69
+ label: compactLabel(node.path.replace(/\.mdx$/, "")),
70
+ radius: 10 + Math.min(9, Math.sqrt(node.estimatedTokens)),
71
+ fill: colorOf(topicColors, null),
72
+ status: node.status,
73
+ tooltip: `${node.path}\n${node.description}`,
74
+ target: { type: "document", value: node.path }
75
+ });
76
+ }
77
+
78
+ const groupByPath = new Map(
79
+ state.nodes.map((node) => [node.path, node.topic ? `topic:${node.topic}` : `doc:${node.path}`])
80
+ );
81
+ const aggregated = new Map();
82
+ for (const edge of state.edges) {
83
+ const left = groupByPath.get(edge.from);
84
+ const right = groupByPath.get(edge.to);
85
+ if (!left || !right || left === right) continue;
86
+ const [from, to] = [left, right].sort();
87
+ const key = `${from}\u0000${to}`;
88
+ const current = aggregated.get(key) ?? { from, to, count: 0, style: "aggregate" };
89
+ current.count += 1;
90
+ aggregated.set(key, current);
91
+ }
92
+
93
+ const edges = [...aggregated.values()]
94
+ .sort((left, right) => `${left.from}\u0000${left.to}`.localeCompare(`${right.from}\u0000${right.to}`))
95
+ .map((edge) => ({ ...edge, width: 1.4 + Math.min(6, edge.count * 1.1) }));
96
+ return { nodes, edges };
97
+ }
98
+
99
+ export function buildDocumentGraph(state, topicColors) {
100
+ const nodes = state.nodes.map((node) => ({
101
+ id: node.path,
102
+ isTopic: false,
103
+ topic: node.topic,
104
+ cluster: node.topic || "·root",
105
+ label: compactLabel(documentName(node.path)),
106
+ radius: 8 + Math.min(11, Math.sqrt(node.estimatedTokens)),
107
+ fill: colorOf(topicColors, node.topic),
108
+ status: node.status,
109
+ tooltip: `${node.path}\n${node.description}`,
110
+ target: { type: "document", value: node.path }
111
+ }));
112
+ const edges = state.edges.map((edge) => ({ ...edge, style: edge.type }));
113
+ return { nodes, edges };
114
+ }
115
+
116
+ export function resolveRelativeDocumentPath(documentPath, href) {
117
+ const rawTarget = href.split(/[?#]/)[0] ?? "";
118
+ const base = documentPath.split("/").slice(0, -1);
119
+ const parts = [...base, ...rawTarget.split("/")];
120
+ const normalized = [];
121
+ for (const part of parts) {
122
+ if (!part || part === ".") continue;
123
+ if (part === "..") normalized.pop();
124
+ else normalized.push(part);
125
+ }
126
+ return normalized.join("/");
127
+ }