# MD-LD **Markdown-Linked Data** β€” Write RDF knowledge graphs as plain Markdown. Parse to quads, generate back, merge documents. Zero dependencies, round-trip safe. MD-LD is the only RDF format that is both writable by humans and parseable by machines in the same document. Unlike Turtle (write-only), JSON-LD (machine-only), and RDFa (embedded-in-HTML-only), MD-LD annotations flow with natural Markdown prose β€” making knowledge graphs readable without a renderer. **[mdld.js.org](https://mdld.js.org/)** [![NPM](https://img.shields.io/npm/v/mdld-parse)](https://www.npmjs.com/package/mdld-parse/) ## 🎯 What is MD-LD? MD-LD is not just another RDF syntax. It's a **universal semantic writing interface** that removes the intermediary between human text and machine-readable graphs. Traditional systems require: ``` Human β†’ UI β†’ App Logic β†’ Hidden Database β†’ APIs β†’ Exports ``` MD-LD enables: ``` Human text β†’ Graph immediately ``` **Core value:** Author and maintain knowledge graphs as plain text with deterministic round-trip safety. No platforms, databases, or proprietary SaaS mediation required. ```markdown [ex] # Alice {=ex:alice .prov:Person label} [Alice Smith] {ex:fullName} [alice@example.com] {ex:email} ``` **Generates RDF quads** that work with n3.js, rdflib, and any RDF/JS-compatible library. ## πŸš€ Quick Start Install the package in Node environment: ```bash pnpm install mdld-parse ``` Or use `importmap` in the browser: ```html ``` ```javascript import { parse, generate, merge, render, deconstruct, highlight } from 'mdld-parse'; // Parse MDLD to RDF quads const { quads, primary, statements, origin } = parse({ text: mdldString }); console.log(quads); // RDF/JS quads console.log(primary); // Primary metadata (subject, type, label, comment) console.log(statements); // Elevated statements console.log(origin); // Provenance tracking // Generate MDLD from quads const { text } = generate({ quads }); // Highlight MDLD text with syntax coloring const highlighted = highlight(text); // Render to semantic HTML with preserved annotations const html = render(text); // Reconstruct MDLD from HTML (lossless roundtrip) const reconstructed = deconstruct(html); const reconstructedQuads = parse(reconstructed).quads; // Same quads as original! // Verify roundtrip integrity by using generate() as canonicalization const canonical = generate({ quads: reconstructedQuads }); console.log('Roundtrip preserved:', text === canonical.text); // Lossy rendering for privacy-preserving publishing const cleanHtml = render(parse(mdldString).md); // Merge multiple documents (CRDT-style) const merged = merge([doc1, doc2, doc3]); ``` ## πŸ’‘ Why MD-LD? ### The Problem with Current Systems Most software today uses graphs internally but hides them behind UIs: - **Notion, Slack, Google Docs** β€” Human interfaces over hidden graphs - **CRMs, task apps, note apps** β€” Proprietary data silos - **Social networks** β€” Platform-controlled knowledge prisons Users cannot access the graph directly. Semantics are hidden. Data is locked in products. ### The MD-LD Solution MD-LD removes the intermediary. Writing becomes publishing. Publishing becomes graph construction. **Key benefits:** - **Graph sovereignty** β€” You own text, graph, provenance, execution, history - **No central platform required** β€” Works offline, in browsers, on servers - **Universal semantic substrate** β€” Agents can read, reason, write, execute, validate - **Continuous semantic narrative** β€” Unifies chat, tasks, notes, emails, calendar, files - **Native time dimension** β€” Every action, statement, correction becomes part of the graph - **Decentralized authority** β€” RFC 4151 tag: URIs enable self-sovereign identity without central registries - **Text-native agent memory** - LLM Agent memory substrate in plain text β€” parse context, write knowledge, merge with other agents, all as Markdown files. No database required. ## πŸ“š Documentation Hub - **πŸ“‹ [Specification](./spec/index.md)** β€” Formal specification and test suite - **πŸ“š [Grammar](./grammar/index.md)** β€” EBNF+TextMate grammar specifications - **πŸ“– [Documentation](./docs/index.md)** β€” Complete documentation with guides and references - **🎯 [Examples](./examples/index.md)** β€” Real-world MD-LD examples and use cases - **πŸ’Ύ [Reference server](./server/index.md)** - a Node.js implementation of the server for git-powered semantic workflows and publishing - **🧩 [Ontologies](./ontologies/index.md)** β€” W3C and related standard ontologies used in RDF ### Real-World Applications #### Personal Knowledge Management ```markdown [alice] # Meeting Notes {=alice:meeting-2024-01-15 .alice:Meeting label} Attendees: **Alice** {+alice:alice ?alice:attendee label} **Bob** {+alice:bob ?alice:attendee label} Action items: **Review proposal** {+alice:task-1 ?alice:actionItem label} ``` #### Developer Documentation ```markdown [api] # Get User by ID {=api:/users/:id .api:Endpoint label} Method: [GET] {+api:methods/GET ?api:method} Path: [/users/:id] {api:path} Status: [OK] {api:status} ``` #### Academic Research ```markdown [alice] # Semantic Web {=alice:research/paper-semantic-markdown .alice:ScholarlyArticle label} Is part of [semantic research] {+alice:research/semantic !member} Authored by [Alice Johnson] {+alice:alice-johnson ?alice:author} on [2026-08-12] {alice:datePublished ^^xsd:date}. ``` #### Content Management ```markdown [blog] # Understanding MD-LD {=blog:post-mdld .blog:Post label} [MD-LD] {blog:emphasized} allows you to embed RDF directly in Markdown. ``` #### Local-First Personal Knowledge Base ```markdown [alice] # Meeting with Bob {=alice:meeting-2026-01-21 .Meeting label} Attendees: [Alice] {=alice:alice}, [Bob] {+alice:bob ?attendees} Location: [Coffee Shop] {alice:location} Discussed [Project Alpha] {alice:discussed} ## ✨ Core Features - **πŸ”— Prefix folding** β€” Build hierarchical namespaces with CURIE-based IRI authoring - **πŸ“ Subject declarations** β€” `{=IRI}` and `{=#fragment}` for context setting - **🎯 Object IRIs** β€” `{+IRI}` and `{+#fragment}` for temporary object declarations - **πŸ”„ Three predicate forms** β€” `p` (Sβ†’L), `?p` (Sβ†’O), `!p` (Oβ†’S) - **🏷️ Type declarations** β€” `.Class` for rdf:type triples - **πŸ“… Datatypes & language** β€” `^^xsd:date` and `@en` support - **🧩 Fragments** β€” Document structuring with `{=#fragment}` - **⚑ Polarity system** β€” Sophisticated diff authoring with `+` and `-` prefixes - **πŸ“ Origin tracking** β€” Complete provenance with lean quad-to-source mapping - **πŸ”— Span chains** β€” Walkable textual topology between semantic blocks for context recovery and resonance - **🎯 Elevated statements** β€” Automatic rdf:Statement pattern detection - **🏷️ Primary metadata quartet** β€” Subject, type, label, comment for document identity - **πŸ”„ Round-trip safety** β€” Deterministic parse ↔ generate cycles - **🌐 HTML Codec** β€” Lossless `render()` and `deconstruct()` pair for web publishing **Bundle size:** 101KB unminified, 24KB gzipped ## πŸ“¦ Installation ### Node.js ```bash pnpm install mdld-parse node -e " import { parse } from 'mdld-parse'; console.log(parse({ text: '# Test {=tag:test@example.org,2026:index .prov:Entity label}' })); " ``` ### Browser ESM (importmap) ```html ``` ### Example use in browser console You can copy and paste this code into your browser console to see the list of tasks as an easy to render JSON object. ```javascript const mdld = await import('https://cdn.jsdelivr.net/npm/mdld-parse/+esm') const text = `[my] # Tasks {=my:tasks .prov:Collection label} ## Task 1 {=my:tasks/1 .prov:Activity label} One of my [urgent] {my:tasks/status} [tasks] {+my:tasks !prov:hadMember} > Explore deeper the concept of a triple in RDF {comment} ## Task 2 {=my:tasks/2 .prov:Activity label} One of my [tasks] {+my:tasks !prov:hadMember} > Start building knowledge graphs {comment} `; const result = parse({ text }); function extractByType (quads, type) { return Object.values( quads.reduce((acc, q) => { const s = q.subject.value; const key = q.predicate.value.split(/[#/]/).pop(); (acc[s] ??= { iri: s })[key] = q.object.value; return acc; }, {}) ) .filter(x => x.type === type) .map(({ type, ...x }) => x); } const tasks = extractByType(result.quads,"http://www.w3.org/ns/prov#Activity") console.log(tasks); /* [ { "iri": "tag:alice@example.org:tasks/1", "label": "Task 1", "status": "urgent", "comment": "Explore deeper the concept of a triple in RDF" }, { "iri": "tag:alice@example.org:tasks/2", "label": "Task 2", "comment": "Start building knowledge graphs" } ] */ ``` ## 🧠 Semantic Model MD-LD encodes a directed labeled multigraph where three nodes may be in scope: - **S** β€” current subject (IRI) - **O** β€” object resource (IRI from link/image) - **L** β€” literal value (string + optional datatype/language) ### Predicate Routing Each predicate form determines the graph edge: | Form | Edge | Example | Meaning | |-------|---------|------------------------------|------------------| | `p` | S β†’ L | `[Alice] {label}` | literal property | | `?p` | S β†’ O | `[NASA] {=ex:nasa ?org}` | object property | | `!p` | O β†’ S | `[Parent] {=ex:p !hasPart}` | reverse object | ## 🎨 Syntax Quick Reference ### Subject Declaration Set current subject (emits no quads): ```markdown [ex] ## Apollo 11 {=ex:apollo11} ``` ### Type Declaration Emit `rdf:type` triple: ```markdown [ex] ## Apollo 11 {=ex:apollo11 .ex:SpaceMission .prov:Entity} ``` ### Literal Properties Inline value carriers emit literal properties: ```markdown [ex] # Mission {=ex:apollo11} [Neil Armstrong] {ex:commander} [1969] {ex:year ^^xsd:gYear} [Historic mission] {ex:description @en} ``` ### Object Properties Links create relationships (use `?` prefix): ```markdown [ex] # Mission {=ex:apollo11} [NASA] {=ex:nasa ?ex:organizer} ``` ### Resource Declaration Declare resources inline with `{+iri}`: ```markdown [ex] # Mission {=ex:apollo11} [Neil Armstrong] {+ex:armstrong ?ex:commander .Person} ``` ### Diff Authoring (Polarity) Use `+` and `-` for retractions: ```markdown [ex] New student [Alice] {=ex:new-student .prov:Person ex:name} is our [class] {+ex:my-class !member}. I think she might know [Bob] {+ex:bob ?ex:knows}. **Correction:** [Her] {=ex:new-student} name is not [Alice] {-ex:name}, it's [Ellie] {ex:name}. **Correction:** I asked her directly - no, she doesn't know [him] {+ex:bob -?ex:knows}. **IRI replacement:** Let's create a proper [Class] {=ex:my-class} record for [Ellie] {+ex:Ellie .prov:Person ex:name label ?member} instead of temporary [Ellie] {+ex:new-student -.prov:Person -ex:name -?member} record created earlier. ``` After `generate(parse({text}))` would look like this: ```markdown [ex] # Ellie {=ex:Ellie .prov:Person label} [Ellie] {ex:name} # my-class {=ex:my-class} [ex:Ellie] {+ex:Ellie ?member} ``` ## πŸ”§ API Reference ### `parse({ text, context, dataFactory, graph })` Parse MDLD to RDF quads with lean origin tracking. **Parameters:** - `text` (string, required) β€” MDLD formatted text - `context` (object, optional) β€” Prefix mappings - `dataFactory` (object, optional) β€” Custom RDF/JS DataFactory - `graph` (string, optional) β€” Named graph IRI **Returns:** `{ quads, remove, statements, origin, context, primarySubject, primary, md }` - `quads` β€” RDF/JS Quads (final resolved graph state) - `remove` β€” RDF/JS Quads (external retractions for diff workflows) - `statements` β€” Elevated SPO quads from rdf:Statement patterns - `origin` β€” Lean origin tracking: `quadIndex`, `blocks`, `spans`, `documentStructure` - `context` β€” Final context with prefixes - `primarySubject` β€” String IRI or null (canonical append identity) - `primary` β€” Primary metadata quartet: `{ subject, type, label, comment }` - `md` β€” Clean Markdown with annotations stripped `primarySubject` is useful to allow each iri have it's page and vice versa - so we can have arbitrary MD content attached to it. This is where we can render the `md` on the entity page if we have it in our custom `const pages = new Map()`. `md` is useful to detect parsing success: `if(originalText!=parsed.md) {console.log('Parse success. Total annotations: ', originalText.length-md.length) letters.` ### `merge(docs, options)` Merge multiple MDLD documents with diff polarity resolution. **Parameters:** - `docs` (array) β€” Array of markdown strings or ParseResult objects - `options` (object, optional): - `context` (object) β€” Prefix mappings **Returns:** `{ quads, remove, statements, origin, context, primarySubjects, primary }` - `quads` β€” RDF/JS Quads (final resolved graph state) - `remove` β€” RDF/JS Quads (external retractions) - `statements` β€” Elevated statements from all documents - `origin` β€” Merge origin with document tracking - `context` β€” Final context with prefixes - `primarySubjects` β€” Array of string IRIs (canonical identities) - `primary` β€” Array of primary metadata objects **Use case:** CRDT-style state management with append-only documents. ### `generate({ quads, context, primarySubject, compactInline, renderReverse, remove, lang })` Generate deterministic MDLD from RDF quads. **Parameters:** - `quads` (array, required) β€” RDF/JS Quads to convert - `context` (object, optional) β€” Prefix mappings - `primarySubject` (string, optional) β€” IRI to place first in output - `compactInline` (boolean, optional) β€” Inline type/label compaction (default: `false`) - `renderReverse` (boolean, optional) β€” Reverse connections as `!p` (default: `false`) - `remove` (array, optional) β€” RDF/JS Quads to retract (for diff generation) - `lang` (string, optional) β€” Preferred language for labels (e.g., `'en'`, `'es'`, `'fr'`). Priority: specified lang β†’ untagged β†’ English β†’ any language **Returns:** `{ text, context, compactStats }` - `text` β€” Generated MDLD text - `context` β€” Full context with prefixes - `compactStats` β€” Compaction metrics **Features:** Visual styling, label-in-heading, round-trip safe, diff generation, language preference. **Canonical output:** `generate()` is a deterministic serializer β€” quads are normalized into a total order (subject β†’ predicate β†’ object β†’ term type β†’ datatype β†’ language) before rendering, so the same quad *set* always produces byte-identical text regardless of input array order. This makes it usable for RDF graph comparison: `generate(g1).text === generate(g2).text` iff the graphs are equal (modulo blank nodes, which are out of scope, and named graphs, which MD-LD does not serialize). Note that options (`context`, `primarySubject`, `compactInline`, `renderReverse`, `lang`, `remove`) are part of the canonical form β€” compare outputs generated with the same options. **Example with language preference:** ```javascript const { text } = generate({ quads: result.quads, lang: 'es' // Prefer Spanish labels }); ``` ### `generateNode({ quads, focusIRI, context, compactInline, renderReverse, lang })` Generate node-centric MDLD for a specific IRI. **Parameters:** - `quads` (array, required) β€” RDF/JS Quads to search - `focusIRI` (string, required) β€” IRI to center view on - `context` (object, optional) β€” Prefix mappings - `compactInline` (boolean, optional) β€” Inline compaction (default: `true`) - `renderReverse` (boolean, optional) β€” Reverse connections (default: `true`) - `lang` (string, optional) β€” Preferred language for labels (e.g., `'en'`, `'es'`, `'fr'`). Priority: specified lang β†’ untagged β†’ English β†’ any language **Returns:** `{ text, context, compactStats }` **Safety:** Returns empty text if focusIRI not found (prevents accidental full database rendering). ### `updateValue({ text, quad, value, origin })` Update carrier text of a literal quad in MDLD text. **Parameters:** - `text` (string) β€” Original MDLD text - `quad` (object) β€” Quad to update - `value` (string) β€” New carrier text - `origin` (object, optional) β€” ParseResult.origin **Returns:** Updated MDLD text (fail-safe) **Use case:** Editor applications updating literal values. ### `locate(quad, origin)` Locate quad origin entry for UI navigation. **Returns:** `{ blockId, range, valueRange, carrierType, ... }` or `null` ### `render(mdld, options?)` Convert MD-LD to semantic HTML with preserved annotations. **Parameters:** - `mdld` (string, required) β€” MD-LD formatted text - `options` (object, optional): - `context` (object) β€” Additional prefix mappings **Returns:** `string` β€” Semantic HTML with `data-annotation` attributes **Features:** - Preserves complete MD-LD syntax in `data-annotation` for roundtrip reconstruction - Resolves IRIs into `data-iri` attributes for easy querying - Adds semantic CSS classes: `.mdld-heading`, `.mdld-link`, `.typed`, `.retracted` - External links (`http(s)://`, `mailto:`, any scheme, protocol-relative) get `target="_blank" rel="noopener noreferrer"`; fragment (`#`) and relative links stay on-page - Full CommonMark inline links: `[text](#fragment)`, `[text](/path)`, `[text](mailto:…)`, titles (`[t](url "title")`), and images `![alt](src)` - Entity references (`&`, `©`, `©`, `©`) decode; backslash escapes (`\*`) suppress markup - Standard Markdown/HTML passthrough: raw HTML blocks (``, `
`, …), inline HTML, hard breaks (`
`), and indented code blocks render per CommonMark; code stays escaped - Platform-agnostic: works in Node.js, Deno, browsers, edge workers **Example:** ```javascript const html = render('# Alice {=ex:alice .Person label}'); ``` produces ```html

Alice

``` ### `deconstruct(html)` Reconstruct MD-LD from rendered HTML via pure string scanning. **Parameters:** - `html` (string, required) β€” HTML produced by `render()` **Returns:** `string` β€” Reconstructed MD-LD text **Roundtrip invariant:** ```javascript parse(deconstruct(render(mdld))).quads === parse(mdld).quads ``` **Example:** ```javascript const html = '

Alice

'; const mdld = deconstruct(html); // # Alice {=ex:alice .Person label} ``` **Use cases:** - Server-side rendering: render MD-LD to HTML, send to client - Client-side graph extraction: `parse(deconstruct(document.body.innerHTML))` - Offline-first apps: cache HTML, reconstruct quads on demand **Notes:** - Raw HTML blocks pass through `deconstruct()` verbatim, so `
` and friends roundtrip losslessly - `deconstruct()` only recognizes elements carrying `mdld-*` classes β€” hand-written HTML without them is treated as raw passthrough **CommonMark compatibility β€” deliberate limitations:** - **Setext headings** (`Title` + `===`/`---`) are not supported: they need lookahead that conflicts with per-line annotation parsing, and `---` already means `
`. Use ATX `#` headings. - **Reference-style links** (`[text][ref]`, `[ref]: url`) are not supported: definitions require document-level state that wouldn't survive `deconstruct()` round-trips anyway. Use inline `[text](url)`. - **Shortcut references** (`[ref]` alone as a link) conflict with MD-LD's `[text]` bracket-span syntax. - **GFM extensions** (pipe tables, `~~strikethrough~~`, task lists, `www.` autolinks) are out of scope β€” use raw HTML for tables. - Combined emphasis `***text***` renders as `*text*`, not nested ``. - Empty link destinations `[text]()` stay literal; indented code inside list items is not recognized; inline HTML tags are dropped by `deconstruct()` (inner text preserved). ## 🎨 Graph Visualization β€” `` Visualize your RDF quads as an interactive force-directed graph with the zero-dependency `` web component. ### Quick Start ```html ``` ### Browser Console Usage ```javascript // Load the modules directly const mdld = await import('https://mdld.js.org/mdld-parse.js'); const graph = await import('https://mdld.js.org/quad-graph.js'); // Create and configure the graph const quadGraph = document.createElement('quad-graph'); quadGraph.height = '600'; document.body.appendChild(quadGraph); // Parse and visualize const result = mdld.parse({ text: yourMdldString }); quadGraph.context = result.context; quadGraph.quads = result.quads; ``` ### Installation ```bash pnpm install mdld-parse ``` ```javascript import { parse } from 'mdld-parse'; import 'mdld-parse/quad-graph'; // Registers custom element ``` ### Features - **Zero dependencies** β€” Pure Canvas2D rendering, ~650 LOC - **Interactive** β€” Wheel/pinch zoom, drag background to pan, drag nodes to move, double-click to pin/unpin - **Force-directed layout** β€” Barnes-Hut quadtree for performance, time-sliced across frames - **Collision-free labels** β€” Greedy placement with viewport culling - **Dark theme** β€” High contrast light text on dark background - **Customizable** β€” Attributes for height, charge, link distance, labels - **API methods** β€” `focus(iri)`, `select(iri)`, `fit()`, `pin(iri, on)`, `reheat()`, `getNode(iri)` ### Attributes | Attribute | Default | Description | |-----------|---------|-------------| | `height` | `480px` | Component height | | `charge` | `40` | Repulsion force between nodes | | `link-dist` | `45` | Preferred link length | | `labels` | `on` | Set to `"off"` to hide labels | ### API Methods ```javascript const graph = document.querySelector('quad-graph'); // Focus on a specific node graph.focus('http://example.org/alice'); // Select a node graph.select('http://example.org/bob'); // Fit graph to viewport graph.fit(); // Pin/unpin a node graph.pin('http://example.org/alice', true); // Reheat the simulation graph.reheat(); // Get node data const nodeData = graph.getNode('http://example.org/alice'); // { id, label, x, y, degree, pinned, type, literals } ``` ### Events ```javascript graph.addEventListener('node-click', (e) => { console.log('Clicked:', e.detail); // IRI string }); graph.addEventListener('node-select', (e) => { console.log('Selected:', e.detail); // IRI string or null }); graph.addEventListener('node-hover', (e) => { console.log('Hovered:', e.detail); // IRI string or null }); graph.addEventListener('settled', () => { console.log('Layout settled'); }); ``` ## Styling by Type Use CSS attribute selectors to style elements by their RDF types: ```css /* Style all Person entities */ [data-iri$="Person"] { color: green; } /* Style all Recipe entities */ [data-types*="Recipe"] { background: #fff3cd; } /* Style entities with specific IRI */ [data-iri="http://example.org/alice"] { font-weight: bold; } ``` ## πŸ•ΈοΈ Crawling the graph β€” `crawl.js` MD-LD documents link to each other with ordinary Markdown links, so the graph is already on the wire β€” you just need to follow it. `crawl.js` is a **zero-dependency crawler primitive** that does exactly that: fetch raw text, extract links, recurse. It knows nothing about MD-LD β€” the parser is applied at the call site, which keeps the core pure and the crawler reusable for *any* linked text format. New in **v1.0.9**. Ships as a separate entry point (`mdld-parse/crawl`) and is self-contained enough to load straight from the browser console β€” no bundler, no build step: ```js // Browser console, on any MD-LD site const { crawl } = await import('/crawl.js'); const { pages, errors } = await crawl('/index.md', { sameOrigin: true }); console.table(pages.map(p => ({ url: p.url, depth: p.depth, links: p.links.length }))); ``` ```js // Node β‰₯ 18 / Deno / Bun import { crawl } from 'mdld-parse/crawl'; const { pages } = await crawl('https://mdld.js.org/index.md', { maxPages: 25 }); ``` Full pipeline β€” crawl the graph, parse every document into its own named graph: ```js import { crawl } from 'mdld-parse/crawl'; import { parse, deconstruct } from 'mdld-parse'; const { pages } = await crawl('/index.md', { sameOrigin: true, cache: myCache }); const results = pages.map(p => parse({ text: p.kind === 'html' ? deconstruct(p.text) : p.text, // HTML is a first-class transport graph: p.finalUrl, // redirect-correct document identity })); const quads = results.flatMap(r => r.quads); // the whole crawled graph, provenance intact ``` ### What it extracts Both scanners run on **every** document β€” inline HTML is valid CommonMark, so documents are routinely mixed: - **Markdown**: inline links & images `[text](url)`, reference definitions `[label]: url`, autolinks `` - **HTML**: `` β€” comment-aware, quote-aware, entities decoded; `