buildContextGraph
Overview
Section titled “Overview”Builds a graph that represents the dependency relationships between documents from a Map of parsed documents. Each document’s relative links and image references are collected as edges, and each node is annotated with its in-degree and out-degree.
Why it exists
Section titled “Why it exists”All other Graph API functions (getImpactSet, topologicalSort, classifyImpact, and so on) take the ContextGraph returned by this function as input. It is the entry point for any graph operation.
Edges are resolved from the source file’s relative links, and are added only when the resolved target exists in the documents Map. Anchor fragments (#section) are stripped, and self-references are ignored. The output is deterministic — both nodes and edges are sorted by file path.
Signature
Section titled “Signature”function buildContextGraph( documents: Map<string, ParsedDocument>,): ContextGraph;The related types are:
interface GraphNode { filePath: string; inDegree: number; outDegree: number;}
interface GraphEdge { source: string; target: string; type: "link" | "image"; line: number;}
interface ContextGraph { nodes: GraphNode[]; edges: GraphEdge[];}Parameters
Section titled “Parameters”| Parameter | Type | Required | Description |
|---|---|---|---|
documents | Map<string, ParsedDocument> | ✓ | A Map keyed by file path with parseDocument results as values. Keys may be relative or absolute, but relative paths are recommended for parity with lintFiles. |
Return value
Section titled “Return value”Returns a ContextGraph.
nodes— Each file path together with its in-degree and out-degree. Sorted by file path.edges— Directed edges fromsourcetotarget.typeindicates whether the edge is a link or an image reference. Sorted by source, target, and line number.
Example
Section titled “Example”import { loadDocuments } from "@contextlint/core";import { buildContextGraph } from "@contextlint/core";
const documents = loadDocuments(["docs/**/*.md"]);const graph = buildContextGraph(documents);
console.log(`${graph.nodes.length} files, ${graph.edges.length} edges`);
for (const edge of graph.edges) { console.log(`${edge.source} → ${edge.target} (${edge.type}, line ${edge.line})`);}Related functions
Section titled “Related functions”getImpactSet— Get the impact set using the graphtopologicalSort— Order the graph by dependencyformatContextGraphSummary— Format a summary of the graph