mdld-parse 0.9.9 → 1.0.0

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 (55) hide show
  1. package/README.md +242 -330
  2. package/dist/index.js +1793 -1336
  3. package/package.json +4 -4
  4. package/dist/.nojekyll +0 -0
  5. package/dist/CNAME +0 -1
  6. package/dist/README.md +0 -500
  7. package/dist/docs/API.md +0 -435
  8. package/dist/docs/Architecture.md +0 -190
  9. package/dist/docs/Guide.md +0 -816
  10. package/dist/docs/LLM-MDLD-Inducer.md +0 -550
  11. package/dist/docs/LiterateRDF.md +0 -472
  12. package/dist/docs/Parser.md +0 -720
  13. package/dist/docs/Performance.md +0 -238
  14. package/dist/docs/Spec-render.md +0 -1439
  15. package/dist/docs/Subject.md +0 -180
  16. package/dist/docs/Syntax.md +0 -463
  17. package/dist/docs/TodoList.md +0 -215
  18. package/dist/docs/Use-Cases.md +0 -354
  19. package/dist/docs/guide-m.md +0 -56
  20. package/dist/docs/index.html +0 -108
  21. package/dist/docs/index.md +0 -56
  22. package/dist/docs/one-page.md +0 -322
  23. package/dist/docs/origin.md +0 -460
  24. package/dist/docs/polarity.md +0 -586
  25. package/dist/docs/primary-subject.md +0 -326
  26. package/dist/docs/statements.md +0 -226
  27. package/dist/docs/tokenization-performance-report.md +0 -164
  28. package/dist/examples/Cookbook.md +0 -32
  29. package/dist/examples/Status-SHACL.md +0 -31
  30. package/dist/examples/demo/index.md +0 -35
  31. package/dist/examples/demo/journal.md +0 -58
  32. package/dist/examples/demo/minimal.md +0 -23
  33. package/dist/examples/demo/project.md +0 -84
  34. package/dist/examples/demo/prov.md +0 -107
  35. package/dist/examples/demo/rdf.md +0 -69
  36. package/dist/examples/demo/recipe.md +0 -50
  37. package/dist/examples/demo/research.md +0 -84
  38. package/dist/examples/demo/shacl.md +0 -161
  39. package/dist/examples/demo/space-mission.md +0 -58
  40. package/dist/examples/demo/tasks.md +0 -175
  41. package/dist/examples/demo/xsd.md +0 -91
  42. package/dist/examples/dogfood.md +0 -288
  43. package/dist/examples/few-shot.md +0 -309
  44. package/dist/examples/graph/rdf-graph.html +0 -473
  45. package/dist/examples/graph/rdf_force_graph_web_component.html +0 -506
  46. package/dist/examples/index.md +0 -45
  47. package/dist/examples/llm-time-workflow.md +0 -173
  48. package/dist/examples/statements.md +0 -43
  49. package/dist/examples/workflow.md +0 -150
  50. package/dist/index.html +0 -3049
  51. package/dist/logo.svg +0 -7
  52. package/dist/spec/Spec-compact.md +0 -368
  53. package/dist/spec/Spec-ultra.md +0 -232
  54. package/dist/spec/Spec.md +0 -1116
  55. package/dist/spec/index.md +0 -46
package/dist/index.js CHANGED
@@ -1,52 +1,102 @@
1
1
  //#region src/constants.js
2
- var e = {
2
+ /**
3
+ * Shared utilities for MD-LD Parser and Renderer
4
+ * Ensures DRY code and consistent CommonMark processing
5
+ */
6
+ var DEFAULT_CONTEXT = {
3
7
  "@vocab": "http://www.w3.org/2000/01/rdf-schema#",
4
8
  rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
5
9
  rdfs: "http://www.w3.org/2000/01/rdf-schema#",
6
10
  xsd: "http://www.w3.org/2001/XMLSchema#",
7
11
  sh: "http://www.w3.org/ns/shacl#",
8
12
  prov: "http://www.w3.org/ns/prov#"
9
- }, t = /^(https?|ftp|mailto|tag|nih|urn|uuid|did|web|ipfs|ipns|data|file|urn:uuid):/, n = /^(https?|ftp|mailto|tag|nih|urn|uuid|did|web|ipfs|ipns|data|file):/, r = class {
10
- constructor(e) {
11
- this.id = e;
13
+ };
14
+ var RDFS_LABEL = "http://www.w3.org/2000/01/rdf-schema#label";
15
+ var RDF_TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
16
+ var RDF_LANG_STRING = "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";
17
+ var XSD_STRING = "http://www.w3.org/2001/XMLSchema#string";
18
+ var XSD_BOOLEAN = "http://www.w3.org/2001/XMLSchema#boolean";
19
+ var XSD_INTEGER = "http://www.w3.org/2001/XMLSchema#integer";
20
+ var XSD_DOUBLE = "http://www.w3.org/2001/XMLSchema#double";
21
+ var URL_REGEX = /^(https?|ftp|mailto|tag|nih|urn|uuid|did|web|ipfs|ipns|data|file|urn:uuid):/;
22
+ //#endregion
23
+ //#region src/utils.js
24
+ var VALID_URI_SCHEMES = /^(https?|ftp|mailto|tag|nih|urn|uuid|did|web|ipfs|ipns|data|file):/;
25
+ var Term = class {
26
+ constructor(id) {
27
+ this.id = id;
12
28
  }
13
- equals(e) {
14
- return !!e && this.termType === e.termType && this.value === e.value;
29
+ equals(other) {
30
+ return !!other && this.termType === other.termType && this.value === other.value;
15
31
  }
16
- }, i = class extends r {
17
- constructor(e) {
18
- super(e), this.termType = "NamedNode", this.value = e;
32
+ };
33
+ var NamedNode = class extends Term {
34
+ constructor(iri) {
35
+ super(iri);
36
+ this.termType = "NamedNode";
37
+ this.value = iri;
19
38
  }
20
- }, a = class extends r {
21
- constructor(e) {
22
- super(e), this.termType = "Literal", this.value = "", this.language = "", this.datatype = null;
23
- let t = e.match(/^"([^"\\]*(?:\\.[^"\\]*)*)"(\^\^([^"]+))?(@([^-]+)(--(.+))?)?$/);
24
- t ? (this.value = t[1].replace(/\\"/g, "\"").replace(/\\\\/g, "\\"), t[5] ? (this.language = t[5], this.datatype = new i("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString")) : t[3] ? this.datatype = new i(t[3]) : this.datatype = new i("http://www.w3.org/2001/XMLSchema#string")) : (this.value = e.replace(/^"|"$/g, ""), this.datatype = new i("http://www.w3.org/2001/XMLSchema#string"));
39
+ };
40
+ var Literal = class extends Term {
41
+ constructor(id) {
42
+ super(id);
43
+ this.termType = "Literal";
44
+ this.value = "";
45
+ this.language = "";
46
+ this.datatype = null;
47
+ const dtMatch = id.match(/^"([^"\\]*(?:\\.[^"\\]*)*)"(\^\^([^"]+))?(@([^-]+)(--(.+))?)?$/);
48
+ if (dtMatch) {
49
+ this.value = dtMatch[1].replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
50
+ if (dtMatch[5]) {
51
+ this.language = dtMatch[5];
52
+ this.datatype = new NamedNode(RDF_LANG_STRING);
53
+ } else if (dtMatch[3]) this.datatype = new NamedNode(dtMatch[3]);
54
+ else this.datatype = new NamedNode(XSD_STRING);
55
+ } else {
56
+ this.value = id.replace(/^"|"$/g, "");
57
+ this.datatype = new NamedNode(XSD_STRING);
58
+ }
25
59
  }
26
- equals(e) {
27
- return !!e && this.termType === e.termType && this.value === e.value && this.language === e.language && this.datatype?.value === e.datatype?.value;
60
+ equals(other) {
61
+ return !!other && this.termType === other.termType && this.value === other.value && this.language === other.language && this.datatype?.value === other.datatype?.value;
28
62
  }
29
- }, o = class extends r {
30
- constructor(e) {
31
- super(e || `b${Math.random().toString(36).slice(2, 11)}`), this.termType = "BlankNode", this.value = this.id;
63
+ };
64
+ var BlankNode = class extends Term {
65
+ constructor(name) {
66
+ super(name || `b${Math.random().toString(36).slice(2, 11)}`);
67
+ this.termType = "BlankNode";
68
+ this.value = this.id;
32
69
  }
33
- }, s = class extends r {
34
- constructor(e) {
35
- super(e), this.termType = "Variable", this.value = e;
70
+ };
71
+ var Variable = class extends Term {
72
+ constructor(name) {
73
+ super(name);
74
+ this.termType = "Variable";
75
+ this.value = name;
36
76
  }
37
- }, c = new class extends r {
77
+ };
78
+ var DefaultGraph = class extends Term {
38
79
  constructor() {
39
- super(""), this.termType = "DefaultGraph", this.value = "";
40
- }
41
- equals(e) {
42
- return !!e && this.termType === e.termType;
80
+ super("");
81
+ this.termType = "DefaultGraph";
82
+ this.value = "";
43
83
  }
44
- }(), l = class extends r {
45
- constructor(e, t, n, r = c) {
46
- super(`${e.id}|${t.id}|${n.id}|${r.id}`), this.termType = "Quad", this.subject = e, this.predicate = t, this.object = n, this.graph = r;
84
+ equals(other) {
85
+ return !!other && this.termType === other.termType;
47
86
  }
48
- equals(e) {
49
- return !!e && this.termType === e.termType && this.subject.equals(e.subject) && this.predicate.equals(e.predicate) && this.object.equals(e.object) && this.graph.equals(e.graph);
87
+ };
88
+ var DEFAULTGRAPH = new DefaultGraph();
89
+ var Quad = class extends Term {
90
+ constructor(subject, predicate, object, graph = DEFAULTGRAPH) {
91
+ super(`${subject.id}|${predicate.id}|${object.id}|${graph.id}`);
92
+ this.termType = "Quad";
93
+ this.subject = subject;
94
+ this.predicate = predicate;
95
+ this.object = object;
96
+ this.graph = graph;
97
+ }
98
+ equals(other) {
99
+ return !!other && this.termType === other.termType && this.subject.equals(other.subject) && this.predicate.equals(other.predicate) && this.object.equals(other.object) && this.graph.equals(other.graph);
50
100
  }
51
101
  toJSON() {
52
102
  return {
@@ -69,120 +119,139 @@ var e = {
69
119
  }
70
120
  };
71
121
  }
72
- }, u = {
73
- boolean: "http://www.w3.org/2001/XMLSchema#boolean",
74
- integer: "http://www.w3.org/2001/XMLSchema#integer",
75
- double: "http://www.w3.org/2001/XMLSchema#double",
76
- string: "http://www.w3.org/2001/XMLSchema#string"
77
- }, d = {
78
- namedNode: (e) => new i(e),
79
- blankNode: (e) => new o(e),
80
- literal: (e, t) => {
81
- let n = String(e).replace(/"/g, "\\\"");
82
- if (typeof t == "string") return new a(`"${n}"@${t.toLowerCase()}`);
83
- if (t !== void 0 && !("termType" in t)) {
84
- let e = t.direction ? `--${t.direction.toLowerCase()}` : "";
85
- return new a(`"${n}"@${t.language.toLowerCase()}${e}`);
122
+ };
123
+ var DataFactory = {
124
+ namedNode: (iri) => new NamedNode(iri),
125
+ blankNode: (name) => new BlankNode(name),
126
+ literal: (value, languageOrDataType) => {
127
+ const escapedValue = String(value).replace(/"/g, "\\\"");
128
+ if (typeof languageOrDataType === "string") return new Literal(`"${escapedValue}"@${languageOrDataType.toLowerCase()}`);
129
+ if (languageOrDataType !== void 0 && !("termType" in languageOrDataType)) {
130
+ const direction = languageOrDataType.direction ? `--${languageOrDataType.direction.toLowerCase()}` : "";
131
+ return new Literal(`"${escapedValue}"@${languageOrDataType.language.toLowerCase()}${direction}`);
86
132
  }
87
- let r = t ? t.value : "";
88
- return r === "" && (typeof e == "boolean" ? r = u.boolean : typeof e == "number" && (Number.isFinite(e) ? r = Number.isInteger(e) ? u.integer : u.double : (r = u.double, Number.isNaN(e) || (e = e > 0 ? "INF" : "-INF")))), r === "" || r === u.string ? new a(`"${n}"`) : new a(`"${n}"^^${r}`);
133
+ let datatype = languageOrDataType ? languageOrDataType.value : "";
134
+ if (datatype === "") {
135
+ if (typeof value === "boolean") datatype = XSD_BOOLEAN;
136
+ else if (typeof value === "number") if (Number.isFinite(value)) datatype = Number.isInteger(value) ? XSD_INTEGER : XSD_DOUBLE;
137
+ else {
138
+ datatype = XSD_DOUBLE;
139
+ if (!Number.isNaN(value)) value = value > 0 ? "INF" : "-INF";
140
+ }
141
+ }
142
+ return datatype === "" || datatype === "http://www.w3.org/2001/XMLSchema#string" ? new Literal(`"${escapedValue}"`) : new Literal(`"${escapedValue}"^^${datatype}`);
89
143
  },
90
- variable: (e) => new s(e),
91
- defaultGraph: () => c,
92
- quad: (e, t, n, r) => new l(e, t, n, r),
93
- triple: (e, t, n, r) => new l(e, t, n, r),
94
- fromTerm: (e) => {
95
- if (e instanceof r) return e;
96
- switch (e.termType) {
97
- case "NamedNode": return new i(e.value);
98
- case "BlankNode": return new o(e.value);
99
- case "Variable": return new s(e.value);
100
- case "DefaultGraph": return c;
144
+ variable: (name) => new Variable(name),
145
+ defaultGraph: () => DEFAULTGRAPH,
146
+ quad: (subject, predicate, object, graph) => new Quad(subject, predicate, object, graph),
147
+ triple: (subject, predicate, object, graph) => new Quad(subject, predicate, object, graph),
148
+ fromTerm: (term) => {
149
+ if (term instanceof Term) return term;
150
+ switch (term.termType) {
151
+ case "NamedNode": return new NamedNode(term.value);
152
+ case "BlankNode": return new BlankNode(term.value);
153
+ case "Variable": return new Variable(term.value);
154
+ case "DefaultGraph": return DEFAULTGRAPH;
101
155
  case "Literal":
102
- let t = String(e.value).replace(/"/g, "\\\"");
103
- return e.language ? new a(`"${t}"@${e.language}`) : e.datatype ? new a(`"${t}"^^${e.datatype.value || e.datatype}`) : new a(`"${t}"`);
104
- case "Quad": return d.fromQuad(e);
105
- default: throw Error(`Unexpected termType: ${e.termType}`);
156
+ const escapedValue = String(term.value).replace(/"/g, "\\\"");
157
+ if (term.language) return new Literal(`"${escapedValue}"@${term.language}`);
158
+ else if (term.datatype) return new Literal(`"${escapedValue}"^^${term.datatype.value || term.datatype}`);
159
+ else return new Literal(`"${escapedValue}"`);
160
+ case "Quad": return DataFactory.fromQuad(term);
161
+ default: throw new Error(`Unexpected termType: ${term.termType}`);
106
162
  }
107
163
  },
108
- fromQuad: (e) => {
109
- if (e instanceof l) return e;
110
- if (e.termType !== "Quad") {
111
- if (e.subject && e.predicate && e.object) return new l(d.fromTerm(e.subject), d.fromTerm(e.predicate), d.fromTerm(e.object), d.fromTerm(e.graph || d.defaultGraph()));
112
- throw Error(`Unexpected termType: ${e.termType}`);
164
+ fromQuad: (inQuad) => {
165
+ if (inQuad instanceof Quad) return inQuad;
166
+ if (inQuad.termType !== "Quad") {
167
+ if (inQuad.subject && inQuad.predicate && inQuad.object) return new Quad(DataFactory.fromTerm(inQuad.subject), DataFactory.fromTerm(inQuad.predicate), DataFactory.fromTerm(inQuad.object), DataFactory.fromTerm(inQuad.graph || DataFactory.defaultGraph()));
168
+ throw new Error(`Unexpected termType: ${inQuad.termType}`);
113
169
  }
114
- return new l(d.fromTerm(e.subject), d.fromTerm(e.predicate), d.fromTerm(e.object), d.fromTerm(e.graph));
170
+ return new Quad(DataFactory.fromTerm(inQuad.subject), DataFactory.fromTerm(inQuad.predicate), DataFactory.fromTerm(inQuad.object), DataFactory.fromTerm(inQuad.graph));
115
171
  }
116
172
  };
117
- function f(e, t) {
118
- if (!e || !t || !t.quadIndex) return null;
119
- let n = te(e);
120
- return n && t.quadIndex.get(n) || null;
121
- }
122
- function p(e) {
123
- let t = 5381;
124
- for (let n = 0; n < e.length; n++) t = (t << 5) + t + e.charCodeAt(n);
125
- return Math.abs(t).toString(16).slice(0, 12);
126
- }
127
- var m = /* @__PURE__ */ new Map();
128
- function h(e, n) {
129
- if (e == null) return null;
130
- let r = `${e}|${n["@vocab"] || ""}|${Object.keys(n).filter((e) => e !== "@vocab").sort().map((e) => `${e}:${n[e]}`).join(",")}`;
131
- if (m.has(r)) return m.get(r);
132
- let i = (typeof e == "string" ? e : typeof e == "object" && typeof e.value == "string" ? e.value : String(e)).trim(), a;
133
- if (i.match(t)) a = i;
134
- else if (i.includes(":")) {
135
- let [e, t] = i.split(":", 2);
136
- e && !n[e] && e !== "@vocab" && console.warn(`Undefined prefix "${e}" in IRI "${i}" - treating as literal`), a = n[e] ? n[e] + t : i;
137
- } else a = (n["@vocab"] || "") + i;
138
- return m.set(r, a), a;
139
- }
140
- function g(e, t) {
141
- if (!e || !n.test(e)) return e;
142
- if (t["@vocab"] && e.startsWith(t["@vocab"])) return e.substring(t["@vocab"].length);
143
- for (let [n, r] of Object.entries(t)) if (n !== "@vocab" && e.startsWith(r) && Object.entries(t).filter(([t, n]) => t !== "@vocab" && e.startsWith(n)).every(([e, t]) => r.length >= t.length || e === n && t.length === r.length)) return n + ":" + e.substring(r.length);
144
- return e;
145
- }
146
- var ee = {
173
+ /**
174
+ * Locate the origin entry for a quad using the lean origin system
175
+ *
176
+ * @param {Object} quad - The quad to locate (subject, predicate, object)
177
+ * @param {Object} origin - Origin object containing quadIndex
178
+ * @returns {Object|null} Origin entry or null if not found
179
+ */
180
+ function locate(quad, origin) {
181
+ if (!quad || !origin || !origin.quadIndex) return null;
182
+ const quadKey = quadToKeyForOrigin(quad);
183
+ if (!quadKey) return null;
184
+ return origin.quadIndex.get(quadKey) || null;
185
+ }
186
+ function hash(str) {
187
+ let h = 5381;
188
+ for (let i = 0; i < str.length; i++) h = (h << 5) + h + str.charCodeAt(i);
189
+ return Math.abs(h).toString(16).slice(0, 12);
190
+ }
191
+ var iriCache$1 = /* @__PURE__ */ new Map();
192
+ function expandIRI(term, ctx) {
193
+ if (term == null) return null;
194
+ const cacheKey = `${term}|${ctx["@vocab"] || ""}|${Object.keys(ctx).filter((k) => k !== "@vocab").sort().map((k) => `${k}:${ctx[k]}`).join(",")}`;
195
+ if (iriCache$1.has(cacheKey)) return iriCache$1.get(cacheKey);
196
+ const t = (typeof term === "string" ? term : typeof term === "object" && typeof term.value === "string" ? term.value : String(term)).trim();
197
+ let result;
198
+ if (t.match(URL_REGEX)) result = t;
199
+ else if (t.includes(":")) {
200
+ const [prefix, ref] = t.split(":", 2);
201
+ if (prefix && !ctx[prefix] && prefix !== "@vocab") console.warn(`Undefined prefix "${prefix}" in IRI "${t}" - treating as literal`);
202
+ result = ctx[prefix] ? ctx[prefix] + ref : t;
203
+ } else result = (ctx["@vocab"] || "") + t;
204
+ iriCache$1.set(cacheKey, result);
205
+ return result;
206
+ }
207
+ function shortenIRI(iri, ctx) {
208
+ if (!iri || !VALID_URI_SCHEMES.test(iri)) return iri;
209
+ if (ctx["@vocab"] && iri.startsWith(ctx["@vocab"])) return iri.substring(ctx["@vocab"].length);
210
+ for (const [prefix, namespace] of Object.entries(ctx)) if (prefix !== "@vocab" && iri.startsWith(namespace)) {
211
+ if (Object.entries(ctx).filter(([p, ns]) => p !== "@vocab" && iri.startsWith(ns)).every(([p, ns]) => namespace.length >= ns.length || p === prefix && ns.length === namespace.length)) return prefix + ":" + iri.substring(namespace.length);
212
+ }
213
+ return iri;
214
+ }
215
+ var TOKEN_PATTERNS = {
147
216
  "=#": {
148
217
  kind: "fragment",
149
- extract: (e) => e.substring(2).replace("}", "")
218
+ extract: (t) => t.substring(2).replace("}", "")
150
219
  },
151
220
  "+#": {
152
221
  kind: "softFragment",
153
- extract: (e) => e.substring(2).replace("}", "")
222
+ extract: (t) => t.substring(2).replace("}", "")
154
223
  },
155
224
  "+": {
156
225
  kind: "object",
157
- extract: (e) => e.substring(1)
226
+ extract: (t) => t.substring(1)
158
227
  },
159
228
  "^^": {
160
229
  kind: "datatype",
161
- extract: (e) => e.substring(2)
230
+ extract: (t) => t.substring(2)
162
231
  },
163
232
  "@": {
164
233
  kind: "language",
165
- extract: (e) => e.substring(1)
234
+ extract: (t) => t.substring(1)
166
235
  },
167
236
  ".": {
168
237
  kind: "type",
169
- extract: (e) => e.substring(1)
238
+ extract: (t) => t.substring(1)
170
239
  },
171
240
  "!": {
172
241
  kind: "property",
173
242
  form: "!",
174
- extract: (e) => e.substring(1)
243
+ extract: (t) => t.substring(1)
175
244
  },
176
245
  "?": {
177
246
  kind: "property",
178
247
  form: "?",
179
- extract: (e) => e.substring(1)
248
+ extract: (t) => t.substring(1)
180
249
  }
181
250
  };
182
- function _(e) {
251
+ function parseSemanticBlock(raw) {
183
252
  try {
184
- let t = String(e || "").trim().replace(/^\{|\}$/g, "").trim();
185
- if (!t) return {
253
+ const cleaned = String(raw || "").trim().replace(/^\{|\}$/g, "").trim();
254
+ if (!cleaned) return {
186
255
  subject: null,
187
256
  object: null,
188
257
  types: [],
@@ -191,7 +260,7 @@ function _(e) {
191
260
  language: null,
192
261
  entries: []
193
262
  };
194
- let n = {
263
+ const result = {
195
264
  subject: null,
196
265
  object: null,
197
266
  types: [],
@@ -199,76 +268,133 @@ function _(e) {
199
268
  datatype: null,
200
269
  language: null,
201
270
  entries: []
202
- }, r = /\S+/g, i;
203
- for (; (i = r.exec(t)) !== null;) {
204
- let e = i[0], t = 1 + i.index, r = t + e.length, a = n.entries.length, o = !1;
205
- if (e.startsWith("-") && e.length > 1 && (o = !0, e = e.slice(1)), e === "=") {
206
- o && console.warn("-= is not valid, subject declarations have no polarity"), n.subject = "RESET", n.entries.push({
271
+ };
272
+ const re = /\S+/g;
273
+ let m;
274
+ while ((m = re.exec(cleaned)) !== null) {
275
+ let token = m[0];
276
+ const relStart = 1 + m.index;
277
+ const relEnd = relStart + token.length;
278
+ const entryIndex = result.entries.length;
279
+ let remove = false;
280
+ if (token.startsWith("-") && token.length > 1) {
281
+ remove = true;
282
+ token = token.slice(1);
283
+ }
284
+ if (token === "=") {
285
+ if (remove) console.warn("-= is not valid, subject declarations have no polarity");
286
+ result.subject = "RESET";
287
+ result.entries.push({
207
288
  kind: "subjectReset",
208
289
  relRange: {
209
- start: t,
210
- end: r
290
+ start: relStart,
291
+ end: relEnd
211
292
  },
212
- raw: e
293
+ raw: token
213
294
  });
214
295
  continue;
215
296
  }
216
- if (e.startsWith("=") && !e.startsWith("=#")) {
217
- o && console.warn("-= is not valid, subject declarations have no polarity");
218
- let i = e.substring(1);
219
- n.subject = i, n.entries.push({
297
+ if (token.startsWith("=") && !token.startsWith("=#")) {
298
+ if (remove) console.warn("-= is not valid, subject declarations have no polarity");
299
+ const iri = token.substring(1);
300
+ result.subject = iri;
301
+ result.entries.push({
220
302
  kind: "subject",
221
- iri: i,
303
+ iri,
222
304
  relRange: {
223
- start: t,
224
- end: r
305
+ start: relStart,
306
+ end: relEnd
225
307
  },
226
- raw: e
308
+ raw: token
227
309
  });
228
310
  continue;
229
311
  }
230
- let s = !1;
231
- for (let [c, l] of Object.entries(ee)) if (e.startsWith(c)) {
232
- let c = {
233
- kind: l.kind,
312
+ let processed = false;
313
+ for (const [pattern, config] of Object.entries(TOKEN_PATTERNS)) if (token.startsWith(pattern)) {
314
+ const entry = {
315
+ kind: config.kind,
234
316
  relRange: {
235
- start: t,
236
- end: r
317
+ start: relStart,
318
+ end: relEnd
237
319
  },
238
- raw: i[0]
239
- }, u = l.extract(e);
240
- l.kind === "fragment" ? (n.subject = `=#${u}`, c.fragment = u) : l.kind === "softFragment" ? (n.object = `#${u}`, c.fragment = u) : l.kind === "object" ? (o && (console.warn("-+ is not valid, object declarations have no polarity"), o = !1), n.object = u, c.iri = u) : l.kind === "datatype" ? (o && (console.warn("-^^ is not valid, datatype modifiers have no polarity"), o = !1), n.language || (n.datatype = u), c.datatype = u) : l.kind === "language" ? (o && (console.warn("-@ is not valid, language modifiers have no polarity"), o = !1), n.language = u, n.datatype = null, c.language = u) : l.kind === "type" ? (n.types.push({
241
- iri: u,
242
- entryIndex: a,
243
- remove: o
244
- }), c.iri = u, c.remove = o) : l.kind === "property" && (n.predicates.push({
245
- iri: u,
246
- form: l.form,
247
- entryIndex: a,
248
- remove: o
249
- }), c.iri = u, c.form = l.form, c.remove = o), n.entries.push(c), s = !0;
320
+ raw: m[0]
321
+ };
322
+ const extracted = config.extract(token);
323
+ if (config.kind === "fragment") {
324
+ result.subject = `=#${extracted}`;
325
+ entry.fragment = extracted;
326
+ } else if (config.kind === "softFragment") {
327
+ result.object = `#${extracted}`;
328
+ entry.fragment = extracted;
329
+ } else if (config.kind === "object") {
330
+ if (remove) {
331
+ console.warn("-+ is not valid, object declarations have no polarity");
332
+ remove = false;
333
+ }
334
+ result.object = extracted;
335
+ entry.iri = extracted;
336
+ } else if (config.kind === "datatype") {
337
+ if (remove) {
338
+ console.warn("-^^ is not valid, datatype modifiers have no polarity");
339
+ remove = false;
340
+ }
341
+ if (!result.language) result.datatype = extracted;
342
+ entry.datatype = extracted;
343
+ } else if (config.kind === "language") {
344
+ if (remove) {
345
+ console.warn("-@ is not valid, language modifiers have no polarity");
346
+ remove = false;
347
+ }
348
+ result.language = extracted;
349
+ result.datatype = null;
350
+ entry.language = extracted;
351
+ } else if (config.kind === "type") {
352
+ result.types.push({
353
+ iri: extracted,
354
+ entryIndex,
355
+ remove
356
+ });
357
+ entry.iri = extracted;
358
+ entry.remove = remove;
359
+ } else if (config.kind === "property") {
360
+ result.predicates.push({
361
+ iri: extracted,
362
+ form: config.form,
363
+ entryIndex,
364
+ remove
365
+ });
366
+ entry.iri = extracted;
367
+ entry.form = config.form;
368
+ entry.remove = remove;
369
+ }
370
+ result.entries.push(entry);
371
+ processed = true;
250
372
  break;
251
373
  }
252
- s || (n.predicates.push({
253
- iri: e,
254
- form: "",
255
- entryIndex: a,
256
- remove: o
257
- }), n.entries.push({
258
- kind: "property",
259
- iri: e,
260
- form: "",
261
- relRange: {
262
- start: t,
263
- end: r
264
- },
265
- raw: i[0],
266
- remove: o
267
- }));
374
+ if (!processed) {
375
+ result.predicates.push({
376
+ iri: token,
377
+ form: "",
378
+ entryIndex,
379
+ remove
380
+ });
381
+ result.entries.push({
382
+ kind: "property",
383
+ iri: token,
384
+ form: "",
385
+ relRange: {
386
+ start: relStart,
387
+ end: relEnd
388
+ },
389
+ raw: m[0],
390
+ remove
391
+ });
392
+ }
268
393
  }
269
- return n;
270
- } catch (t) {
271
- return console.error(`Error parsing semantic block ${e}:`, t), {
394
+ return result;
395
+ } catch (error) {
396
+ console.error(`Error parsing semantic block ${raw}:`, error);
397
+ return {
272
398
  subject: null,
273
399
  object: null,
274
400
  types: [],
@@ -279,438 +405,648 @@ function _(e) {
279
405
  };
280
406
  }
281
407
  }
282
- function v(e, t, n) {
283
- let r = n.termType === "Literal" ? JSON.stringify({
408
+ function quadIndexKey(subject, predicate, object) {
409
+ const objKey = object.termType === "Literal" ? JSON.stringify({
284
410
  t: "Literal",
285
- v: n.value,
286
- lang: n.language || "",
287
- dt: n.datatype?.value || ""
411
+ v: object.value,
412
+ lang: object.language || "",
413
+ dt: object.datatype?.value || ""
288
414
  }) : JSON.stringify({
289
- t: n.termType,
290
- v: n.value
415
+ t: object.termType,
416
+ v: object.value
291
417
  });
292
418
  return JSON.stringify([
293
- e.value,
294
- t.value,
295
- r
419
+ subject.value,
420
+ predicate.value,
421
+ objKey
296
422
  ]);
297
423
  }
298
- function te(e) {
299
- return e ? v(e.subject, e.predicate, e.object) : null;
424
+ function quadToKeyForOrigin(q) {
425
+ return q ? quadIndexKey(q.subject, q.predicate, q.object) : null;
300
426
  }
301
- function ne(e, t, n, r, i) {
302
- return t ? i.literal(e, i.namedNode(h(t, r))) : n ? i.literal(e, n) : i.literal(e);
427
+ function createLiteral(value, datatype, language, context, dataFactory) {
428
+ if (datatype) return dataFactory.literal(value, dataFactory.namedNode(expandIRI(datatype, context)));
429
+ if (language) return dataFactory.literal(value, language);
430
+ return dataFactory.literal(value);
303
431
  }
304
432
  //#endregion
305
433
  //#region src/tokenizers.js
306
- function re(e) {
307
- if (e.length < 3) return null;
308
- let t = e[0];
309
- if (t !== "`" && t !== "~") return null;
310
- let n = 1;
311
- for (; n < e.length && e[n] === t;) n++;
312
- if (n < 3) return null;
313
- let r = e.slice(n).trimStart(), i = r.match(/^([^\s{]+)/), a = i ? i[1] : "", o = r.match(/\{([^}]+)\}/), s = o ? o[1] : null;
434
+ /**
435
+ * Character-based Tokenizers for MDLD
436
+ *
437
+ * Replaces regex patterns with direct character scanning for better performance.
438
+ * Each tokenizer follows the EBNF grammar exactly.
439
+ */
440
+ /**
441
+ * Detect code fence: 3+ backticks or tildes at line start
442
+ * EBNF: backticks = "`", "`", "`", { "`" } | tildes = "~", "~", "~", { "~" }
443
+ */
444
+ function detectFence(line) {
445
+ if (line.length < 3) return null;
446
+ const char = line[0];
447
+ if (char !== "`" && char !== "~") return null;
448
+ let count = 1;
449
+ while (count < line.length && line[count] === char) count++;
450
+ if (count < 3) return null;
451
+ const infoString = line.slice(count).trimStart();
452
+ const langMatch = infoString.match(/^([^\s{]+)/);
453
+ const lang = langMatch ? langMatch[1] : "";
454
+ const attrsMatch = infoString.match(/\{([^}]+)\}/);
455
+ const attrs = attrsMatch ? attrsMatch[1] : null;
314
456
  return {
315
- fenceChar: t,
316
- fenceLength: n,
317
- lang: a,
318
- attrs: s,
319
- infoString: r
457
+ fenceChar: char,
458
+ fenceLength: count,
459
+ lang,
460
+ attrs,
461
+ infoString
320
462
  };
321
463
  }
322
- function ie(e) {
323
- if (e[0] !== "[") return null;
324
- let t = e.indexOf("]", 1);
325
- if (t === -1) return null;
326
- let n = e.slice(1, t).trim();
327
- if (!n) return null;
328
- let r = t + 1;
329
- for (; r < e.length && (e[r] === " " || e[r] === " ");) r++;
330
- if (r >= e.length || e[r] !== "<") return null;
331
- let i = e.indexOf(">", r + 1);
332
- if (i === -1) return null;
333
- let a = e.slice(r + 1, i).trim();
334
- return a ? {
335
- prefix: n,
336
- iri: a
337
- } : null;
338
- }
339
- function ae(e) {
340
- if (e[0] !== "#") return null;
341
- let t = 1;
342
- for (; t < e.length && t < 6 && e[t] === "#";) t++;
343
- if (t >= e.length || e[t] !== " " && e[t] !== " ") return null;
344
- let n = t;
345
- for (; n < e.length && (e[n] === " " || e[n] === " ");) n++;
346
- let r = e.slice(n), i = r.match(/\s*\{([^}]+)\}\s*$/), a = r, o = null;
347
- return i && (o = i[1], a = r.slice(0, -i[0].length).trim()), {
348
- depth: t,
349
- content: a,
350
- attrs: o
464
+ /**
465
+ * Detect prefix declaration: [prefix] <IRI>
466
+ * EBNF: contextDecl = "[", contextKey, "]", whitespace, "<", contextIri, ">"
467
+ */
468
+ function detectPrefix(line) {
469
+ if (line[0] !== "[") return null;
470
+ const closeBracket = line.indexOf("]", 1);
471
+ if (closeBracket === -1) return null;
472
+ const prefix = line.slice(1, closeBracket).trim();
473
+ if (!prefix) return null;
474
+ let pos = closeBracket + 1;
475
+ while (pos < line.length && (line[pos] === " " || line[pos] === " ")) pos++;
476
+ if (pos >= line.length || line[pos] !== "<") return null;
477
+ const closeAngle = line.indexOf(">", pos + 1);
478
+ if (closeAngle === -1) return null;
479
+ const iri = line.slice(pos + 1, closeAngle).trim();
480
+ if (!iri) return null;
481
+ return {
482
+ prefix,
483
+ iri
351
484
  };
352
485
  }
353
- function y(e) {
354
- let t = 0;
355
- for (; t < e.length && (e[t] === " " || e[t] === " ");) t++;
356
- let n = t;
357
- if (t >= e.length) return null;
358
- let r = e[t], i, a = t + 1;
359
- if (r === "-" || r === "*" || r === "+") i = r;
360
- else if (r >= "0" && r <= "9") {
361
- let n = t + 1;
362
- for (; n < e.length && e[n] >= "0" && e[n] <= "9";) n++;
363
- if (n >= e.length || e[n] !== ".") return null;
364
- i = e.slice(t, n + 1), a = n + 1;
486
+ /**
487
+ * Detect heading: 1-6 # characters followed by space and text
488
+ * EBNF: heading = "#", { "#" }, whitespace, text
489
+ */
490
+ function detectHeading(line) {
491
+ if (line[0] !== "#") return null;
492
+ let depth = 1;
493
+ while (depth < line.length && depth < 6 && line[depth] === "#") depth++;
494
+ if (depth >= line.length || line[depth] !== " " && line[depth] !== " ") return null;
495
+ let contentStart = depth;
496
+ while (contentStart < line.length && (line[contentStart] === " " || line[contentStart] === " ")) contentStart++;
497
+ const trimmed = line.slice(contentStart);
498
+ const attrsMatch = trimmed.match(/\s*\{([^}]+)\}\s*$/);
499
+ let content = trimmed;
500
+ let attrs = null;
501
+ if (attrsMatch) {
502
+ attrs = attrsMatch[1];
503
+ content = trimmed.slice(0, -attrsMatch[0].length).trim();
504
+ }
505
+ return {
506
+ depth,
507
+ content,
508
+ attrs
509
+ };
510
+ }
511
+ /**
512
+ * Detect list item: -, *, +, or digits followed by .
513
+ * EBNF: listMarker = "-" | "*" | "+" | digit, { digit }, "."
514
+ */
515
+ function detectList(line) {
516
+ let pos = 0;
517
+ while (pos < line.length && (line[pos] === " " || line[pos] === " ")) pos++;
518
+ const indent = pos;
519
+ if (pos >= line.length) return null;
520
+ const char = line[pos];
521
+ let marker;
522
+ let contentStart = pos + 1;
523
+ if (char === "-" || char === "*" || char === "+") marker = char;
524
+ else if (char >= "0" && char <= "9") {
525
+ let numEnd = pos + 1;
526
+ while (numEnd < line.length && line[numEnd] >= "0" && line[numEnd] <= "9") numEnd++;
527
+ if (numEnd >= line.length || line[numEnd] !== ".") return null;
528
+ marker = line.slice(pos, numEnd + 1);
529
+ contentStart = numEnd + 1;
365
530
  } else return null;
366
- if (a >= e.length || e[a] !== " " && e[a] !== " ") return null;
367
- for (; a < e.length && (e[a] === " " || e[a] === " ");) a++;
368
- let o = e.slice(a), s = null, c = o.match(/\s*\{([^}]+)\}\s*$/);
369
- return c && (s = c[1], o = o.slice(0, -c[0].length).trim()), {
370
- indent: n,
371
- marker: i,
372
- content: o,
373
- attrs: s
531
+ if (contentStart >= line.length || line[contentStart] !== " " && line[contentStart] !== " ") return null;
532
+ while (contentStart < line.length && (line[contentStart] === " " || line[contentStart] === " ")) contentStart++;
533
+ let content = line.slice(contentStart);
534
+ let attrs = null;
535
+ const attrsMatch = content.match(/\s*\{([^}]+)\}\s*$/);
536
+ if (attrsMatch) {
537
+ attrs = attrsMatch[1];
538
+ content = content.slice(0, -attrsMatch[0].length).trim();
539
+ }
540
+ return {
541
+ indent,
542
+ marker,
543
+ content,
544
+ attrs
545
+ };
546
+ }
547
+ /**
548
+ * Detect blockquote: > followed by space and text
549
+ * EBNF: blockquote = ">", whitespace, text
550
+ */
551
+ function detectBlockquote(line) {
552
+ if (line[0] !== ">") return null;
553
+ if (line.length > 1 && line[1] !== " " && line[1] !== " ") return null;
554
+ let contentStart = 1;
555
+ while (contentStart < line.length && (line[contentStart] === " " || line[contentStart] === " ")) contentStart++;
556
+ let content = line.slice(contentStart);
557
+ let attrs = null;
558
+ const attrsMatch = content.match(/\s*\{([^}]+)\}\s*$/);
559
+ if (attrsMatch) {
560
+ attrs = attrsMatch[1];
561
+ content = content.slice(0, -attrsMatch[0].length).trim();
562
+ }
563
+ return {
564
+ content,
565
+ attrs
374
566
  };
375
567
  }
376
- function oe(e) {
377
- if (e[0] !== ">" || e.length > 1 && e[1] !== " " && e[1] !== " ") return null;
378
- let t = 1;
379
- for (; t < e.length && (e[t] === " " || e[t] === " ");) t++;
380
- let n = e.slice(t), r = null, i = n.match(/\s*\{([^}]+)\}\s*$/);
381
- return i && (r = i[1], n = n.slice(0, -i[0].length).trim()), {
382
- content: n,
383
- attrs: r
568
+ /**
569
+ * Detect standalone subject: {=...} with optional whitespace
570
+ * EBNF: standaloneSubject = whitespace*, "{", "=", ( iriRef | "#", fragment ), "}", whitespace*
571
+ */
572
+ function detectStandaloneSubject(line) {
573
+ let pos = 0;
574
+ while (pos < line.length && (line[pos] === " " || line[pos] === " ")) pos++;
575
+ if (pos >= line.length || line[pos] !== "{") return null;
576
+ pos++;
577
+ if (pos >= line.length || line[pos] !== "=") return null;
578
+ pos++;
579
+ const contentStart = pos;
580
+ let braceCount = 1;
581
+ while (pos < line.length && braceCount > 0) {
582
+ if (line[pos] === "{") braceCount++;
583
+ if (line[pos] === "}") braceCount--;
584
+ if (braceCount > 0) pos++;
585
+ }
586
+ if (braceCount > 0) return null;
587
+ const content = line.slice(contentStart, pos).trim();
588
+ pos++;
589
+ while (pos < line.length && (line[pos] === " " || line[pos] === " ")) pos++;
590
+ if (pos < line.length) return null;
591
+ return { content };
592
+ }
593
+ /**
594
+ * Find matching closing bracket, accounting for nesting
595
+ */
596
+ function findMatchingBracket(text, startPos, openChar = "[", closeChar = "]") {
597
+ let depth = 1;
598
+ let pos = startPos + 1;
599
+ while (pos < text.length && depth > 0) {
600
+ if (text[pos] === openChar) depth++;
601
+ if (text[pos] === closeChar) depth--;
602
+ if (depth > 0) pos++;
603
+ }
604
+ return depth === 0 ? pos : null;
605
+ }
606
+ /**
607
+ * Extract attributes block after a position: {...}
608
+ */
609
+ function extractAttributes(text, startPos) {
610
+ let pos = startPos;
611
+ while (pos < text.length && (text[pos] === " " || text[pos] === " ")) pos++;
612
+ if (pos >= text.length || text[pos] !== "{") return null;
613
+ const closeBrace = text.indexOf("}", pos + 1);
614
+ if (closeBrace === -1) return null;
615
+ return {
616
+ attrs: text.slice(pos + 1, closeBrace),
617
+ endPos: closeBrace + 1
384
618
  };
385
619
  }
386
- function se(e) {
387
- let t = 0;
388
- for (; t < e.length && (e[t] === " " || e[t] === " ");) t++;
389
- if (t >= e.length || e[t] !== "{" || (t++, t >= e.length || e[t] !== "=")) return null;
390
- t++;
391
- let n = t, r = 1;
392
- for (; t < e.length && r > 0;) e[t] === "{" && r++, e[t] === "}" && r--, r > 0 && t++;
393
- if (r > 0) return null;
394
- let i = e.slice(n, t).trim();
395
- for (t++; t < e.length && (e[t] === " " || e[t] === " ");) t++;
396
- return t < e.length ? null : { content: i };
397
- }
398
- function ce(e, t, n = "[", r = "]") {
399
- let i = 1, a = t + 1;
400
- for (; a < e.length && i > 0;) e[a] === n && i++, e[a] === r && i--, i > 0 && a++;
401
- return i === 0 ? a : null;
402
- }
403
- function b(e, t) {
404
- let n = t;
405
- for (; n < e.length && (e[n] === " " || e[n] === " ");) n++;
406
- if (n >= e.length || e[n] !== "{") return null;
407
- let r = e.indexOf("}", n + 1);
408
- return r === -1 ? null : {
409
- attrs: e.slice(n + 1, r),
410
- endPos: r + 1
620
+ /**
621
+ * Detect URL in angle brackets: <URL>
622
+ * Returns null if not a valid URL per EBNF scheme rules
623
+ */
624
+ function detectAngleBracketUrl(text, startPos) {
625
+ if (text[startPos] !== "<") return null;
626
+ const closeAngle = text.indexOf(">", startPos + 1);
627
+ if (closeAngle === -1) return null;
628
+ const url = text.slice(startPos + 1, closeAngle).trim();
629
+ if (!url.match(/^[a-zA-Z][a-zA-Z0-9+\-.]*:/)) return null;
630
+ return {
631
+ url,
632
+ endPos: closeAngle + 1,
633
+ contentStart: startPos + 1,
634
+ contentEnd: closeAngle
411
635
  };
412
636
  }
413
- function le(e, t) {
414
- if (e[t] !== "<") return null;
415
- let n = e.indexOf(">", t + 1);
416
- if (n === -1) return null;
417
- let r = e.slice(t + 1, n).trim();
418
- return r.match(/^[a-zA-Z][a-zA-Z0-9+\-.]*:/) ? {
419
- url: r,
420
- endPos: n + 1,
421
- contentStart: t + 1,
422
- contentEnd: n
423
- } : null;
424
- }
425
- function ue(e, t) {
426
- let n = e[t];
427
- if (n !== "*" && n !== "_") return null;
428
- let r = 1;
429
- for (; t + r < e.length && e[t + r] === n;) r++;
430
- if (r > 2) return null;
431
- let i = r === 1 ? "emphasis" : "strong", a = n.repeat(r), o = t + r, s = o;
432
- for (; s < e.length;) {
433
- if (e.slice(s, s + r) === a) {
434
- if (s + r < e.length && e[s + r] === n) {
435
- s++;
637
+ /**
638
+ * Detect emphasis/strong spans: *text* or _text_
639
+ * EBNF: emphasisSpan = "*", text, "*" | "_", text, "_"
640
+ * strongSpan = "**", text, "**" | "__", text, "__"
641
+ */
642
+ function detectEmphasis(text, startPos) {
643
+ const char = text[startPos];
644
+ if (char !== "*" && char !== "_") return null;
645
+ let delimCount = 1;
646
+ while (startPos + delimCount < text.length && text[startPos + delimCount] === char) delimCount++;
647
+ if (delimCount > 2) return null;
648
+ const type = delimCount === 1 ? "emphasis" : "strong";
649
+ const closer = char.repeat(delimCount);
650
+ const contentStart = startPos + delimCount;
651
+ let pos = contentStart;
652
+ while (pos < text.length) {
653
+ if (text.slice(pos, pos + delimCount) === closer) {
654
+ if (pos + delimCount < text.length && text[pos + delimCount] === char) {
655
+ pos++;
436
656
  continue;
437
657
  }
438
- let t = e.slice(o, s), a = s + r, c = b(e, a), l = c ? c.endPos : a;
658
+ const content = text.slice(contentStart, pos);
659
+ const endPos = pos + delimCount;
660
+ const attrsResult = extractAttributes(text, endPos);
661
+ const finalPos = attrsResult ? attrsResult.endPos : endPos;
439
662
  return {
440
- type: i,
441
- content: t,
442
- attrs: c?.attrs || null,
443
- endPos: l,
444
- contentStart: o,
445
- contentEnd: s
663
+ type,
664
+ content,
665
+ attrs: attrsResult?.attrs || null,
666
+ endPos: finalPos,
667
+ contentStart,
668
+ contentEnd: pos
446
669
  };
447
670
  }
448
- s++;
671
+ pos++;
449
672
  }
450
673
  return null;
451
674
  }
452
- function de(e, t) {
453
- if (e[t] !== "`") return null;
454
- let n = 1;
455
- for (; t + n < e.length && e[t + n] === "`";) n++;
456
- if (n > 2) return null;
457
- let r = "`".repeat(n), i = t + n, a = i;
458
- for (; a < e.length;) {
459
- if (e.slice(a, a + n) === r) {
460
- let t = e.slice(i, a), r = a + n, o = b(e, r), s = o ? o.endPos : r;
675
+ /**
676
+ * Detect code span: `text` or ``text``
677
+ * EBNF: codeSpan = "`", text, "`" | "``", text, "``"
678
+ */
679
+ function detectCodeSpan(text, startPos) {
680
+ if (text[startPos] !== "`") return null;
681
+ let backtickCount = 1;
682
+ while (startPos + backtickCount < text.length && text[startPos + backtickCount] === "`") backtickCount++;
683
+ if (backtickCount > 2) return null;
684
+ const opener = "`".repeat(backtickCount);
685
+ const contentStart = startPos + backtickCount;
686
+ let pos = contentStart;
687
+ while (pos < text.length) {
688
+ if (text.slice(pos, pos + backtickCount) === opener) {
689
+ const content = text.slice(contentStart, pos);
690
+ const endPos = pos + backtickCount;
691
+ const attrsResult = extractAttributes(text, endPos);
692
+ const finalPos = attrsResult ? attrsResult.endPos : endPos;
461
693
  return {
462
694
  type: "code",
463
- content: t,
464
- attrs: o?.attrs || null,
465
- endPos: s,
466
- contentStart: i,
467
- contentEnd: a
695
+ content,
696
+ attrs: attrsResult?.attrs || null,
697
+ endPos: finalPos,
698
+ contentStart,
699
+ contentEnd: pos
468
700
  };
469
701
  }
470
- a++;
702
+ pos++;
471
703
  }
472
704
  return null;
473
705
  }
474
- function fe(e, t) {
475
- if (e[t] !== "[") return null;
476
- let n = ce(e, t, "[", "]");
477
- if (!n) return null;
478
- let r = e.slice(t + 1, n), i = n + 1, a = null;
479
- if (i < e.length && e[i] === "(") {
480
- let t = e.indexOf(")", i + 1);
481
- t !== -1 && (a = e.slice(i + 1, t), i = t + 1);
482
- } else if (i < e.length && e[i] === "<") {
483
- let t = e.indexOf(">", i + 1);
484
- if (t !== -1) {
485
- let n = e.slice(i + 1, t).trim();
486
- n.match(/^[a-zA-Z][a-zA-Z0-9+\-.]*:/) && (a = n, i = t + 1);
706
+ /**
707
+ * Detect bracket link: [text](url) or [text]{...} or [text] alone
708
+ * EBNF: linkSpan = "[", text, "](", text, ")" | "[", text, "]"
709
+ */
710
+ function detectBracketLink(text, startPos) {
711
+ if (text[startPos] !== "[") return null;
712
+ const bracketEnd = findMatchingBracket(text, startPos, "[", "]");
713
+ if (!bracketEnd) return null;
714
+ const linkText = text.slice(startPos + 1, bracketEnd);
715
+ let pos = bracketEnd + 1;
716
+ let url = null;
717
+ if (pos < text.length && text[pos] === "(") {
718
+ const parenEnd = text.indexOf(")", pos + 1);
719
+ if (parenEnd !== -1) {
720
+ url = text.slice(pos + 1, parenEnd);
721
+ pos = parenEnd + 1;
722
+ }
723
+ } else if (pos < text.length && text[pos] === "<") {
724
+ const closeAngle = text.indexOf(">", pos + 1);
725
+ if (closeAngle !== -1) {
726
+ const angleUrl = text.slice(pos + 1, closeAngle).trim();
727
+ if (angleUrl.match(/^[a-zA-Z][a-zA-Z0-9+\-.]*:/)) {
728
+ url = angleUrl;
729
+ pos = closeAngle + 1;
730
+ }
487
731
  }
488
732
  }
489
- let o = b(e, i), s = o ? o.endPos : i;
733
+ const attrsResult = extractAttributes(text, pos);
734
+ const finalPos = attrsResult ? attrsResult.endPos : pos;
490
735
  return {
491
- type: a ? "link" : "span",
492
- text: r,
493
- url: a,
494
- attrs: o?.attrs || null,
495
- endPos: s,
496
- contentStart: t + 1,
497
- contentEnd: n
736
+ type: url ? "link" : "span",
737
+ text: linkText,
738
+ url,
739
+ attrs: attrsResult?.attrs || null,
740
+ endPos: finalPos,
741
+ contentStart: startPos + 1,
742
+ contentEnd: bracketEnd
498
743
  };
499
744
  }
500
- function x(e, t = 0) {
501
- let n = [], r = e.length, i = 0;
502
- for (; i < r;) {
503
- let r = e[i], a = null;
504
- switch (r) {
745
+ /**
746
+ * Scan text for all inline carriers using character-based detection
747
+ * Memory-optimized version - minimizes object allocations
748
+ */
749
+ function scanInlineCarriers(text, baseOffset = 0) {
750
+ const carriers = [];
751
+ const len = text.length;
752
+ let pos = 0;
753
+ while (pos < len) {
754
+ const char = text[pos];
755
+ let detected = null;
756
+ switch (char) {
505
757
  case "<":
506
- if (a = le(e, i), a) {
507
- let t = b(e, a.endPos);
508
- t && (a.attrs = t.attrs, a.endPos = t.endPos), a.type = "link", a.text = a.url;
758
+ detected = detectAngleBracketUrl(text, pos);
759
+ if (detected) {
760
+ const attrsResult = extractAttributes(text, detected.endPos);
761
+ if (attrsResult) {
762
+ detected.attrs = attrsResult.attrs;
763
+ detected.endPos = attrsResult.endPos;
764
+ }
765
+ detected.type = "link";
766
+ detected.text = detected.url;
509
767
  }
510
768
  break;
511
769
  case "[":
512
- a = fe(e, i);
770
+ detected = detectBracketLink(text, pos);
513
771
  break;
514
772
  case "*":
515
773
  case "_":
516
- a = ue(e, i);
774
+ detected = detectEmphasis(text, pos);
517
775
  break;
518
776
  case "`":
519
- a = de(e, i);
777
+ detected = detectCodeSpan(text, pos);
520
778
  break;
521
779
  }
522
- if (!a) {
523
- i++;
780
+ if (!detected) {
781
+ pos++;
524
782
  continue;
525
783
  }
526
- let o = a.url, s = a.type, c = a.attrs;
527
- if (o?.startsWith("=") || s === "link" && !c && !o) {
528
- i = a.endPos;
784
+ const url = detected.url;
785
+ const type = detected.type;
786
+ const attrs = detected.attrs;
787
+ if (url?.startsWith("=") || type === "link" && !attrs && !url) {
788
+ pos = detected.endPos;
529
789
  continue;
530
790
  }
531
- let l = t + i, u = t + a.endPos, d = t + a.contentEnd, f = [t + a.contentStart, t + a.contentEnd], p = {
532
- type: s,
533
- text: a.content === void 0 ? a.text === void 0 ? o : a.text : a.content,
534
- range: [l, u],
535
- valueRange: f,
536
- attrs: c,
537
- url: o,
538
- pos: a.endPos
791
+ const absStart = baseOffset + pos;
792
+ const absEnd = baseOffset + detected.endPos;
793
+ const absContentEnd = baseOffset + detected.contentEnd;
794
+ const valueRange = [baseOffset + detected.contentStart, baseOffset + detected.contentEnd];
795
+ const carrier = {
796
+ type,
797
+ text: detected.content !== void 0 ? detected.content : detected.text !== void 0 ? detected.text : url,
798
+ range: [absStart, absEnd],
799
+ valueRange,
800
+ attrs,
801
+ url,
802
+ pos: detected.endPos
539
803
  };
540
- c && (p.attrsRange = [d, u]), n.push(p), i = a.endPos;
804
+ if (attrs) carrier.attrsRange = [absContentEnd, absEnd];
805
+ carriers.push(carrier);
806
+ pos = detected.endPos;
541
807
  }
542
- return n;
808
+ return carriers;
543
809
  }
544
810
  //#endregion
545
811
  //#region src/shared.js
546
- var S = /* @__PURE__ */ new Map();
547
- function pe(e) {
548
- return S.has(e) || S.set(e, RegExp(`^(${e}{3,})`)), S.get(e);
812
+ var FENCE_CLOSE_PATTERNS = /* @__PURE__ */ new Map();
813
+ function getFenceClosePattern(fenceChar) {
814
+ if (!FENCE_CLOSE_PATTERNS.has(fenceChar)) FENCE_CLOSE_PATTERNS.set(fenceChar, new RegExp(`^(${fenceChar}{3,})`));
815
+ return FENCE_CLOSE_PATTERNS.get(fenceChar);
549
816
  }
550
- function C(e, t, n, r, i) {
551
- let a = r + (r < e.length && e[r] === " " ? 1 : e.slice(r).match(/^\s+/)?.[0]?.length || 0);
817
+ function calcRangeInfo(line, attrs, lineStart, prefixLength, valueLength) {
818
+ const valueStartInLine = prefixLength + (prefixLength < line.length && line[prefixLength] === " " ? 1 : line.slice(prefixLength).match(/^\s+/)?.[0]?.length || 0);
552
819
  return {
553
- valueRange: [n + a, n + a + i],
554
- attrsRange: w(e, t, n)
820
+ valueRange: [lineStart + valueStartInLine, lineStart + valueStartInLine + valueLength],
821
+ attrsRange: calcAttrsRange(line, attrs, lineStart)
555
822
  };
556
823
  }
557
- function w(e, t, n) {
558
- if (!t) return null;
559
- let r = e.lastIndexOf(t);
560
- return r >= 0 ? [n + r, n + r + t.length] : null;
561
- }
562
- function T(e, t, n, r = null, i = null, a = null, o = {}) {
563
- let s = {
564
- type: e,
565
- range: t,
566
- text: n,
567
- attrs: r,
568
- attrsRange: i,
569
- valueRange: a,
570
- ...o
824
+ function calcAttrsRange(line, attrs, lineStart) {
825
+ if (!attrs) return null;
826
+ const attrsStartInLine = line.lastIndexOf(attrs);
827
+ return attrsStartInLine >= 0 ? [lineStart + attrsStartInLine, lineStart + attrsStartInLine + attrs.length] : null;
828
+ }
829
+ function createToken(type, range, text, attrs = null, attrsRange = null, valueRange = null, extra = {}) {
830
+ const token = {
831
+ type,
832
+ range,
833
+ text,
834
+ attrs,
835
+ attrsRange,
836
+ valueRange,
837
+ ...extra
571
838
  };
572
- return Object.defineProperty(s, "_carriers", {
573
- enumerable: !1,
574
- writable: !0,
839
+ Object.defineProperty(token, "_carriers", {
840
+ enumerable: false,
841
+ writable: true,
575
842
  value: null
576
- }), s;
843
+ });
844
+ return token;
577
845
  }
578
- function me(e, t, n, r, i) {
579
- let a = i[4] || null, o = C(t, a, n, i[1].length + (i[2] ? i[2].length : 0), i[3].length);
580
- return T(e, [n, r - 1], i[3].trim(), a, o.attrsRange, o.valueRange, { indent: i[1].length });
846
+ function createListToken(type, line, lineStart, pos, match) {
847
+ const attrs = match[4] || null;
848
+ const rangeInfo = calcRangeInfo(line, attrs, lineStart, match[1].length + (match[2] ? match[2].length : 0), match[3].length);
849
+ return createToken(type, [lineStart, pos - 1], match[3].trim(), attrs, rangeInfo.attrsRange, rangeInfo.valueRange, { indent: match[1].length });
581
850
  }
582
- var E = {}, he = Object.freeze({
851
+ var semCache = {};
852
+ var EMPTY_SEM = Object.freeze({
583
853
  predicates: [],
584
854
  types: [],
585
855
  subject: null
586
856
  });
587
- function D(e) {
588
- if (!e) return he;
589
- let t = E[e];
590
- return t || (t = Object.freeze(_(e)), E[e] = t), t;
591
- }
592
- function ge(e, t) {
593
- if (!e.range || !t) return 0;
594
- let n = t.substring(e.range.start, e.range.end).match(/^(\s*)/), r = n ? n[1].length : 0;
595
- return Math.floor(r / 2);
596
- }
597
- function _e(e, t, n = null) {
598
- if (!t || !e) return "";
599
- let r = e.substring(t[0], t[1]);
600
- return n && (r = r.substring(0, n[0] - t[0]) + r.substring(n[1] - t[0])), r.trim();
601
- }
602
- function ve(e) {
603
- if (!e.text) return "";
604
- let t = e.text;
605
- e.attrsRange && (t = t.substring(0, e.attrsRange[0] - (e.range?.[0] || 0)) + t.substring(e.attrsRange[1] - (e.range?.[0] || 0)));
606
- let n = (e._carriers || []).filter((e) => e.attrsRange).map((t) => t.attrsRange.map((t) => t - (e.range?.[0] || 0))).filter(([e, n]) => e >= 0 && n <= t.length).sort((e, t) => t[0] - e[0]);
607
- for (let [e, r] of n) t = t.substring(0, e) + t.substring(r);
608
- switch (e.type) {
609
- case "heading": return t.replace(/^#+\s*/, "").trim();
610
- case "list": return t.replace(/^[-*+]\s*/, "").trim();
611
- case "blockquote": return t.replace(/^>\s*/, "").trim();
612
- default: return t.trim();
613
- }
614
- }
615
- function ye(e, t, n, r = null) {
857
+ function parseSemCached(attrs) {
858
+ if (!attrs) return EMPTY_SEM;
859
+ let sem = semCache[attrs];
860
+ if (!sem) {
861
+ sem = Object.freeze(parseSemanticBlock(attrs));
862
+ semCache[attrs] = sem;
863
+ }
864
+ return sem;
865
+ }
866
+ function extractCleanText(token) {
867
+ if (!token.text) return "";
868
+ let text = token.text;
869
+ if (token.attrsRange) text = text.substring(0, token.attrsRange[0] - (token.range?.[0] || 0)) + text.substring(token.attrsRange[1] - (token.range?.[0] || 0));
870
+ const inlineRanges = (token._carriers || []).filter((carrier) => carrier.attrsRange).map((carrier) => carrier.attrsRange.map((pos) => pos - (token.range?.[0] || 0))).filter(([start, end]) => start >= 0 && end <= text.length).sort((a, b) => b[0] - a[0]);
871
+ for (const [relativeStart, relativeEnd] of inlineRanges) text = text.substring(0, relativeStart) + text.substring(relativeEnd);
872
+ switch (token.type) {
873
+ case "heading": return text.replace(/^#+\s*/, "").trim();
874
+ case "list": return text.replace(/^[-*+]\s*/, "").trim();
875
+ case "blockquote": return text.replace(/^>\s*/, "").trim();
876
+ default: return text.trim();
877
+ }
878
+ }
879
+ function createLeanOriginEntry(block, subject, predicate, meta = null) {
616
880
  return {
617
- blockId: e.id,
618
- range: e.range,
619
- valueRange: e.valueRange || null,
620
- carrierType: e.carrierType,
621
- subject: t.value,
622
- predicate: n.value,
623
- context: e.context,
624
- polarity: r?.remove ? "-" : "+",
625
- value: e.text || ""
881
+ blockId: block.id,
882
+ range: block.range,
883
+ valueRange: block.valueRange || null,
884
+ carrierType: block.carrierType,
885
+ subject: subject.value,
886
+ predicate: predicate.value,
887
+ context: block.context,
888
+ polarity: meta?.remove ? "-" : "+",
889
+ value: block.text || ""
626
890
  };
627
891
  }
628
- function O(e, t, n) {
629
- if (!t) return null;
630
- let r = t.value, i = r.indexOf("#"), a = i > -1 ? r.slice(0, i) : r;
631
- return n.namedNode(a + "#" + e);
892
+ function resolveFragment(fragment, currentSubject, dataFactory) {
893
+ if (!currentSubject) return null;
894
+ const subjectValue = currentSubject.value;
895
+ const hashIndex = subjectValue.indexOf("#");
896
+ const baseIRI = hashIndex > -1 ? subjectValue.slice(0, hashIndex) : subjectValue;
897
+ return dataFactory.namedNode(baseIRI + "#" + fragment);
632
898
  }
633
- function k(e, t) {
634
- return e.subject ? e.subject === "RESET" ? (t.currentSubject = null, null) : e.subject.startsWith("=#") ? O(e.subject.substring(2), t.currentSubject, t.df) : t.df.namedNode(h(e.subject, t.ctx)) : null;
635
- }
636
- function be(e, t) {
637
- return e.object ? e.object.startsWith("#") ? O(e.object.substring(1), t.currentSubject, t.df) : t.df.namedNode(h(e.object, t.ctx)) : null;
899
+ function resolveSubject(sem, state) {
900
+ if (!sem.subject) return null;
901
+ if (sem.subject === "RESET") {
902
+ state.currentSubject = null;
903
+ return null;
904
+ }
905
+ if (sem.subject.startsWith("=#")) return resolveFragment(sem.subject.substring(2), state.currentSubject, state.df);
906
+ return state.df.namedNode(expandIRI(sem.subject, state.ctx));
638
907
  }
639
- function A(e) {
640
- return e ? e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;") : "";
908
+ function resolveObject(sem, state) {
909
+ if (!sem.object) return null;
910
+ if (sem.object.startsWith("#")) return resolveFragment(sem.object.substring(1), state.currentSubject, state.df);
911
+ return state.df.namedNode(expandIRI(sem.object, state.ctx));
641
912
  }
642
- function j(e) {
643
- return e?.termType === "Literal";
913
+ function isLiteral(term) {
914
+ return term?.termType === "Literal";
644
915
  }
645
- function M(e) {
646
- return e?.termType === "NamedNode";
916
+ function isNamedNode(term) {
917
+ return term?.termType === "NamedNode";
647
918
  }
648
- function xe(e) {
649
- return e?.value === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
919
+ function isRdfType(term) {
920
+ return term?.value === RDF_TYPE;
650
921
  }
651
- function N(e, t) {
652
- if (!e) return null;
653
- let n = g(e, t);
654
- return n.includes(":") ? n.split(":")[0] : null;
922
+ function getPrefixFromIRI(iri, context) {
923
+ if (!iri) return null;
924
+ const shortened = shortenIRI(iri, context);
925
+ if (shortened.includes(":")) return shortened.split(":")[0];
926
+ return null;
655
927
  }
656
- function Se(e, t) {
657
- let n = /* @__PURE__ */ new Set();
658
- for (let r of e.values()) for (let e of r) {
659
- let r = N(e.subject.value, t);
660
- r && n.add(r);
661
- let i = N(e.predicate.value, t);
662
- if (i && n.add(i), M(e.object)) {
663
- let r = N(e.object.value, t);
664
- r && n.add(r);
928
+ function collectUsedPrefixes(subjectGroups, context) {
929
+ const usedPrefixes = /* @__PURE__ */ new Set();
930
+ for (const subjectQuads of subjectGroups.values()) for (const quad of subjectQuads) {
931
+ const subjectPrefix = getPrefixFromIRI(quad.subject.value, context);
932
+ if (subjectPrefix) usedPrefixes.add(subjectPrefix);
933
+ const predicatePrefix = getPrefixFromIRI(quad.predicate.value, context);
934
+ if (predicatePrefix) usedPrefixes.add(predicatePrefix);
935
+ if (isNamedNode(quad.object)) {
936
+ const objectPrefix = getPrefixFromIRI(quad.object.value, context);
937
+ if (objectPrefix) usedPrefixes.add(objectPrefix);
665
938
  }
666
- if (e.object.datatype && e.object.datatype.value) {
667
- let r = N(e.object.datatype.value, t);
668
- r && n.add(r);
939
+ if (quad.object.datatype && quad.object.datatype.value) {
940
+ const datatypePrefix = getPrefixFromIRI(quad.object.datatype.value, context);
941
+ if (datatypePrefix) usedPrefixes.add(datatypePrefix);
669
942
  }
670
943
  }
671
- return n;
672
- }
673
- function P(e, t, n, r, i = []) {
674
- let a = r(e, t);
675
- t.currentBlock = a, t.blockStack.push(a.id), i.forEach((n) => n(e, t)), n(e, t, e.type), t.blockStack.pop(), t.currentBlock = t.blockStack.length > 0 ? t.origin.blocks.get(t.blockStack[t.blockStack.length - 1]) : null;
676
- }
677
- function F(e) {
678
- return e.sort((e, t) => e.predicate.value.localeCompare(t.predicate.value));
679
- }
680
- var Ce = (e, t) => `[${e}] <${t}>\n`;
681
- function we(e, t) {
682
- let n = g(e.predicate.value, t);
683
- e.object.language ? n += ` @${e.object.language}` : e.object.datatype.value !== "http://www.w3.org/2001/XMLSchema#string" && (n += ` ^^${g(e.object.datatype.value, t)}`);
684
- let r = e.object.value || e.object, i = typeof r == "string" ? r : String(r), a = e.object.datatype?.value || "";
685
- return i.includes("\n") ? `~~~ {${n}}\n${i}\n~~~\n\n` : a.includes("integer") || a.includes("decimal") || a.includes("double") || a.includes("float") ? `\`${i}\` {${n}}\n` : a.includes("date") || a.includes("time") ? `*${i}* {${n}}\n` : a.includes("boolean") ? `**${i}** {${n}}\n` : `[${i}] {${n}}\n`;
686
- }
687
- var Te = (e, t, n = null) => {
688
- let r = g(e.object.value, t), i = g(e.predicate.value, t);
689
- return `[${n && n.has(e.object.value) ? n.get(e.object.value) : r}] {+${r} ?${i}}\n`;
944
+ return usedPrefixes;
945
+ }
946
+ function processTokenWithBlockTracking(token, state, processAnnotations, createBlockEntry, additionalProcessors = []) {
947
+ const blockEntry = createBlockEntry(token, state);
948
+ state.currentBlock = blockEntry;
949
+ state.blockStack.push(blockEntry.id);
950
+ additionalProcessors.forEach((processor) => processor(token, state));
951
+ processAnnotations(token, state, token.type);
952
+ state.blockStack.pop();
953
+ state.currentBlock = state.blockStack.length > 0 ? state.origin.blocks.get(state.blockStack[state.blockStack.length - 1]) : null;
954
+ }
955
+ function sortQuadsByPredicate(quads) {
956
+ return quads.sort((a, b) => a.predicate.value.localeCompare(b.predicate.value));
957
+ }
958
+ var generatePrefixDeclaration = (prefix, namespace) => `[${prefix}] <${namespace}>\n`;
959
+ function generateLiteralText(quad, context) {
960
+ let annotation = shortenIRI(quad.predicate.value, context);
961
+ if (quad.object.language) annotation += ` @${quad.object.language}`;
962
+ else if (quad.object.datatype.value !== "http://www.w3.org/2001/XMLSchema#string") annotation += ` ^^${shortenIRI(quad.object.datatype.value, context)}`;
963
+ const rawValue = quad.object.value || quad.object;
964
+ const value = typeof rawValue === "string" ? rawValue : String(rawValue);
965
+ const datatype = quad.object.datatype?.value || "";
966
+ if (value.includes("\n")) return `~~~ {${annotation}}\n${value}\n~~~\n\n`;
967
+ if (datatype.includes("integer") || datatype.includes("decimal") || datatype.includes("double") || datatype.includes("float")) return `\`${value}\` {${annotation}}\n`;
968
+ if (datatype.includes("date") || datatype.includes("time")) return `*${value}* {${annotation}}\n`;
969
+ if (datatype.includes("boolean")) return `**${value}** {${annotation}}\n`;
970
+ return `[${value}] {${annotation}}\n`;
971
+ }
972
+ var generateObjectText = (quad, context, labelLookup = null, filteredGroups = null, renderedQuads = null, compactInline = true, compactStats = null) => {
973
+ const objShort = shortenIRI(quad.object.value, context);
974
+ const predShort = shortenIRI(quad.predicate.value, context);
975
+ const displayText = labelLookup && labelLookup.has(quad.object.value) ? labelLookup.get(quad.object.value) : objShort;
976
+ let inlineAnnotation = "";
977
+ if (compactInline && filteredGroups && labelLookup && renderedQuads) {
978
+ const filtered = filteredGroups.get(quad.object.value);
979
+ if (filtered) {
980
+ const { types } = filtered;
981
+ const hasLabel = labelLookup.has(quad.object.value);
982
+ if (!(types.some((t) => renderedQuads.has(t)) || hasLabel && types.some((t) => t.predicate.value === "http://www.w3.org/2000/01/rdf-schema#label" && renderedQuads.has(t)))) {
983
+ const typeAnnotations = types.length > 0 ? types.map((t) => "." + shortenIRI(t.object.value, context)).sort().join(" ") : "";
984
+ const labelAnnotation = hasLabel ? "label" : "";
985
+ if (typeAnnotations || labelAnnotation) {
986
+ inlineAnnotation = " " + [typeAnnotations, labelAnnotation].filter(Boolean).join(" ");
987
+ if (compactStats) compactStats.inlineAnnotations++;
988
+ types.forEach((q) => renderedQuads.add(q));
989
+ if (hasLabel) {
990
+ const labelQuad = types.find((q) => q.predicate.value === RDFS_LABEL);
991
+ if (labelQuad) renderedQuads.add(labelQuad);
992
+ }
993
+ }
994
+ }
995
+ }
996
+ }
997
+ return `[${displayText}] {+${objShort} ?${predShort}${inlineAnnotation}}\n`;
690
998
  };
691
- function Ee(e) {
692
- let t = [], n = [], r = [];
693
- for (let i of e) xe(i.predicate) ? t.push(i) : j(i.object) ? n.push(i) : M(i.object) && r.push(i);
999
+ function filterQuadsByType(subjectQuads) {
1000
+ const types = [], literals = [], objects = [];
1001
+ for (const q of subjectQuads) if (isRdfType(q.predicate)) types.push(q);
1002
+ else if (isLiteral(q.object)) literals.push(q);
1003
+ else if (isNamedNode(q.object)) objects.push(q);
694
1004
  return {
695
- types: t,
696
- literals: n,
697
- objects: r
1005
+ types,
1006
+ literals,
1007
+ objects
698
1008
  };
699
1009
  }
1010
+ function generateRetractionText(quad, context) {
1011
+ const predShort = shortenIRI(quad.predicate.value, context);
1012
+ let annotation;
1013
+ if (quad.predicate.value === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type") {
1014
+ annotation = `-.${shortenIRI(quad.object.value, context)}`;
1015
+ return `> {${annotation}}\n`;
1016
+ } else if (isNamedNode(quad.object)) {
1017
+ const objShort = shortenIRI(quad.object.value, context);
1018
+ annotation = `-?${predShort}`;
1019
+ return `[${objShort}] {+${objShort} ${annotation}}\n`;
1020
+ } else {
1021
+ annotation = `-${predShort}`;
1022
+ if (quad.object.language) annotation += ` @${quad.object.language}`;
1023
+ else if (quad.object.datatype.value !== "http://www.w3.org/2001/XMLSchema#string") annotation += ` ^^${shortenIRI(quad.object.datatype.value, context)}`;
1024
+ const rawValue = quad.object.value || quad.object;
1025
+ const value = typeof rawValue === "string" ? rawValue : String(rawValue);
1026
+ const datatype = quad.object.datatype?.value || "";
1027
+ if (value.includes("\n")) return `~~~ {${annotation}}\n${value}\n~~~\n`;
1028
+ if (datatype.includes("integer") || datatype.includes("decimal") || datatype.includes("double") || datatype.includes("float")) return `\`${value}\` {${annotation}}\n`;
1029
+ if (datatype.includes("boolean")) return `**${value}** {${annotation}}\n`;
1030
+ return `[${value}] {${annotation}}\n`;
1031
+ }
1032
+ }
700
1033
  //#endregion
701
1034
  //#region src/parse.js
702
- function I(t, n = {}) {
703
- let r = typeof t == "object" && !!t && "text" in t, i = r ? t.text : t, a = r ? {
704
- context: t.context,
705
- dataFactory: t.dataFactory,
706
- graph: t.graph
707
- } : n, o = {
1035
+ function parse(firstArg, secondArg = {}) {
1036
+ const isNamedParams = typeof firstArg === "object" && firstArg !== null && "text" in firstArg;
1037
+ const text = isNamedParams ? firstArg.text : firstArg;
1038
+ const options = isNamedParams ? {
1039
+ context: firstArg.context,
1040
+ dataFactory: firstArg.dataFactory,
1041
+ graph: firstArg.graph
1042
+ } : secondArg;
1043
+ const state = {
708
1044
  ctx: {
709
- ...e,
710
- ...a.context || {}
1045
+ ...DEFAULT_CONTEXT,
1046
+ ...options.context || {}
711
1047
  },
712
- df: a.dataFactory || d,
713
- graph: a.graph ? d.namedNode(a.graph) : d.defaultGraph(),
1048
+ df: options.dataFactory || DataFactory,
1049
+ graph: options.graph ? DataFactory.namedNode(options.graph) : DataFactory.defaultGraph(),
714
1050
  quads: [],
715
1051
  quadBuffer: /* @__PURE__ */ new Map(),
716
1052
  removeSet: /* @__PURE__ */ new Set(),
@@ -729,1068 +1065,1189 @@ function I(t, n = {}) {
729
1065
  statementCandidates: /* @__PURE__ */ new Map(),
730
1066
  currentBlock: null,
731
1067
  blockStack: []
732
- }, s = De(i);
733
- o.tokens = s.tokens;
734
- for (let e = 0; e < o.tokens.length; e++) {
735
- let t = o.tokens[e];
736
- if (o.currentTokenIndex = e, t.type === "prefix") {
737
- let e = t.iri;
738
- if (t.iri.includes(":")) {
739
- let n = t.iri.indexOf(":"), r = t.iri.substring(0, n), i = t.iri.substring(n + 1);
740
- o.ctx[r] && r !== "@vocab" && (e = o.ctx[r] + i);
1068
+ };
1069
+ const scanResult = scanTokens(text);
1070
+ state.tokens = scanResult.tokens;
1071
+ for (let i = 0; i < state.tokens.length; i++) {
1072
+ const token = state.tokens[i];
1073
+ state.currentTokenIndex = i;
1074
+ if (token.type === "prefix") {
1075
+ let resolvedIri = token.iri;
1076
+ if (token.iri.includes(":")) {
1077
+ const colonIndex = token.iri.indexOf(":");
1078
+ const potentialPrefix = token.iri.substring(0, colonIndex);
1079
+ const reference = token.iri.substring(colonIndex + 1);
1080
+ if (state.ctx[potentialPrefix] && potentialPrefix !== "@vocab") resolvedIri = state.ctx[potentialPrefix] + reference;
741
1081
  }
742
- o.ctx[t.prefix] = e;
1082
+ state.ctx[token.prefix] = resolvedIri;
743
1083
  continue;
744
1084
  }
745
- Le[t.type]?.(t, o);
746
- }
747
- let c = /* @__PURE__ */ new Set();
748
- for (let e of o.quads) c.add(v(e.subject, e.predicate, e.object));
749
- let l = [];
750
- for (let e of o.removeSet) {
751
- let t = v(e.subject, e.predicate, e.object);
752
- c.has(t) || l.push(e);
753
- }
754
- let u = {
755
- subject: o.primarySubject,
756
- type: o.primaryType,
757
- label: o.primaryLabel,
758
- comment: o.primaryComment
1085
+ TOKEN_PROCESSORS[token.type]?.(token, state);
1086
+ }
1087
+ const quadKeys = /* @__PURE__ */ new Set();
1088
+ for (const quad of state.quads) quadKeys.add(quadIndexKey(quad.subject, quad.predicate, quad.object));
1089
+ const filteredRemove = [];
1090
+ for (const quad of state.removeSet) {
1091
+ const key = quadIndexKey(quad.subject, quad.predicate, quad.object);
1092
+ if (!quadKeys.has(key)) filteredRemove.push(quad);
1093
+ }
1094
+ const primary = {
1095
+ subject: state.primarySubject,
1096
+ type: state.primaryType,
1097
+ label: state.primaryLabel,
1098
+ comment: state.primaryComment
759
1099
  };
760
1100
  return {
761
- quads: o.quads,
762
- remove: l,
763
- statements: o.statements,
764
- origin: o.origin,
765
- context: o.ctx,
766
- primarySubject: o.primarySubject,
767
- primary: u,
768
- md: s.md
1101
+ quads: state.quads,
1102
+ remove: filteredRemove,
1103
+ statements: state.statements,
1104
+ origin: state.origin,
1105
+ context: state.ctx,
1106
+ primarySubject: state.primarySubject,
1107
+ primary,
1108
+ md: scanResult.md
769
1109
  };
770
1110
  }
771
- function L(e) {
772
- return e.type === "code" ? [] : e._carriers || (e._carriers = Oe(e.text, e.range[0]));
773
- }
774
- function De(e) {
775
- let t = [], n = [], r = e.split("\n"), i = 0, a = null, o = [
1111
+ function getCarriers(token) {
1112
+ if (token.type === "code") return [];
1113
+ return token._carriers || (token._carriers = extractInlineCarriers(token.text, token.range[0]));
1114
+ }
1115
+ function scanTokens(text) {
1116
+ const tokens = [];
1117
+ const mdLines = [];
1118
+ const lines = text.split("\n");
1119
+ let pos = 0;
1120
+ let codeBlock = null;
1121
+ const PROCESSORS = [
776
1122
  {
777
1123
  type: "fence",
778
- test: (e) => re(e.trim()),
779
- process: s
1124
+ test: (line) => detectFence(line.trim()),
1125
+ process: handleFence
780
1126
  },
781
1127
  {
782
1128
  type: "content",
783
- test: () => a,
784
- process: (e) => a.content.push(e)
1129
+ test: () => codeBlock,
1130
+ process: (line) => codeBlock.content.push(line)
785
1131
  },
786
1132
  {
787
1133
  type: "prefix",
788
- test: (e) => ie(e),
789
- process: c
1134
+ test: (line) => detectPrefix(line),
1135
+ process: handlePrefix
790
1136
  },
791
1137
  {
792
1138
  type: "standalone",
793
- test: (e) => se(e),
794
- process: p
1139
+ test: (line) => detectStandaloneSubject(line),
1140
+ process: handleStandaloneSubject
795
1141
  },
796
1142
  {
797
1143
  type: "heading",
798
- test: (e) => ae(e),
799
- process: l
1144
+ test: (line) => detectHeading(line),
1145
+ process: handleHeading
800
1146
  },
801
1147
  {
802
1148
  type: "list",
803
- test: (e) => y(e),
804
- process: u
1149
+ test: (line) => detectList(line),
1150
+ process: handleList
805
1151
  },
806
1152
  {
807
1153
  type: "blockquote",
808
- test: (e) => oe(e),
809
- process: d
1154
+ test: (line) => detectBlockquote(line),
1155
+ process: handleBlockquote
810
1156
  },
811
1157
  {
812
1158
  type: "para",
813
- test: (e) => e.trim(),
814
- process: f
1159
+ test: (line) => line.trim(),
1160
+ process: handlePara
815
1161
  }
816
1162
  ];
817
- function s(e, r, i) {
818
- let o = e.trim();
819
- if (a) {
820
- let i = a.fence[0], s = i.repeat(a.fence.length), c = o.match(pe(i));
821
- if (c && c[1] === s) {
822
- let i = a.valueRangeStart, o = Math.max(i, r - 1);
823
- t.push({
1163
+ function handleFence(line, lineStart, pos) {
1164
+ const trimmedLine = line.trim();
1165
+ if (!codeBlock) {
1166
+ const fenceResult = detectFence(trimmedLine);
1167
+ if (!fenceResult) return false;
1168
+ const attrsText = fenceResult.attrs;
1169
+ const attrsStartInLine = attrsText ? line.indexOf(attrsText) : -1;
1170
+ const contentStart = lineStart + line.length + 1;
1171
+ codeBlock = {
1172
+ fence: fenceResult.fenceChar.repeat(fenceResult.fenceLength),
1173
+ start: lineStart,
1174
+ content: [],
1175
+ lang: fenceResult.lang,
1176
+ attrs: attrsText,
1177
+ attrsRange: attrsText && attrsStartInLine >= 0 ? [lineStart + attrsStartInLine, lineStart + attrsStartInLine + attrsText.length] : null,
1178
+ valueRangeStart: contentStart
1179
+ };
1180
+ const cleanFence = line.replace(/\s*\{[^}]+\}\s*$/, "");
1181
+ mdLines.push(cleanFence);
1182
+ } else {
1183
+ const fenceChar = codeBlock.fence[0];
1184
+ const expectedFence = fenceChar.repeat(codeBlock.fence.length);
1185
+ const fenceMatch = trimmedLine.match(getFenceClosePattern(fenceChar));
1186
+ if (fenceMatch && fenceMatch[1] === expectedFence) {
1187
+ const valueStart = codeBlock.valueRangeStart;
1188
+ const valueEnd = Math.max(valueStart, lineStart - 1);
1189
+ tokens.push({
824
1190
  type: "code",
825
- range: [a.start, r],
826
- text: a.content.join("\n"),
827
- lang: a.lang,
828
- attrs: a.attrs,
829
- attrsRange: a.attrsRange,
830
- valueRange: [i, o]
1191
+ range: [codeBlock.start, lineStart],
1192
+ text: codeBlock.content.join("\n"),
1193
+ lang: codeBlock.lang,
1194
+ attrs: codeBlock.attrs,
1195
+ attrsRange: codeBlock.attrsRange,
1196
+ valueRange: [valueStart, valueEnd]
831
1197
  });
832
- for (let e of a.content) n.push(e);
833
- a = null;
834
- let s = e.replace(/\r?\n.*$/, "");
835
- n.push(s);
1198
+ for (const contentLine of codeBlock.content) mdLines.push(contentLine);
1199
+ codeBlock = null;
1200
+ const closingFence = line.replace(/\r?\n.*$/, "");
1201
+ mdLines.push(closingFence);
836
1202
  }
837
- } else {
838
- let t = re(o);
839
- if (!t) return !1;
840
- let i = t.attrs, s = i ? e.indexOf(i) : -1, c = r + e.length + 1;
841
- a = {
842
- fence: t.fenceChar.repeat(t.fenceLength),
843
- start: r,
844
- content: [],
845
- lang: t.lang,
846
- attrs: i,
847
- attrsRange: i && s >= 0 ? [r + s, r + s + i.length] : null,
848
- valueRangeStart: c
849
- };
850
- let l = e.replace(/\s*\{[^}]+\}\s*$/, "");
851
- n.push(l);
852
1203
  }
853
- return !0;
1204
+ return true;
854
1205
  }
855
- function c(e, n, r) {
856
- let i = ie(e);
857
- return t.push({
1206
+ function handlePrefix(line, lineStart, pos) {
1207
+ const result = detectPrefix(line);
1208
+ tokens.push({
858
1209
  type: "prefix",
859
- prefix: i.prefix,
860
- iri: i.iri
861
- }), !0;
862
- }
863
- function l(e, r, i) {
864
- let a = ae(e), o = a.attrs, s = a.depth, c = C(e, o, r, s, a.content.length);
865
- t.push(T("heading", [r, i - 1], a.content, o, c.attrsRange, c.valueRange, { depth: a.depth }));
866
- let l = `${"#".repeat(a.depth)} ${a.content}`;
867
- return n.push(l), !0;
868
- }
869
- function u(e, r, i) {
870
- let a = y(e), o = " ".repeat(a.indent), s = [
871
- e,
872
- o,
873
- a.marker,
874
- a.content,
875
- a.attrs
1210
+ prefix: result.prefix,
1211
+ iri: result.iri
1212
+ });
1213
+ return true;
1214
+ }
1215
+ function handleHeading(line, lineStart, pos) {
1216
+ const result = detectHeading(line);
1217
+ const attrs = result.attrs;
1218
+ const afterHashes = result.depth;
1219
+ const rangeInfo = calcRangeInfo(line, attrs, lineStart, afterHashes, result.content.length);
1220
+ tokens.push(createToken("heading", [lineStart, pos - 1], result.content, attrs, rangeInfo.attrsRange, rangeInfo.valueRange, { depth: result.depth }));
1221
+ const cleanHeading = `${"#".repeat(result.depth)} ${result.content}`;
1222
+ mdLines.push(cleanHeading);
1223
+ return true;
1224
+ }
1225
+ function handleList(line, lineStart, pos) {
1226
+ const result = detectList(line);
1227
+ const indentStr = " ".repeat(result.indent);
1228
+ const match = [
1229
+ line,
1230
+ indentStr,
1231
+ result.marker,
1232
+ result.content,
1233
+ result.attrs
876
1234
  ];
877
- t.push(me("list", e, r, i, s));
878
- let c = `${o}${a.marker} ${a.content}`;
879
- return n.push(c), !0;
880
- }
881
- function d(e, r, i) {
882
- let a = oe(e), o = a.attrs, s = e.startsWith("> ") ? 2 : e.indexOf(">") + 1, c = s + a.content.length;
883
- t.push(T("blockquote", [r, i - 1], a.content, o, w(e, o, r), [r + s, r + c]));
884
- let l = `> ${a.content}`;
885
- return n.push(l), !0;
886
- }
887
- function f(e, r, i) {
888
- t.push(T("para", [r, i - 1], e.trim()));
889
- let a = e, o = x(a, 0);
890
- for (let e of o) if (e.attrs && (e.type === "emphasis" || e.type === "code")) {
891
- let t = a.substring(0, e.range[0]), n = a.substring(e.range[1]);
892
- a = t + (e.text || "") + n;
1235
+ tokens.push(createListToken("list", line, lineStart, pos, match));
1236
+ const cleanList = `${indentStr}${result.marker} ${result.content}`;
1237
+ mdLines.push(cleanList);
1238
+ return true;
1239
+ }
1240
+ function handleBlockquote(line, lineStart, pos) {
1241
+ const result = detectBlockquote(line);
1242
+ const attrs = result.attrs;
1243
+ const valueStartInLine = line.startsWith("> ") ? 2 : line.indexOf(">") + 1;
1244
+ const valueEndInLine = valueStartInLine + result.content.length;
1245
+ tokens.push(createToken("blockquote", [lineStart, pos - 1], result.content, attrs, calcAttrsRange(line, attrs, lineStart), [lineStart + valueStartInLine, lineStart + valueEndInLine]));
1246
+ const cleanBlockquote = `> ${result.content}`;
1247
+ mdLines.push(cleanBlockquote);
1248
+ return true;
1249
+ }
1250
+ function handlePara(line, lineStart, pos) {
1251
+ tokens.push(createToken("para", [lineStart, pos - 1], line.trim()));
1252
+ let cleanPara = line;
1253
+ const carriers = scanInlineCarriers(cleanPara, 0);
1254
+ for (const carrier of carriers) if (carrier.attrs && (carrier.type === "emphasis" || carrier.type === "code")) {
1255
+ const before = cleanPara.substring(0, carrier.range[0]);
1256
+ const after = cleanPara.substring(carrier.range[1]);
1257
+ cleanPara = before + (carrier.text || "") + after;
893
1258
  }
894
- return a = a.replace(/\[([^\]]+)\]\s*\{[^}]+\}/g, "$1"), a = a.replace(/\s*\{[^}]+\}\s*/g, " "), a = a.replace(/\s+/g, " ").trim(), n.push(a), !0;
895
- }
896
- function p(e, n, r) {
897
- return t.push({
1259
+ cleanPara = cleanPara.replace(/\[([^\]]+)\]\s*\{[^}]+\}/g, "$1");
1260
+ cleanPara = cleanPara.replace(/\s*\{[^}]+\}\s*/g, " ");
1261
+ cleanPara = cleanPara.replace(/\s+/g, " ").trim();
1262
+ mdLines.push(cleanPara);
1263
+ return true;
1264
+ }
1265
+ function handleStandaloneSubject(line, lineStart, pos) {
1266
+ tokens.push({
898
1267
  type: "standalone",
899
- text: e.trim(),
900
- range: [n, r - 1]
901
- }), !0;
1268
+ text: line.trim(),
1269
+ range: [lineStart, pos - 1]
1270
+ });
1271
+ return true;
902
1272
  }
903
- for (let e = 0; e < r.length; e++) {
904
- let t = r[e], n = i;
905
- i += t.length + 1;
906
- for (let e of o) if (e.test(t) && e.process(t, n, i)) break;
1273
+ for (let i = 0; i < lines.length; i++) {
1274
+ const line = lines[i];
1275
+ const lineStart = pos;
1276
+ pos += line.length + 1;
1277
+ for (const processor of PROCESSORS) if (processor.test(line) && processor.process(line, lineStart, pos)) break;
907
1278
  }
908
1279
  return {
909
- tokens: t,
910
- md: n.join("\n")
1280
+ tokens,
1281
+ md: mdLines.join("\n")
911
1282
  };
912
1283
  }
913
- function Oe(e, t = 0) {
914
- return x(e, t);
915
- }
916
- function R(e, t) {
917
- let n = e._blockId || p(`${e.type}:${e.range?.[0]}:${e.range?.[1]}`);
918
- e._blockId = n;
919
- let r = L(e), i = ve(e), a = {
920
- id: n,
921
- type: e.type,
922
- range: e.range,
923
- text: i,
1284
+ function extractInlineCarriers(text, baseOffset = 0) {
1285
+ return scanInlineCarriers(text, baseOffset);
1286
+ }
1287
+ function createBlockEntry(token, state) {
1288
+ const blockId = token._blockId || hash(`${token.type}:${token.range?.[0]}:${token.range?.[1]}`);
1289
+ token._blockId = blockId;
1290
+ const carriers = getCarriers(token);
1291
+ const cleanText = extractCleanText(token);
1292
+ const blockEntry = {
1293
+ id: blockId,
1294
+ type: token.type,
1295
+ range: token.range,
1296
+ text: cleanText,
924
1297
  subject: null,
925
1298
  types: [],
926
1299
  predicates: [],
927
1300
  carriers: [],
928
- listLevel: e.indent || 0,
929
- parentBlockId: t.blockStack.length > 0 ? t.blockStack[t.blockStack.length - 1] : null,
1301
+ listLevel: token.indent || 0,
1302
+ parentBlockId: state.blockStack.length > 0 ? state.blockStack[state.blockStack.length - 1] : null,
930
1303
  quadKeys: []
931
1304
  };
932
- for (let e of r) {
933
- let t = {
934
- type: e.type,
935
- range: e.range,
936
- text: e.text,
1305
+ for (const carrier of carriers) {
1306
+ const carrierInfo = {
1307
+ type: carrier.type,
1308
+ range: carrier.range,
1309
+ text: carrier.text,
937
1310
  subject: null,
938
1311
  predicates: [],
939
1312
  sem: null
940
1313
  };
941
- if (e.attrs) {
942
- let n = D(e.attrs);
943
- t.sem = n, t.predicates = n.predicates || [], t.subject = n.subject, t.types = n.types || [];
1314
+ if (carrier.attrs) {
1315
+ const carrierSem = parseSemCached(carrier.attrs);
1316
+ carrierInfo.sem = carrierSem;
1317
+ carrierInfo.predicates = carrierSem.predicates || [];
1318
+ carrierInfo.subject = carrierSem.subject;
1319
+ carrierInfo.types = carrierSem.types || [];
944
1320
  }
945
- a.carriers.push(t);
946
- }
947
- return t.origin.blocks.set(n, a), t.origin.documentStructure.push(a), a;
948
- }
949
- function ke(e, t, n, r) {
950
- if (t.subject && t.subject !== "RESET") {
951
- let n = k(t, r);
952
- n && (e.subject = n.value);
953
- }
954
- if (t.types && t.types.length > 0 && t.types.forEach((t) => {
955
- let n = h(typeof t == "string" ? t : t.iri, r.ctx);
956
- e.types.includes(n) || e.types.push(n);
957
- }), t.predicates && t.predicates.length > 0 && t.predicates.forEach((t) => {
958
- let n = {
959
- iri: h(t.iri, r.ctx),
960
- form: t.form || "",
1321
+ blockEntry.carriers.push(carrierInfo);
1322
+ }
1323
+ state.origin.blocks.set(blockId, blockEntry);
1324
+ state.origin.documentStructure.push(blockEntry);
1325
+ return blockEntry;
1326
+ }
1327
+ function enrichBlockFromAnnotation(blockEntry, sem, carrier, state) {
1328
+ if (sem.subject && sem.subject !== "RESET") {
1329
+ const resolvedSubject = resolveSubject(sem, state);
1330
+ if (resolvedSubject) blockEntry.subject = resolvedSubject.value;
1331
+ }
1332
+ if (sem.types && sem.types.length > 0) sem.types.forEach((t) => {
1333
+ const expanded = expandIRI(typeof t === "string" ? t : t.iri, state.ctx);
1334
+ if (!blockEntry.types.includes(expanded)) blockEntry.types.push(expanded);
1335
+ });
1336
+ if (sem.predicates && sem.predicates.length > 0) sem.predicates.forEach((pred) => {
1337
+ const expandedPred = {
1338
+ iri: expandIRI(pred.iri, state.ctx),
1339
+ form: pred.form || "",
961
1340
  object: null
962
1341
  };
963
- e.predicates.push(n);
964
- }), n) {
965
- let t = {
966
- type: n.type,
967
- range: n.range,
968
- text: n.text,
1342
+ blockEntry.predicates.push(expandedPred);
1343
+ });
1344
+ if (carrier) {
1345
+ const carrierInfo = {
1346
+ type: carrier.type,
1347
+ range: carrier.range,
1348
+ text: carrier.text,
969
1349
  subject: null,
970
1350
  predicates: []
971
1351
  };
972
- if (n.attrs) {
973
- let e = D(n.attrs);
974
- t.sem = e, t.predicates = e.predicates || [], t.subject = e.subject, t.types = e.types || [];
1352
+ if (carrier.attrs) {
1353
+ const carrierSem = parseSemCached(carrier.attrs);
1354
+ carrierInfo.sem = carrierSem;
1355
+ carrierInfo.predicates = carrierSem.predicates || [];
1356
+ carrierInfo.subject = carrierSem.subject;
1357
+ carrierInfo.types = carrierSem.types || [];
975
1358
  }
976
- e.carriers.push(t);
1359
+ blockEntry.carriers.push(carrierInfo);
977
1360
  }
978
1361
  }
979
- function Ae(e, t, n, r = {}) {
980
- let { preserveGlobalSubject: i = !1, implicitSubject: a = null } = r;
981
- if (t.subject === "RESET") {
982
- n.currentSubject = null;
1362
+ function processAnnotationWithBlockTracking(carrier, sem, state, options = {}) {
1363
+ const { preserveGlobalSubject = false, implicitSubject = null } = options;
1364
+ if (sem.subject === "RESET") {
1365
+ state.currentSubject = null;
983
1366
  return;
984
1367
  }
985
- let o = n.currentSubject, s = k(t, n), c = be(t, n);
986
- s && !n.primarySubject && !t.subject.startsWith("=#") && (n.primarySubject = s.value), s && !i && !a && (n.currentSubject = s);
987
- let l = i ? s || o : a || n.currentSubject;
988
- if (!l) return;
989
- let u = je(l.value, t.types, t.predicates, e.range, e.attrsRange || null, e.valueRange || null, e.type || null, n.ctx, e.text), d = ne(e.text, t.datatype, t.language, n.ctx, n.df), f = e.url ? n.df.namedNode(h(e.url, n.ctx)) : null, p = s || f;
990
- n.currentBlock && ke(n.currentBlock, t, e, n), Pe(t, s, c, f, l, u, n, e), Ie(t, s, o, c, p, l, d, u, n, e);
991
- }
992
- function je(e, t, n, r, i, a, o, s, c) {
993
- let l = {
994
- subject: e,
995
- types: t.map((e) => h(typeof e == "string" ? e : e.iri, s)),
996
- predicates: n.map((e) => ({
997
- iri: h(e.iri, s),
998
- form: e.form
1368
+ const previousSubject = state.currentSubject;
1369
+ const newSubject = resolveSubject(sem, state);
1370
+ const localObject = resolveObject(sem, state);
1371
+ if (newSubject && !state.primarySubject && !sem.subject.startsWith("=#")) state.primarySubject = newSubject.value;
1372
+ if (newSubject && !preserveGlobalSubject && !implicitSubject) state.currentSubject = newSubject;
1373
+ const S = preserveGlobalSubject ? newSubject || previousSubject : implicitSubject || state.currentSubject;
1374
+ if (!S) return;
1375
+ const block = createBlock(S.value, sem.types, sem.predicates, carrier.range, carrier.attrsRange || null, carrier.valueRange || null, carrier.type || null, state.ctx, carrier.text);
1376
+ const L = createLiteral(carrier.text, sem.datatype, sem.language, state.ctx, state.df);
1377
+ const carrierO = carrier.url ? state.df.namedNode(expandIRI(carrier.url, state.ctx)) : null;
1378
+ const newSubjectOrCarrierO = newSubject || carrierO;
1379
+ if (state.currentBlock) enrichBlockFromAnnotation(state.currentBlock, sem, carrier, state);
1380
+ processTypeAnnotations(sem, newSubject, localObject, carrierO, S, block, state, carrier);
1381
+ processPredicateAnnotations(sem, newSubject, previousSubject, localObject, newSubjectOrCarrierO, S, L, block, state, carrier);
1382
+ }
1383
+ function createBlock(subject, types, predicates, range, attrsRange, valueRange, carrierType, ctx, text) {
1384
+ const expanded = {
1385
+ subject,
1386
+ types: types.map((t) => expandIRI(typeof t === "string" ? t : t.iri, ctx)),
1387
+ predicates: predicates.map((p) => ({
1388
+ iri: expandIRI(p.iri, ctx),
1389
+ form: p.form
999
1390
  }))
1000
1391
  };
1001
1392
  return {
1002
- id: p([
1003
- e,
1004
- o || "unknown",
1005
- l.types.join(","),
1006
- l.predicates.map((e) => `${e.form}${e.iri}`).join(",")
1393
+ id: hash([
1394
+ subject,
1395
+ carrierType || "unknown",
1396
+ expanded.types.join(","),
1397
+ expanded.predicates.map((p) => `${p.form}${p.iri}`).join(",")
1007
1398
  ].join("|")),
1008
1399
  range: {
1009
- start: r[0],
1010
- end: r[1]
1400
+ start: range[0],
1401
+ end: range[1]
1011
1402
  },
1012
- valueRange: a ? {
1013
- start: a[0],
1014
- end: a[1]
1403
+ valueRange: valueRange ? {
1404
+ start: valueRange[0],
1405
+ end: valueRange[1]
1015
1406
  } : null,
1016
- carrierType: o || null,
1017
- subject: e,
1018
- types: l.types,
1019
- predicates: l.predicates,
1020
- context: s,
1021
- text: c || ""
1407
+ carrierType: carrierType || null,
1408
+ subject,
1409
+ types: expanded.types,
1410
+ predicates: expanded.predicates,
1411
+ context: ctx,
1412
+ text: text || ""
1022
1413
  };
1023
1414
  }
1024
- function z(e, t, n, r, i, a, o, s, c, l = null, u = null, d = null, f = null) {
1025
- if (!a || !o || !s) return;
1026
- let p = c.quad(a, o, s);
1027
- if (l?.remove) {
1028
- let i = v(p.subject, p.predicate, p.object);
1029
- if (t.has(i)) {
1030
- t.delete(i);
1031
- let n = e.findIndex((e) => e.subject.value === p.subject.value && e.predicate.value === p.predicate.value && e.object.value === p.object.value);
1032
- n !== -1 && e.splice(n, 1), r.delete(i);
1033
- } else n.add(p);
1415
+ function emitQuad(quads, quadBuffer, removeSet, quadIndex, block, subject, predicate, object, dataFactory, meta = null, statements = null, statementCandidates = null, state = null) {
1416
+ if (!subject || !predicate || !object) return;
1417
+ const quad = dataFactory.quad(subject, predicate, object);
1418
+ if (meta?.remove || false) {
1419
+ const quadKey = quadIndexKey(quad.subject, quad.predicate, quad.object);
1420
+ if (quadBuffer.has(quadKey)) {
1421
+ quadBuffer.delete(quadKey);
1422
+ const index = quads.findIndex((q) => q.subject.value === quad.subject.value && q.predicate.value === quad.predicate.value && q.object.value === quad.object.value);
1423
+ if (index !== -1) quads.splice(index, 1);
1424
+ quadIndex.delete(quadKey);
1425
+ } else removeSet.add(quad);
1034
1426
  } else {
1035
- let n = v(p.subject, p.predicate, p.object);
1036
- t.set(n, p), e.push(p), f && (!f.primaryType && o.value === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && (f.primaryType = s.value), !f.primaryLabel && o.value === "http://www.w3.org/2000/01/rdf-schema#label" && s.termType === "Literal" && (f.primaryLabel = s.value), !f.primaryComment && o.value === "http://www.w3.org/2000/01/rdf-schema#comment" && s.termType === "Literal" && (f.primaryComment = s.value)), Me(p, c, l, u, d);
1037
- let m = ye(i, a, o, l);
1038
- r.set(n, m), f.currentBlock && i.id === f.currentBlock.id && (f.currentBlock.quadKeys || (f.currentBlock.quadKeys = []), f.currentBlock.quadKeys.push(n));
1039
- }
1040
- }
1041
- function Me(e, t, n, r = null, i = null) {
1042
- if (!r || !i) return;
1043
- let a = e.predicate.value;
1044
- if (a !== "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && a !== "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject" && a !== "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate" && a !== "http://www.w3.org/1999/02/22-rdf-syntax-ns#object") return;
1045
- if (a === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && e.object.value === "http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement") {
1046
- i.set(e.subject.value, { spo: {} });
1047
- return;
1048
- }
1049
- let o = i.get(e.subject.value);
1050
- if (o && (a === "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject" ? o.spo.subject = e.object : a === "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate" ? o.spo.predicate = e.object : a === "http://www.w3.org/1999/02/22-rdf-syntax-ns#object" && (o.spo.object = e.object, o.objectQuad = e), o.spo.subject && o.spo.predicate && o.spo.object)) {
1051
- let n = t.quad(o.spo.subject, o.spo.predicate, o.spo.object);
1052
- r.push(n), i.delete(e.subject.value);
1427
+ const quadKey = quadIndexKey(quad.subject, quad.predicate, quad.object);
1428
+ quadBuffer.set(quadKey, quad);
1429
+ quads.push(quad);
1430
+ if (state) {
1431
+ if (!state.primaryType && predicate.value === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type") state.primaryType = object.value;
1432
+ if (!state.primaryLabel && predicate.value === "http://www.w3.org/2000/01/rdf-schema#label" && object.termType === "Literal") state.primaryLabel = object.value;
1433
+ if (!state.primaryComment && predicate.value === "http://www.w3.org/2000/01/rdf-schema#comment" && object.termType === "Literal") state.primaryComment = object.value;
1434
+ }
1435
+ detectStatementPatternSinglePass(quad, dataFactory, meta, statements, statementCandidates);
1436
+ const originEntry = createLeanOriginEntry(block, subject, predicate, meta);
1437
+ quadIndex.set(quadKey, originEntry);
1438
+ if (state.currentBlock && block.id === state.currentBlock.id) {
1439
+ if (!state.currentBlock.quadKeys) state.currentBlock.quadKeys = [];
1440
+ state.currentBlock.quadKeys.push(quadKey);
1441
+ }
1053
1442
  }
1054
1443
  }
1055
- var Ne = (e, t, n, r, i = null) => {
1056
- let a = h(e, n.ctx), o = typeof i == "object" ? i : {
1057
- entryIndex: i,
1058
- remove: !1
1444
+ function detectStatementPatternSinglePass(quad, dataFactory, meta, statements = null, statementCandidates = null) {
1445
+ if (!statements || !statementCandidates) return;
1446
+ const predicate = quad.predicate.value;
1447
+ if (predicate !== "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && predicate !== "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject" && predicate !== "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate" && predicate !== "http://www.w3.org/1999/02/22-rdf-syntax-ns#object") return;
1448
+ if (predicate === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && quad.object.value === "http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement") {
1449
+ statementCandidates.set(quad.subject.value, { spo: {} });
1450
+ return;
1451
+ }
1452
+ const candidate = statementCandidates.get(quad.subject.value);
1453
+ if (!candidate) return;
1454
+ if (predicate === "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject") candidate.spo.subject = quad.object;
1455
+ else if (predicate === "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate") candidate.spo.predicate = quad.object;
1456
+ else if (predicate === "http://www.w3.org/1999/02/22-rdf-syntax-ns#object") {
1457
+ candidate.spo.object = quad.object;
1458
+ candidate.objectQuad = quad;
1459
+ }
1460
+ if (candidate.spo.subject && candidate.spo.predicate && candidate.spo.object) {
1461
+ const spoQuad = dataFactory.quad(candidate.spo.subject, candidate.spo.predicate, candidate.spo.object);
1462
+ statements.push(spoQuad);
1463
+ statementCandidates.delete(quad.subject.value);
1464
+ }
1465
+ }
1466
+ var createTypeQuad = (typeIRI, subject, state, block, entryIndex = null) => {
1467
+ const expandedType = expandIRI(typeIRI, state.ctx);
1468
+ const typeInfo = typeof entryIndex === "object" ? entryIndex : {
1469
+ entryIndex,
1470
+ remove: false
1059
1471
  };
1060
- z(n.quads, n.quadBuffer, n.removeSet, n.origin.quadIndex, r, t, n.df.namedNode(h("rdf:type", n.ctx)), n.df.namedNode(a), n.df, {
1472
+ emitQuad(state.quads, state.quadBuffer, state.removeSet, state.origin.quadIndex, block, subject, state.df.namedNode(expandIRI("rdf:type", state.ctx)), state.df.namedNode(expandedType), state.df, {
1061
1473
  kind: "type",
1062
- token: `.${e}`,
1063
- expandedType: a,
1064
- entryIndex: o.entryIndex,
1065
- remove: o.remove
1066
- }, n.statements, n.statementCandidates, n);
1474
+ token: `.${typeIRI}`,
1475
+ expandedType,
1476
+ entryIndex: typeInfo.entryIndex,
1477
+ remove: typeInfo.remove
1478
+ }, state.statements, state.statementCandidates, state);
1067
1479
  };
1068
- function Pe(e, t, n, r, i, a, o, s) {
1069
- e.types.forEach((e) => {
1070
- Ne(typeof e == "string" ? e : e.iri, t || n || r || i, o, a, typeof e == "string" ? {
1480
+ function processTypeAnnotations(sem, newSubject, localObject, carrierO, S, block, state, carrier) {
1481
+ sem.types.forEach((t) => {
1482
+ createTypeQuad(typeof t === "string" ? t : t.iri, newSubject || localObject || carrierO || S, state, block, typeof t === "string" ? {
1071
1483
  entryIndex: null,
1072
- remove: !1
1073
- } : e);
1484
+ remove: false
1485
+ } : t);
1074
1486
  });
1075
1487
  }
1076
- var Fe = (e, t, n, r, i, a, o, s) => {
1077
- if (e.form === "" && t?.type === "link" && t?.url && t.text === t.url) return null;
1078
- switch (e.form) {
1079
- case "": return n ? {
1080
- subject: i || o,
1081
- object: s
1082
- } : t?.type === "link" && t?.url && t.text !== t.url ? {
1083
- subject: a,
1084
- object: s
1488
+ var determinePredicateRole = (pred, carrier, newSubject, previousSubject, localObject, newSubjectOrCarrierO, S, L) => {
1489
+ if (pred.form === "" && carrier?.type === "link" && carrier?.url && carrier.text === carrier.url) return null;
1490
+ switch (pred.form) {
1491
+ case "": return newSubject ? {
1492
+ subject: localObject || S,
1493
+ object: L
1494
+ } : carrier?.type === "link" && carrier?.url && carrier.text !== carrier.url ? {
1495
+ subject: newSubjectOrCarrierO,
1496
+ object: L
1085
1497
  } : {
1086
- subject: i || o,
1087
- object: s
1498
+ subject: localObject || S,
1499
+ object: L
1088
1500
  };
1089
1501
  case "?": return {
1090
- subject: n ? r : o,
1091
- object: i || a
1502
+ subject: newSubject ? previousSubject : S,
1503
+ object: localObject || newSubjectOrCarrierO
1092
1504
  };
1093
1505
  case "!": return {
1094
- subject: i || a,
1095
- object: n ? r : o
1506
+ subject: localObject || newSubjectOrCarrierO,
1507
+ object: newSubject ? previousSubject : S
1096
1508
  };
1097
1509
  default: return null;
1098
1510
  }
1099
1511
  };
1100
- function Ie(e, t, n, r, i, a, o, s, c, l) {
1101
- e.predicates.forEach((e) => {
1102
- let u = Fe(e, l, t, n, r, i, a, o);
1103
- if (u) {
1104
- let t = c.df.namedNode(h(e.iri, c.ctx));
1105
- z(c.quads, c.quadBuffer, c.removeSet, c.origin.quadIndex, s, u.subject, t, u.object, c.df, {
1512
+ function processPredicateAnnotations(sem, newSubject, previousSubject, localObject, newSubjectOrCarrierO, S, L, block, state, carrier) {
1513
+ sem.predicates.forEach((pred) => {
1514
+ const role = determinePredicateRole(pred, carrier, newSubject, previousSubject, localObject, newSubjectOrCarrierO, S, L);
1515
+ if (role) {
1516
+ const P = state.df.namedNode(expandIRI(pred.iri, state.ctx));
1517
+ emitQuad(state.quads, state.quadBuffer, state.removeSet, state.origin.quadIndex, block, role.subject, P, role.object, state.df, {
1106
1518
  kind: "pred",
1107
- token: `${e.form}${e.iri}`,
1108
- form: e.form,
1109
- expandedPredicate: t.value,
1110
- entryIndex: e.entryIndex,
1111
- remove: e.remove || !1
1112
- }, c.statements, c.statementCandidates, c);
1519
+ token: `${pred.form}${pred.iri}`,
1520
+ form: pred.form,
1521
+ expandedPredicate: P.value,
1522
+ entryIndex: pred.entryIndex,
1523
+ remove: pred.remove || false
1524
+ }, state.statements, state.statementCandidates, state);
1113
1525
  }
1114
1526
  });
1115
1527
  }
1116
- function B(e, t, n, r = {}) {
1117
- Ae(e, t, n, r);
1118
- }
1119
- function V(e, t, n) {
1120
- if (e.attrs) {
1121
- let r = D(e.attrs);
1122
- B({
1123
- type: n,
1124
- text: e.text,
1125
- range: e.range,
1126
- attrsRange: e.attrsRange || null,
1127
- valueRange: e.valueRange || null
1128
- }, r, t);
1129
- }
1130
- L(e).forEach((e) => {
1131
- e.attrs && B(e, D(e.attrs), t);
1528
+ function processAnnotation(carrier, sem, state, options = {}) {
1529
+ processAnnotationWithBlockTracking(carrier, sem, state, options);
1530
+ }
1531
+ function processTokenAnnotations(token, state, tokenType) {
1532
+ if (token.attrs) {
1533
+ const sem = parseSemCached(token.attrs);
1534
+ processAnnotation({
1535
+ type: tokenType,
1536
+ text: token.text,
1537
+ range: token.range,
1538
+ attrsRange: token.attrsRange || null,
1539
+ valueRange: token.valueRange || null
1540
+ }, sem, state);
1541
+ }
1542
+ getCarriers(token).forEach((carrier) => {
1543
+ if (carrier.attrs) processAnnotation(carrier, parseSemCached(carrier.attrs), state);
1132
1544
  });
1133
1545
  }
1134
- function H(e, t) {
1135
- let n = se(e.text);
1136
- if (!n) return;
1137
- let r = D(`{=${n.content}}`), i = e.range[0] + e.text.indexOf("{=");
1138
- B({
1546
+ function processStandaloneSubject(token, state) {
1547
+ const result = detectStandaloneSubject(token.text);
1548
+ if (!result) return;
1549
+ const sem = parseSemCached(`{=${result.content}}`);
1550
+ const attrsStart = token.range[0] + token.text.indexOf("{=");
1551
+ processAnnotation({
1139
1552
  type: "standalone",
1140
1553
  text: "",
1141
- range: e.range,
1142
- attrsRange: [i, i + (n.content ? n.content.length : 0)],
1554
+ range: token.range,
1555
+ attrsRange: [attrsStart, attrsStart + (result.content ? result.content.length : 0)],
1143
1556
  valueRange: null
1144
- }, r, t);
1145
- }
1146
- var Le = {
1147
- heading: (e, t) => P(e, t, V, R),
1148
- code: (e, t) => P(e, t, V, R),
1149
- blockquote: (e, t) => P(e, t, V, R),
1150
- para: (e, t) => P(e, t, V, R, [H]),
1151
- list: (e, t) => P(e, t, V, R),
1152
- standalone: (e, t) => H(e, t)
1557
+ }, sem, state);
1558
+ }
1559
+ var TOKEN_PROCESSORS = {
1560
+ heading: (token, state) => processTokenWithBlockTracking(token, state, processTokenAnnotations, createBlockEntry),
1561
+ code: (token, state) => processTokenWithBlockTracking(token, state, processTokenAnnotations, createBlockEntry),
1562
+ blockquote: (token, state) => processTokenWithBlockTracking(token, state, processTokenAnnotations, createBlockEntry),
1563
+ para: (token, state) => processTokenWithBlockTracking(token, state, processTokenAnnotations, createBlockEntry, [processStandaloneSubject]),
1564
+ list: (token, state) => processTokenWithBlockTracking(token, state, processTokenAnnotations, createBlockEntry),
1565
+ standalone: (token, state) => processStandaloneSubject(token, state)
1153
1566
  };
1154
1567
  //#endregion
1155
1568
  //#region src/merge.js
1156
- function U(e) {
1157
- return te(e);
1158
- }
1159
- function Re(e, t, n) {
1160
- return typeof e == "string" ? I({
1161
- text: e,
1162
- ...t,
1569
+ /**
1570
+ * Creates a unique key for quad identity matching - using shared utility
1571
+ * @param {Quad} quad
1572
+ * @returns {string}
1573
+ */
1574
+ function quadKey(quad) {
1575
+ return quadToKeyForOrigin(quad);
1576
+ }
1577
+ /**
1578
+ * Normalizes merge input to ParseResult format
1579
+ * @param {string|ParseResult} input
1580
+ * @param {Object} options
1581
+ * @param {Object} docContext
1582
+ * @returns {ParseResult}
1583
+ */
1584
+ function normalizeInput(input, options, docContext) {
1585
+ if (typeof input === "string") return parse({
1586
+ text: input,
1587
+ ...options,
1163
1588
  context: {
1164
- ...n,
1165
- ...t.context
1589
+ ...docContext,
1590
+ ...options.context
1166
1591
  }
1167
- }) : e;
1168
- }
1169
- function ze(t, n = {}) {
1170
- let r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Set(), a = [], o = /* @__PURE__ */ new Map(), s = [], c = /* @__PURE__ */ new Map(), l = [], u = [];
1171
- for (let d = 0; d < t.length; d++) {
1172
- let f = t[d], p = Re(f, n, {
1173
- ...e,
1174
- ...n.context
1592
+ });
1593
+ return input;
1594
+ }
1595
+ /**
1596
+ * Merges multiple MDLD documents with diff polarity resolution
1597
+ * @param {Array<string|ParseResult>} docs
1598
+ * @param {Object} options
1599
+ * @returns {Object} Merge result with quads, remove, statements, origin, and context
1600
+ */
1601
+ function merge(docs, options = {}) {
1602
+ const sessionBuffer = /* @__PURE__ */ new Map();
1603
+ const sessionRemoveSet = /* @__PURE__ */ new Set();
1604
+ const allDocuments = [];
1605
+ const quadIndex = /* @__PURE__ */ new Map();
1606
+ const allStatements = [];
1607
+ const accumulatedContext = /* @__PURE__ */ new Map();
1608
+ const primaryObjects = [];
1609
+ const primarySubjects = [];
1610
+ for (let i = 0; i < docs.length; i++) {
1611
+ const input = docs[i];
1612
+ const doc = normalizeInput(input, options, {
1613
+ ...DEFAULT_CONTEXT,
1614
+ ...options.context
1175
1615
  });
1176
- if (p.context) for (let [t, n] of Object.entries(p.context)) !c.has(t) && !e[t] && c.set(t, n);
1177
- let m = {
1178
- index: d,
1179
- input: typeof f == "string" ? "string" : "ParseResult",
1180
- origin: p.origin,
1181
- context: p.context,
1182
- statementsCount: p.statements?.length || 0
1616
+ if (doc.context) {
1617
+ for (const [prefix, namespace] of Object.entries(doc.context)) if (!accumulatedContext.has(prefix) && !DEFAULT_CONTEXT[prefix]) accumulatedContext.set(prefix, namespace);
1618
+ }
1619
+ const documentOrigin = {
1620
+ index: i,
1621
+ input: typeof input === "string" ? "string" : "ParseResult",
1622
+ origin: doc.origin,
1623
+ context: doc.context,
1624
+ statementsCount: doc.statements?.length || 0
1183
1625
  };
1184
- a.push(m), p.statements && p.statements.length > 0 && s.push(...p.statements), p.primary && (p.primary.subject || p.primary.type || p.primary.label) && l.push(p.primary), p.primarySubject && u.push(p.primarySubject);
1185
- for (let e of p.quads) {
1186
- let t = U(e);
1187
- r.set(t, e);
1188
- let n = p.origin.quadIndex.get(t);
1189
- o.set(t, {
1190
- ...n || {},
1191
- documentIndex: d,
1626
+ allDocuments.push(documentOrigin);
1627
+ if (doc.statements && doc.statements.length > 0) allStatements.push(...doc.statements);
1628
+ if (doc.primary && (doc.primary.subject || doc.primary.type || doc.primary.label)) primaryObjects.push(doc.primary);
1629
+ if (doc.primarySubject) primarySubjects.push(doc.primarySubject);
1630
+ for (const quad of doc.quads) {
1631
+ const key = quadKey(quad);
1632
+ sessionBuffer.set(key, quad);
1633
+ const existingOrigin = doc.origin.quadIndex.get(key);
1634
+ quadIndex.set(key, {
1635
+ ...existingOrigin || {},
1636
+ documentIndex: i,
1192
1637
  polarity: "+"
1193
1638
  });
1194
1639
  }
1195
- for (let e of p.remove) {
1196
- let t = U(e);
1197
- r.has(t) ? r.delete(t) : i.add(e);
1198
- let n = p.origin.quadIndex.get(t);
1199
- o.set(t, {
1200
- ...n || {},
1201
- documentIndex: d,
1640
+ for (const quad of doc.remove) {
1641
+ const key = quadKey(quad);
1642
+ if (sessionBuffer.has(key)) sessionBuffer.delete(key);
1643
+ else sessionRemoveSet.add(quad);
1644
+ const existingOrigin = doc.origin.quadIndex.get(key);
1645
+ quadIndex.set(key, {
1646
+ ...existingOrigin || {},
1647
+ documentIndex: i,
1202
1648
  polarity: "-"
1203
1649
  });
1204
1650
  }
1205
1651
  }
1206
- let d = Array.from(r.values()), f = Array.from(i), p = {
1207
- documents: a,
1208
- quadIndex: o
1209
- }, m = {
1210
- ...e,
1211
- ...n.context,
1212
- ...Object.fromEntries(c)
1213
- }, h = new Set(d.map(U)), g = new Set(f.map(U));
1652
+ const finalQuads = Array.from(sessionBuffer.values());
1653
+ const finalRemove = Array.from(sessionRemoveSet);
1654
+ const mergeOrigin = {
1655
+ documents: allDocuments,
1656
+ quadIndex
1657
+ };
1658
+ const finalContext = {
1659
+ ...DEFAULT_CONTEXT,
1660
+ ...options.context,
1661
+ ...Object.fromEntries(accumulatedContext)
1662
+ };
1663
+ const quadKeys = new Set(finalQuads.map(quadKey));
1664
+ const removeKeys = new Set(finalRemove.map(quadKey));
1214
1665
  return {
1215
- quads: d.filter((e) => !g.has(U(e))),
1216
- remove: f.filter((e) => !h.has(U(e))),
1217
- statements: s,
1218
- origin: p,
1219
- context: m,
1220
- primarySubjects: u,
1221
- primary: l
1666
+ quads: finalQuads.filter((quad) => !removeKeys.has(quadKey(quad))),
1667
+ remove: finalRemove.filter((quad) => !quadKeys.has(quadKey(quad))),
1668
+ statements: allStatements,
1669
+ origin: mergeOrigin,
1670
+ context: finalContext,
1671
+ primarySubjects,
1672
+ primary: primaryObjects
1222
1673
  };
1223
1674
  }
1224
1675
  //#endregion
1225
1676
  //#region src/generate.js
1226
- var W = /* @__PURE__ */ new Map(), G = 1e3;
1227
- function K(e, t) {
1228
- let n = `${e}|${JSON.stringify(t)}`;
1229
- if (W.has(n)) return W.get(n);
1230
- let r = g(e, t);
1231
- return W.size >= G && Array.from(W.keys()).slice(0, Math.floor(G / 2)).forEach((e) => W.delete(e)), W.set(n, r), r;
1232
- }
1233
- function Be(e, t = {}) {
1234
- if (!e) return e;
1235
- for (let [n, r] of Object.entries(t)) if (e.startsWith(r) || e.startsWith(r.slice(0, -1))) return e.substring(r.length);
1236
- for (let t of [
1677
+ var iriCache = /* @__PURE__ */ new Map();
1678
+ var CACHE_SIZE_LIMIT = 1e3;
1679
+ function getCachedShortIRI(iri, context) {
1680
+ const cacheKey = `${iri}|${JSON.stringify(context)}`;
1681
+ if (iriCache.has(cacheKey)) return iriCache.get(cacheKey);
1682
+ const result = shortenIRI(iri, context);
1683
+ if (iriCache.size >= CACHE_SIZE_LIMIT) Array.from(iriCache.keys()).slice(0, Math.floor(CACHE_SIZE_LIMIT / 2)).forEach((key) => iriCache.delete(key));
1684
+ iriCache.set(cacheKey, result);
1685
+ return result;
1686
+ }
1687
+ function extractLocalName(iri, ctx = {}) {
1688
+ if (!iri) return iri;
1689
+ for (const [prefix, namespace] of Object.entries(ctx)) if (iri.startsWith(namespace) || iri.startsWith(namespace.slice(0, -1))) return iri.substring(namespace.length);
1690
+ for (const sep of [
1237
1691
  "#",
1238
1692
  "/",
1239
1693
  ":"
1240
1694
  ]) {
1241
- let n = e.lastIndexOf(t);
1242
- if (n !== -1 && n < e.length - 1) return e.substring(n + 1);
1243
- }
1244
- return e;
1245
- }
1246
- function Ve({ quads: t, context: n = {}, primarySubject: r = null }) {
1247
- let i = Object.assign({}, e, n), a = Ue(t), o = We(a), s = r;
1248
- !s && a.length > 0 && (s = a[0].subject.value);
1249
- let { text: c } = Ke(o, i, s);
1695
+ const lastSep = iri.lastIndexOf(sep);
1696
+ if (lastSep !== -1 && lastSep < iri.length - 1) return iri.substring(lastSep + 1);
1697
+ }
1698
+ return iri;
1699
+ }
1700
+ /**
1701
+ * Generate deterministic MDLD from RDF quads
1702
+ * Purpose: TTL→MDLD conversion with canonical structure
1703
+ * Input: RDF quads + context + optional primarySubject (string IRI) + compactInline (boolean) + remove (array)
1704
+ * Output: MDLD text + context + compactStats
1705
+ */
1706
+ function generate({ quads, context = {}, primarySubject = null, compactInline = false, renderReverse = false, remove = [] }) {
1707
+ const fullContext = Object.assign({}, DEFAULT_CONTEXT, context);
1708
+ const normalizedQuads = normalizeAndSortQuads(quads);
1709
+ const normalizedRemove = normalizeAndSortQuads(remove);
1710
+ const { subjectGroups, reverseIndex } = groupQuadsBySubject(normalizedQuads);
1711
+ const removeBySubject = groupQuadsBySubject(normalizedRemove).subjectGroups;
1712
+ const { text, compactStats } = buildDeterministicMDLD(subjectGroups, fullContext, primarySubject, primarySubject && renderReverse ? reverseIndex : null, compactInline, removeBySubject);
1250
1713
  return {
1251
- text: c,
1252
- context: i
1714
+ text,
1715
+ context: fullContext,
1716
+ compactStats
1253
1717
  };
1254
1718
  }
1255
- function He({ quads: t, focusIRI: n, context: r = {} }) {
1256
- if (!t?.length || !n) return {
1719
+ /**
1720
+ * Generate node-centric MDLD showing all quads where a specific IRI appears
1721
+ * in any position: subject, object, predicate, type, or datatype.
1722
+ * Perfect for exploring individual nodes and their complete relationship graph.
1723
+ */
1724
+ function generateNode({ quads, focusIRI, context = {}, compactInline = true, renderReverse = true }) {
1725
+ if (!quads?.length || !focusIRI) return {
1257
1726
  text: "",
1258
- context: Object.assign({}, e, r)
1727
+ context: Object.assign({}, DEFAULT_CONTEXT, context),
1728
+ compactStats: null
1259
1729
  };
1260
- let i = Object.assign({}, e, r), a = Ge(Ue(t));
1261
- if (!a.has(n)) return {
1730
+ const fullContext = Object.assign({}, DEFAULT_CONTEXT, context);
1731
+ const { nodeGroups, reverseIndex } = groupQuadsByNode(normalizeAndSortQuads(quads));
1732
+ if (!nodeGroups.has(focusIRI)) return {
1262
1733
  text: "",
1263
- context: i
1734
+ context: fullContext,
1735
+ compactStats: null
1264
1736
  };
1265
- let { text: o } = Ke(a, i, n);
1737
+ const { text, compactStats } = buildDeterministicMDLD(nodeGroups, fullContext, focusIRI, renderReverse ? reverseIndex : null, compactInline);
1266
1738
  return {
1267
- text: o,
1268
- context: i
1739
+ text,
1740
+ context: fullContext,
1741
+ compactStats
1269
1742
  };
1270
1743
  }
1271
- function Ue(e) {
1272
- return !e || e.length === 0 ? [] : e.map((e) => e.subject.termType && e.predicate.termType && e.object.termType ? e : {
1273
- subject: d.fromTerm(e.subject),
1274
- predicate: d.fromTerm(e.predicate),
1275
- object: d.fromTerm(e.object)
1276
- }).sort((e, t) => {
1277
- let n = e.subject.value.localeCompare(t.subject.value);
1278
- if (n !== 0) return n;
1279
- let r = e.predicate.value.localeCompare(t.predicate.value);
1280
- if (r !== 0) return r;
1281
- let i = (j(e.object), e.object.value), a = (j(t.object), t.object.value);
1282
- return i.localeCompare(a);
1744
+ function normalizeAndSortQuads(quads) {
1745
+ if (!quads || quads.length === 0) return [];
1746
+ return quads.map((quad) => {
1747
+ if (quad.subject.termType && quad.predicate.termType && quad.object.termType) return quad;
1748
+ return {
1749
+ subject: DataFactory.fromTerm(quad.subject),
1750
+ predicate: DataFactory.fromTerm(quad.predicate),
1751
+ object: DataFactory.fromTerm(quad.object)
1752
+ };
1753
+ }).sort((a, b) => {
1754
+ const sComp = a.subject.value.localeCompare(b.subject.value);
1755
+ if (sComp !== 0) return sComp;
1756
+ const pComp = a.predicate.value.localeCompare(b.predicate.value);
1757
+ if (pComp !== 0) return pComp;
1758
+ const oA = isLiteral(a.object) ? a.object.value : a.object.value;
1759
+ const oB = isLiteral(b.object) ? b.object.value : b.object.value;
1760
+ return oA.localeCompare(oB);
1283
1761
  });
1284
1762
  }
1285
- function We(e) {
1286
- let t = /* @__PURE__ */ new Map();
1287
- for (let n of e) {
1288
- let e = n.subject.value, r = t.get(e);
1289
- r ? r.push(n) : t.set(e, [n]);
1290
- }
1291
- return t;
1292
- }
1293
- function Ge(e) {
1294
- let t = /* @__PURE__ */ new Map(), n = (e) => {
1295
- let n = t.get(e);
1296
- if (n) return n;
1297
- let r = [];
1298
- return t.set(e, r), r;
1299
- };
1300
- for (let t of e) {
1301
- let { subject: e, predicate: r, object: i } = t;
1302
- n(e.value).push(t), i.termType === "NamedNode" && n(i.value).push(t), n(r.value).push(t), r.value === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && i.termType === "NamedNode" && n(i.value).push(t), i.termType === "Literal" && i.datatype && n(i.datatype.value || i.datatype).push(t);
1303
- }
1304
- return t;
1305
- }
1306
- function Ke(t, n, r = null) {
1307
- let i = [], a = Se(t, n), o = qe(t), s = Object.entries(n).sort(([e], [t]) => e.localeCompare(t));
1308
- for (let [t, n] of s) t !== "@vocab" && !t.startsWith("@") && !e[t] && a.has(t) && i.push(Ce(t, n));
1309
- s.length > 0 && i.push("\n");
1310
- let c = Array.from(t.keys()).sort(), l = r, u = l ? [l, ...c.filter((e) => e !== l)] : c;
1311
- for (let e of u) {
1312
- let r = t.get(e);
1313
- if (!r) continue;
1314
- let a = K(e, n), { types: s, literals: c, objects: l } = Ee(r), u = o.has(e), d = u ? o.get(e) : Be(e, n), f = s.length > 0 ? s.map((e) => "." + K(e.object.value, n)).sort().join(" ") : "";
1315
- u && (f += (f ? " " : "") + "label");
1316
- let p = f ? " " + f : "";
1317
- i.push(`# ${d} {=${a}${p}}\n`);
1318
- let m = u ? o.get(e) : null;
1319
- F(c).forEach((e) => {
1320
- e.predicate.value === "http://www.w3.org/2000/01/rdf-schema#label" && e.object.value === m || i.push(we(e, n));
1321
- }), F(l).forEach((e) => {
1322
- i.push(Te(e, n, o));
1323
- }), i.push("\n");
1324
- }
1325
- return { text: i.join("") };
1326
- }
1327
- function qe(e) {
1328
- let t = /* @__PURE__ */ new Map();
1329
- for (let n of e.values()) for (let e of n) e.predicate.value === "http://www.w3.org/2000/01/rdf-schema#label" && e.object.termType === "Literal" && t.set(e.subject.value, e.object.value);
1330
- return t;
1331
- }
1332
- //#endregion
1333
- //#region src/render.js
1334
- function Je(e, t = {}) {
1335
- let n = I({
1336
- text: e,
1337
- context: t.context || {}
1338
- }), r = Ye(n, t, e), i = {
1339
- html: ht(Xe(n.origin.blocks, r), r.ctx),
1340
- context: r.ctx,
1341
- metadata: {
1342
- blockCount: n.origin.blocks.size,
1343
- quadCount: n.quads.length,
1344
- renderedRDFaCount: r.renderedRDFaCount,
1345
- renderTime: Date.now()
1763
+ function groupQuadsBySubject(quads) {
1764
+ const groups = /* @__PURE__ */ new Map();
1765
+ const reverseIndex = /* @__PURE__ */ new Map();
1766
+ for (const quad of quads) {
1767
+ const subjectValue = quad.subject.value;
1768
+ const existing = groups.get(subjectValue);
1769
+ if (existing) existing.push(quad);
1770
+ else groups.set(subjectValue, [quad]);
1771
+ if (quad.object.termType === "NamedNode") {
1772
+ const objectValue = quad.object.value;
1773
+ const reverseList = reverseIndex.get(objectValue);
1774
+ if (reverseList) reverseList.push(quad);
1775
+ else reverseIndex.set(objectValue, [quad]);
1346
1776
  }
1347
- };
1348
- return t.debug && (i.debug = {
1349
- originBlocks: Array.from(n.origin.blocks.values()),
1350
- quadIndex: Array.from(n.origin.quadIndex.entries()),
1351
- renderMap: r.renderMap
1352
- }), i;
1353
- }
1354
- function Ye(t, n, r) {
1777
+ }
1355
1778
  return {
1356
- ctx: t.context || {
1357
- ...e,
1358
- ...n.context || {}
1359
- },
1360
- df: n.dataFactory || d,
1361
- baseIRI: n.baseIRI || "",
1362
- sourceText: r,
1363
- output: [],
1364
- currentSubject: null,
1365
- quadIndex: t.origin.quadIndex,
1366
- blocks: t.origin.blocks,
1367
- renderMap: /* @__PURE__ */ new Map(),
1368
- renderedRDFaCount: 0,
1369
- validation: n.validate || !1
1779
+ subjectGroups: groups,
1780
+ reverseIndex
1370
1781
  };
1371
1782
  }
1372
- function Xe(e, t) {
1373
- let n = Array.from(e.values()).sort((e, t) => (e.range?.start || 0) - (t.range?.start || 0)), r = n.filter((e) => e.carrierType === "list");
1374
- return n.filter((e) => e.carrierType !== "list").forEach((e) => {
1375
- Ze(e, t);
1376
- }), r.length > 0 && lt(r, t), t.output.join("");
1377
- }
1378
- function Ze(e, t) {
1379
- e.subject && e.subject !== "RESET" && (t.currentSubject = e.subject);
1380
- let n = Qe(e, t);
1381
- switch (n && t.renderMap.set(e.id || gt(e), n), e.type || e.carrierType) {
1382
- case "heading":
1383
- et(e, n, t);
1384
- break;
1385
- case "para":
1386
- tt(e, n, t);
1387
- break;
1388
- case "list": break;
1389
- case "quote":
1390
- nt(e, n, t);
1391
- break;
1392
- case "code":
1393
- rt(e, n, t);
1394
- break;
1395
- default: it(e, n, t);
1396
- }
1397
- }
1398
- function Qe(e, t) {
1399
- let n = [];
1400
- if (!e.subject || e.subject === "RESET" || e.subject.startsWith("=#") || e.subject.startsWith("+")) return "";
1401
- let r = h(e.subject, t.ctx);
1402
- if (n.push(`about="${A(r)}"`), e.types && e.types.length > 0) {
1403
- let r = e.types.map((e) => h(typeof e == "string" ? e : e.iri, t.ctx)).join(" ");
1404
- n.push(`typeof="${A(r)}"`);
1405
- }
1406
- let i = [];
1407
- if (e.predicates && e.predicates.length > 0 && i.push(...e.predicates), e.carriers && e.carriers.length > 0) for (let t of e.carriers) t.predicates && t.predicates.length > 0 && i.push(...t.predicates);
1408
- if (i.length > 0) {
1409
- let { literalProps: e, objectProps: r, reverseProps: a } = $e(i, t.ctx);
1410
- e.length > 0 && n.push(`property="${A(e.join(" "))}"`), r.length > 0 && n.push(`rel="${A(r.join(" "))}"`), a.length > 0 && n.push(`rev="${A(a.join(" "))}"`);
1411
- }
1412
- return n.length > 1 && t.renderedRDFaCount++, n.length > 0 ? ` ${n.join(" ")}` : "";
1413
- }
1414
- function $e(e, t) {
1415
- let n = [], r = [], i = [];
1416
- for (let a of e) {
1417
- let e = h(typeof a == "string" ? a : a.iri, t);
1418
- a.polarity === "-" ? i.push(e) : a.object && a.object.termType === "NamedNode" ? r.push(e) : n.push(e);
1783
+ function groupQuadsByNode(quads) {
1784
+ const groups = /* @__PURE__ */ new Map();
1785
+ const reverseIndex = /* @__PURE__ */ new Map();
1786
+ const ensure = (key) => {
1787
+ const existing = groups.get(key);
1788
+ if (existing) return existing;
1789
+ const newArray = [];
1790
+ groups.set(key, newArray);
1791
+ return newArray;
1792
+ };
1793
+ for (const quad of quads) {
1794
+ const { subject, predicate, object } = quad;
1795
+ ensure(subject.value).push(quad);
1796
+ if (object.termType === "NamedNode") {
1797
+ ensure(object.value).push(quad);
1798
+ const objectValue = object.value;
1799
+ const reverseList = reverseIndex.get(objectValue);
1800
+ if (reverseList) reverseList.push(quad);
1801
+ else reverseIndex.set(objectValue, [quad]);
1802
+ }
1803
+ ensure(predicate.value).push(quad);
1804
+ if (predicate.value === RDFS_TYPE && object.termType === "NamedNode") ensure(object.value).push(quad);
1805
+ if (object.termType === "Literal" && object.datatype) ensure(object.datatype.value || object.datatype).push(quad);
1419
1806
  }
1420
1807
  return {
1421
- literalProps: n,
1422
- objectProps: r,
1423
- reverseProps: i
1808
+ nodeGroups: groups,
1809
+ reverseIndex
1424
1810
  };
1425
1811
  }
1426
- function et(e, t, n) {
1427
- let r = `h${e.text && e.text.match(/^#+/)?.[0]?.length || 1}`, i = _e(n.sourceText, e.range);
1428
- i = i.replace(/\s*\{[^}]+\}\s*$/g, "").trim(), n.output.push(`<${r}${t}>${A(i)}</${r}>`);
1429
- }
1430
- function tt(e, t, n) {
1431
- let r = q(e, n);
1432
- n.output.push(`<p${t}>${r}</p>`);
1433
- }
1434
- function nt(e, t, n) {
1435
- let r = q(e, n);
1436
- n.output.push(`<blockquote${t}>${r}</blockquote>`);
1437
- }
1438
- function rt(e, t, n) {
1439
- let r = e.info || "", i = e.text || "";
1440
- n.output.push(`<pre><code${t}${r ? ` class="language-${A(r)}"` : ""}>${A(i)}</code></pre>`);
1441
- }
1442
- function it(e, t, n) {
1443
- let r = q(e, n);
1444
- n.output.push(`<div${t}>${r}</div>`);
1445
- }
1446
- function q(e, t) {
1447
- if (!e.carriers || e.carriers.length === 0) return A(at(t.sourceText, e.range));
1448
- let n = ot(e);
1449
- return st(at(t.sourceText, e.range), n, t);
1450
- }
1451
- function at(e, t) {
1452
- if (!t || !e) return "";
1453
- let n = e.substring(t[0], t[1]);
1454
- return n = n.replace(/\s*\{[^}]*\}\s*$/gm, ""), n = n.replace(/\{[^}]*\}/g, ""), n = n.replace(/\s+/g, " ").trim(), n = n.replace(/\]$/, ""), n;
1455
- }
1456
- function ot(e) {
1457
- let t = [];
1458
- if (!e.carriers) return t;
1459
- for (let n of e.carriers) !n.text || !n.range || t.push({
1460
- pos: n.range[0] - e.range[0],
1461
- carrier: n,
1462
- length: n.text.length
1463
- });
1464
- return t.sort((e, t) => e.pos - t.pos);
1465
- }
1466
- function st(e, t, n) {
1467
- if (t.length === 0) return A(e);
1468
- let r = "", i = 0;
1469
- for (let a of t) a.pos > i && (r += A(e.substring(i, a.pos))), r += ct(a.carrier, n), i = a.pos + a.length;
1470
- return i < e.length && (r += A(e.substring(i))), r;
1471
- }
1472
- function ct(e, t) {
1473
- let n = [], r = e.subject || t.currentSubject;
1474
- if (!r || r === "RESET" || r.startsWith("=#") || r.startsWith("+")) return A(e.text || "");
1475
- let i = g(h(r, t.ctx), t.ctx);
1476
- if (n.push(`about="${A(i)}"`), e.types && e.types.length > 0) {
1477
- let r = e.types.map((e) => g(h(typeof e == "string" ? e : e.iri, t.ctx), t.ctx)).join(" ");
1478
- n.push(`typeof="${A(r)}"`);
1479
- }
1480
- if (e.predicates && e.predicates.length > 0) {
1481
- let { literalProps: r, objectProps: i, reverseProps: a } = $e(e.predicates, t.ctx);
1482
- if (r.length > 0) {
1483
- let e = r.map((e) => g(e, t.ctx)).join(" ");
1484
- n.push(`property="${A(e)}"`);
1812
+ function buildDeterministicMDLD(subjectGroups, context, primarySubject = null, reverseIndex = null, compactInline = true, removeBySubject = /* @__PURE__ */ new Map()) {
1813
+ const textParts = [];
1814
+ const usedPrefixes = collectUsedPrefixes(subjectGroups, context);
1815
+ const labelLookup = buildLabelLookup(subjectGroups);
1816
+ const compactStats = {
1817
+ compactedSubjects: 0,
1818
+ skippedHeadings: 0,
1819
+ inlineAnnotations: 0
1820
+ };
1821
+ const renderedQuads = /* @__PURE__ */ new Set();
1822
+ const filteredGroups = /* @__PURE__ */ new Map();
1823
+ for (const [subjectIRI, quads] of subjectGroups.entries()) filteredGroups.set(subjectIRI, filterQuadsByType(quads));
1824
+ const sortedPrefixes = Object.entries(context).sort(([a], [b]) => a.localeCompare(b));
1825
+ for (const [prefix, namespace] of sortedPrefixes) if (prefix !== "@vocab" && !prefix.startsWith("@") && !DEFAULT_CONTEXT[prefix] && usedPrefixes.has(prefix)) textParts.push(generatePrefixDeclaration(prefix, namespace));
1826
+ if (sortedPrefixes.length > 0) textParts.push("\n");
1827
+ const sortedSubjects = Array.from(subjectGroups.keys()).sort();
1828
+ const primarySubjectIRI = primarySubject;
1829
+ const orderedSubjects = primarySubjectIRI ? [primarySubjectIRI, ...sortedSubjects.filter((s) => s !== primarySubjectIRI)] : sortedSubjects;
1830
+ for (const subjectIRI of orderedSubjects) {
1831
+ const subjectQuads = subjectGroups.get(subjectIRI);
1832
+ if (!subjectQuads) continue;
1833
+ if (subjectQuads.every((q) => renderedQuads.has(q))) {
1834
+ compactStats.skippedHeadings++;
1835
+ compactStats.compactedSubjects++;
1836
+ continue;
1485
1837
  }
1486
- if (i.length > 0) {
1487
- let e = i.map((e) => g(e, t.ctx)).join(" ");
1488
- n.push(`rel="${A(e)}"`);
1838
+ const { types, literals, objects } = filteredGroups.get(subjectIRI);
1839
+ const shortSubject = getCachedShortIRI(subjectIRI, context);
1840
+ const hasLabel = labelLookup.has(subjectIRI);
1841
+ const displayName = hasLabel ? labelLookup.get(subjectIRI) : extractLocalName(subjectIRI, context);
1842
+ const typesNotRendered = types.filter((t) => !renderedQuads.has(t));
1843
+ let annotations = typesNotRendered.length > 0 ? typesNotRendered.map((t) => "." + getCachedShortIRI(t.object.value, context)).sort().join(" ") : "";
1844
+ const labelQuad = subjectQuads.find((q) => q.predicate.value === RDFS_LABEL);
1845
+ if (hasLabel && (!labelQuad || !renderedQuads.has(labelQuad))) annotations += (annotations ? " " : "") + "label";
1846
+ const annotationStr = annotations ? " " + annotations : "";
1847
+ textParts.push(`# ${displayName} {=${shortSubject}${annotationStr}}\n`);
1848
+ types.forEach((t) => renderedQuads.add(t));
1849
+ if (labelQuad) renderedQuads.add(labelQuad);
1850
+ const headingLabel = hasLabel ? labelLookup.get(subjectIRI) : null;
1851
+ sortQuadsByPredicate(literals).forEach((quad) => {
1852
+ if (quad.predicate.value === "http://www.w3.org/2000/01/rdf-schema#label" && quad.object.value === headingLabel) return;
1853
+ textParts.push(generateLiteralText(quad, context));
1854
+ });
1855
+ sortQuadsByPredicate(objects).forEach((quad) => {
1856
+ if (renderedQuads.has(quad)) return;
1857
+ textParts.push(generateObjectText(quad, context, labelLookup, filteredGroups, renderedQuads, compactInline, compactStats));
1858
+ });
1859
+ if (subjectIRI === primarySubjectIRI && reverseIndex && reverseIndex.has(subjectIRI)) {
1860
+ const reverseQuads = reverseIndex.get(subjectIRI);
1861
+ reverseQuads.sort((a, b) => a.predicate.value.localeCompare(b.predicate.value));
1862
+ for (const quad of reverseQuads) {
1863
+ renderedQuads.add(quad);
1864
+ const subjectQuads = subjectGroups.get(quad.subject.value);
1865
+ const subjectLabel = labelLookup.has(quad.subject.value) ? labelLookup.get(quad.subject.value) : extractLocalName(quad.subject.value, context);
1866
+ const shortSubject = getCachedShortIRI(quad.subject.value, context);
1867
+ const shortPredicate = getCachedShortIRI(quad.predicate.value, context);
1868
+ let inlineAnnotation = "";
1869
+ if (compactInline && subjectQuads) {
1870
+ const { types } = filteredGroups.get(quad.subject.value) || { types: [] };
1871
+ const hasLabel = labelLookup.has(quad.subject.value);
1872
+ const typeAnnotations = types.length > 0 ? types.map((t) => "." + getCachedShortIRI(t.object.value, context)).sort().join(" ") : "";
1873
+ const labelAnnotation = hasLabel ? "label" : "";
1874
+ if (typeAnnotations || labelAnnotation) {
1875
+ inlineAnnotation = " " + [typeAnnotations, labelAnnotation].filter(Boolean).join(" ");
1876
+ compactStats.inlineAnnotations++;
1877
+ types.forEach((q) => renderedQuads.add(q));
1878
+ if (hasLabel) {
1879
+ const labelQuad = subjectQuads.find((q) => q.predicate.value === RDFS_LABEL);
1880
+ if (labelQuad) renderedQuads.add(labelQuad);
1881
+ }
1882
+ }
1883
+ if (subjectQuads.every((q) => renderedQuads.has(q))) {
1884
+ compactStats.skippedHeadings++;
1885
+ compactStats.compactedSubjects++;
1886
+ }
1887
+ }
1888
+ textParts.push(`[${subjectLabel}] {+${shortSubject} !${shortPredicate}${inlineAnnotation}}\n`);
1889
+ }
1489
1890
  }
1490
- if (a.length > 0) {
1491
- let e = a.map((e) => g(e, t.ctx)).join(" ");
1492
- n.push(`rev="${A(e)}"`);
1891
+ if (removeBySubject.has(subjectIRI)) {
1892
+ const removeQuads = removeBySubject.get(subjectIRI);
1893
+ for (const quad of removeQuads) textParts.push(generateRetractionText(quad, context));
1894
+ removeBySubject.delete(subjectIRI);
1493
1895
  }
1896
+ textParts.push("\n");
1494
1897
  }
1495
- let a = n.length > 0 ? ` ${n.join(" ")}` : "";
1496
- switch (e.type) {
1497
- case "emphasis": return `<em${a}>${A(e.text || "")}</em>`;
1498
- case "strong": return `<strong${a}>${A(e.text || "")}</strong>`;
1499
- case "code": return `<code${a}>${A(e.text || "")}</code>`;
1500
- case "link": return `<a href="${A(e.url || "")}"${a}>${A(e.text || "")}</a>`;
1501
- default: return `<span${a}>${A(e.text || "")}</span>`;
1898
+ for (const [subjectIRI, removeQuads] of removeBySubject) {
1899
+ const shortSubject = getCachedShortIRI(subjectIRI, context);
1900
+ const displayName = extractLocalName(subjectIRI, context);
1901
+ textParts.push(`# ${displayName} {=${shortSubject}}\n`);
1902
+ for (const quad of removeQuads) textParts.push(generateRetractionText(quad, context));
1903
+ textParts.push("\n");
1502
1904
  }
1503
- }
1504
- function lt(e, t) {
1505
- ut(e, t.sourceText).forEach((e) => {
1506
- dt(e, t);
1507
- });
1508
- }
1509
- function ut(e, t) {
1510
- let n = [], r = null, i = e.sort((e, t) => (e.range?.start || 0) - (t.range?.start || 0));
1511
- for (let e of i) ge(e, t) === 0 ? (r && n.push(r), r = {
1512
- contextName: "Items",
1513
- blocks: [e]
1514
- }) : r ? r.blocks.push(e) : r = {
1515
- contextName: "Items",
1516
- blocks: [e]
1905
+ return {
1906
+ text: textParts.join(""),
1907
+ compactStats
1517
1908
  };
1518
- return r && n.push(r), n;
1519
- }
1520
- function dt(e, t) {
1521
- t.output.push("<ul>");
1522
- for (let n of e.blocks) ft(n, t);
1523
- t.output.push("</ul>");
1524
1909
  }
1525
- function ft(e, t) {
1526
- let n = Qe(e, t), r = q(e, t);
1527
- t.output.push(`<li${n}>${r}</li>`);
1528
- }
1529
- function pt(e) {
1530
- let t = [];
1531
- for (let [n, r] of Object.entries(e)) n !== "@vocab" && t.push(`${n}: ${r}`);
1532
- return t.length > 0 ? ` prefix="${t.join(" ")}"` : "";
1533
- }
1534
- function mt(e) {
1535
- return e["@vocab"] ? ` vocab="${e["@vocab"]}"` : "";
1536
- }
1537
- function ht(e, t) {
1538
- return `<div${pt(t)}${mt(t)}>${e}</div>`;
1539
- }
1540
- function gt(e) {
1541
- return _t(`${e.type || e.carrierType}|${e.subject || ""}|${e.text || ""}`);
1542
- }
1543
- function _t(e) {
1544
- let t = 0;
1545
- for (let n = 0; n < e.length; n++) {
1546
- let r = e.charCodeAt(n);
1547
- t = (t << 5) - t + r, t &= t;
1548
- }
1549
- return t.toString(36);
1910
+ function buildLabelLookup(subjectGroups) {
1911
+ const labelLookup = /* @__PURE__ */ new Map();
1912
+ for (const subjectQuads of subjectGroups.values()) for (const quad of subjectQuads) if (quad.predicate.value === "http://www.w3.org/2000/01/rdf-schema#label" && quad.object.termType === "Literal") labelLookup.set(quad.subject.value, quad.object.value);
1913
+ return labelLookup;
1550
1914
  }
1551
1915
  //#endregion
1552
1916
  //#region src/highlight.js
1553
- function J(e) {
1554
- return String(e).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
1555
- }
1556
- var Y = {
1917
+ /**
1918
+ * MD-LD Syntax Highlighter
1919
+ *
1920
+ * A performant, token-based syntax highlighter for MD-LD (Markdown Linked Data).
1921
+ * Uses simple string operations rather than complex grammars for reliability
1922
+ * and maintainability.
1923
+ *
1924
+ * Features:
1925
+ * - Token-based parsing with string operations
1926
+ * - Markdown formatting support with semantic distinction
1927
+ * - Lookahead detection for legal value carriers
1928
+ * - Orange semantic markers vs default markdown spans
1929
+ * - Annotation, value carrier, and heading highlighting
1930
+ */
1931
+ function escapeHtml(s) {
1932
+ return String(s).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
1933
+ }
1934
+ var TOKEN_COLORS = {
1557
1935
  text: "#6b7280",
1558
1936
  marker: "#f97316",
1559
1937
  retraction: "#dc2626",
1560
1938
  value: "#eab308",
1561
1939
  annotation: "#4b5563"
1562
1940
  };
1563
- function X(e, t) {
1564
- let n = t;
1565
- for (; n < e.length && e[n] !== "\n" && e[n] !== "\r";) {
1566
- if (e[n] === "{") return !0;
1567
- n++;
1568
- }
1569
- return !1;
1570
- }
1571
- function vt(e, t) {
1572
- let n = e[t];
1573
- if (n === "*" && t + 1 < e.length && e[t + 1] === "*") {
1574
- let n = e.indexOf("**", t + 2);
1575
- if (n !== -1) {
1576
- let r = e.slice(t + 2, n), i = X(e, n + 2) ? ` style="color: ${Y.marker}"` : "";
1941
+ function hasFollowingAnnotation(code, endPos) {
1942
+ let i = endPos;
1943
+ while (i < code.length && code[i] !== "\n" && code[i] !== "\r") {
1944
+ if (code[i] === "{") return true;
1945
+ i++;
1946
+ }
1947
+ return false;
1948
+ }
1949
+ function processMarkdownFormattingAtPosition(code, startPos) {
1950
+ const char = code[startPos];
1951
+ if (char === "*" && startPos + 1 < code.length && code[startPos + 1] === "*") {
1952
+ const endPos = code.indexOf("**", startPos + 2);
1953
+ if (endPos !== -1) {
1954
+ const content = code.slice(startPos + 2, endPos);
1955
+ const color = hasFollowingAnnotation(code, endPos + 2) ? ` style="color: ${TOKEN_COLORS.marker}"` : "";
1577
1956
  return {
1578
- html: `<span${i}>**</span><strong>${J(r)}</strong><span${i}>**</span>`,
1579
- nextIndex: n + 2
1957
+ html: `<span${color}>**</span><strong>${escapeHtml(content)}</strong><span${color}>**</span>`,
1958
+ nextIndex: endPos + 2
1580
1959
  };
1581
1960
  }
1582
1961
  }
1583
- if (n === "_" && t + 1 < e.length && e[t + 1] === "_") {
1584
- let n = e.indexOf("__", t + 2);
1585
- if (n !== -1) {
1586
- let r = e.slice(t + 2, n), i = X(e, n + 2) ? ` style="color: ${Y.marker}"` : "";
1962
+ if (char === "_" && startPos + 1 < code.length && code[startPos + 1] === "_") {
1963
+ const endPos = code.indexOf("__", startPos + 2);
1964
+ if (endPos !== -1) {
1965
+ const content = code.slice(startPos + 2, endPos);
1966
+ const color = hasFollowingAnnotation(code, endPos + 2) ? ` style="color: ${TOKEN_COLORS.marker}"` : "";
1587
1967
  return {
1588
- html: `<span${i}>__</span><strong>${J(r)}</strong><span${i}>__</span>`,
1589
- nextIndex: n + 2
1968
+ html: `<span${color}>__</span><strong>${escapeHtml(content)}</strong><span${color}>__</span>`,
1969
+ nextIndex: endPos + 2
1590
1970
  };
1591
1971
  }
1592
1972
  }
1593
- if (n === "*") {
1594
- let n = e.indexOf("*", t + 1);
1595
- if (n !== -1) {
1596
- let r = e.slice(t + 1, n), i = X(e, n + 1) ? ` style="color: ${Y.marker}"` : "";
1973
+ if (char === "*") {
1974
+ const endPos = code.indexOf("*", startPos + 1);
1975
+ if (endPos !== -1) {
1976
+ const content = code.slice(startPos + 1, endPos);
1977
+ const color = hasFollowingAnnotation(code, endPos + 1) ? ` style="color: ${TOKEN_COLORS.marker}"` : "";
1597
1978
  return {
1598
- html: `<span${i}>*</span><em>${J(r)}</em><span${i}>*</span>`,
1599
- nextIndex: n + 1
1979
+ html: `<span${color}>*</span><em>${escapeHtml(content)}</em><span${color}>*</span>`,
1980
+ nextIndex: endPos + 1
1600
1981
  };
1601
1982
  }
1602
1983
  }
1603
- if (n === "_") {
1604
- let n = e.indexOf("_", t + 1);
1605
- if (n !== -1) {
1606
- let r = e.slice(t + 1, n), i = X(e, n + 1) ? ` style="color: ${Y.marker}"` : "";
1984
+ if (char === "_") {
1985
+ const endPos = code.indexOf("_", startPos + 1);
1986
+ if (endPos !== -1) {
1987
+ const content = code.slice(startPos + 1, endPos);
1988
+ const color = hasFollowingAnnotation(code, endPos + 1) ? ` style="color: ${TOKEN_COLORS.marker}"` : "";
1607
1989
  return {
1608
- html: `<span${i}>_</span><em>${J(r)}</em><span${i}>_</span>`,
1609
- nextIndex: n + 1
1990
+ html: `<span${color}>_</span><em>${escapeHtml(content)}</em><span${color}>_</span>`,
1991
+ nextIndex: endPos + 1
1610
1992
  };
1611
1993
  }
1612
1994
  }
1613
- if (n === "`") {
1614
- let n = e.indexOf("`", t + 1);
1615
- if (n !== -1) {
1616
- let r = e.slice(t + 1, n), i = X(e, n + 1) ? ` style="color: ${Y.marker}"` : "";
1995
+ if (char === "`") {
1996
+ const endPos = code.indexOf("`", startPos + 1);
1997
+ if (endPos !== -1) {
1998
+ const content = code.slice(startPos + 1, endPos);
1999
+ const color = hasFollowingAnnotation(code, endPos + 1) ? ` style="color: ${TOKEN_COLORS.marker}"` : "";
1617
2000
  return {
1618
- html: `<span${i}>\`</span><code style="background-color:#7773">${J(r)}</code><span${i}>\`</span>`,
1619
- nextIndex: n + 1
2001
+ html: `<span${color}>\`</span><code style="background-color:#7773">${escapeHtml(content)}</code><span${color}>\`</span>`,
2002
+ nextIndex: endPos + 1
1620
2003
  };
1621
2004
  }
1622
2005
  }
1623
2006
  return null;
1624
2007
  }
1625
- var Z = /* @__PURE__ */ new Map();
1626
- function yt(e) {
1627
- let t = 0;
1628
- for (let n = 0; n < e.length; n++) {
1629
- let r = e.charCodeAt(n);
1630
- t = (t << 5) - t + r, t &= t;
1631
- }
1632
- return Math.abs(t);
1633
- }
1634
- function Q(e) {
1635
- if (Z.has(e)) return Z.get(e);
1636
- let t = yt(e), n = `hsl(${t % 360}, ${15 + t % 10}%, ${45 + t % 10}%)`;
1637
- return Z.set(e, n), n;
1638
- }
1639
- function bt(t) {
1640
- let n = /* @__PURE__ */ new Map(), r = /^\[(\w+)\]\s*<([^>]*)>\s*$/gm, i;
1641
- for (; (i = r.exec(t)) !== null;) {
1642
- let e = i[1], t = i[2];
1643
- if (t.includes(":")) {
1644
- let e = t.indexOf(":");
1645
- if (e > 0) {
1646
- let r = t.slice(0, e), i = t.slice(e + 1);
1647
- n.has(r) && (t = n.get(r) + i);
2008
+ var colorCache = /* @__PURE__ */ new Map();
2009
+ function hashIRI(iri) {
2010
+ let hash = 0;
2011
+ for (let i = 0; i < iri.length; i++) {
2012
+ const char = iri.charCodeAt(i);
2013
+ hash = (hash << 5) - hash + char;
2014
+ hash = hash & hash;
2015
+ }
2016
+ return Math.abs(hash);
2017
+ }
2018
+ function getIRIColor(iri) {
2019
+ if (colorCache.has(iri)) return colorCache.get(iri);
2020
+ const hash = hashIRI(iri);
2021
+ const color = `hsl(${hash % 360}, ${15 + hash % 10}%, ${45 + hash % 10}%)`;
2022
+ colorCache.set(iri, color);
2023
+ return color;
2024
+ }
2025
+ function extractPrefixes(code) {
2026
+ const prefixes = /* @__PURE__ */ new Map();
2027
+ const prefixRegex = /^\[(\w+)\]\s*<([^>]*)>\s*$/gm;
2028
+ let match;
2029
+ while ((match = prefixRegex.exec(code)) !== null) {
2030
+ const prefixName = match[1];
2031
+ let iri = match[2];
2032
+ if (iri.includes(":")) {
2033
+ const colonIndex = iri.indexOf(":");
2034
+ if (colonIndex > 0) {
2035
+ const refPrefix = iri.slice(0, colonIndex);
2036
+ const refSuffix = iri.slice(colonIndex + 1);
2037
+ if (prefixes.has(refPrefix)) iri = prefixes.get(refPrefix) + refSuffix;
1648
2038
  }
1649
2039
  }
1650
- n.set(e, t);
1651
- }
1652
- for (let [t, r] of Object.entries(e)) t !== "@vocab" && n.set(t, r);
1653
- return n;
1654
- }
1655
- function $(e, t, n) {
1656
- let r = t ? Y.retraction : Y.text, i = e.indexOf(":");
1657
- if (i > 0) {
1658
- let t = e.slice(0, i), r = e.slice(i + 1);
1659
- if (n.has(t)) {
1660
- let e = n.get(t), i = Q(e), a = e + r, o = Q(a);
1661
- return `<span style="color: ${i}">${J(t)}</span><span style="color: ${Y.marker}">:</span><span data-iri="${a}" style="color: ${o}">${J(r)}</span> `;
2040
+ prefixes.set(prefixName, iri);
2041
+ }
2042
+ for (const [key, iri] of Object.entries(DEFAULT_CONTEXT)) if (key !== "@vocab") prefixes.set(key, iri);
2043
+ return prefixes;
2044
+ }
2045
+ function renderTerm(part, isRetracted, prefixes) {
2046
+ const baseColor = isRetracted ? TOKEN_COLORS.retraction : TOKEN_COLORS.text;
2047
+ const colonIndex = part.indexOf(":");
2048
+ if (colonIndex > 0) {
2049
+ const prefix = part.slice(0, colonIndex);
2050
+ const local = part.slice(colonIndex + 1);
2051
+ if (prefixes.has(prefix)) {
2052
+ const prefixIRI = prefixes.get(prefix);
2053
+ const prefixColor = getIRIColor(prefixIRI);
2054
+ const fullIRI = prefixIRI + local;
2055
+ const localColor = getIRIColor(fullIRI);
2056
+ return `<span style="color: ${prefixColor}">${escapeHtml(prefix)}</span><span style="color: ${TOKEN_COLORS.marker}">:</span><span data-iri="${fullIRI}" style="color: ${localColor}">${escapeHtml(local)}</span> `;
1662
2057
  }
1663
2058
  }
1664
- return e.startsWith("http:") || e.startsWith("https:") || e.startsWith("tag:") || e.startsWith("urn:") ? `<span style="color: ${Q(e)}">${J(e)}</span> ` : `<span style="color: ${r}">${J(e)}</span> `;
1665
- }
1666
- function xt(e, t) {
1667
- let n = e.trim().split(/\s+/), r = "", i = !1;
1668
- for (let e = 0; e < n.length; e++) {
1669
- let a = n[e];
1670
- if (!a) continue;
1671
- if (a.startsWith("=") || a.startsWith("+")) {
1672
- let e = a[0], n = a.slice(1);
1673
- r += `<span style="color: ${Y.marker}">${J(e)}</span>${$(n, !1, t)}`;
2059
+ if (part.startsWith("http:") || part.startsWith("https:") || part.startsWith("tag:") || part.startsWith("urn:")) return `<span style="color: ${getIRIColor(part)}">${escapeHtml(part)}</span> `;
2060
+ return `<span style="color: ${baseColor}">${escapeHtml(part)}</span> `;
2061
+ }
2062
+ function parseAnnotation(content, prefixes) {
2063
+ const parts = content.trim().split(/\s+/);
2064
+ let result = "";
2065
+ let nextTermIsRetracted = false;
2066
+ for (let i = 0; i < parts.length; i++) {
2067
+ const part = parts[i];
2068
+ if (!part) continue;
2069
+ if (part.startsWith("=") || part.startsWith("+")) {
2070
+ const marker = part[0];
2071
+ const rest = part.slice(1);
2072
+ result += `<span style="color: ${TOKEN_COLORS.marker}">${escapeHtml(marker)}</span>${renderTerm(rest, false, prefixes)}`;
1674
2073
  continue;
1675
2074
  }
1676
- if (a === "-") {
1677
- i = !0, r += `<span style="color: ${Y.retraction}">${J(a)}</span> `;
2075
+ if (part === "-") {
2076
+ nextTermIsRetracted = true;
2077
+ result += `<span style="color: ${TOKEN_COLORS.retraction}">${escapeHtml(part)}</span> `;
1678
2078
  continue;
1679
2079
  }
1680
- if (a.startsWith("-") && a.length > 1) {
1681
- r += `<span style="color: ${Y.retraction}">${J(a)}</span> `;
2080
+ if (part.startsWith("-") && part.length > 1) {
2081
+ result += `<span style="color: ${TOKEN_COLORS.retraction}">${escapeHtml(part)}</span> `;
1682
2082
  continue;
1683
2083
  }
1684
- let o = i;
1685
- if (i = !1, a.startsWith("?") || a.startsWith("!")) {
1686
- let e = a[0], n = a.slice(1), i = o ? Y.retraction : Y.marker;
1687
- r += `<span style="color: ${i}">${J(e)}</span>${$(n, o, t)}`;
2084
+ const isRetracted = nextTermIsRetracted;
2085
+ nextTermIsRetracted = false;
2086
+ if (part.startsWith("?") || part.startsWith("!")) {
2087
+ const marker = part[0];
2088
+ const rest = part.slice(1);
2089
+ const color = isRetracted ? TOKEN_COLORS.retraction : TOKEN_COLORS.marker;
2090
+ result += `<span style="color: ${color}">${escapeHtml(marker)}</span>${renderTerm(rest, isRetracted, prefixes)}`;
1688
2091
  continue;
1689
2092
  }
1690
- if (a.startsWith("^^")) {
1691
- let e = a.slice(2), n = o ? Y.retraction : Y.marker;
1692
- r += `<span style="color: ${n}">${J("^^")}</span>${$(e, o, t)}`;
2093
+ if (part.startsWith("^^")) {
2094
+ const marker = "^^";
2095
+ const rest = part.slice(2);
2096
+ const color = isRetracted ? TOKEN_COLORS.retraction : TOKEN_COLORS.marker;
2097
+ result += `<span style="color: ${color}">${escapeHtml(marker)}</span>${renderTerm(rest, isRetracted, prefixes)}`;
1693
2098
  continue;
1694
2099
  }
1695
- if (a.startsWith("@")) {
1696
- let e = a.slice(1), n = o ? Y.retraction : Y.marker;
1697
- r += `<span style="color: ${n}">${J("@")}</span>${$(e, o, t)}`;
2100
+ if (part.startsWith("@")) {
2101
+ const marker = "@";
2102
+ const rest = part.slice(1);
2103
+ const color = isRetracted ? TOKEN_COLORS.retraction : TOKEN_COLORS.marker;
2104
+ result += `<span style="color: ${color}">${escapeHtml(marker)}</span>${renderTerm(rest, isRetracted, prefixes)}`;
1698
2105
  continue;
1699
2106
  }
1700
- if (a.startsWith(".")) {
1701
- let e = a.slice(1), n = o ? Y.retraction : Y.marker;
1702
- r += `<span style="color: ${n}">${J(".")}</span>${$(e, o, t)}`;
2107
+ if (part.startsWith(".")) {
2108
+ const marker = ".";
2109
+ const rest = part.slice(1);
2110
+ const color = isRetracted ? TOKEN_COLORS.retraction : TOKEN_COLORS.marker;
2111
+ result += `<span style="color: ${color}">${escapeHtml(marker)}</span>${renderTerm(rest, isRetracted, prefixes)}`;
1703
2112
  continue;
1704
2113
  }
1705
- r += $(a, o, t);
1706
- }
1707
- return r.trim();
1708
- }
1709
- function St(e) {
1710
- let t = bt(e), n = "", r = 0;
1711
- for (; r < e.length;) {
1712
- let i = e[r];
1713
- if (i === "{") {
1714
- let a = e.indexOf("}", r);
1715
- if (a === -1) {
1716
- n += J(i), r++;
2114
+ result += renderTerm(part, isRetracted, prefixes);
2115
+ }
2116
+ return result.trim();
2117
+ }
2118
+ function highlightMDLD(code) {
2119
+ const prefixes = extractPrefixes(code);
2120
+ let result = "";
2121
+ let i = 0;
2122
+ while (i < code.length) {
2123
+ const char = code[i];
2124
+ if (char === "{") {
2125
+ const endIdx = code.indexOf("}", i);
2126
+ if (endIdx === -1) {
2127
+ result += escapeHtml(char);
2128
+ i++;
1717
2129
  continue;
1718
2130
  }
1719
- let o = xt(e.slice(r + 1, a), t);
1720
- n += `<span style="color: ${Y.annotation}; opacity: 0.75">{</span>`, n += o, n += `<span style="color: ${Y.annotation}; opacity: 0.75">}</span>`, r = a + 1;
2131
+ const parsed = parseAnnotation(code.slice(i + 1, endIdx), prefixes);
2132
+ result += `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">{</span>`;
2133
+ result += parsed;
2134
+ result += `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">}</span>`;
2135
+ i = endIdx + 1;
1721
2136
  continue;
1722
2137
  }
1723
- if (i === "[") {
1724
- let a = e.indexOf("]", r);
1725
- if (a === -1) {
1726
- n += J(i), r++;
2138
+ if (char === "[") {
2139
+ const endBracket = code.indexOf("]", i);
2140
+ if (endBracket === -1) {
2141
+ result += escapeHtml(char);
2142
+ i++;
1727
2143
  continue;
1728
2144
  }
1729
- let o = e.slice(r + 1, a), s = a + 1;
1730
- for (; s < e.length && /\s/.test(e[s]);) s++;
1731
- if (s < e.length && e[s] === "<") {
1732
- let i = e.indexOf(">", s);
1733
- if (i !== -1) {
1734
- let a = e.slice(s + 1, i), c = t.has(o) ? Q(t.get(o)) : Y.text;
1735
- n += `<span style="color: ${Y.annotation}; opacity: 0.75">[</span><span style="color: ${c}">${J(o)}</span><span style="color: ${Y.annotation}; opacity: 0.75">]</span> <span style="color: ${Y.text}; opacity: 0.6">&lt;${J(a)}&gt;</span>`, r = i + 1;
2145
+ const prefixName = code.slice(i + 1, endBracket);
2146
+ let j = endBracket + 1;
2147
+ while (j < code.length && /\s/.test(code[j])) j++;
2148
+ if (j < code.length && code[j] === "<") {
2149
+ const iriEnd = code.indexOf(">", j);
2150
+ if (iriEnd !== -1) {
2151
+ const iriContent = code.slice(j + 1, iriEnd);
2152
+ const prefixColor = prefixes.has(prefixName) ? getIRIColor(prefixes.get(prefixName)) : TOKEN_COLORS.text;
2153
+ result += `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">[</span><span style="color: ${prefixColor}">${escapeHtml(prefixName)}</span><span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">]</span> <span style="color: ${TOKEN_COLORS.text}; opacity: 0.6">&lt;${escapeHtml(iriContent)}&gt;</span>`;
2154
+ i = iriEnd + 1;
1736
2155
  continue;
1737
2156
  }
1738
2157
  }
1739
- let c = e.slice(r + 1, a), l = X(e, a + 1) ? Y.marker : Y.value, u = J(c);
1740
- n += `<span style="color: ${l}; opacity: 0.85">[</span><span style=" opacity: 1.0">${u}</span><span style="color: ${l}; opacity: 0.85">]</span>`, r = a + 1;
2158
+ const content = code.slice(i + 1, endBracket);
2159
+ const bracketColor = hasFollowingAnnotation(code, endBracket + 1) ? TOKEN_COLORS.marker : TOKEN_COLORS.value;
2160
+ const escapedContent = escapeHtml(content);
2161
+ result += `<span style="color: ${bracketColor}; opacity: 0.85">[</span><span style=" opacity: 1.0">${escapedContent}</span><span style="color: ${bracketColor}; opacity: 0.85">]</span>`;
2162
+ i = endBracket + 1;
1741
2163
  continue;
1742
2164
  }
1743
- if (i === "*" || i === "_" || i === "`") {
1744
- let t = vt(e, r);
1745
- if (t) {
1746
- n += t.html, r = t.nextIndex;
2165
+ if (char === "*" || char === "_" || char === "`") {
2166
+ const processed = processMarkdownFormattingAtPosition(code, i);
2167
+ if (processed) {
2168
+ result += processed.html;
2169
+ i = processed.nextIndex;
1747
2170
  continue;
1748
2171
  }
1749
2172
  }
1750
- if (i === "#") {
1751
- let i = 0, a = r;
1752
- for (; a < e.length && e[a] === "#";) i++, a++;
1753
- if (i <= 6 && (a >= e.length || e[a] === " " || e[a] === " ")) {
1754
- let o = e.indexOf("\n", a), s = o === -1 ? e.length : o, c = e.slice(a, s).trim(), l = "", u = 0, d = c.indexOf("{");
1755
- for (; d !== -1;) {
1756
- let e = c.indexOf("}", d);
1757
- if (e === -1) break;
1758
- let n = c.slice(u, d);
1759
- l += J(n);
1760
- let r = xt(c.slice(d + 1, e), t);
1761
- l += `<span style="color: ${Y.annotation}; opacity: 0.75">{</span>` + r + `<span style="color: ${Y.annotation}; opacity: 0.75">}</span>`, u = e + 1, d = c.indexOf("{", u);
2173
+ if (char === "#") {
2174
+ let hashCount = 0;
2175
+ let j = i;
2176
+ while (j < code.length && code[j] === "#") {
2177
+ hashCount++;
2178
+ j++;
2179
+ }
2180
+ if (hashCount <= 6 && (j >= code.length || code[j] === " " || code[j] === " ")) {
2181
+ const lineEnd = code.indexOf("\n", j);
2182
+ const endIdx = lineEnd === -1 ? code.length : lineEnd;
2183
+ const headerText = code.slice(j, endIdx).trim();
2184
+ let processedHeaderText = "";
2185
+ let lastIndex = 0;
2186
+ let annotationStart = headerText.indexOf("{");
2187
+ while (annotationStart !== -1) {
2188
+ const annotationEnd = headerText.indexOf("}", annotationStart);
2189
+ if (annotationEnd === -1) break;
2190
+ const beforeText = headerText.slice(lastIndex, annotationStart);
2191
+ processedHeaderText += escapeHtml(beforeText);
2192
+ const parsedAnnotation = parseAnnotation(headerText.slice(annotationStart + 1, annotationEnd), prefixes);
2193
+ processedHeaderText += `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">{</span>` + parsedAnnotation + `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">}</span>`;
2194
+ lastIndex = annotationEnd + 1;
2195
+ annotationStart = headerText.indexOf("{", lastIndex);
1762
2196
  }
1763
- l += J(c.slice(u));
1764
- let f = c.includes("{") && c.includes("}"), p = `h${i}`, m = "#".repeat(i), h = f ? `color: ${Y.marker}; opacity: 0.8` : "";
1765
- n += `<${p} style="margin: 0; font-weight: 600;"><span style="${h}">${m}</span> ${l}</${p}>`, r = s;
2197
+ processedHeaderText += escapeHtml(headerText.slice(lastIndex));
2198
+ const hasAnnotation = headerText.includes("{") && headerText.includes("}");
2199
+ const headingTag = `h${hashCount}`;
2200
+ const headingStyle = `margin: 0; font-weight: 600;`;
2201
+ const hashes = "#".repeat(hashCount);
2202
+ const hashColor = hasAnnotation ? `color: ${TOKEN_COLORS.marker}; opacity: 0.8` : "";
2203
+ result += `<${headingTag} style="${headingStyle}"><span style="${hashColor}">${hashes}</span> ${processedHeaderText}</${headingTag}>`;
2204
+ i = endIdx;
1766
2205
  continue;
1767
2206
  }
1768
2207
  }
1769
- if (i === "-" || i === "*") {
1770
- let t = r > 0 ? e[r - 1] : "\n";
1771
- if ((t === "\n" || t === "\r" || t === " " || t === " ") && e[r + 1] === " ") {
1772
- let t = X(e, r + 2) ? `color: ${Y.marker}; opacity: 0.85` : "";
1773
- n += `<span style="${t}">${J(i)}</span>`, r++;
1774
- continue;
2208
+ if (char === "-" || char === "*") {
2209
+ const prevChar = i > 0 ? code[i - 1] : "\n";
2210
+ if (prevChar === "\n" || prevChar === "\r" || prevChar === " " || prevChar === " ") {
2211
+ if (code[i + 1] === " ") {
2212
+ const markerColor = hasFollowingAnnotation(code, i + 2) ? `color: ${TOKEN_COLORS.marker}; opacity: 0.85` : "";
2213
+ result += `<span style="${markerColor}">${escapeHtml(char)}</span>`;
2214
+ i++;
2215
+ continue;
2216
+ }
1775
2217
  }
1776
2218
  }
1777
- if (i === ">") {
1778
- let t = r > 0 ? e[r - 1] : "\n";
1779
- if ((t === "\n" || t === "\r" || t === " " || t === " ") && e[r + 1] === " ") {
1780
- let t = X(e, r + 2) ? `color: ${Y.marker}; opacity: 0.85` : "";
1781
- n += `<span style="${t}">${J(i)}</span>`, r++;
1782
- continue;
2219
+ if (char === ">") {
2220
+ const prevChar = i > 0 ? code[i - 1] : "\n";
2221
+ if (prevChar === "\n" || prevChar === "\r" || prevChar === " " || prevChar === " ") {
2222
+ if (code[i + 1] === " ") {
2223
+ const markerColor = hasFollowingAnnotation(code, i + 2) ? `color: ${TOKEN_COLORS.marker}; opacity: 0.85` : "";
2224
+ result += `<span style="${markerColor}">${escapeHtml(char)}</span>`;
2225
+ i++;
2226
+ continue;
2227
+ }
1783
2228
  }
1784
2229
  }
1785
- n += J(i), r++;
2230
+ result += escapeHtml(char);
2231
+ i++;
1786
2232
  }
1787
- return n;
2233
+ return result;
1788
2234
  }
1789
2235
  //#endregion
1790
2236
  //#region src/index.js
1791
- function Ct({ text: e, quad: t, value: n, origin: r }) {
1792
- let i = f(t, r?.quadIndex ? r : I({ text: e }).origin);
1793
- return !i || !i.valueRange ? e : e.substring(0, i.valueRange.start) + n + e.substring(i.valueRange.end);
2237
+ /**
2238
+ * Update the value of a quad in MDLD text and return the updated text
2239
+ *
2240
+ * @param {Object} params - Parameters object
2241
+ * @param {string} params.text - The original MDLD text
2242
+ * @param {Object} params.quad - The quad to update (subject, predicate, object)
2243
+ * @param {string} params.value - The new value to set
2244
+ * @param {Object} [params.origin] - Origin object or ParseResult (if not provided, text will be parsed)
2245
+ * @returns {string} Updated MDLD text, or original if update fails
2246
+ */
2247
+ function updateValue({ text, quad, value, origin }) {
2248
+ const location = locate(quad, origin?.quadIndex ? origin : parse({ text }).origin);
2249
+ if (!location || !location.valueRange) return text;
2250
+ return text.substring(0, location.valueRange.start) + value + text.substring(location.valueRange.end);
1794
2251
  }
1795
2252
  //#endregion
1796
- export { e as DEFAULT_CONTEXT, d as DataFactory, h as expandIRI, Ve as generate, He as generateNode, Q as getIRIColor, p as hash, yt as hashIRI, St as highlightMDLD, f as locate, ze as merge, I as parse, _ as parseSemanticBlock, Je as render, g as shortenIRI, Ct as updateValue };
2253
+ export { DEFAULT_CONTEXT, DataFactory, expandIRI, generate, generateNode, getIRIColor, hash, hashIRI, highlightMDLD, locate, merge, parse, parseSemanticBlock, shortenIRI, updateValue };