mdld-parse 0.9.8 → 1.0.0

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