mdld-parse 0.9.9 → 1.0.1

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 +263 -326
  2. package/dist/index.js +1860 -1337
  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 = "";
80
+ super("");
81
+ this.termType = "DefaultGraph";
82
+ this.value = "";
40
83
  }
41
- equals(e) {
42
- return !!e && this.termType === e.termType;
84
+ equals(other) {
85
+ return !!other && this.termType === other.termType;
43
86
  }
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;
47
- }
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}`);
132
+ }
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
+ }
86
141
  }
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}`);
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,444 +405,655 @@ 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;
456
+ return {
457
+ fenceChar: char,
458
+ fenceLength: count,
459
+ lang,
460
+ attrs,
461
+ infoString
462
+ };
463
+ }
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;
314
481
  return {
315
- fenceChar: t,
316
- fenceLength: n,
317
- lang: a,
318
- attrs: s,
319
- infoString: r
482
+ prefix,
483
+ iri
320
484
  };
321
485
  }
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
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
351
509
  };
352
510
  }
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;
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
374
545
  };
375
546
  }
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
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
384
566
  };
385
567
  }
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
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
411
618
  };
412
619
  }
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++;
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
635
+ };
636
+ }
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(),
717
1053
  origin: {
718
1054
  quadIndex: /* @__PURE__ */ new Map(),
719
1055
  blocks: /* @__PURE__ */ new Map(),
1056
+ spans: /* @__PURE__ */ new Map(),
720
1057
  documentStructure: []
721
1058
  },
722
1059
  currentSubject: null,
@@ -728,1069 +1065,1255 @@ function I(t, n = {}) {
728
1065
  statements: [],
729
1066
  statementCandidates: /* @__PURE__ */ new Map(),
730
1067
  currentBlock: null,
731
- 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
+ blockStack: [],
1069
+ lastBlockEnd: 0,
1070
+ lastBlockId: null,
1071
+ lastSpanId: null
1072
+ };
1073
+ const scanResult = scanTokens(text);
1074
+ state.tokens = scanResult.tokens;
1075
+ for (let i = 0; i < state.tokens.length; i++) {
1076
+ const token = state.tokens[i];
1077
+ state.currentTokenIndex = i;
1078
+ if (token.type === "prefix") {
1079
+ let resolvedIri = token.iri;
1080
+ if (token.iri.includes(":")) {
1081
+ const colonIndex = token.iri.indexOf(":");
1082
+ const potentialPrefix = token.iri.substring(0, colonIndex);
1083
+ const reference = token.iri.substring(colonIndex + 1);
1084
+ if (state.ctx[potentialPrefix] && potentialPrefix !== "@vocab") resolvedIri = state.ctx[potentialPrefix] + reference;
741
1085
  }
742
- o.ctx[t.prefix] = e;
1086
+ state.ctx[token.prefix] = resolvedIri;
743
1087
  continue;
744
1088
  }
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
1089
+ TOKEN_PROCESSORS[token.type]?.(token, state);
1090
+ }
1091
+ const quadKeys = /* @__PURE__ */ new Set();
1092
+ for (const quad of state.quads) quadKeys.add(quadIndexKey(quad.subject, quad.predicate, quad.object));
1093
+ const filteredRemove = [];
1094
+ for (const quad of state.removeSet) {
1095
+ const key = quadIndexKey(quad.subject, quad.predicate, quad.object);
1096
+ if (!quadKeys.has(key)) filteredRemove.push(quad);
1097
+ }
1098
+ const primary = {
1099
+ subject: state.primarySubject,
1100
+ type: state.primaryType,
1101
+ label: state.primaryLabel,
1102
+ comment: state.primaryComment
759
1103
  };
760
1104
  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
1105
+ quads: state.quads,
1106
+ remove: filteredRemove,
1107
+ statements: state.statements,
1108
+ origin: state.origin,
1109
+ context: state.ctx,
1110
+ primarySubject: state.primarySubject,
1111
+ primary,
1112
+ md: scanResult.md
769
1113
  };
770
1114
  }
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 = [
1115
+ function getCarriers(token) {
1116
+ if (token.type === "code") return [];
1117
+ return token._carriers || (token._carriers = extractInlineCarriers(token.text, token.range[0]));
1118
+ }
1119
+ function scanTokens(text) {
1120
+ const tokens = [];
1121
+ const mdLines = [];
1122
+ const lines = text.split("\n");
1123
+ let pos = 0;
1124
+ let codeBlock = null;
1125
+ const PROCESSORS = [
776
1126
  {
777
1127
  type: "fence",
778
- test: (e) => re(e.trim()),
779
- process: s
1128
+ test: (line) => detectFence(line.trim()),
1129
+ process: handleFence
780
1130
  },
781
1131
  {
782
1132
  type: "content",
783
- test: () => a,
784
- process: (e) => a.content.push(e)
1133
+ test: () => codeBlock,
1134
+ process: (line) => codeBlock.content.push(line)
785
1135
  },
786
1136
  {
787
1137
  type: "prefix",
788
- test: (e) => ie(e),
789
- process: c
1138
+ test: (line) => detectPrefix(line),
1139
+ process: handlePrefix
790
1140
  },
791
1141
  {
792
1142
  type: "standalone",
793
- test: (e) => se(e),
794
- process: p
1143
+ test: (line) => detectStandaloneSubject(line),
1144
+ process: handleStandaloneSubject
795
1145
  },
796
1146
  {
797
1147
  type: "heading",
798
- test: (e) => ae(e),
799
- process: l
1148
+ test: (line) => detectHeading(line),
1149
+ process: handleHeading
800
1150
  },
801
1151
  {
802
1152
  type: "list",
803
- test: (e) => y(e),
804
- process: u
1153
+ test: (line) => detectList(line),
1154
+ process: handleList
805
1155
  },
806
1156
  {
807
1157
  type: "blockquote",
808
- test: (e) => oe(e),
809
- process: d
1158
+ test: (line) => detectBlockquote(line),
1159
+ process: handleBlockquote
810
1160
  },
811
1161
  {
812
1162
  type: "para",
813
- test: (e) => e.trim(),
814
- process: f
1163
+ test: (line) => line.trim(),
1164
+ process: handlePara
815
1165
  }
816
1166
  ];
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({
1167
+ function handleFence(line, lineStart, pos) {
1168
+ const trimmedLine = line.trim();
1169
+ if (!codeBlock) {
1170
+ const fenceResult = detectFence(trimmedLine);
1171
+ if (!fenceResult) return false;
1172
+ const attrsText = fenceResult.attrs;
1173
+ const attrsStartInLine = attrsText ? line.indexOf(attrsText) : -1;
1174
+ const contentStart = lineStart + line.length + 1;
1175
+ codeBlock = {
1176
+ fence: fenceResult.fenceChar.repeat(fenceResult.fenceLength),
1177
+ start: lineStart,
1178
+ content: [],
1179
+ lang: fenceResult.lang,
1180
+ attrs: attrsText,
1181
+ attrsRange: attrsText && attrsStartInLine >= 0 ? [lineStart + attrsStartInLine, lineStart + attrsStartInLine + attrsText.length] : null,
1182
+ valueRangeStart: contentStart
1183
+ };
1184
+ const cleanFence = line.replace(/\s*\{[^}]+\}\s*$/, "");
1185
+ mdLines.push(cleanFence);
1186
+ } else {
1187
+ const fenceChar = codeBlock.fence[0];
1188
+ const expectedFence = fenceChar.repeat(codeBlock.fence.length);
1189
+ const fenceMatch = trimmedLine.match(getFenceClosePattern(fenceChar));
1190
+ if (fenceMatch && fenceMatch[1] === expectedFence) {
1191
+ const valueStart = codeBlock.valueRangeStart;
1192
+ const valueEnd = Math.max(valueStart, lineStart - 1);
1193
+ tokens.push({
824
1194
  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]
1195
+ range: [codeBlock.start, lineStart],
1196
+ text: codeBlock.content.join("\n"),
1197
+ lang: codeBlock.lang,
1198
+ attrs: codeBlock.attrs,
1199
+ attrsRange: codeBlock.attrsRange,
1200
+ valueRange: [valueStart, valueEnd]
831
1201
  });
832
- for (let e of a.content) n.push(e);
833
- a = null;
834
- let s = e.replace(/\r?\n.*$/, "");
835
- n.push(s);
1202
+ for (const contentLine of codeBlock.content) mdLines.push(contentLine);
1203
+ codeBlock = null;
1204
+ const closingFence = line.replace(/\r?\n.*$/, "");
1205
+ mdLines.push(closingFence);
836
1206
  }
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
1207
  }
853
- return !0;
1208
+ return true;
854
1209
  }
855
- function c(e, n, r) {
856
- let i = ie(e);
857
- return t.push({
1210
+ function handlePrefix(line, lineStart, pos) {
1211
+ const result = detectPrefix(line);
1212
+ tokens.push({
858
1213
  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
1214
+ prefix: result.prefix,
1215
+ iri: result.iri
1216
+ });
1217
+ return true;
1218
+ }
1219
+ function handleHeading(line, lineStart, pos) {
1220
+ const result = detectHeading(line);
1221
+ const attrs = result.attrs;
1222
+ const afterHashes = result.depth;
1223
+ const rangeInfo = calcRangeInfo(line, attrs, lineStart, afterHashes, result.content.length);
1224
+ tokens.push(createToken("heading", [lineStart, pos - 1], result.content, attrs, rangeInfo.attrsRange, rangeInfo.valueRange, { depth: result.depth }));
1225
+ const cleanHeading = `${"#".repeat(result.depth)} ${result.content}`;
1226
+ mdLines.push(cleanHeading);
1227
+ return true;
1228
+ }
1229
+ function handleList(line, lineStart, pos) {
1230
+ const result = detectList(line);
1231
+ const indentStr = " ".repeat(result.indent);
1232
+ const match = [
1233
+ line,
1234
+ indentStr,
1235
+ result.marker,
1236
+ result.content,
1237
+ result.attrs
876
1238
  ];
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;
1239
+ tokens.push(createListToken("list", line, lineStart, pos, match));
1240
+ const cleanList = `${indentStr}${result.marker} ${result.content}`;
1241
+ mdLines.push(cleanList);
1242
+ return true;
1243
+ }
1244
+ function handleBlockquote(line, lineStart, pos) {
1245
+ const result = detectBlockquote(line);
1246
+ const attrs = result.attrs;
1247
+ const valueStartInLine = line.startsWith("> ") ? 2 : line.indexOf(">") + 1;
1248
+ const valueEndInLine = valueStartInLine + result.content.length;
1249
+ tokens.push(createToken("blockquote", [lineStart, pos - 1], result.content, attrs, calcAttrsRange(line, attrs, lineStart), [lineStart + valueStartInLine, lineStart + valueEndInLine]));
1250
+ const cleanBlockquote = `> ${result.content}`;
1251
+ mdLines.push(cleanBlockquote);
1252
+ return true;
1253
+ }
1254
+ function handlePara(line, lineStart, pos) {
1255
+ tokens.push(createToken("para", [lineStart, pos - 1], line.trim()));
1256
+ let cleanPara = line;
1257
+ const carriers = scanInlineCarriers(cleanPara, 0);
1258
+ for (const carrier of carriers) if (carrier.attrs && (carrier.type === "emphasis" || carrier.type === "code")) {
1259
+ const before = cleanPara.substring(0, carrier.range[0]);
1260
+ const after = cleanPara.substring(carrier.range[1]);
1261
+ cleanPara = before + (carrier.text || "") + after;
893
1262
  }
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({
1263
+ cleanPara = cleanPara.replace(/\[([^\]]+)\]\s*\{[^}]+\}/g, "$1");
1264
+ cleanPara = cleanPara.replace(/\s*\{[^}]+\}\s*/g, " ");
1265
+ cleanPara = cleanPara.replace(/\s+/g, " ").trim();
1266
+ mdLines.push(cleanPara);
1267
+ return true;
1268
+ }
1269
+ function handleStandaloneSubject(line, lineStart, pos) {
1270
+ tokens.push({
898
1271
  type: "standalone",
899
- text: e.trim(),
900
- range: [n, r - 1]
901
- }), !0;
1272
+ text: line.trim(),
1273
+ range: [lineStart, pos - 1]
1274
+ });
1275
+ return true;
902
1276
  }
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;
1277
+ for (let i = 0; i < lines.length; i++) {
1278
+ const line = lines[i];
1279
+ const lineStart = pos;
1280
+ pos += line.length + 1;
1281
+ for (const processor of PROCESSORS) if (processor.test(line) && processor.process(line, lineStart, pos)) break;
907
1282
  }
908
1283
  return {
909
- tokens: t,
910
- md: n.join("\n")
1284
+ tokens,
1285
+ md: mdLines.join("\n")
911
1286
  };
912
1287
  }
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,
1288
+ function extractInlineCarriers(text, baseOffset = 0) {
1289
+ return scanInlineCarriers(text, baseOffset);
1290
+ }
1291
+ function createBlockEntry(token, state) {
1292
+ const blockId = token._blockId || hash(`${token.type}:${token.range?.[0]}:${token.range?.[1]}`);
1293
+ token._blockId = blockId;
1294
+ const carriers = getCarriers(token);
1295
+ const cleanText = extractCleanText(token);
1296
+ const blockStart = token.range[0];
1297
+ const blockEnd = token.range[1];
1298
+ let prevSpanId = null;
1299
+ if (state.lastBlockId !== null) {
1300
+ const spanStart = state.lastBlockEnd;
1301
+ const spanEnd = blockStart;
1302
+ if (spanEnd > spanStart) {
1303
+ const spanId = hash(`span:${spanStart}:${spanEnd}`);
1304
+ const span = {
1305
+ id: spanId,
1306
+ range: [spanStart, spanEnd],
1307
+ prevBlockId: state.lastBlockId,
1308
+ nextBlockId: blockId,
1309
+ prevSpanId: state.lastSpanId || null,
1310
+ nextSpanId: null,
1311
+ byteLength: spanEnd - spanStart
1312
+ };
1313
+ state.origin.spans.set(spanId, span);
1314
+ if (state.lastSpanId) {
1315
+ const prevSpan = state.origin.spans.get(state.lastSpanId);
1316
+ if (prevSpan) prevSpan.nextSpanId = spanId;
1317
+ }
1318
+ const prevBlock = state.origin.blocks.get(state.lastBlockId);
1319
+ if (prevBlock) prevBlock.nextSpanId = spanId;
1320
+ state.lastSpanId = spanId;
1321
+ prevSpanId = spanId;
1322
+ }
1323
+ }
1324
+ state.lastBlockEnd = blockEnd;
1325
+ state.lastBlockId = blockId;
1326
+ const blockEntry = {
1327
+ id: blockId,
1328
+ type: token.type,
1329
+ range: token.range,
1330
+ text: cleanText,
924
1331
  subject: null,
925
1332
  types: [],
926
1333
  predicates: [],
927
1334
  carriers: [],
928
- listLevel: e.indent || 0,
929
- parentBlockId: t.blockStack.length > 0 ? t.blockStack[t.blockStack.length - 1] : null,
930
- quadKeys: []
1335
+ listLevel: token.indent || 0,
1336
+ parentBlockId: state.blockStack.length > 0 ? state.blockStack[state.blockStack.length - 1] : null,
1337
+ quadKeys: [],
1338
+ prevSpanId,
1339
+ nextSpanId: null
931
1340
  };
932
- for (let e of r) {
933
- let t = {
934
- type: e.type,
935
- range: e.range,
936
- text: e.text,
1341
+ for (const carrier of carriers) {
1342
+ const carrierInfo = {
1343
+ type: carrier.type,
1344
+ range: carrier.range,
1345
+ text: carrier.text,
937
1346
  subject: null,
938
1347
  predicates: [],
939
1348
  sem: null
940
1349
  };
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 || [];
1350
+ if (carrier.attrs) {
1351
+ const carrierSem = parseSemCached(carrier.attrs);
1352
+ carrierInfo.sem = carrierSem;
1353
+ carrierInfo.predicates = carrierSem.predicates || [];
1354
+ carrierInfo.subject = carrierSem.subject;
1355
+ carrierInfo.types = carrierSem.types || [];
944
1356
  }
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 || "",
1357
+ blockEntry.carriers.push(carrierInfo);
1358
+ }
1359
+ state.origin.blocks.set(blockId, blockEntry);
1360
+ state.origin.documentStructure.push(blockEntry);
1361
+ return blockEntry;
1362
+ }
1363
+ function enrichBlockFromAnnotation(blockEntry, sem, carrier, state) {
1364
+ if (sem.subject && sem.subject !== "RESET") {
1365
+ const resolvedSubject = resolveSubject(sem, state);
1366
+ if (resolvedSubject) blockEntry.subject = resolvedSubject.value;
1367
+ }
1368
+ if (sem.types && sem.types.length > 0) sem.types.forEach((t) => {
1369
+ const expanded = expandIRI(typeof t === "string" ? t : t.iri, state.ctx);
1370
+ if (!blockEntry.types.includes(expanded)) blockEntry.types.push(expanded);
1371
+ });
1372
+ if (sem.predicates && sem.predicates.length > 0) sem.predicates.forEach((pred) => {
1373
+ const expandedPred = {
1374
+ iri: expandIRI(pred.iri, state.ctx),
1375
+ form: pred.form || "",
961
1376
  object: null
962
1377
  };
963
- e.predicates.push(n);
964
- }), n) {
965
- let t = {
966
- type: n.type,
967
- range: n.range,
968
- text: n.text,
1378
+ blockEntry.predicates.push(expandedPred);
1379
+ });
1380
+ if (carrier) {
1381
+ const carrierInfo = {
1382
+ type: carrier.type,
1383
+ range: carrier.range,
1384
+ text: carrier.text,
969
1385
  subject: null,
970
1386
  predicates: []
971
1387
  };
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 || [];
1388
+ if (carrier.attrs) {
1389
+ const carrierSem = parseSemCached(carrier.attrs);
1390
+ carrierInfo.sem = carrierSem;
1391
+ carrierInfo.predicates = carrierSem.predicates || [];
1392
+ carrierInfo.subject = carrierSem.subject;
1393
+ carrierInfo.types = carrierSem.types || [];
975
1394
  }
976
- e.carriers.push(t);
1395
+ blockEntry.carriers.push(carrierInfo);
977
1396
  }
978
1397
  }
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;
1398
+ function processAnnotationWithBlockTracking(carrier, sem, state, options = {}) {
1399
+ const { preserveGlobalSubject = false, implicitSubject = null } = options;
1400
+ if (sem.subject === "RESET") {
1401
+ state.currentSubject = null;
983
1402
  return;
984
1403
  }
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
1404
+ const previousSubject = state.currentSubject;
1405
+ const newSubject = resolveSubject(sem, state);
1406
+ const localObject = resolveObject(sem, state);
1407
+ if (newSubject && !state.primarySubject && !sem.subject.startsWith("=#")) state.primarySubject = newSubject.value;
1408
+ if (newSubject && !preserveGlobalSubject && !implicitSubject) state.currentSubject = newSubject;
1409
+ const S = preserveGlobalSubject ? newSubject || previousSubject : implicitSubject || state.currentSubject;
1410
+ if (!S) return;
1411
+ const block = createBlock(S.value, sem.types, sem.predicates, carrier.range, carrier.attrsRange || null, carrier.valueRange || null, carrier.type || null, state.ctx, carrier.text);
1412
+ const L = createLiteral(carrier.text, sem.datatype, sem.language, state.ctx, state.df);
1413
+ const carrierO = carrier.url ? state.df.namedNode(expandIRI(carrier.url, state.ctx)) : null;
1414
+ const newSubjectOrCarrierO = newSubject || carrierO;
1415
+ if (state.currentBlock) enrichBlockFromAnnotation(state.currentBlock, sem, carrier, state);
1416
+ processTypeAnnotations(sem, newSubject, localObject, carrierO, S, block, state, carrier);
1417
+ processPredicateAnnotations(sem, newSubject, previousSubject, localObject, newSubjectOrCarrierO, S, L, block, state, carrier);
1418
+ }
1419
+ function createBlock(subject, types, predicates, range, attrsRange, valueRange, carrierType, ctx, text) {
1420
+ const expanded = {
1421
+ subject,
1422
+ types: types.map((t) => expandIRI(typeof t === "string" ? t : t.iri, ctx)),
1423
+ predicates: predicates.map((p) => ({
1424
+ iri: expandIRI(p.iri, ctx),
1425
+ form: p.form
999
1426
  }))
1000
1427
  };
1001
1428
  return {
1002
- id: p([
1003
- e,
1004
- o || "unknown",
1005
- l.types.join(","),
1006
- l.predicates.map((e) => `${e.form}${e.iri}`).join(",")
1429
+ id: hash([
1430
+ subject,
1431
+ carrierType || "unknown",
1432
+ expanded.types.join(","),
1433
+ expanded.predicates.map((p) => `${p.form}${p.iri}`).join(",")
1007
1434
  ].join("|")),
1008
1435
  range: {
1009
- start: r[0],
1010
- end: r[1]
1436
+ start: range[0],
1437
+ end: range[1]
1011
1438
  },
1012
- valueRange: a ? {
1013
- start: a[0],
1014
- end: a[1]
1439
+ valueRange: valueRange ? {
1440
+ start: valueRange[0],
1441
+ end: valueRange[1]
1015
1442
  } : null,
1016
- carrierType: o || null,
1017
- subject: e,
1018
- types: l.types,
1019
- predicates: l.predicates,
1020
- context: s,
1021
- text: c || ""
1443
+ carrierType: carrierType || null,
1444
+ subject,
1445
+ types: expanded.types,
1446
+ predicates: expanded.predicates,
1447
+ context: ctx,
1448
+ text: text || ""
1022
1449
  };
1023
1450
  }
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);
1451
+ function emitQuad(quads, quadBuffer, removeSet, quadIndex, block, subject, predicate, object, dataFactory, meta = null, statements = null, statementCandidates = null, state = null) {
1452
+ if (!subject || !predicate || !object) return;
1453
+ const quad = dataFactory.quad(subject, predicate, object);
1454
+ if (meta?.remove || false) {
1455
+ const quadKey = quadIndexKey(quad.subject, quad.predicate, quad.object);
1456
+ if (quadBuffer.has(quadKey)) {
1457
+ quadBuffer.delete(quadKey);
1458
+ const index = quads.findIndex((q) => q.subject.value === quad.subject.value && q.predicate.value === quad.predicate.value && q.object.value === quad.object.value);
1459
+ if (index !== -1) quads.splice(index, 1);
1460
+ quadIndex.delete(quadKey);
1461
+ } else removeSet.add(quad);
1034
1462
  } 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);
1463
+ const quadKey = quadIndexKey(quad.subject, quad.predicate, quad.object);
1464
+ quadBuffer.set(quadKey, quad);
1465
+ quads.push(quad);
1466
+ if (state) {
1467
+ if (!state.primaryType && predicate.value === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type") state.primaryType = object.value;
1468
+ if (!state.primaryLabel && predicate.value === "http://www.w3.org/2000/01/rdf-schema#label" && object.termType === "Literal") state.primaryLabel = object.value;
1469
+ if (!state.primaryComment && predicate.value === "http://www.w3.org/2000/01/rdf-schema#comment" && object.termType === "Literal") state.primaryComment = object.value;
1470
+ }
1471
+ detectStatementPatternSinglePass(quad, dataFactory, meta, statements, statementCandidates);
1472
+ const originEntry = createLeanOriginEntry(block, subject, predicate, meta);
1473
+ quadIndex.set(quadKey, originEntry);
1474
+ if (state.currentBlock && block.id === state.currentBlock.id) {
1475
+ if (!state.currentBlock.quadKeys) state.currentBlock.quadKeys = [];
1476
+ state.currentBlock.quadKeys.push(quadKey);
1477
+ }
1053
1478
  }
1054
1479
  }
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
1480
+ function detectStatementPatternSinglePass(quad, dataFactory, meta, statements = null, statementCandidates = null) {
1481
+ if (!statements || !statementCandidates) return;
1482
+ const predicate = quad.predicate.value;
1483
+ 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;
1484
+ 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") {
1485
+ statementCandidates.set(quad.subject.value, { spo: {} });
1486
+ return;
1487
+ }
1488
+ const candidate = statementCandidates.get(quad.subject.value);
1489
+ if (!candidate) return;
1490
+ if (predicate === "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject") candidate.spo.subject = quad.object;
1491
+ else if (predicate === "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate") candidate.spo.predicate = quad.object;
1492
+ else if (predicate === "http://www.w3.org/1999/02/22-rdf-syntax-ns#object") {
1493
+ candidate.spo.object = quad.object;
1494
+ candidate.objectQuad = quad;
1495
+ }
1496
+ if (candidate.spo.subject && candidate.spo.predicate && candidate.spo.object) {
1497
+ const spoQuad = dataFactory.quad(candidate.spo.subject, candidate.spo.predicate, candidate.spo.object);
1498
+ statements.push(spoQuad);
1499
+ statementCandidates.delete(quad.subject.value);
1500
+ }
1501
+ }
1502
+ var createTypeQuad = (typeIRI, subject, state, block, entryIndex = null) => {
1503
+ const expandedType = expandIRI(typeIRI, state.ctx);
1504
+ const typeInfo = typeof entryIndex === "object" ? entryIndex : {
1505
+ entryIndex,
1506
+ remove: false
1059
1507
  };
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, {
1508
+ 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
1509
  kind: "type",
1062
- token: `.${e}`,
1063
- expandedType: a,
1064
- entryIndex: o.entryIndex,
1065
- remove: o.remove
1066
- }, n.statements, n.statementCandidates, n);
1510
+ token: `.${typeIRI}`,
1511
+ expandedType,
1512
+ entryIndex: typeInfo.entryIndex,
1513
+ remove: typeInfo.remove
1514
+ }, state.statements, state.statementCandidates, state);
1067
1515
  };
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" ? {
1516
+ function processTypeAnnotations(sem, newSubject, localObject, carrierO, S, block, state, carrier) {
1517
+ sem.types.forEach((t) => {
1518
+ createTypeQuad(typeof t === "string" ? t : t.iri, newSubject || localObject || carrierO || S, state, block, typeof t === "string" ? {
1071
1519
  entryIndex: null,
1072
- remove: !1
1073
- } : e);
1520
+ remove: false
1521
+ } : t);
1074
1522
  });
1075
1523
  }
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
1524
+ var determinePredicateRole = (pred, carrier, newSubject, previousSubject, localObject, newSubjectOrCarrierO, S, L) => {
1525
+ if (pred.form === "" && carrier?.type === "link" && carrier?.url && carrier.text === carrier.url) return null;
1526
+ switch (pred.form) {
1527
+ case "": return newSubject ? {
1528
+ subject: localObject || S,
1529
+ object: L
1530
+ } : carrier?.type === "link" && carrier?.url && carrier.text !== carrier.url ? {
1531
+ subject: newSubjectOrCarrierO,
1532
+ object: L
1085
1533
  } : {
1086
- subject: i || o,
1087
- object: s
1534
+ subject: localObject || S,
1535
+ object: L
1088
1536
  };
1089
1537
  case "?": return {
1090
- subject: n ? r : o,
1091
- object: i || a
1538
+ subject: newSubject ? previousSubject : S,
1539
+ object: localObject || newSubjectOrCarrierO
1092
1540
  };
1093
1541
  case "!": return {
1094
- subject: i || a,
1095
- object: n ? r : o
1542
+ subject: localObject || newSubjectOrCarrierO,
1543
+ object: newSubject ? previousSubject : S
1096
1544
  };
1097
1545
  default: return null;
1098
1546
  }
1099
1547
  };
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, {
1548
+ function processPredicateAnnotations(sem, newSubject, previousSubject, localObject, newSubjectOrCarrierO, S, L, block, state, carrier) {
1549
+ sem.predicates.forEach((pred) => {
1550
+ const role = determinePredicateRole(pred, carrier, newSubject, previousSubject, localObject, newSubjectOrCarrierO, S, L);
1551
+ if (role) {
1552
+ const P = state.df.namedNode(expandIRI(pred.iri, state.ctx));
1553
+ emitQuad(state.quads, state.quadBuffer, state.removeSet, state.origin.quadIndex, block, role.subject, P, role.object, state.df, {
1106
1554
  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);
1555
+ token: `${pred.form}${pred.iri}`,
1556
+ form: pred.form,
1557
+ expandedPredicate: P.value,
1558
+ entryIndex: pred.entryIndex,
1559
+ remove: pred.remove || false
1560
+ }, state.statements, state.statementCandidates, state);
1113
1561
  }
1114
1562
  });
1115
1563
  }
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);
1564
+ function processAnnotation(carrier, sem, state, options = {}) {
1565
+ processAnnotationWithBlockTracking(carrier, sem, state, options);
1566
+ }
1567
+ function processTokenAnnotations(token, state, tokenType) {
1568
+ if (token.attrs) {
1569
+ const sem = parseSemCached(token.attrs);
1570
+ processAnnotation({
1571
+ type: tokenType,
1572
+ text: token.text,
1573
+ range: token.range,
1574
+ attrsRange: token.attrsRange || null,
1575
+ valueRange: token.valueRange || null
1576
+ }, sem, state);
1577
+ }
1578
+ getCarriers(token).forEach((carrier) => {
1579
+ if (carrier.attrs) processAnnotation(carrier, parseSemCached(carrier.attrs), state);
1132
1580
  });
1133
1581
  }
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({
1582
+ function processStandaloneSubject(token, state) {
1583
+ const result = detectStandaloneSubject(token.text);
1584
+ if (!result) return;
1585
+ const sem = parseSemCached(`{=${result.content}}`);
1586
+ const attrsStart = token.range[0] + token.text.indexOf("{=");
1587
+ processAnnotation({
1139
1588
  type: "standalone",
1140
1589
  text: "",
1141
- range: e.range,
1142
- attrsRange: [i, i + (n.content ? n.content.length : 0)],
1590
+ range: token.range,
1591
+ attrsRange: [attrsStart, attrsStart + (result.content ? result.content.length : 0)],
1143
1592
  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)
1593
+ }, sem, state);
1594
+ }
1595
+ var TOKEN_PROCESSORS = {
1596
+ heading: (token, state) => processTokenWithBlockTracking(token, state, processTokenAnnotations, createBlockEntry),
1597
+ code: (token, state) => processTokenWithBlockTracking(token, state, processTokenAnnotations, createBlockEntry),
1598
+ blockquote: (token, state) => processTokenWithBlockTracking(token, state, processTokenAnnotations, createBlockEntry),
1599
+ para: (token, state) => processTokenWithBlockTracking(token, state, processTokenAnnotations, createBlockEntry, [processStandaloneSubject]),
1600
+ list: (token, state) => processTokenWithBlockTracking(token, state, processTokenAnnotations, createBlockEntry),
1601
+ standalone: (token, state) => processStandaloneSubject(token, state)
1153
1602
  };
1154
1603
  //#endregion
1155
1604
  //#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,
1605
+ /**
1606
+ * Creates a unique key for quad identity matching - using shared utility
1607
+ * @param {Quad} quad
1608
+ * @returns {string}
1609
+ */
1610
+ function quadKey(quad) {
1611
+ return quadToKeyForOrigin(quad);
1612
+ }
1613
+ /**
1614
+ * Normalizes merge input to ParseResult format
1615
+ * @param {string|ParseResult} input
1616
+ * @param {Object} options
1617
+ * @param {Object} docContext
1618
+ * @returns {ParseResult}
1619
+ */
1620
+ function normalizeInput(input, options, docContext) {
1621
+ if (typeof input === "string") return parse({
1622
+ text: input,
1623
+ ...options,
1163
1624
  context: {
1164
- ...n,
1165
- ...t.context
1625
+ ...docContext,
1626
+ ...options.context
1166
1627
  }
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
1628
+ });
1629
+ return input;
1630
+ }
1631
+ /**
1632
+ * Merges multiple MDLD documents with diff polarity resolution
1633
+ * @param {Array<string|ParseResult>} docs
1634
+ * @param {Object} options
1635
+ * @returns {Object} Merge result with quads, remove, statements, origin, and context
1636
+ */
1637
+ function merge(docs, options = {}) {
1638
+ const sessionBuffer = /* @__PURE__ */ new Map();
1639
+ const sessionRemoveSet = /* @__PURE__ */ new Set();
1640
+ const allDocuments = [];
1641
+ const quadIndex = /* @__PURE__ */ new Map();
1642
+ const allStatements = [];
1643
+ const accumulatedContext = /* @__PURE__ */ new Map();
1644
+ const primaryObjects = [];
1645
+ const primarySubjects = [];
1646
+ for (let i = 0; i < docs.length; i++) {
1647
+ const input = docs[i];
1648
+ const doc = normalizeInput(input, options, {
1649
+ ...DEFAULT_CONTEXT,
1650
+ ...options.context
1175
1651
  });
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
1652
+ if (doc.context) {
1653
+ for (const [prefix, namespace] of Object.entries(doc.context)) if (!accumulatedContext.has(prefix) && !DEFAULT_CONTEXT[prefix]) accumulatedContext.set(prefix, namespace);
1654
+ }
1655
+ const documentOrigin = {
1656
+ index: i,
1657
+ input: typeof input === "string" ? "string" : "ParseResult",
1658
+ origin: doc.origin,
1659
+ context: doc.context,
1660
+ statementsCount: doc.statements?.length || 0
1183
1661
  };
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,
1662
+ allDocuments.push(documentOrigin);
1663
+ if (doc.statements && doc.statements.length > 0) allStatements.push(...doc.statements);
1664
+ if (doc.primary && (doc.primary.subject || doc.primary.type || doc.primary.label)) primaryObjects.push(doc.primary);
1665
+ if (doc.primarySubject) primarySubjects.push(doc.primarySubject);
1666
+ for (const quad of doc.quads) {
1667
+ const key = quadKey(quad);
1668
+ sessionBuffer.set(key, quad);
1669
+ const existingOrigin = doc.origin.quadIndex.get(key);
1670
+ quadIndex.set(key, {
1671
+ ...existingOrigin || {},
1672
+ documentIndex: i,
1192
1673
  polarity: "+"
1193
1674
  });
1194
1675
  }
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,
1676
+ for (const quad of doc.remove) {
1677
+ const key = quadKey(quad);
1678
+ if (sessionBuffer.has(key)) sessionBuffer.delete(key);
1679
+ else sessionRemoveSet.add(quad);
1680
+ const existingOrigin = doc.origin.quadIndex.get(key);
1681
+ quadIndex.set(key, {
1682
+ ...existingOrigin || {},
1683
+ documentIndex: i,
1202
1684
  polarity: "-"
1203
1685
  });
1204
1686
  }
1205
1687
  }
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));
1688
+ const finalQuads = Array.from(sessionBuffer.values());
1689
+ const finalRemove = Array.from(sessionRemoveSet);
1690
+ const mergeOrigin = {
1691
+ documents: allDocuments,
1692
+ quadIndex
1693
+ };
1694
+ const finalContext = {
1695
+ ...DEFAULT_CONTEXT,
1696
+ ...options.context,
1697
+ ...Object.fromEntries(accumulatedContext)
1698
+ };
1699
+ const quadKeys = new Set(finalQuads.map(quadKey));
1700
+ const removeKeys = new Set(finalRemove.map(quadKey));
1214
1701
  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
1702
+ quads: finalQuads.filter((quad) => !removeKeys.has(quadKey(quad))),
1703
+ remove: finalRemove.filter((quad) => !quadKeys.has(quadKey(quad))),
1704
+ statements: allStatements,
1705
+ origin: mergeOrigin,
1706
+ context: finalContext,
1707
+ primarySubjects,
1708
+ primary: primaryObjects
1222
1709
  };
1223
1710
  }
1224
1711
  //#endregion
1225
1712
  //#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 [
1713
+ var iriCache = /* @__PURE__ */ new Map();
1714
+ var CACHE_SIZE_LIMIT = 1e3;
1715
+ function getCachedShortIRI(iri, context) {
1716
+ const cacheKey = `${iri}|${JSON.stringify(context)}`;
1717
+ if (iriCache.has(cacheKey)) return iriCache.get(cacheKey);
1718
+ const result = shortenIRI(iri, context);
1719
+ if (iriCache.size >= CACHE_SIZE_LIMIT) Array.from(iriCache.keys()).slice(0, Math.floor(CACHE_SIZE_LIMIT / 2)).forEach((key) => iriCache.delete(key));
1720
+ iriCache.set(cacheKey, result);
1721
+ return result;
1722
+ }
1723
+ function extractLocalName(iri, ctx = {}) {
1724
+ if (!iri) return iri;
1725
+ for (const [prefix, namespace] of Object.entries(ctx)) if (iri.startsWith(namespace) || iri.startsWith(namespace.slice(0, -1))) return iri.substring(namespace.length);
1726
+ for (const sep of [
1237
1727
  "#",
1238
1728
  "/",
1239
1729
  ":"
1240
1730
  ]) {
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);
1731
+ const lastSep = iri.lastIndexOf(sep);
1732
+ if (lastSep !== -1 && lastSep < iri.length - 1) return iri.substring(lastSep + 1);
1733
+ }
1734
+ return iri;
1735
+ }
1736
+ /**
1737
+ * Generate deterministic MDLD from RDF quads
1738
+ * Purpose: TTL→MDLD conversion with canonical structure
1739
+ * Input: RDF quads + context + optional primarySubject (string IRI) + compactInline (boolean) + remove (array) + lang (string)
1740
+ * Output: MDLD text + context + compactStats
1741
+ */
1742
+ function generate({ quads, context = {}, primarySubject = null, compactInline = false, renderReverse = false, remove = [], lang = null }) {
1743
+ const fullContext = Object.assign({}, DEFAULT_CONTEXT, context);
1744
+ const normalizedQuads = normalizeAndSortQuads(quads);
1745
+ const normalizedRemove = normalizeAndSortQuads(remove);
1746
+ const { subjectGroups, reverseIndex } = groupQuadsBySubject(normalizedQuads);
1747
+ const removeBySubject = groupQuadsBySubject(normalizedRemove).subjectGroups;
1748
+ const { text, compactStats } = buildDeterministicMDLD(subjectGroups, fullContext, primarySubject, primarySubject && renderReverse ? reverseIndex : null, compactInline, removeBySubject, lang);
1250
1749
  return {
1251
- text: c,
1252
- context: i
1750
+ text,
1751
+ context: fullContext,
1752
+ compactStats
1253
1753
  };
1254
1754
  }
1255
- function He({ quads: t, focusIRI: n, context: r = {} }) {
1256
- if (!t?.length || !n) return {
1755
+ /**
1756
+ * Generate node-centric MDLD showing all quads where a specific IRI appears
1757
+ * in any position: subject, object, predicate, type, or datatype.
1758
+ * Perfect for exploring individual nodes and their complete relationship graph.
1759
+ */
1760
+ function generateNode({ quads, focusIRI, context = {}, compactInline = true, renderReverse = true, lang = null }) {
1761
+ if (!quads?.length || !focusIRI) return {
1257
1762
  text: "",
1258
- context: Object.assign({}, e, r)
1763
+ context: Object.assign({}, DEFAULT_CONTEXT, context),
1764
+ compactStats: null
1259
1765
  };
1260
- let i = Object.assign({}, e, r), a = Ge(Ue(t));
1261
- if (!a.has(n)) return {
1766
+ const fullContext = Object.assign({}, DEFAULT_CONTEXT, context);
1767
+ const { nodeGroups, reverseIndex } = groupQuadsByNode(normalizeAndSortQuads(quads));
1768
+ if (!nodeGroups.has(focusIRI)) return {
1262
1769
  text: "",
1263
- context: i
1770
+ context: fullContext,
1771
+ compactStats: null
1264
1772
  };
1265
- let { text: o } = Ke(a, i, n);
1773
+ const { text, compactStats } = buildDeterministicMDLD(nodeGroups, fullContext, focusIRI, renderReverse ? reverseIndex : null, compactInline, /* @__PURE__ */ new Map(), lang);
1266
1774
  return {
1267
- text: o,
1268
- context: i
1775
+ text,
1776
+ context: fullContext,
1777
+ compactStats
1269
1778
  };
1270
1779
  }
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);
1780
+ function normalizeAndSortQuads(quads) {
1781
+ if (!quads || quads.length === 0) return [];
1782
+ return quads.map((quad) => {
1783
+ if (quad.subject.termType && quad.predicate.termType && quad.object.termType) return quad;
1784
+ return {
1785
+ subject: DataFactory.fromTerm(quad.subject),
1786
+ predicate: DataFactory.fromTerm(quad.predicate),
1787
+ object: DataFactory.fromTerm(quad.object)
1788
+ };
1789
+ }).sort((a, b) => {
1790
+ const sComp = a.subject.value.localeCompare(b.subject.value);
1791
+ if (sComp !== 0) return sComp;
1792
+ const pComp = a.predicate.value.localeCompare(b.predicate.value);
1793
+ if (pComp !== 0) return pComp;
1794
+ const oA = isLiteral(a.object) ? a.object.value : a.object.value;
1795
+ const oB = isLiteral(b.object) ? b.object.value : b.object.value;
1796
+ return oA.localeCompare(oB);
1283
1797
  });
1284
1798
  }
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()
1799
+ function groupQuadsBySubject(quads) {
1800
+ const groups = /* @__PURE__ */ new Map();
1801
+ const reverseIndex = /* @__PURE__ */ new Map();
1802
+ for (const quad of quads) {
1803
+ const subjectValue = quad.subject.value;
1804
+ const existing = groups.get(subjectValue);
1805
+ if (existing) existing.push(quad);
1806
+ else groups.set(subjectValue, [quad]);
1807
+ if (quad.object.termType === "NamedNode") {
1808
+ const objectValue = quad.object.value;
1809
+ const reverseList = reverseIndex.get(objectValue);
1810
+ if (reverseList) reverseList.push(quad);
1811
+ else reverseIndex.set(objectValue, [quad]);
1346
1812
  }
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) {
1813
+ }
1355
1814
  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
1815
+ subjectGroups: groups,
1816
+ reverseIndex
1370
1817
  };
1371
1818
  }
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);
1819
+ function groupQuadsByNode(quads) {
1820
+ const groups = /* @__PURE__ */ new Map();
1821
+ const reverseIndex = /* @__PURE__ */ new Map();
1822
+ const ensure = (key) => {
1823
+ const existing = groups.get(key);
1824
+ if (existing) return existing;
1825
+ const newArray = [];
1826
+ groups.set(key, newArray);
1827
+ return newArray;
1828
+ };
1829
+ for (const quad of quads) {
1830
+ const { subject, predicate, object } = quad;
1831
+ ensure(subject.value).push(quad);
1832
+ if (object.termType === "NamedNode") {
1833
+ ensure(object.value).push(quad);
1834
+ const objectValue = object.value;
1835
+ const reverseList = reverseIndex.get(objectValue);
1836
+ if (reverseList) reverseList.push(quad);
1837
+ else reverseIndex.set(objectValue, [quad]);
1838
+ }
1839
+ ensure(predicate.value).push(quad);
1840
+ if (predicate.value === RDFS_TYPE && object.termType === "NamedNode") ensure(object.value).push(quad);
1841
+ if (object.termType === "Literal" && object.datatype) ensure(object.datatype.value || object.datatype).push(quad);
1419
1842
  }
1420
1843
  return {
1421
- literalProps: n,
1422
- objectProps: r,
1423
- reverseProps: i
1844
+ nodeGroups: groups,
1845
+ reverseIndex
1424
1846
  };
1425
1847
  }
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)}"`);
1848
+ function buildDeterministicMDLD(subjectGroups, context, primarySubject = null, reverseIndex = null, compactInline = true, removeBySubject = /* @__PURE__ */ new Map(), lang = null) {
1849
+ const textParts = [];
1850
+ const usedPrefixes = collectUsedPrefixes(subjectGroups, context);
1851
+ const labelLookup = buildLabelLookup(subjectGroups, lang);
1852
+ const compactStats = {
1853
+ compactedSubjects: 0,
1854
+ skippedHeadings: 0,
1855
+ inlineAnnotations: 0
1856
+ };
1857
+ const renderedQuads = /* @__PURE__ */ new Set();
1858
+ const filteredGroups = /* @__PURE__ */ new Map();
1859
+ for (const [subjectIRI, quads] of subjectGroups.entries()) filteredGroups.set(subjectIRI, filterQuadsByType(quads));
1860
+ const sortedPrefixes = Object.entries(context).sort(([a], [b]) => a.localeCompare(b));
1861
+ for (const [prefix, namespace] of sortedPrefixes) if (prefix !== "@vocab" && !prefix.startsWith("@") && !DEFAULT_CONTEXT[prefix] && usedPrefixes.has(prefix)) textParts.push(generatePrefixDeclaration(prefix, namespace));
1862
+ if (sortedPrefixes.length > 0) textParts.push("\n");
1863
+ const sortedSubjects = Array.from(subjectGroups.keys()).sort();
1864
+ const primarySubjectIRI = primarySubject;
1865
+ const orderedSubjects = primarySubjectIRI ? [primarySubjectIRI, ...sortedSubjects.filter((s) => s !== primarySubjectIRI)] : sortedSubjects;
1866
+ for (const subjectIRI of orderedSubjects) {
1867
+ const subjectQuads = subjectGroups.get(subjectIRI);
1868
+ if (!subjectQuads) continue;
1869
+ if (subjectQuads.every((q) => renderedQuads.has(q))) {
1870
+ compactStats.skippedHeadings++;
1871
+ compactStats.compactedSubjects++;
1872
+ continue;
1873
+ }
1874
+ const { types, literals, objects } = filteredGroups.get(subjectIRI);
1875
+ const shortSubject = getCachedShortIRI(subjectIRI, context);
1876
+ const labelEntry = labelLookup.get(subjectIRI);
1877
+ const hasLabel = !!labelEntry;
1878
+ const displayName = hasLabel ? labelEntry.value : extractLocalName(subjectIRI, context);
1879
+ const typesNotRendered = types.filter((t) => !renderedQuads.has(t));
1880
+ let annotations = typesNotRendered.length > 0 ? typesNotRendered.map((t) => "." + getCachedShortIRI(t.object.value, context)).sort().join(" ") : "";
1881
+ const labelQuad = subjectQuads.find((q) => q.predicate.value === RDFS_LABEL);
1882
+ if (hasLabel && (!labelQuad || !renderedQuads.has(labelQuad))) {
1883
+ const langTag = labelEntry.language ? " @" + labelEntry.language : "";
1884
+ annotations += (annotations ? " " : "") + "label" + langTag;
1485
1885
  }
1486
- if (i.length > 0) {
1487
- let e = i.map((e) => g(e, t.ctx)).join(" ");
1488
- n.push(`rel="${A(e)}"`);
1886
+ const annotationStr = annotations ? " " + annotations : "";
1887
+ textParts.push(`# ${displayName} {=${shortSubject}${annotationStr}}\n`);
1888
+ types.forEach((t) => renderedQuads.add(t));
1889
+ if (labelQuad) renderedQuads.add(labelQuad);
1890
+ const headingLabel = hasLabel ? labelEntry.value : null;
1891
+ sortQuadsByPredicate(literals).forEach((quad) => {
1892
+ if (quad.predicate.value === "http://www.w3.org/2000/01/rdf-schema#label" && quad.object.value === headingLabel) return;
1893
+ textParts.push(generateLiteralText(quad, context));
1894
+ });
1895
+ sortQuadsByPredicate(objects).forEach((quad) => {
1896
+ if (renderedQuads.has(quad)) return;
1897
+ textParts.push(generateObjectText(quad, context, labelLookup, filteredGroups, renderedQuads, compactInline, compactStats));
1898
+ });
1899
+ if (subjectIRI === primarySubjectIRI && reverseIndex && reverseIndex.has(subjectIRI)) {
1900
+ const reverseQuads = reverseIndex.get(subjectIRI);
1901
+ reverseQuads.sort((a, b) => a.predicate.value.localeCompare(b.predicate.value));
1902
+ for (const quad of reverseQuads) {
1903
+ renderedQuads.add(quad);
1904
+ const subjectQuads = subjectGroups.get(quad.subject.value);
1905
+ const subjectLabelEntry = labelLookup.get(quad.subject.value);
1906
+ const subjectLabel = subjectLabelEntry ? subjectLabelEntry.value : extractLocalName(quad.subject.value, context);
1907
+ const shortSubject = getCachedShortIRI(quad.subject.value, context);
1908
+ const shortPredicate = getCachedShortIRI(quad.predicate.value, context);
1909
+ let inlineAnnotation = "";
1910
+ if (compactInline && subjectQuads) {
1911
+ const { types } = filteredGroups.get(quad.subject.value) || { types: [] };
1912
+ const reverseSubjectLabelEntry = labelLookup.get(quad.subject.value);
1913
+ const hasLabel = !!reverseSubjectLabelEntry;
1914
+ const typeAnnotations = types.length > 0 ? types.map((t) => "." + getCachedShortIRI(t.object.value, context)).sort().join(" ") : "";
1915
+ const labelAnnotation = hasLabel ? "label" + (reverseSubjectLabelEntry.language ? " @" + reverseSubjectLabelEntry.language : "") : "";
1916
+ if (typeAnnotations || labelAnnotation) {
1917
+ inlineAnnotation = " " + [typeAnnotations, labelAnnotation].filter(Boolean).join(" ");
1918
+ compactStats.inlineAnnotations++;
1919
+ types.forEach((q) => renderedQuads.add(q));
1920
+ if (hasLabel) {
1921
+ const labelQuad = subjectQuads.find((q) => q.predicate.value === RDFS_LABEL);
1922
+ if (labelQuad) renderedQuads.add(labelQuad);
1923
+ }
1924
+ }
1925
+ if (subjectQuads.every((q) => renderedQuads.has(q))) {
1926
+ compactStats.skippedHeadings++;
1927
+ compactStats.compactedSubjects++;
1928
+ }
1929
+ }
1930
+ textParts.push(`[${subjectLabel}] {+${shortSubject} !${shortPredicate}${inlineAnnotation}}\n`);
1931
+ }
1489
1932
  }
1490
- if (a.length > 0) {
1491
- let e = a.map((e) => g(e, t.ctx)).join(" ");
1492
- n.push(`rev="${A(e)}"`);
1933
+ if (removeBySubject.has(subjectIRI)) {
1934
+ const removeQuads = removeBySubject.get(subjectIRI);
1935
+ for (const quad of removeQuads) textParts.push(generateRetractionText(quad, context));
1936
+ removeBySubject.delete(subjectIRI);
1493
1937
  }
1938
+ textParts.push("\n");
1494
1939
  }
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>`;
1940
+ for (const [subjectIRI, removeQuads] of removeBySubject) {
1941
+ const shortSubject = getCachedShortIRI(subjectIRI, context);
1942
+ const displayName = extractLocalName(subjectIRI, context);
1943
+ textParts.push(`# ${displayName} {=${shortSubject}}\n`);
1944
+ for (const quad of removeQuads) textParts.push(generateRetractionText(quad, context));
1945
+ textParts.push("\n");
1502
1946
  }
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]
1947
+ return {
1948
+ text: textParts.join(""),
1949
+ compactStats
1517
1950
  };
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
- }
1525
- function ft(e, t) {
1526
- let n = Qe(e, t), r = q(e, t);
1527
- t.output.push(`<li${n}>${r}</li>`);
1528
1951
  }
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;
1952
+ function buildLabelLookup(subjectGroups, lang = null) {
1953
+ const labelLookup = /* @__PURE__ */ new Map();
1954
+ const labelsBySubject = /* @__PURE__ */ new Map();
1955
+ 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") {
1956
+ const subjectIRI = quad.subject.value;
1957
+ if (!labelsBySubject.has(subjectIRI)) labelsBySubject.set(subjectIRI, []);
1958
+ labelsBySubject.get(subjectIRI).push(quad.object);
1959
+ }
1960
+ const selectBestLabel = (candidates) => {
1961
+ if (candidates.length === 0) return null;
1962
+ candidates.sort((a, b) => {
1963
+ const lenDiff = a.value.length - b.value.length;
1964
+ return lenDiff !== 0 ? lenDiff : a.value.localeCompare(b.value);
1965
+ });
1966
+ return candidates[0];
1967
+ };
1968
+ for (const [subjectIRI, labels] of labelsBySubject) {
1969
+ let selectedLabel = null;
1970
+ if (lang) selectedLabel = selectBestLabel(labels.filter((lit) => lit.language === lang));
1971
+ if (!selectedLabel) selectedLabel = selectBestLabel(labels.filter((lit) => !lit.language));
1972
+ if (!selectedLabel) selectedLabel = selectBestLabel(labels.filter((lit) => lit.language === "en"));
1973
+ if (!selectedLabel) selectedLabel = selectBestLabel(labels.filter((lit) => lit.language));
1974
+ if (selectedLabel) labelLookup.set(subjectIRI, {
1975
+ value: selectedLabel.value,
1976
+ language: selectedLabel.language || null
1977
+ });
1548
1978
  }
1549
- return t.toString(36);
1979
+ return labelLookup;
1550
1980
  }
1551
1981
  //#endregion
1552
1982
  //#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 = {
1983
+ /**
1984
+ * MD-LD Syntax Highlighter
1985
+ *
1986
+ * A performant, token-based syntax highlighter for MD-LD (Markdown Linked Data).
1987
+ * Uses simple string operations rather than complex grammars for reliability
1988
+ * and maintainability.
1989
+ *
1990
+ * Features:
1991
+ * - Token-based parsing with string operations
1992
+ * - Markdown formatting support with semantic distinction
1993
+ * - Lookahead detection for legal value carriers
1994
+ * - Orange semantic markers vs default markdown spans
1995
+ * - Annotation, value carrier, and heading highlighting
1996
+ */
1997
+ function escapeHtml(s) {
1998
+ return String(s).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
1999
+ }
2000
+ var TOKEN_COLORS = {
1557
2001
  text: "#6b7280",
1558
2002
  marker: "#f97316",
1559
2003
  retraction: "#dc2626",
1560
2004
  value: "#eab308",
1561
2005
  annotation: "#4b5563"
1562
2006
  };
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}"` : "";
2007
+ function hasFollowingAnnotation(code, endPos) {
2008
+ let i = endPos;
2009
+ while (i < code.length && code[i] !== "\n" && code[i] !== "\r") {
2010
+ if (code[i] === "{") return true;
2011
+ i++;
2012
+ }
2013
+ return false;
2014
+ }
2015
+ function processMarkdownFormattingAtPosition(code, startPos) {
2016
+ const char = code[startPos];
2017
+ if (char === "*" && startPos + 1 < code.length && code[startPos + 1] === "*") {
2018
+ const endPos = code.indexOf("**", startPos + 2);
2019
+ if (endPos !== -1) {
2020
+ const content = code.slice(startPos + 2, endPos);
2021
+ const color = hasFollowingAnnotation(code, endPos + 2) ? ` style="color: ${TOKEN_COLORS.marker}"` : "";
1577
2022
  return {
1578
- html: `<span${i}>**</span><strong>${J(r)}</strong><span${i}>**</span>`,
1579
- nextIndex: n + 2
2023
+ html: `<span${color}>**</span><strong>${escapeHtml(content)}</strong><span${color}>**</span>`,
2024
+ nextIndex: endPos + 2
1580
2025
  };
1581
2026
  }
1582
2027
  }
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}"` : "";
2028
+ if (char === "_" && startPos + 1 < code.length && code[startPos + 1] === "_") {
2029
+ const endPos = code.indexOf("__", startPos + 2);
2030
+ if (endPos !== -1) {
2031
+ const content = code.slice(startPos + 2, endPos);
2032
+ const color = hasFollowingAnnotation(code, endPos + 2) ? ` style="color: ${TOKEN_COLORS.marker}"` : "";
1587
2033
  return {
1588
- html: `<span${i}>__</span><strong>${J(r)}</strong><span${i}>__</span>`,
1589
- nextIndex: n + 2
2034
+ html: `<span${color}>__</span><strong>${escapeHtml(content)}</strong><span${color}>__</span>`,
2035
+ nextIndex: endPos + 2
1590
2036
  };
1591
2037
  }
1592
2038
  }
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}"` : "";
2039
+ if (char === "*") {
2040
+ const endPos = code.indexOf("*", startPos + 1);
2041
+ if (endPos !== -1) {
2042
+ const content = code.slice(startPos + 1, endPos);
2043
+ const color = hasFollowingAnnotation(code, endPos + 1) ? ` style="color: ${TOKEN_COLORS.marker}"` : "";
1597
2044
  return {
1598
- html: `<span${i}>*</span><em>${J(r)}</em><span${i}>*</span>`,
1599
- nextIndex: n + 1
2045
+ html: `<span${color}>*</span><em>${escapeHtml(content)}</em><span${color}>*</span>`,
2046
+ nextIndex: endPos + 1
1600
2047
  };
1601
2048
  }
1602
2049
  }
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}"` : "";
2050
+ if (char === "_") {
2051
+ const endPos = code.indexOf("_", startPos + 1);
2052
+ if (endPos !== -1) {
2053
+ const content = code.slice(startPos + 1, endPos);
2054
+ const color = hasFollowingAnnotation(code, endPos + 1) ? ` style="color: ${TOKEN_COLORS.marker}"` : "";
1607
2055
  return {
1608
- html: `<span${i}>_</span><em>${J(r)}</em><span${i}>_</span>`,
1609
- nextIndex: n + 1
2056
+ html: `<span${color}>_</span><em>${escapeHtml(content)}</em><span${color}>_</span>`,
2057
+ nextIndex: endPos + 1
1610
2058
  };
1611
2059
  }
1612
2060
  }
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}"` : "";
2061
+ if (char === "`") {
2062
+ const endPos = code.indexOf("`", startPos + 1);
2063
+ if (endPos !== -1) {
2064
+ const content = code.slice(startPos + 1, endPos);
2065
+ const color = hasFollowingAnnotation(code, endPos + 1) ? ` style="color: ${TOKEN_COLORS.marker}"` : "";
1617
2066
  return {
1618
- html: `<span${i}>\`</span><code style="background-color:#7773">${J(r)}</code><span${i}>\`</span>`,
1619
- nextIndex: n + 1
2067
+ html: `<span${color}>\`</span><code style="background-color:#7773">${escapeHtml(content)}</code><span${color}>\`</span>`,
2068
+ nextIndex: endPos + 1
1620
2069
  };
1621
2070
  }
1622
2071
  }
1623
2072
  return null;
1624
2073
  }
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);
2074
+ var colorCache = /* @__PURE__ */ new Map();
2075
+ function hashIRI(iri) {
2076
+ let hash = 0;
2077
+ for (let i = 0; i < iri.length; i++) {
2078
+ const char = iri.charCodeAt(i);
2079
+ hash = (hash << 5) - hash + char;
2080
+ hash = hash & hash;
2081
+ }
2082
+ return Math.abs(hash);
2083
+ }
2084
+ function getIRIColor(iri) {
2085
+ if (colorCache.has(iri)) return colorCache.get(iri);
2086
+ const hash = hashIRI(iri);
2087
+ const color = `hsl(${hash % 360}, ${15 + hash % 10}%, ${45 + hash % 10}%)`;
2088
+ colorCache.set(iri, color);
2089
+ return color;
2090
+ }
2091
+ function extractPrefixes(code) {
2092
+ const prefixes = /* @__PURE__ */ new Map();
2093
+ const prefixRegex = /^\[(\w+)\]\s*<([^>]*)>\s*$/gm;
2094
+ let match;
2095
+ while ((match = prefixRegex.exec(code)) !== null) {
2096
+ const prefixName = match[1];
2097
+ let iri = match[2];
2098
+ if (iri.includes(":")) {
2099
+ const colonIndex = iri.indexOf(":");
2100
+ if (colonIndex > 0) {
2101
+ const refPrefix = iri.slice(0, colonIndex);
2102
+ const refSuffix = iri.slice(colonIndex + 1);
2103
+ if (prefixes.has(refPrefix)) iri = prefixes.get(refPrefix) + refSuffix;
1648
2104
  }
1649
2105
  }
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> `;
2106
+ prefixes.set(prefixName, iri);
2107
+ }
2108
+ for (const [key, iri] of Object.entries(DEFAULT_CONTEXT)) if (key !== "@vocab") prefixes.set(key, iri);
2109
+ return prefixes;
2110
+ }
2111
+ function renderTerm(part, isRetracted, prefixes) {
2112
+ const baseColor = isRetracted ? TOKEN_COLORS.retraction : TOKEN_COLORS.text;
2113
+ const colonIndex = part.indexOf(":");
2114
+ if (colonIndex > 0) {
2115
+ const prefix = part.slice(0, colonIndex);
2116
+ const local = part.slice(colonIndex + 1);
2117
+ if (prefixes.has(prefix)) {
2118
+ const prefixIRI = prefixes.get(prefix);
2119
+ const prefixColor = getIRIColor(prefixIRI);
2120
+ const fullIRI = prefixIRI + local;
2121
+ const localColor = getIRIColor(fullIRI);
2122
+ 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
2123
  }
1663
2124
  }
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)}`;
2125
+ if (part.startsWith("http:") || part.startsWith("https:") || part.startsWith("tag:") || part.startsWith("urn:")) return `<span style="color: ${getIRIColor(part)}">${escapeHtml(part)}</span> `;
2126
+ return `<span style="color: ${baseColor}">${escapeHtml(part)}</span> `;
2127
+ }
2128
+ function parseAnnotation(content, prefixes) {
2129
+ const parts = content.trim().split(/\s+/);
2130
+ let result = "";
2131
+ let nextTermIsRetracted = false;
2132
+ for (let i = 0; i < parts.length; i++) {
2133
+ const part = parts[i];
2134
+ if (!part) continue;
2135
+ if (part.startsWith("=") || part.startsWith("+")) {
2136
+ const marker = part[0];
2137
+ const rest = part.slice(1);
2138
+ result += `<span style="color: ${TOKEN_COLORS.marker}">${escapeHtml(marker)}</span>${renderTerm(rest, false, prefixes)}`;
1674
2139
  continue;
1675
2140
  }
1676
- if (a === "-") {
1677
- i = !0, r += `<span style="color: ${Y.retraction}">${J(a)}</span> `;
2141
+ if (part === "-") {
2142
+ nextTermIsRetracted = true;
2143
+ result += `<span style="color: ${TOKEN_COLORS.retraction}">${escapeHtml(part)}</span> `;
1678
2144
  continue;
1679
2145
  }
1680
- if (a.startsWith("-") && a.length > 1) {
1681
- r += `<span style="color: ${Y.retraction}">${J(a)}</span> `;
2146
+ if (part.startsWith("-") && part.length > 1) {
2147
+ result += `<span style="color: ${TOKEN_COLORS.retraction}">${escapeHtml(part)}</span> `;
1682
2148
  continue;
1683
2149
  }
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)}`;
2150
+ const isRetracted = nextTermIsRetracted;
2151
+ nextTermIsRetracted = false;
2152
+ if (part.startsWith("?") || part.startsWith("!")) {
2153
+ const marker = part[0];
2154
+ const rest = part.slice(1);
2155
+ const color = isRetracted ? TOKEN_COLORS.retraction : TOKEN_COLORS.marker;
2156
+ result += `<span style="color: ${color}">${escapeHtml(marker)}</span>${renderTerm(rest, isRetracted, prefixes)}`;
1688
2157
  continue;
1689
2158
  }
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)}`;
2159
+ if (part.startsWith("^^")) {
2160
+ const marker = "^^";
2161
+ const rest = part.slice(2);
2162
+ const color = isRetracted ? TOKEN_COLORS.retraction : TOKEN_COLORS.marker;
2163
+ result += `<span style="color: ${color}">${escapeHtml(marker)}</span>${renderTerm(rest, isRetracted, prefixes)}`;
1693
2164
  continue;
1694
2165
  }
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)}`;
2166
+ if (part.startsWith("@")) {
2167
+ const marker = "@";
2168
+ const rest = part.slice(1);
2169
+ const color = isRetracted ? TOKEN_COLORS.retraction : TOKEN_COLORS.marker;
2170
+ result += `<span style="color: ${color}">${escapeHtml(marker)}</span>${renderTerm(rest, isRetracted, prefixes)}`;
1698
2171
  continue;
1699
2172
  }
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)}`;
2173
+ if (part.startsWith(".")) {
2174
+ const marker = ".";
2175
+ const rest = part.slice(1);
2176
+ const color = isRetracted ? TOKEN_COLORS.retraction : TOKEN_COLORS.marker;
2177
+ result += `<span style="color: ${color}">${escapeHtml(marker)}</span>${renderTerm(rest, isRetracted, prefixes)}`;
1703
2178
  continue;
1704
2179
  }
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++;
2180
+ result += renderTerm(part, isRetracted, prefixes);
2181
+ }
2182
+ return result.trim();
2183
+ }
2184
+ function highlightMDLD(code) {
2185
+ const prefixes = extractPrefixes(code);
2186
+ let result = "";
2187
+ let i = 0;
2188
+ while (i < code.length) {
2189
+ const char = code[i];
2190
+ if (char === "{") {
2191
+ const endIdx = code.indexOf("}", i);
2192
+ if (endIdx === -1) {
2193
+ result += escapeHtml(char);
2194
+ i++;
1717
2195
  continue;
1718
2196
  }
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;
2197
+ const parsed = parseAnnotation(code.slice(i + 1, endIdx), prefixes);
2198
+ result += `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">{</span>`;
2199
+ result += parsed;
2200
+ result += `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">}</span>`;
2201
+ i = endIdx + 1;
1721
2202
  continue;
1722
2203
  }
1723
- if (i === "[") {
1724
- let a = e.indexOf("]", r);
1725
- if (a === -1) {
1726
- n += J(i), r++;
2204
+ if (char === "[") {
2205
+ const endBracket = code.indexOf("]", i);
2206
+ if (endBracket === -1) {
2207
+ result += escapeHtml(char);
2208
+ i++;
1727
2209
  continue;
1728
2210
  }
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;
2211
+ const prefixName = code.slice(i + 1, endBracket);
2212
+ let j = endBracket + 1;
2213
+ while (j < code.length && /\s/.test(code[j])) j++;
2214
+ if (j < code.length && code[j] === "<") {
2215
+ const iriEnd = code.indexOf(">", j);
2216
+ if (iriEnd !== -1) {
2217
+ const iriContent = code.slice(j + 1, iriEnd);
2218
+ const prefixColor = prefixes.has(prefixName) ? getIRIColor(prefixes.get(prefixName)) : TOKEN_COLORS.text;
2219
+ 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>`;
2220
+ i = iriEnd + 1;
1736
2221
  continue;
1737
2222
  }
1738
2223
  }
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;
2224
+ const content = code.slice(i + 1, endBracket);
2225
+ const bracketColor = hasFollowingAnnotation(code, endBracket + 1) ? TOKEN_COLORS.marker : TOKEN_COLORS.value;
2226
+ const escapedContent = escapeHtml(content);
2227
+ result += `<span style="color: ${bracketColor}; opacity: 0.85">[</span><span style=" opacity: 1.0">${escapedContent}</span><span style="color: ${bracketColor}; opacity: 0.85">]</span>`;
2228
+ i = endBracket + 1;
1741
2229
  continue;
1742
2230
  }
1743
- if (i === "*" || i === "_" || i === "`") {
1744
- let t = vt(e, r);
1745
- if (t) {
1746
- n += t.html, r = t.nextIndex;
2231
+ if (char === "*" || char === "_" || char === "`") {
2232
+ const processed = processMarkdownFormattingAtPosition(code, i);
2233
+ if (processed) {
2234
+ result += processed.html;
2235
+ i = processed.nextIndex;
1747
2236
  continue;
1748
2237
  }
1749
2238
  }
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);
2239
+ if (char === "#") {
2240
+ let hashCount = 0;
2241
+ let j = i;
2242
+ while (j < code.length && code[j] === "#") {
2243
+ hashCount++;
2244
+ j++;
2245
+ }
2246
+ if (hashCount <= 6 && (j >= code.length || code[j] === " " || code[j] === " ")) {
2247
+ const lineEnd = code.indexOf("\n", j);
2248
+ const endIdx = lineEnd === -1 ? code.length : lineEnd;
2249
+ const headerText = code.slice(j, endIdx).trim();
2250
+ let processedHeaderText = "";
2251
+ let lastIndex = 0;
2252
+ let annotationStart = headerText.indexOf("{");
2253
+ while (annotationStart !== -1) {
2254
+ const annotationEnd = headerText.indexOf("}", annotationStart);
2255
+ if (annotationEnd === -1) break;
2256
+ const beforeText = headerText.slice(lastIndex, annotationStart);
2257
+ processedHeaderText += escapeHtml(beforeText);
2258
+ const parsedAnnotation = parseAnnotation(headerText.slice(annotationStart + 1, annotationEnd), prefixes);
2259
+ processedHeaderText += `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">{</span>` + parsedAnnotation + `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">}</span>`;
2260
+ lastIndex = annotationEnd + 1;
2261
+ annotationStart = headerText.indexOf("{", lastIndex);
1762
2262
  }
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;
2263
+ processedHeaderText += escapeHtml(headerText.slice(lastIndex));
2264
+ const hasAnnotation = headerText.includes("{") && headerText.includes("}");
2265
+ const headingTag = `h${hashCount}`;
2266
+ const headingStyle = `margin: 0; font-weight: 600;`;
2267
+ const hashes = "#".repeat(hashCount);
2268
+ const hashColor = hasAnnotation ? `color: ${TOKEN_COLORS.marker}; opacity: 0.8` : "";
2269
+ result += `<${headingTag} style="${headingStyle}"><span style="${hashColor}">${hashes}</span> ${processedHeaderText}</${headingTag}>`;
2270
+ i = endIdx;
1766
2271
  continue;
1767
2272
  }
1768
2273
  }
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;
2274
+ if (char === "-" || char === "*") {
2275
+ const prevChar = i > 0 ? code[i - 1] : "\n";
2276
+ if (prevChar === "\n" || prevChar === "\r" || prevChar === " " || prevChar === " ") {
2277
+ if (code[i + 1] === " ") {
2278
+ const markerColor = hasFollowingAnnotation(code, i + 2) ? `color: ${TOKEN_COLORS.marker}; opacity: 0.85` : "";
2279
+ result += `<span style="${markerColor}">${escapeHtml(char)}</span>`;
2280
+ i++;
2281
+ continue;
2282
+ }
1775
2283
  }
1776
2284
  }
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;
2285
+ if (char === ">") {
2286
+ const prevChar = i > 0 ? code[i - 1] : "\n";
2287
+ if (prevChar === "\n" || prevChar === "\r" || prevChar === " " || prevChar === " ") {
2288
+ if (code[i + 1] === " ") {
2289
+ const markerColor = hasFollowingAnnotation(code, i + 2) ? `color: ${TOKEN_COLORS.marker}; opacity: 0.85` : "";
2290
+ result += `<span style="${markerColor}">${escapeHtml(char)}</span>`;
2291
+ i++;
2292
+ continue;
2293
+ }
1783
2294
  }
1784
2295
  }
1785
- n += J(i), r++;
2296
+ result += escapeHtml(char);
2297
+ i++;
1786
2298
  }
1787
- return n;
2299
+ return result;
1788
2300
  }
1789
2301
  //#endregion
1790
2302
  //#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);
2303
+ /**
2304
+ * Update the value of a quad in MDLD text and return the updated text
2305
+ *
2306
+ * @param {Object} params - Parameters object
2307
+ * @param {string} params.text - The original MDLD text
2308
+ * @param {Object} params.quad - The quad to update (subject, predicate, object)
2309
+ * @param {string} params.value - The new value to set
2310
+ * @param {Object} [params.origin] - Origin object or ParseResult (if not provided, text will be parsed)
2311
+ * @returns {string} Updated MDLD text, or original if update fails
2312
+ */
2313
+ function updateValue({ text, quad, value, origin }) {
2314
+ const location = locate(quad, origin?.quadIndex ? origin : parse({ text }).origin);
2315
+ if (!location || !location.valueRange) return text;
2316
+ return text.substring(0, location.valueRange.start) + value + text.substring(location.valueRange.end);
1794
2317
  }
1795
2318
  //#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 };
2319
+ export { DEFAULT_CONTEXT, DataFactory, expandIRI, generate, generateNode, getIRIColor, hash, hashIRI, highlightMDLD, locate, merge, parse, parseSemanticBlock, shortenIRI, updateValue };