mdld-parse 1.0.7 → 1.0.8

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.
Files changed (3) hide show
  1. package/README.md +131 -3
  2. package/dist/index.js +366 -1
  3. package/package.json +2 -1
package/README.md CHANGED
@@ -43,7 +43,7 @@ pnpm install mdld-parse
43
43
  ```
44
44
 
45
45
  ```javascript
46
- import { parse, generate, merge } from 'mdld-parse';
46
+ import { parse, generate, merge, render, deconstruct } from 'mdld-parse';
47
47
 
48
48
  // Parse MDLD to RDF quads
49
49
  const result = parse({ text: mdldString });
@@ -55,6 +55,16 @@ console.log(result.origin); // Provenance tracking
55
55
  // Generate MDLD from quads
56
56
  const { text } = generate({ quads: result.quads });
57
57
 
58
+ // Render to semantic HTML with preserved annotations
59
+ const html = render(mdldString);
60
+
61
+ // Reconstruct MDLD from HTML (lossless roundtrip)
62
+ const reconstructed = deconstruct(html);
63
+ const quads = parse(reconstructed).quads; // Same quads as original!
64
+
65
+ // Lossy rendering for privacy-preserving publishing
66
+ const cleanHtml = render(parse(mdldString).md);
67
+
58
68
  // Merge multiple documents (CRDT-style)
59
69
  const merged = merge([doc1, doc2, doc3]);
60
70
  ```
@@ -128,6 +138,15 @@ Authored by [Alice Johnson] {+alice:alice-johnson ?alice:author} on [2026-08-12]
128
138
  [MD-LD] {blog:emphasized} allows you to embed RDF directly in Markdown.
129
139
  ```
130
140
 
141
+ #### Local-First Personal Knowledge Base
142
+ ```markdown
143
+ [alice] <tag:alice@example.com,2026:>
144
+
145
+ # Meeting with Bob {=alice:meeting-2026-01-21 .Meeting label}
146
+ Attendees: [Alice] {=alice:alice}, [Bob] {+alice:bob ?attendees}
147
+ Location: [Coffee Shop] {alice:location}
148
+ Discussed [Project Alpha] {alice:discussed}
149
+
131
150
  ## ✨ Core Features
132
151
 
133
152
  - **🔗 Prefix folding** — Build hierarchical namespaces with CURIE-based IRI authoring
@@ -143,8 +162,9 @@ Authored by [Alice Johnson] {+alice:alice-johnson ?alice:author} on [2026-08-12]
143
162
  - **🎯 Elevated statements** — Automatic rdf:Statement pattern detection
144
163
  - **🏷️ Primary metadata quartet** — Subject, type, label, comment for document identity
145
164
  - **🔄 Round-trip safety** — Deterministic parse ↔ generate cycles
165
+ - **🌐 HTML Codec** — Lossless `render()` and `deconstruct()` pair for web publishing
146
166
 
147
- **Bundle size:** 86KB unminified, 20KB gzipped
167
+ **Bundle size:** 101KB unminified, 24KB gzipped
148
168
 
149
169
  ## 📦 Installation
150
170
 
@@ -442,6 +462,74 @@ Locate quad origin entry for UI navigation.
442
462
 
443
463
  **Returns:** `{ blockId, range, valueRange, carrierType, ... }` or `null`
444
464
 
465
+ ### `render(mdld, options?)`
466
+
467
+ Convert MD-LD to semantic HTML with preserved annotations.
468
+
469
+ **Parameters:**
470
+ - `mdld` (string, required) — MD-LD formatted text
471
+ - `options` (object, optional):
472
+ - `context` (object) — Additional prefix mappings
473
+
474
+ **Returns:** `string` — Semantic HTML with `data-annotation` attributes
475
+
476
+ **Features:**
477
+ - Preserves complete MD-LD syntax in `data-annotation` for roundtrip reconstruction
478
+ - Resolves IRIs into `data-iri` attributes for easy querying
479
+ - Adds semantic CSS classes: `.mdld-heading`, `.mdld-link`, `.typed`, `.retracted`
480
+ - Platform-agnostic: works in Node.js, Deno, browsers, edge workers
481
+
482
+ **Example:**
483
+ ```javascript
484
+ const html = render('# Alice {=ex:alice .Person label}');
485
+ ```
486
+ produces
487
+ ```html
488
+ <h1 class="mdld-heading typed"
489
+ data-annotation="{=ex:alice .Person label}"
490
+ data-iri="http://example.org/alice">Alice</h1>
491
+ ```
492
+
493
+ ### `deconstruct(html)`
494
+
495
+ Reconstruct MD-LD from rendered HTML via pure string scanning.
496
+
497
+ **Parameters:**
498
+ - `html` (string, required) — HTML produced by `render()`
499
+
500
+ **Returns:** `string` — Reconstructed MD-LD text
501
+
502
+ **Roundtrip invariant:**
503
+ ```javascript
504
+ parse(deconstruct(render(mdld))).quads === parse(mdld).quads
505
+ ```
506
+
507
+ **Example:**
508
+ ```javascript
509
+ const html = '<h1 data-annotation="{=ex:alice .Person label}">Alice</h1>';
510
+ const mdld = deconstruct(html);
511
+ // # Alice {=ex:alice .Person label}
512
+ ```
513
+
514
+ **Use cases:**
515
+ - Server-side rendering: render MD-LD to HTML, send to client
516
+ - Client-side graph extraction: `parse(deconstruct(document.body.innerHTML))`
517
+ - Offline-first apps: cache HTML, reconstruct quads on demand
518
+
519
+ ## Styling by Type
520
+
521
+ Use CSS attribute selectors to style elements by their RDF types:
522
+
523
+ ```css
524
+ /* Style all Person entities */
525
+ [data-iri$="Person"] { color: green; }
526
+
527
+ /* Style all Recipe entities */
528
+ [data-types*="Recipe"] { background: #fff3cd; }
529
+
530
+ /* Style entities with specific IRI */
531
+ [data-iri="http://example.org/alice"] { font-weight: bold; }
532
+
445
533
  ### Utility Functions
446
534
 
447
535
  ```javascript
@@ -458,13 +546,14 @@ import {
458
546
  ## 🏗️ Architecture
459
547
 
460
548
  ### Design Principles
461
- - **Zero dependencies** — Pure JavaScript, 85KB unminified (20KB gzipped)
549
+ - **Zero dependencies** — Pure JavaScript, 101KB unminified (24KB gzipped)
462
550
  - **Streaming-first** — Single-pass parsing, O(n) complexity
463
551
  - **Character-based tokenization** — 20-28% faster than regex-based approaches
464
552
  - **Standards-compliant** — RDF/JS data model, W3C CURIE 1.0 syntax
465
553
  - **Deterministic** — Same input always produces same output
466
554
  - **Explicit semantics** — No guessing, inference, or heuristics
467
555
  - **Dual-layer origin** — Every parse emits both a semantic quad graph and a walkable textual topology graph simultaneously
556
+ - **HTML as codec** — Lossless roundtrip between MD-LD and HTML via `render()`/`deconstruct()`
468
557
 
469
558
  ### Origin: Blocks and Spans
470
559
 
@@ -479,6 +568,42 @@ The parser output includes a complete document chain at no extra cost:
479
568
 
480
569
  Spans store no text — content is always recovered via `sourceText.slice(span.range[0], span.range[1])`. This unlocks context-aware UI, autocomplete neighborhood retrieval, and cross-document topology without any parser-level interpretation.
481
570
 
571
+ ### HTML Codec: Server/Client Equivalence
572
+
573
+ The `render()` and `deconstruct()` pair enables two equivalent workflows:
574
+
575
+ **Server-Side Rendering (SSR):**
576
+ ```
577
+ MD-LD files → render() → HTML → Browser
578
+ ↓
579
+ deconstruct() → parse() → quads
580
+ ```
581
+
582
+ **Client-Side Rendering (CSR):**
583
+ ```
584
+ MD-LD files → Browser → render() → HTML
585
+ ↓
586
+ deconstruct() → parse() → quads
587
+ ```
588
+
589
+ Both modes produce identical quads. The choice depends on your deployment model:
590
+ - **SSR:** Better for SEO, faster initial page load, works without JavaScript
591
+ - **CSR:** Better for offline-first apps, reduces server load, enables dynamic updates
592
+
593
+ **Bandwidth optimization:**
594
+ - Full fidelity: `render(mdld)` includes `data-annotation` for roundtrip
595
+ - Lossy mode: `render(parse(mdld).md)` strips annotations for privacy-preserving publishing
596
+ - HTML payload is 2-3x smaller than MD-LD + JSON-LD combination
597
+
598
+ **Use cases:**
599
+ - Personal knowledge bases (Obsidian-like, web-native)
600
+ - Community wikis with semantic search
601
+ - Offline-first research notes with citations
602
+ - Collaborative task management with provenance
603
+ - Reading lists that become knowledge graphs
604
+ - Meeting notes with automatic linking
605
+ - Decentralized community event calendars
606
+
482
607
  ### Performance Characteristics
483
608
  - **Real-time (60fps):** Up to 4,527 quads per frame
484
609
  - **Batch processing:** Up to 225,059 quads per second
@@ -512,6 +637,7 @@ Comprehensive test suite covering:
512
637
  - Elevated statements detection
513
638
  - Primary metadata extraction
514
639
  - Round-trip parse/generate cycles
640
+ - HTML codec roundtrip — `mdld = deconstruct(render(mdld))`
515
641
  - Origin tracking and provenance
516
642
 
517
643
 
@@ -537,6 +663,7 @@ Comprehensive test suite covering:
537
663
  - [Subject System](./docs/Subject.md)
538
664
  - [API Reference](./docs/API.md)
539
665
  - [Generate: Quads to MDLD](./docs/generate.md)
666
+ - [Render MDLD to HTML and deconstruct it back](./docs/render.md)
540
667
  - [Diff Documents](./docs/diff.md)
541
668
  - [Syntax Reference](./docs/Syntax.md)
542
669
  - [Architecture & Design](./docs/Architecture.md)
@@ -560,6 +687,7 @@ Comprehensive test suite covering:
560
687
  - [Task Management System](./examples/demo/tasks.md)
561
688
  - [Cassini-Huygens Mission](./examples/demo/space-mission.md)
562
689
  - [RDF Fundamentals](./examples/demo/rdf.md)
690
+ - [Statements Golden Graph](./examples/statements.md)
563
691
  - [PROV-O Patterns](./examples/demo/prov.md)
564
692
  - [SHACL Validation](./examples/demo/shacl.md)
565
693
  - [XSD Datatypes](./examples/demo/xsd.md)
package/dist/index.js CHANGED
@@ -910,6 +910,10 @@ function resolveObject(sem, state) {
910
910
  if (sem.object.startsWith("#")) return resolveFragment(sem.object.substring(1), state.currentSubject, state.df);
911
911
  return state.df.namedNode(expandIRI(sem.object, state.ctx));
912
912
  }
913
+ function escapeHtml$1(text) {
914
+ if (!text) return "";
915
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
916
+ }
913
917
  function isLiteral(term) {
914
918
  return term?.termType === "Literal";
915
919
  }
@@ -2028,6 +2032,367 @@ function buildLabelLookup(subjectGroups, lang = null) {
2028
2032
  return labelLookup;
2029
2033
  }
2030
2034
  //#endregion
2035
+ //#region src/render.js
2036
+ /**
2037
+ * MD-LD UI Renderer
2038
+ *
2039
+ * Generates clean, semantic HTML for presentation.
2040
+ * Preserves the raw MD-LD annotation in `data-annotation` for client-side
2041
+ * JS/CSS targeting, and resolves the primary IRI into `data-iri`.
2042
+ */
2043
+ function render(src, options = {}) {
2044
+ const lines = src.split("\n");
2045
+ const context = buildRenderContext(lines, options.context);
2046
+ function safeExpand(term) {
2047
+ if (!term || term === "RESET") return null;
2048
+ if (term.startsWith("=#") || term.startsWith("#")) return term;
2049
+ return expandIRI(term, context);
2050
+ }
2051
+ function getAttrs(rawAnnotation, parsedSem, isLink = false, fallbackHref = null) {
2052
+ const attrs = [];
2053
+ const classes = [];
2054
+ if (rawAnnotation) attrs.push(`data-annotation="${escapeHtml$1("{" + rawAnnotation + "}")}"`);
2055
+ let iri = null;
2056
+ if (parsedSem?.subject && parsedSem.subject !== "RESET") iri = safeExpand(parsedSem.subject);
2057
+ else if (parsedSem?.object) iri = safeExpand(parsedSem.object);
2058
+ else if (isLink && fallbackHref) iri = safeExpand(fallbackHref);
2059
+ if (iri) {
2060
+ attrs.push(`data-iri="${escapeHtml$1(iri)}"`);
2061
+ if (isLink) attrs.push(`href="${escapeHtml$1(iri)}"`);
2062
+ } else if (isLink && fallbackHref) attrs.push(`href="${escapeHtml$1(fallbackHref)}"`);
2063
+ if (parsedSem?.types?.some((t) => !t.remove)) classes.push("typed");
2064
+ if (parsedSem?.predicates?.some((p) => p.remove) || parsedSem?.types?.some((t) => t.remove)) classes.push("retracted");
2065
+ if (classes.length > 0) attrs.unshift(`class="${classes.join(" ")}"`);
2066
+ return attrs.join(" ");
2067
+ }
2068
+ function mergeClasses(baseClass, customAttrs) {
2069
+ const classMatch = customAttrs.match(/class="([^"]*)"/);
2070
+ let finalClass = baseClass;
2071
+ let remainingAttrs = customAttrs;
2072
+ if (classMatch) {
2073
+ finalClass += " " + classMatch[1];
2074
+ remainingAttrs = customAttrs.replace(/class="[^"]*"/, "").trim();
2075
+ }
2076
+ return `class="${finalClass}"${remainingAttrs ? " " + remainingAttrs : ""}`;
2077
+ }
2078
+ function renderInline(text) {
2079
+ const carriers = scanInlineCarriers(text, 0);
2080
+ if (carriers.length === 0) return escapeHtml$1(text);
2081
+ let out = "";
2082
+ let lastPos = 0;
2083
+ for (const c of carriers) {
2084
+ if (c.range[0] > lastPos) out += escapeHtml$1(text.slice(lastPos, c.range[0]));
2085
+ const sem = c.attrs ? parseSemanticBlock(c.attrs) : null;
2086
+ const raw = c.attrs || "";
2087
+ const isLink = c.type === "link";
2088
+ const fallbackHref = c.url || null;
2089
+ let tag = "span";
2090
+ let baseClass = "mdld-bracket";
2091
+ if (c.type === "link") {
2092
+ tag = "a";
2093
+ baseClass = "mdld-link";
2094
+ } else if (c.type === "code") {
2095
+ tag = "code";
2096
+ baseClass = "mdld-code";
2097
+ } else if (c.type === "strong") {
2098
+ tag = "strong";
2099
+ baseClass = "mdld-bold";
2100
+ } else if (c.type === "emphasis") {
2101
+ tag = "em";
2102
+ baseClass = "mdld-italic";
2103
+ }
2104
+ const customAttrs = getAttrs(raw, sem, isLink, fallbackHref);
2105
+ const attrString = mergeClasses(baseClass, customAttrs);
2106
+ out += `<${tag} ${attrString}>${renderInline(c.text)}</${tag}>`;
2107
+ lastPos = c.range[1];
2108
+ }
2109
+ if (lastPos < text.length) out += escapeHtml$1(text.slice(lastPos));
2110
+ return out;
2111
+ }
2112
+ const out = [];
2113
+ let i = 0;
2114
+ let codeBlock = null;
2115
+ while (i < lines.length) {
2116
+ const line = lines[i];
2117
+ if (codeBlock) {
2118
+ if (new RegExp(`^${codeBlock.fenceChar}{${codeBlock.fenceLength},}\\s*$`).test(line.trim())) {
2119
+ const sem = codeBlock.attrs ? parseSemanticBlock(codeBlock.attrs) : null;
2120
+ const carrierText = codeBlock.content.join("\n");
2121
+ const customAttrs = getAttrs(codeBlock.attrs, sem);
2122
+ const attrString = mergeClasses(`mdld-codeblock language-${codeBlock.lang || "text"}`, customAttrs);
2123
+ out.push(`<pre><code ${attrString}>${escapeHtml$1(carrierText)}</code></pre>`);
2124
+ codeBlock = null;
2125
+ } else codeBlock.content.push(line);
2126
+ i++;
2127
+ continue;
2128
+ }
2129
+ if (line.trim() === "") {
2130
+ i++;
2131
+ continue;
2132
+ }
2133
+ const fence = detectFence(line.trim());
2134
+ if (fence) {
2135
+ codeBlock = {
2136
+ fenceChar: fence.fenceChar,
2137
+ fenceLength: fence.fenceLength,
2138
+ lang: fence.lang,
2139
+ attrs: fence.attrs,
2140
+ content: []
2141
+ };
2142
+ i++;
2143
+ continue;
2144
+ }
2145
+ const prefix = detectPrefix(line);
2146
+ if (prefix) {
2147
+ const resolvedIri = context[prefix.prefix];
2148
+ out.push(`<div class="mdld-prefix" data-prefix="${prefix.prefix}" data-raw="${escapeHtml$1(prefix.iri)}" data-iri="${escapeHtml$1(resolvedIri)}" style="display:none"></div>`);
2149
+ i++;
2150
+ continue;
2151
+ }
2152
+ const heading = detectHeading(line);
2153
+ if (heading) {
2154
+ const sem = heading.attrs ? parseSemanticBlock(heading.attrs) : null;
2155
+ const attrString = mergeClasses("mdld-heading", getAttrs(heading.attrs, sem));
2156
+ out.push(`<h${heading.depth} ${attrString}>${renderInline(heading.content)}</h${heading.depth}>`);
2157
+ i++;
2158
+ continue;
2159
+ }
2160
+ if (detectList(line)) {
2161
+ out.push("<ul class=\"mdld-list\">");
2162
+ while (i < lines.length) {
2163
+ const l = detectList(lines[i]);
2164
+ if (!l) break;
2165
+ const sem = l.attrs ? parseSemanticBlock(l.attrs) : null;
2166
+ const attrString = mergeClasses("mdld-item", getAttrs(l.attrs, sem));
2167
+ out.push(`<li ${attrString}>${renderInline(l.content)}</li>`);
2168
+ i++;
2169
+ }
2170
+ out.push("</ul>");
2171
+ continue;
2172
+ }
2173
+ const blockquote = detectBlockquote(line);
2174
+ if (blockquote) {
2175
+ let quoteLines = [blockquote.content];
2176
+ i++;
2177
+ while (i < lines.length) {
2178
+ const bq = detectBlockquote(lines[i]);
2179
+ if (!bq) break;
2180
+ quoteLines.push(bq.content);
2181
+ i++;
2182
+ }
2183
+ const sem = blockquote.attrs ? parseSemanticBlock(blockquote.attrs) : null;
2184
+ const attrString = mergeClasses("mdld-quote", getAttrs(blockquote.attrs, sem));
2185
+ const carrierText = quoteLines.join("\n");
2186
+ out.push(`<blockquote ${attrString}>${renderInline(carrierText)}</blockquote>`);
2187
+ continue;
2188
+ }
2189
+ const standalone = detectStandaloneSubject(line);
2190
+ if (standalone) {
2191
+ const fakeSem = parseSemanticBlock(`=${standalone.content}`);
2192
+ const attrString = mergeClasses("mdld-standalone", getAttrs(`=${standalone.content}`, fakeSem));
2193
+ out.push(`<div ${attrString} style="display:none"></div>`);
2194
+ i++;
2195
+ continue;
2196
+ }
2197
+ let paraLines = [line];
2198
+ i++;
2199
+ while (i < lines.length && lines[i].trim() !== "" && !detectFence(lines[i].trim()) && !detectPrefix(lines[i]) && !detectHeading(lines[i]) && !detectList(lines[i]) && !detectBlockquote(lines[i]) && !detectStandaloneSubject(lines[i])) {
2200
+ paraLines.push(lines[i]);
2201
+ i++;
2202
+ }
2203
+ const paraText = paraLines.join("\n");
2204
+ out.push(`<p class="mdld-paragraph">${renderInline(paraText)}</p>`);
2205
+ }
2206
+ return out.join("\n");
2207
+ }
2208
+ function buildRenderContext(lines, userContext = {}) {
2209
+ const context = {
2210
+ ...DEFAULT_CONTEXT,
2211
+ ...userContext
2212
+ };
2213
+ for (const line of lines) {
2214
+ const prefix = detectPrefix(line);
2215
+ if (prefix) {
2216
+ let iri = prefix.iri;
2217
+ if (iri.includes(":")) {
2218
+ const colonIndex = iri.indexOf(":");
2219
+ const p = iri.substring(0, colonIndex);
2220
+ const ref = iri.substring(colonIndex + 1);
2221
+ if (context[p] && p !== "@vocab") iri = context[p] + ref;
2222
+ }
2223
+ context[prefix.prefix] = iri;
2224
+ }
2225
+ }
2226
+ return context;
2227
+ }
2228
+ /**
2229
+ * Reconstruct MD-LD from rendered HTML.
2230
+ * Pure string scanning over our constrained output format.
2231
+ * Platform-agnostic: no DOMParser, no browser APIs required.
2232
+ */
2233
+ function deconstruct(html) {
2234
+ const blocks = [];
2235
+ let pos = 0;
2236
+ while (pos < html.length) {
2237
+ while (pos < html.length && /\s/.test(html[pos])) pos++;
2238
+ if (pos >= html.length) break;
2239
+ if (html.startsWith("<div class=\"mdld-prefix\"", pos)) {
2240
+ const end = html.indexOf("></div>", pos);
2241
+ if (end === -1) break;
2242
+ const tag = html.slice(pos, end + 7);
2243
+ const prefix = extractAttr(tag, "data-prefix");
2244
+ const raw = extractAttr(tag, "data-raw") || extractAttr(tag, "data-iri");
2245
+ blocks.push(`[${prefix}] <${raw}>`);
2246
+ pos = end + 7;
2247
+ } else if (html.startsWith("<div class=\"mdld-standalone\"", pos)) {
2248
+ const end = html.indexOf("</div>", pos);
2249
+ if (end === -1) break;
2250
+ const ann = extractAttr(html.slice(pos, end + 6), "data-annotation");
2251
+ if (ann) blocks.push(ann);
2252
+ pos = end + 6;
2253
+ } else if (html.startsWith("<pre><code", pos)) {
2254
+ const closePre = html.indexOf("</code></pre>", pos);
2255
+ if (closePre === -1) break;
2256
+ const full = html.slice(pos, closePre + 13);
2257
+ const preClose = full.indexOf(">") + 1;
2258
+ const codeOpenEnd = full.indexOf(">", preClose) + 1;
2259
+ const codeTag = full.slice(preClose, codeOpenEnd);
2260
+ const content = full.slice(codeOpenEnd, full.length - 13);
2261
+ const langMatch = (extractAttr(codeTag, "class") || "").match(/language-(\w+)/);
2262
+ const lang = langMatch ? langMatch[1] : "";
2263
+ const ann = extractAttr(codeTag, "data-annotation");
2264
+ blocks.push(`\`\`\`${lang}${ann ? " " + ann : ""}\n${unescapeHtml(content)}\n\`\`\``);
2265
+ pos = closePre + 13;
2266
+ } else if (html[pos] === "<" && /^<h[1-6]/.test(html.slice(pos, pos + 4))) {
2267
+ const level = html[pos + 2];
2268
+ const closeTag = `</h${level}>`;
2269
+ const close = html.indexOf(closeTag, pos);
2270
+ if (close === -1) break;
2271
+ const full = html.slice(pos, close + closeTag.length);
2272
+ const openEnd = full.indexOf(">") + 1;
2273
+ const openTag = full.slice(0, openEnd);
2274
+ const content = full.slice(openEnd, full.length - closeTag.length);
2275
+ const hashes = "#".repeat(parseInt(level));
2276
+ const ann = extractAttr(openTag, "data-annotation");
2277
+ blocks.push(`${hashes} ${deconstructInline(content)}${ann ? " " + ann : ""}`);
2278
+ pos = close + closeTag.length;
2279
+ } else if (html.startsWith("<blockquote", pos)) {
2280
+ const close = html.indexOf("</blockquote>", pos);
2281
+ if (close === -1) break;
2282
+ const full = html.slice(pos, close + 13);
2283
+ const openEnd = full.indexOf(">") + 1;
2284
+ const openTag = full.slice(0, openEnd);
2285
+ const content = full.slice(openEnd, full.length - 13);
2286
+ const ann = extractAttr(openTag, "data-annotation");
2287
+ const quoted = deconstructInline(content).split("\n").map((l) => l.trim() ? `> ${l}` : ">").join("\n");
2288
+ blocks.push(ann ? `${quoted} ${ann}` : quoted);
2289
+ pos = close + 13;
2290
+ } else if (html.startsWith("<ul class=\"mdld-list\">", pos)) {
2291
+ const close = html.indexOf("</ul>", pos);
2292
+ if (close === -1) break;
2293
+ const inner = html.slice(pos + 21, close);
2294
+ const items = [];
2295
+ let itemPos = 0;
2296
+ while (itemPos < inner.length) {
2297
+ const liStart = inner.indexOf("<li", itemPos);
2298
+ if (liStart === -1) break;
2299
+ const liClose = inner.indexOf("</li>", liStart);
2300
+ if (liClose === -1) break;
2301
+ const liFull = inner.slice(liStart, liClose + 5);
2302
+ const openEnd = liFull.indexOf(">") + 1;
2303
+ const openTag = liFull.slice(0, openEnd);
2304
+ const liContent = liFull.slice(openEnd, liFull.length - 5);
2305
+ const ann = extractAttr(openTag, "data-annotation");
2306
+ items.push(`- ${deconstructInline(liContent)}${ann ? " " + ann : ""}`);
2307
+ itemPos = liClose + 5;
2308
+ }
2309
+ blocks.push(items.join("\n"));
2310
+ pos = close + 5;
2311
+ } else if (html.startsWith("<p class=\"mdld-paragraph\">", pos)) {
2312
+ const close = html.indexOf("</p>", pos);
2313
+ if (close === -1) break;
2314
+ const content = html.slice(pos + 25, close);
2315
+ blocks.push(deconstructInline(content));
2316
+ pos = close + 4;
2317
+ } else pos++;
2318
+ }
2319
+ return blocks.join("\n\n");
2320
+ }
2321
+ function deconstructInline(html) {
2322
+ let out = "";
2323
+ let i = 0;
2324
+ while (i < html.length) if (html[i] === "<") {
2325
+ const closeGt = html.indexOf(">", i);
2326
+ if (closeGt === -1) {
2327
+ out += html.slice(i);
2328
+ break;
2329
+ }
2330
+ const tagContent = html.slice(i + 1, closeGt);
2331
+ if (tagContent.startsWith("/")) {
2332
+ i = closeGt + 1;
2333
+ continue;
2334
+ }
2335
+ const spaceOrEnd = tagContent.search(/[\s/]/);
2336
+ const tagName = (spaceOrEnd === -1 ? tagContent : tagContent.slice(0, spaceOrEnd)).toLowerCase();
2337
+ const attrs = spaceOrEnd === -1 ? "" : tagContent.slice(spaceOrEnd);
2338
+ const closeTag = `</${tagName}>`;
2339
+ let depth = 1;
2340
+ let j = closeGt + 1;
2341
+ let found = false;
2342
+ while (j < html.length && depth > 0) {
2343
+ const nextOpen = html.indexOf(`<${tagName}`, j);
2344
+ const nextClose = html.indexOf(closeTag, j);
2345
+ if (nextClose === -1) break;
2346
+ if (nextOpen !== -1 && nextOpen < nextClose) {
2347
+ depth++;
2348
+ j = nextOpen + 1;
2349
+ } else {
2350
+ depth--;
2351
+ if (depth === 0) {
2352
+ const inner = html.slice(closeGt + 1, nextClose);
2353
+ out += deconstructInlineElement(tagName, attrs, inner);
2354
+ i = nextClose + closeTag.length;
2355
+ found = true;
2356
+ break;
2357
+ }
2358
+ j = nextClose + 1;
2359
+ }
2360
+ }
2361
+ if (!found) {
2362
+ out += html[i];
2363
+ i++;
2364
+ }
2365
+ } else {
2366
+ const nextTag = html.indexOf("<", i);
2367
+ const textEnd = nextTag === -1 ? html.length : nextTag;
2368
+ out += unescapeHtml(html.slice(i, textEnd));
2369
+ i = textEnd;
2370
+ }
2371
+ return out;
2372
+ }
2373
+ function deconstructInlineElement(tagName, attrs, inner) {
2374
+ const ann = extractAttr(attrs, "data-annotation");
2375
+ const content = deconstructInline(inner);
2376
+ const suffix = ann ? " " + ann : "";
2377
+ switch (tagName) {
2378
+ case "a": return `[${content}](${extractAttr(attrs, "href") || ""})${suffix}`;
2379
+ case "span": return `[${content}]${suffix}`;
2380
+ case "code": return `\`${content}\`${suffix}`;
2381
+ case "strong": return `**${content}**${suffix}`;
2382
+ case "em": return `*${content}*${suffix}`;
2383
+ default: return content + suffix;
2384
+ }
2385
+ }
2386
+ function extractAttr(tag, name) {
2387
+ const re = new RegExp(`${name}=(?:"([^"]*)"|'([^']*)')`, "i");
2388
+ const m = tag.match(re);
2389
+ if (!m) return null;
2390
+ return unescapeHtml(m[1] !== void 0 ? m[1] : m[2]);
2391
+ }
2392
+ function unescapeHtml(s) {
2393
+ return String(s).replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#39;/g, "'");
2394
+ }
2395
+ //#endregion
2031
2396
  //#region src/highlight.js
2032
2397
  /**
2033
2398
  * MD-LD Syntax Highlighter
@@ -2365,4 +2730,4 @@ function updateValue({ text, quad, value, origin }) {
2365
2730
  return text.substring(0, location.valueRange.start) + value + text.substring(location.valueRange.end);
2366
2731
  }
2367
2732
  //#endregion
2368
- export { DEFAULT_CONTEXT, DataFactory, expandIRI, generate, generateNode, getIRIColor, hash, hashIRI, highlightMDLD, locate, merge, parse, parseSemanticBlock, shortenIRI, updateValue };
2733
+ export { DEFAULT_CONTEXT, DataFactory, deconstruct, expandIRI, generate, generateNode, getIRIColor, hash, hashIRI, highlightMDLD, locate, merge, parse, parseSemanticBlock, render, shortenIRI, updateValue };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mdld-parse",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "Write RDF knowledge graphs as plain Markdown. Parse to quads, generate back, merge documents. The human-friendly semantic web format.",
5
5
  "keywords": [
6
6
  "rdf",
@@ -52,6 +52,7 @@
52
52
  "codejar": "^4.3.0",
53
53
  "markdown-it": "^15.0.2",
54
54
  "n3": "^2.7.12",
55
+ "rdfa-parse": "^1.0.1",
55
56
  "shiki": "^4.4.3",
56
57
  "unocss": "^66.10.2",
57
58
  "vite": "^8.3.0",