1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
// DOM glue and D3 force graph for the vuln-notif record viewer.
//
// Records live in IndexedDB (seeded from the PDS listRecords endpoint on first
// load) and update live from the jetstream firehose.
const d3 = window.d3;
import {
GraphModel,
WANTED_COLLECTIONS,
extractEdges,
nsidColor,
nsidLabel,
pdslsUrl,
toYaml,
} from "./graph.js";
import * as db from "./db.js";
import * as jetstream from "./jetstream.js";
const SEED_PAGE_LIMIT = 100;
const SEED_COLLECTION_CAP = 1000;
const RENDER_DELAY_MS = 80;
const statusEl = document.getElementById("status");
const countsEl = document.getElementById("counts");
const nodeCountEl = document.getElementById("node-count");
const edgeCountEl = document.getElementById("edge-count");
const indexedCountEl = document.getElementById("indexed-count");
const legendEl = document.getElementById("legend");
const tooltipEl = document.getElementById("tooltip");
const emptyStateEl = document.getElementById("empty-state");
const modal = document.getElementById("node-modal");
const modalCloseBtn = document.getElementById("modal-close");
const detailTitle = document.getElementById("detail-title");
const detailUri = document.getElementById("detail-uri");
const detailDid = document.getElementById("detail-did");
const detailYaml = document.getElementById("detail-yaml");
const detailPdsls = document.getElementById("detail-pdsls");
const detailFocusBtn = document.getElementById("detail-focus");
let model = null;
let simulation = null;
let svg = null;
let gZoom = null;
let linkG = null;
let nodeG = null;
let labelG = null;
let zoomBehavior = null;
let nodeSel = null;
let linkSel = null;
let labelSel = null;
let edgeLabelSel = null;
let simNodes = [];
let simEdges = [];
let selectedId = null;
let repoDid = null;
let pdsUrl = null;
let graphInitialized = false;
let renderTimer = null;
let legendSignature = "";
let seeding = false;
let seedIndex = 0;
let seedTotal = WANTED_COLLECTIONS.length;
let seedError = null;
const nodeMap = new Map();
const edgeMap = new Map();
const LABEL_LIMIT = 120;
function edgeKey(edge) {
return `${edge.source}\u0000${edge.target}\u0000${edge.label}`;
}
// ---------------------------------------------------------------------------
// Detail dialog
// ---------------------------------------------------------------------------
function safeYaml(record) {
try {
return toYaml(record || {});
} catch (error) {
try {
return JSON.stringify(record || {}, null, 2);
} catch {
return String(record);
}
}
}
function renderYaml(yaml) {
detailYaml.textContent = yaml;
detailYaml.removeAttribute("data-highlighted");
detailYaml.classList.add("language-yaml");
const hljs = window.hljs;
if (!hljs || typeof hljs.highlightElement !== "function") return;
try {
hljs.highlightElement(detailYaml);
} catch (error) {
detailYaml.textContent = yaml;
}
}
function openNode(node) {
if (!node) return;
selectedId = node.id;
if (model) model.clearFocus();
detailTitle.textContent = `${node.collection} ${String.fromCharCode(183)} ${node.rkey}`;
detailUri.textContent = node.uri;
detailDid.textContent = `DID: ${node.did}`;
detailPdsls.href = pdslsUrl(node.uri);
detailPdsls.title = pdslsUrl(node.uri);
detailFocusBtn.setAttribute("aria-pressed", "false");
renderYaml(safeYaml(node.record));
if (!modal.open) modal.showModal();
applyFocusAndSelection();
}
function closeModal() {
if (modal.open) modal.close();
}
let keepFocusOnClose = false;
modal.addEventListener("close", () => {
if (keepFocusOnClose) {
keepFocusOnClose = false;
return;
}
selectedId = null;
if (model) model.clearFocus();
applyFocusAndSelection();
refreshLabels();
ticked();
});
modalCloseBtn.addEventListener("click", closeModal);
modal.addEventListener("click", (event) => {
if (event.target === modal) closeModal();
});
detailFocusBtn.addEventListener("click", () => {
if (!model || !selectedId) return;
model.setFocus(selectedId);
keepFocusOnClose = true;
modal.close();
applyFocusAndSelection();
refreshLabels();
ticked();
});
// ---------------------------------------------------------------------------
// Legend and collection filters
// ---------------------------------------------------------------------------
function buildLegend() {
if (!model) {
legendEl.hidden = true;
return;
}
legendEl.innerHTML = "";
legendEl.hidden = false;
const table = document.createElement("table");
const tbody = document.createElement("tbody");
for (const [collection, count] of model.collectionCounts()) {
const row = document.createElement("tr");
const cell = document.createElement("td");
const label = document.createElement("label");
label.title = collection;
const input = document.createElement("input");
input.type = "checkbox";
input.checked = model.isCollectionVisible(collection);
input.addEventListener("change", () => {
model.setCollectionVisible(collection, input.checked);
label.querySelector(".legend-label").classList.toggle("off", !input.checked);
restartSimulation();
});
const swatch = document.createElement("span");
swatch.className = "swatch";
swatch.style.background = nsidColor(collection);
const text = document.createElement("span");
text.className = "legend-label";
text.textContent = collection;
text.classList.toggle("off", !input.checked);
const countEl = document.createElement("span");
countEl.className = "legend-count";
countEl.textContent = String(count);
label.append(input, swatch, text, countEl);
cell.appendChild(label);
row.appendChild(cell);
tbody.appendChild(row);
}
table.appendChild(tbody);
legendEl.appendChild(table);
}
// ---------------------------------------------------------------------------
// D3 force graph
// ---------------------------------------------------------------------------
function initGraph() {
svg = d3.select("#graph");
svg.selectAll("*").remove();
svg.on("click", (event) => {
if (event.target !== svg.node()) return;
if (model) model.clearFocus();
selectedId = null;
closeModal();
applyFocusAndSelection();
refreshLabels();
ticked();
});
gZoom = svg.append("g");
zoomBehavior = d3.zoom()
.scaleExtent([0.04, 10])
.on("zoom", (event) => gZoom.attr("transform", event.transform));
svg.call(zoomBehavior);
linkG = gZoom.append("g").attr("class", "links");
nodeG = gZoom.append("g").attr("class", "nodes");
labelG = gZoom.append("g").attr("class", "labels");
simulation = d3.forceSimulation()
.force("link", d3.forceLink().id((node) => node.id).distance(55).strength(0.35).iterations(1))
.force("charge", d3.forceManyBody().strength(-140).distanceMin(10).distanceMax(520))
.force("collide", d3.forceCollide(8).strength(0.7).iterations(2))
.force("center", d3.forceCenter(0, 0).strength(0.08))
.alphaDecay(0.04)
.velocityDecay(0.45)
.on("tick", ticked);
resizeGraph();
window.addEventListener("resize", resizeGraph);
const initialScale = model && model.nodes.length > 150 ? 0.42 : 1;
svg.call(zoomBehavior.transform, d3.zoomIdentity.scale(initialScale));
}
function resizeGraph() {
const pane = document.getElementById("graph-pane");
const width = pane.clientWidth || window.innerWidth;
const height = pane.clientHeight || window.innerHeight;
if (svg) svg.attr("viewBox", [-width / 2, -height / 2, width, height]);
}
function shouldShowNodeLabels() {
return model.hasFocus() || simNodes.length <= LABEL_LIMIT;
}
function shouldShowEdgeLabels() {
// Edge labels clutter connected-only mode; the modal already shows the
// relationship path for the selected record.
return false;
}
function refreshLabels() {
if (!labelG) return;
const labelData = shouldShowNodeLabels() ? simNodes : [];
labelSel = labelG.selectAll("text.node-label").data(labelData, (node) => node.id);
labelSel.exit().remove();
labelSel = labelSel.enter()
.append("text")
.attr("class", "node-label")
.text((node) => node.label || node.rkey)
.merge(labelSel);
const edgeData = shouldShowEdgeLabels() ? simEdges : [];
edgeLabelSel = labelG.selectAll("text.edge-label")
.data(edgeData, (edge) => `${edge.from}->${edge.to}@${edge.label}`);
edgeLabelSel.exit().remove();
edgeLabelSel = edgeLabelSel.enter()
.append("text")
.attr("class", "edge-label")
.text((edge) => edge.label || "")
.merge(edgeLabelSel);
// Labels are recreated above, so reapply focus visibility or hidden nodes
// would leave their long label text visible after focus mode.
applyFocusAndSelection();
}
function restartSimulation() {
const nodes = model.visibleNodes();
const edges = model.visibleEdges();
nodeCountEl.textContent = String(nodes.length);
edgeCountEl.textContent = String(edges.length);
countsEl.title = `${model.nodes.length} total nodes, ${model.edges.length} total edges`;
const previous = new Map(simNodes.map((node) => [node.id, node]));
simNodes = nodes.map((node) => {
const existing = previous.get(node.id);
if (existing) {
Object.assign(existing, node);
return existing;
}
return { ...node };
});
simEdges = edges.map((edge) => ({ ...edge }));
linkSel = linkG.selectAll("line.edge")
.data(simEdges, (edge) => `${edge.from}->${edge.to}@${edge.label}`);
linkSel.exit().remove();
linkSel = linkSel.enter()
.append("line")
.attr("class", "edge")
.attr("stroke", (edge) => nsidColor(edge.collection))
.attr("stroke-width", 1.2)
.merge(linkSel);
nodeSel = nodeG.selectAll("circle.node").data(simNodes, (node) => node.id);
nodeSel.exit().remove();
nodeSel = nodeSel.enter()
.append("circle")
.attr("class", "node")
.attr("r", 5.5)
.attr("fill", (node) => nsidColor(node.collection))
.call(d3.drag()
.on("start", dragStarted)
.on("drag", dragged)
.on("end", dragEnded))
.on("click", (event, node) => {
event.stopPropagation();
openNode(node);
})
.on("mouseenter", (event, node) => {
tooltipEl.hidden = false;
tooltipEl.textContent = `${node.label || node.rkey} | ${nsidLabel(node.collection)}`;
positionTooltip(event);
})
.on("mousemove", positionTooltip)
.on("mouseleave", () => {
tooltipEl.hidden = true;
})
.merge(nodeSel);
refreshLabels();
simulation.nodes(simNodes);
simulation.force("link").links(simEdges);
simulation.alpha(0.5).restart();
applyFocusAndSelection();
ticked();
}
function positionTooltip(event) {
tooltipEl.style.left = `${event.clientX}px`;
tooltipEl.style.top = `${event.clientY}px`;
}
function ticked() {
if (linkSel) {
linkSel
.attr("x1", (edge) => edge.source.x)
.attr("y1", (edge) => edge.source.y)
.attr("x2", (edge) => edge.target.x)
.attr("y2", (edge) => edge.target.y);
}
if (nodeSel) {
nodeSel
.attr("cx", (node) => node.x)
.attr("cy", (node) => node.y);
}
if (labelSel) {
labelSel
.attr("x", (node) => node.x)
.attr("y", (node) => node.y + 12);
}
if (edgeLabelSel) {
edgeLabelSel
.attr("x", (edge) => (edge.source.x + edge.target.x) / 2)
.attr("y", (edge) => (edge.source.y + edge.target.y) / 2);
}
}
function applyFocusAndSelection() {
if (!model) return;
const focusActive = model.hasFocus();
if (nodeSel) {
nodeSel
.classed("selected", (node) => node.id === selectedId)
.classed("focus-hidden", (node) => focusActive && !model.isFocusConnected(node.id))
.attr("r", (node) => (node.id === selectedId ? 8 : 5.5));
}
if (linkSel) {
linkSel.classed("focus-hidden", (edge) =>
focusActive && !(model.isFocusConnected(edge.from) && model.isFocusConnected(edge.to)));
}
if (labelSel) {
labelSel.classed("focus-hidden", (node) => focusActive && !model.isFocusConnected(node.id));
}
if (edgeLabelSel) {
edgeLabelSel.classed("focus-hidden", (edge) =>
focusActive && !(model.isFocusConnected(edge.from) && model.isFocusConnected(edge.to)));
}
detailFocusBtn.setAttribute("aria-pressed", focusActive ? "true" : "false");
}
function dragStarted(event, node) {
if (!event.active) simulation.alphaTarget(0.2).restart();
node.fx = node.x;
node.fy = node.y;
}
function dragged(event, node) {
node.fx = event.x;
node.fy = event.y;
}
function dragEnded(event, node) {
if (!event.active) simulation.alphaTarget(0);
node.fx = null;
node.fy = null;
}
// ---------------------------------------------------------------------------
// In-memory mirror of IndexedDB
// ---------------------------------------------------------------------------
function toNode(record) {
return {
id: record.uri,
uri: record.uri,
did: record.did,
collection: record.collection,
rkey: record.rkey,
label: record.rkey,
record: record.record,
cid: record.cid,
indexedAt: record.indexedAt,
};
}
function upsertMemory(record, edges) {
nodeMap.set(record.uri, toNode(record));
for (const [key, edge] of edgeMap) {
if (edge.source === record.uri) edgeMap.delete(key);
}
for (const edge of edges) {
edgeMap.set(edgeKey(edge), { ...edge, from: edge.source, to: edge.target });
}
}
function deleteMemory(uri) {
nodeMap.delete(uri);
for (const [key, edge] of edgeMap) {
if (edge.source === uri) edgeMap.delete(key);
}
if (selectedId === uri) {
selectedId = null;
if (model) model.clearFocus();
closeModal();
applyFocusAndSelection();
refreshLabels();
ticked();
}
}
function buildModel() {
const nodes = [...nodeMap.values()];
const edges = [...edgeMap.values()].map((edge) => ({
...edge,
from: edge.source,
to: edge.target,
}));
const hidden = model ? new Set(model.hiddenCollections) : new Set();
const focus = model ? model.focus : null;
model = new GraphModel(nodes, edges);
for (const collection of hidden) model.setCollectionVisible(collection, false);
if (focus && model.byId.has(focus)) model.setFocus(focus);
}
function render() {
buildModel();
const signature = model.collectionCounts()
.map(([collection, count]) => `${collection}:${count}`)
.join("|");
if (signature !== legendSignature) {
legendSignature = signature;
buildLegend();
}
if (!graphInitialized) {
graphInitialized = true;
initGraph();
}
restartSimulation();
updateIndexedCount();
updateEmptyState();
}
function scheduleRender() {
if (renderTimer !== null) return;
renderTimer = setTimeout(() => {
renderTimer = null;
render();
}, RENDER_DELAY_MS);
}
function updateIndexedCount() {
indexedCountEl.textContent = `${nodeMap.size} indexed`;
indexedCountEl.title = `${nodeMap.size} records, ${edgeMap.size} link rows in IndexedDB`;
}
function updateEmptyState() {
const empty = nodeMap.size === 0;
emptyStateEl.hidden = !empty;
if (!empty) return;
if (!repoDid) {
emptyStateEl.textContent =
"Missing repo_did in config.json. Run spa/build.py with --repo-did and serve spa/dist.";
} else if (seeding) {
emptyStateEl.textContent = `Seeding records from the PDS (collection ${seedIndex}/${seedTotal})...`;
} else if (seedError) {
emptyStateEl.textContent = `Seeding failed: ${seedError}`;
} else {
emptyStateEl.textContent = "No records found in the local IndexedDB mirror.";
}
}
// ---------------------------------------------------------------------------
// Status
// ---------------------------------------------------------------------------
function statusLabel(state) {
const dot = String.fromCharCode(0x25cf);
if (state === "live") return `${dot} live`;
if (state === "reconnecting") return `${dot} reconnecting`;
if (state === "error") return `${dot} error`;
return "connecting...";
}
function updateStatus() {
if (!repoDid) {
statusEl.textContent = "missing repo_did in config.json";
statusEl.classList.add("error");
updateEmptyState();
return;
}
const state = jetstream.status();
const label = statusLabel(state);
if (seeding) {
statusEl.textContent = `seeding collection ${seedIndex}/${seedTotal} - ${label}`;
} else if (seedError && nodeMap.size === 0) {
statusEl.textContent = `seed error: ${seedError}`;
} else {
statusEl.textContent = label;
}
statusEl.classList.toggle("error", state === "error" || (Boolean(seedError) && nodeMap.size === 0));
statusEl.title = `repo ${repoDid}`;
updateEmptyState();
}
// ---------------------------------------------------------------------------
// Live events and seeding
// ---------------------------------------------------------------------------
function recordFromListItem(item, collection) {
const uri = item && typeof item.uri === "string" ? item.uri : "";
const parts = uri.split("/");
if (!uri.startsWith("at://") || parts.length < 5) return null;
return {
uri,
collection,
rkey: parts.slice(4).join("/"),
did: parts[2],
cid: typeof item.cid === "string" ? item.cid : "",
record: item.value && typeof item.value === "object" ? item.value : {},
indexedAt: new Date().toISOString(),
};
}
async function processEvent(event) {
try {
if (event.kind === "delete") {
await db.deleteRecordByUri(event.uri);
deleteMemory(event.uri);
await db.setMeta("lastEventAt", new Date().toISOString());
scheduleRender();
updateStatus();
return;
}
const record = {
uri: event.uri,
collection: event.collection,
rkey: event.rkey,
did: event.did,
cid: event.cid,
record: event.record || {},
indexedAt: new Date().toISOString(),
};
const edges = extractEdges(record.uri, record.collection, record.record);
await db.putRecord(record);
await db.replaceEdgesForSource(record.uri, edges);
await db.setMeta("lastEventAt", record.indexedAt);
upsertMemory(record, edges);
scheduleRender();
updateStatus();
} catch (error) {
console.error("failed to apply live event", error);
}
}
async function ingestFrame(frame) {
const event = jetstream.parseFrame(frame, repoDid);
if (!event || !WANTED_COLLECTIONS.includes(event.collection)) return false;
await processEvent(event);
return true;
}
async function resolvePds(did) {
const response = await fetch(`https://plc.directory/${did}`, { cache: "no-store" });
if (!response.ok) throw new Error(`PLC directory returned HTTP ${response.status}`);
const document = await response.json();
const services = Array.isArray(document.service) ? document.service : [];
const service = services.find(
(entry) => typeof entry.id === "string" && entry.id.endsWith("#atproto_pds"),
);
if (!service || typeof service.serviceEndpoint !== "string") {
throw new Error("DID document has no #atproto_pds service endpoint");
}
return service.serviceEndpoint.replace(/\/+$/, "");
}
async function seed() {
if (seeding || !repoDid) return;
seeding = true;
seedError = null;
seedIndex = 0;
updateStatus();
try {
if (!pdsUrl) pdsUrl = await resolvePds(repoDid);
await db.setMeta("repoDid", repoDid);
await db.setMeta("pdsUrl", pdsUrl);
for (let index = 0; index < WANTED_COLLECTIONS.length; index += 1) {
const collection = WANTED_COLLECTIONS[index];
seedIndex = index + 1;
updateStatus();
let cursor = null;
let fetched = 0;
while (fetched < SEED_COLLECTION_CAP) {
const url = new URL(`${pdsUrl}/xrpc/com.atproto.repo.listRecords`);
url.searchParams.set("repo", repoDid);
url.searchParams.set("collection", collection);
url.searchParams.set("limit", String(SEED_PAGE_LIMIT));
if (cursor) url.searchParams.set("cursor", cursor);
const response = await fetch(url.toString(), { cache: "no-store" });
if (!response.ok) {
throw new Error(`listRecords ${collection}: HTTP ${response.status}`);
}
const body = await response.json();
const items = Array.isArray(body.records) ? body.records : [];
const take = items.slice(0, SEED_COLLECTION_CAP - fetched);
const records = [];
const edges = [];
for (const item of take) {
const record = recordFromListItem(item, collection);
if (!record) continue;
records.push(record);
edges.push(...extractEdges(record.uri, record.collection, record.record));
}
if (records.length > 0) {
await db.putBatch(records, edges);
const bySource = new Map();
for (const edge of edges) {
if (!bySource.has(edge.source)) bySource.set(edge.source, []);
bySource.get(edge.source).push(edge);
}
for (const record of records) {
upsertMemory(record, bySource.get(record.uri) || []);
}
}
fetched += take.length;
cursor = typeof body.cursor === "string" ? body.cursor : null;
scheduleRender();
updateStatus();
if (!cursor || items.length === 0) break;
}
}
await db.setMeta("seededAt", new Date().toISOString());
await db.setMeta("repoDid", repoDid);
await db.setMeta("pdsUrl", pdsUrl);
} catch (error) {
seedError = error.message || String(error);
console.error("seeding failed", error);
} finally {
seeding = false;
updateStatus();
render();
}
}
async function loadStored() {
const records = await db.allRecords();
for (const record of records) {
const parts = record.uri.split("/");
const rkey = parts.length >= 5 ? parts.slice(4).join("/") : record.rkey || "";
nodeMap.set(record.uri, toNode({ ...record, rkey }));
}
const edges = await db.allEdges();
for (const edge of edges) {
edgeMap.set(edgeKey(edge), { ...edge, from: edge.source, to: edge.target });
}
}
async function loadConfig() {
try {
const response = await fetch("./config.json", { cache: "no-store" });
if (!response.ok) return null;
const data = await response.json();
return data && typeof data === "object" ? data : null;
} catch (error) {
return null;
}
}
// ---------------------------------------------------------------------------
// Load and init
// ---------------------------------------------------------------------------
function selectNodeById(id) {
if (!model) return false;
const node = model.byId.get(id);
if (!node) return false;
openNode(node);
return true;
}
async function init() {
try {
await db.openDb();
} catch (error) {
statusEl.textContent = "IndexedDB unavailable";
statusEl.classList.add("error");
emptyStateEl.textContent = `IndexedDB is unavailable: ${error.message || error}`;
return;
}
try {
await loadStored();
} catch (error) {
console.error("failed to read IndexedDB", error);
}
const config = await loadConfig();
repoDid =
(config && (config.repo_did || config.repoDid)) ||
(await db.getMeta("repoDid")) ||
null;
pdsUrl =
(config && (config.pds_url || config.pdsUrl)) ||
(await db.getMeta("pdsUrl")) ||
null;
if (pdsUrl) pdsUrl = String(pdsUrl).replace(/\/+$/, "");
if (repoDid) {
await db.setMeta("repoDid", repoDid);
// Start the live stream before seeding finishes (and regardless of it).
const cursor = await db.getMeta("jetstreamCursor");
jetstream.start(processEvent, {
repoDid,
collections: WANTED_COLLECTIONS,
cursor,
onStatus: updateStatus,
onCursor: (timeUs) => {
db.setMeta("jetstreamCursor", timeUs).catch((error) => {
console.error("failed to save jetstream cursor", error);
});
},
});
}
render();
updateStatus();
if (!repoDid) return;
let empty = true;
try {
empty = await db.isEmpty();
} catch (error) {
console.error("failed to count IndexedDB records", error);
}
if (empty) {
seed();
} else if (pdsUrl) {
await db.setMeta("pdsUrl", pdsUrl);
}
}
window.__selectNodeById = selectNodeById;
window.__graphModel = () => model;
window.__vulnGraph = {
ingest: ingestFrame,
reseed: async () => {
await db.clearAll();
nodeMap.clear();
edgeMap.clear();
selectedId = null;
closeModal();
if (model) model.clearFocus();
model = null;
legendSignature = null;
seedError = null;
render();
await seed();
},
clear: async () => {
await db.clearAll();
nodeMap.clear();
edgeMap.clear();
selectedId = null;
closeModal();
if (model) model.clearFocus();
model = null;
legendSignature = null;
render();
},
counts: () => ({ records: nodeMap.size, edges: edgeMap.size }),
get db() {
return db.getHandle();
},
};
document.addEventListener("DOMContentLoaded", init);