@teipublisher/oddity-language-server 0.0.0-stage → 0.1.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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +48 -2
  3. package/dist/edit.js +313 -0
  4. package/dist/edit.js.map +7 -0
  5. package/dist/index.js +803 -0
  6. package/dist/index.js.map +7 -0
  7. package/dist/node.cjs +44962 -0
  8. package/dist/node.cjs.map +7 -0
  9. package/package.json +74 -4
  10. package/schema/README.md +41 -0
  11. package/schema/docbook/docbook.rng +18457 -0
  12. package/schema/jats/BITS-embedded-index2.ent.rng +340 -0
  13. package/schema/jats/BITS-question-answer2.ent.rng +795 -0
  14. package/schema/jats/JATS-XHTMLtablesetup1-3.ent.rng +614 -0
  15. package/schema/jats/JATS-ali-namespace1-3.ent.rng +284 -0
  16. package/schema/jats/JATS-archivearticle1-3-mathml3.rng +1277 -0
  17. package/schema/jats/JATS-archivecustom-classes1-3.ent.rng +427 -0
  18. package/schema/jats/JATS-archivecustom-mixes1-3.ent.rng +630 -0
  19. package/schema/jats/JATS-archivecustom-models1-3.ent.rng +2205 -0
  20. package/schema/jats/JATS-articlemeta1-3.ent.rng +3138 -0
  21. package/schema/jats/JATS-backmatter1-3.ent.rng +601 -0
  22. package/schema/jats/JATS-chars1-3.ent.rng +715 -0
  23. package/schema/jats/JATS-common-atts1-3.ent.rng +367 -0
  24. package/schema/jats/JATS-common1-3.ent.rng +6007 -0
  25. package/schema/jats/JATS-default-classes1-3.ent.rng +1953 -0
  26. package/schema/jats/JATS-default-mixes1-3.ent.rng +583 -0
  27. package/schema/jats/JATS-display1-3.ent.rng +1669 -0
  28. package/schema/jats/JATS-format1-3.ent.rng +1256 -0
  29. package/schema/jats/JATS-funding1-3.ent.rng +1389 -0
  30. package/schema/jats/JATS-journalmeta1-3.ent.rng +691 -0
  31. package/schema/jats/JATS-link1-3.ent.rng +664 -0
  32. package/schema/jats/JATS-list1-3.ent.rng +747 -0
  33. package/schema/jats/JATS-math1-3.ent.rng +620 -0
  34. package/schema/jats/JATS-mathml3-mathmlsetup1-3.ent.rng +459 -0
  35. package/schema/jats/JATS-nlmcitation1-3.ent.rng +522 -0
  36. package/schema/jats/JATS-para1-3.ent.rng +780 -0
  37. package/schema/jats/JATS-phrase1-3.ent.rng +725 -0
  38. package/schema/jats/JATS-references1-3.ent.rng +1713 -0
  39. package/schema/jats/JATS-related-object1-3.ent.rng +453 -0
  40. package/schema/jats/JATS-section1-3.ent.rng +482 -0
  41. package/schema/jats/mathml3-qname1.mod.rng +61 -0
  42. package/schema/jats/mathml3.rng +4094 -0
  43. package/schema/jats/xhtml-inlstyle-1.mod.rng +37 -0
  44. package/schema/jats/xhtml-table-1.mod.rng +426 -0
  45. package/schema/odd/teipublisher_odds.rng +12769 -0
  46. package/schema/tei/tei_all.rng +23212 -0
  47. package/src/core/association.ts +155 -0
  48. package/src/core/complete.ts +147 -0
  49. package/src/core/elements.ts +86 -0
  50. package/src/core/outline.ts +156 -0
  51. package/src/core/schema.ts +55 -0
  52. package/src/core/tags.ts +104 -0
  53. package/src/core/toml.ts +64 -0
  54. package/src/core/validate.ts +128 -0
  55. package/src/core/wellformed.ts +16 -0
  56. package/src/edit.ts +11 -0
  57. package/src/index.ts +16 -0
  58. package/src/node.ts +39 -0
  59. package/src/server/server.ts +248 -0
package/dist/index.js ADDED
@@ -0,0 +1,803 @@
1
+ // src/core/validate.ts
2
+ import {
3
+ AnyName,
4
+ AttributeNameError,
5
+ AttributeValueError,
6
+ ChoiceError,
7
+ DefaultNameResolver,
8
+ Name,
9
+ NameChoice,
10
+ NsName
11
+ } from "salve-annos";
12
+ import { SaxesParser } from "saxes";
13
+ var MAX = 200;
14
+ function nameText(n, resolver, attribute) {
15
+ if (n instanceof Name) {
16
+ if (!n.ns || attribute && n.ns === "") return n.name;
17
+ const q2 = resolver.unresolveName(n.ns, n.name);
18
+ return q2 ?? `${n.name} (${n.ns})`;
19
+ }
20
+ if (n instanceof NameChoice) return `${nameText(n.a, resolver, attribute)} or ${nameText(n.b, resolver, attribute)}`;
21
+ if (n instanceof NsName) return `any name in ${n.ns}`;
22
+ if (n instanceof AnyName) return "any name";
23
+ return String(n);
24
+ }
25
+ function messageOf(e, resolver, value) {
26
+ const attribute = e instanceof AttributeNameError || e instanceof AttributeValueError;
27
+ const names2 = e.getNames().map((n) => nameText(n, resolver, attribute));
28
+ const one = names2.join(", ");
29
+ switch (e.msg) {
30
+ case "tag not allowed here":
31
+ return `<${one}> is not allowed here`;
32
+ case "tag required":
33
+ return `<${one}> is required here`;
34
+ case "unexpected end tag":
35
+ return `</${one}> was not expected here`;
36
+ case "attribute not allowed here":
37
+ return `@${one} is not allowed here`;
38
+ case "attribute missing":
39
+ return `Required attribute @${one} is missing`;
40
+ case "invalid attribute value":
41
+ return value === void 0 ? `Invalid value for @${one}` : `"${value}" is not a valid value for @${one}`;
42
+ case "text not allowed here":
43
+ return "Text is not allowed here";
44
+ }
45
+ if (e instanceof ChoiceError) return `Expected one of: ${names2.map((n) => `<${n}>`).join(", ")}`;
46
+ const text = e.toStringWithNames(names2);
47
+ return text.charAt(0).toUpperCase() + text.slice(1);
48
+ }
49
+ function validate(grammar, xml) {
50
+ const resolver = new DefaultNameResolver();
51
+ const walker = grammar.newWalker(resolver);
52
+ const parser = new SaxesParser({ xmlns: true, position: true });
53
+ const problems = [];
54
+ let broken = false;
55
+ let tagFrom = 0, tagTo = 0, textFrom = 0;
56
+ let text = "";
57
+ const report = (r, from, to, value) => {
58
+ if (!r) return;
59
+ for (const e of r) if (problems.length < MAX) problems.push({ from, to, message: messageOf(e, resolver, value) });
60
+ };
61
+ const flush = () => {
62
+ if (text === "") return;
63
+ if (text.trim() !== "") report(walker.fireEvent("text", [text]), textFrom, tagFrom);
64
+ text = "";
65
+ };
66
+ const nameSpan = (from, name, closing) => {
67
+ const start = from + (closing ? 2 : 1);
68
+ return [start, start + name.length];
69
+ };
70
+ parser.on("opentag", (node) => {
71
+ if (broken) return;
72
+ tagTo = parser.position;
73
+ tagFrom = xml.lastIndexOf("<", tagTo - 1);
74
+ flush();
75
+ resolver.enterContext();
76
+ for (const [qn, a] of Object.entries(node.attributes)) {
77
+ if (qn === "xmlns") resolver.definePrefix("", a.value);
78
+ else if (a.prefix === "xmlns") resolver.definePrefix(a.local, a.value);
79
+ }
80
+ const [nf, nt] = nameSpan(tagFrom, node.name, false);
81
+ report(walker.fireEvent("enterStartTag", [node.uri, node.local]), nf, nt);
82
+ const tag = xml.slice(tagFrom, tagTo);
83
+ for (const [qn, a] of Object.entries(node.attributes)) {
84
+ if (qn === "xmlns" || a.prefix === "xmlns") continue;
85
+ const at = tag.search(new RegExp(`\\s${qn.replace(/[.*+?^${}()|[\]\\-]/g, "\\$&")}\\s*=`));
86
+ const af = at < 0 ? nf : tagFrom + at + 1, aend = at < 0 ? nt : af + qn.length;
87
+ report(walker.fireEvent("attributeName", [a.uri, a.local]), af, aend);
88
+ report(walker.fireEvent("attributeValue", [a.value]), af, aend, a.value);
89
+ }
90
+ report(walker.fireEvent("leaveStartTag", []), nf, nt);
91
+ if (node.isSelfClosing) return;
92
+ textFrom = tagTo;
93
+ });
94
+ parser.on("closetag", (node) => {
95
+ if (broken) return;
96
+ if (node.isSelfClosing) {
97
+ report(walker.fireEvent("endTag", [node.uri, node.local]), ...nameSpan(tagFrom, node.name, false));
98
+ } else {
99
+ tagTo = parser.position;
100
+ tagFrom = xml.lastIndexOf("</", tagTo - 1);
101
+ flush();
102
+ report(walker.fireEvent("endTag", [node.uri, node.local]), ...nameSpan(tagFrom, node.name, true));
103
+ }
104
+ resolver.leaveContext();
105
+ textFrom = tagTo;
106
+ });
107
+ parser.on("text", (s) => {
108
+ text += s;
109
+ });
110
+ parser.on("cdata", (s) => {
111
+ text += s;
112
+ });
113
+ parser.on("error", (e) => {
114
+ if (broken) return;
115
+ broken = true;
116
+ const at = Math.min(parser.position, xml.length);
117
+ problems.push({ from: Math.max(0, at - 1), to: at, message: e.message.replace(/^(?:[^:\n]*:)?\d+:\d+: /, "") });
118
+ });
119
+ try {
120
+ parser.write(xml).close();
121
+ } catch {
122
+ }
123
+ if (broken) return problems;
124
+ const end = walker.end();
125
+ report(end, tagFrom, tagTo);
126
+ return problems;
127
+ }
128
+
129
+ // src/core/complete.ts
130
+ import { DefaultNameResolver as DefaultNameResolver2, Name as Name2, NameChoice as NameChoice2 } from "salve-annos";
131
+ import { SaxesParser as SaxesParser2 } from "saxes";
132
+ var DETAIL_MAX = 80;
133
+ function described(doc) {
134
+ const text = (doc ?? "").replace(/\s+/g, " ").trim().replace(/\s*\[\d+(?:\.\d+)*\.\s[^[\]]*\]$/, "");
135
+ if (!text) return {};
136
+ const gloss = text.match(/^\(([^()]+)\)\s*(.*)$/);
137
+ if (gloss) return gloss[2] ? { detail: gloss[1], info: gloss[2] } : { detail: gloss[1] };
138
+ let detail = text.split(/(?<=[.;:])\s/, 1)[0].replace(/[.;:]$/, "");
139
+ if (detail.length > DETAIL_MAX) detail = detail.slice(0, DETAIL_MAX).replace(/\s\S*$/, "") + "\u2026";
140
+ return detail === text ? { detail } : { detail, info: text };
141
+ }
142
+ function names(n, resolver, attribute) {
143
+ if (n instanceof NameChoice2) return [...names(n.a, resolver, attribute), ...names(n.b, resolver, attribute)];
144
+ if (!(n instanceof Name2)) return [];
145
+ const label = attribute && n.ns === "" ? n.name : resolver.unresolveName(n.ns, n.name);
146
+ return label ? [{ label, doc: n.documentation }] : [];
147
+ }
148
+ var ATTR = /\s([^\s=/>]+)\s*=\s*("[^"]*"|'[^']*')/g;
149
+ function context(before) {
150
+ for (const [open, close] of [["<!--", "-->"], ["<![CDATA[", "]]>"], ["<?", "?>"]]) {
151
+ if (before.lastIndexOf(open) > before.lastIndexOf(close)) return null;
152
+ }
153
+ const lt = before.lastIndexOf("<");
154
+ if (lt <= before.lastIndexOf(">")) return { at: "text", tagStart: before.length };
155
+ const tag = before.slice(lt);
156
+ if (/^<[/!?]/.test(tag)) return null;
157
+ const partialName = tag.match(/^<([^\s/>]*)$/);
158
+ if (partialName) return { at: "name", tagStart: lt, typed: partialName[1] };
159
+ const name = tag.match(/^<([^\s/>]+)/)?.[1];
160
+ if (!name) return null;
161
+ const done = [...tag.matchAll(ATTR)];
162
+ const tail = tag.slice(done.length ? done[done.length - 1].index + done[done.length - 1][0].length : name.length + 1);
163
+ const attrs = done.map((m) => ({ name: m[1], value: m[2].slice(1, -1) }));
164
+ const inValue = tail.match(/\s([^\s=/>]+)\s*=\s*(["'])([^"']*)$/);
165
+ if (inValue) return { at: "value", tagStart: lt, name, attrs, attr: inValue[1], typed: inValue[3] };
166
+ const inName = tail.match(/\s([^\s=/>]*)$/);
167
+ if (inName) return { at: "attribute", tagStart: lt, name, attrs, typed: inName[1] };
168
+ return null;
169
+ }
170
+ function possibleAt(grammar, xml, at) {
171
+ const before = xml.slice(0, at);
172
+ const ctx = context(before);
173
+ if (!ctx) return null;
174
+ const resolver = new DefaultNameResolver2();
175
+ const walker = grammar.newWalker(resolver);
176
+ const parser = new SaxesParser2({ xmlns: true });
177
+ let text = "";
178
+ const flush = () => {
179
+ if (text.trim() !== "") walker.fireEvent("text", [text]);
180
+ text = "";
181
+ };
182
+ parser.on("error", () => {
183
+ });
184
+ parser.on("opentag", (node) => {
185
+ flush();
186
+ resolver.enterContext();
187
+ for (const [qn, a] of Object.entries(node.attributes)) {
188
+ if (qn === "xmlns") resolver.definePrefix("", a.value);
189
+ else if (a.prefix === "xmlns") resolver.definePrefix(a.local, a.value);
190
+ }
191
+ walker.fireEvent("enterStartTag", [node.uri, node.local]);
192
+ for (const [qn, a] of Object.entries(node.attributes)) {
193
+ if (qn === "xmlns" || a.prefix === "xmlns") continue;
194
+ walker.fireEvent("attributeName", [a.uri, a.local]);
195
+ walker.fireEvent("attributeValue", [a.value]);
196
+ }
197
+ walker.fireEvent("leaveStartTag", []);
198
+ });
199
+ parser.on("closetag", (node) => {
200
+ flush();
201
+ walker.fireEvent("endTag", [node.uri, node.local]);
202
+ resolver.leaveContext();
203
+ });
204
+ parser.on("text", (s) => {
205
+ text += s;
206
+ });
207
+ parser.on("cdata", (s) => {
208
+ text += s;
209
+ });
210
+ try {
211
+ parser.write(xml.slice(0, ctx.tagStart));
212
+ } catch {
213
+ }
214
+ flush();
215
+ const seen = /* @__PURE__ */ new Set();
216
+ const suggestions = [];
217
+ const add = (kind, label, doc) => {
218
+ if (seen.has(label)) return;
219
+ seen.add(label);
220
+ suggestions.push({ kind, label, ...described(doc) });
221
+ };
222
+ if (ctx.at === "text" || ctx.at === "name") {
223
+ for (const ev of walker.possible()) {
224
+ if (ev.name === "enterStartTag") for (const n2 of names(ev.param, resolver, false)) add("element", n2.label, n2.doc);
225
+ }
226
+ return { from: at - (ctx.at === "name" ? ctx.typed.length : 0), inTag: ctx.at === "name", suggestions };
227
+ }
228
+ resolver.enterContext();
229
+ for (const a of ctx.attrs) {
230
+ if (a.name === "xmlns") resolver.definePrefix("", a.value);
231
+ else if (a.name.startsWith("xmlns:")) resolver.definePrefix(a.name.slice(6), a.value);
232
+ }
233
+ const element = resolver.resolveName(ctx.name);
234
+ if (!element) return null;
235
+ walker.fireEvent("enterStartTag", [element.ns, element.name]);
236
+ const written = /* @__PURE__ */ new Set();
237
+ for (const a of ctx.attrs) {
238
+ written.add(a.name);
239
+ if (a.name === "xmlns" || a.name.startsWith("xmlns:") || ctx.at === "value" && a.name === ctx.attr) continue;
240
+ const n2 = resolver.resolveName(a.name, true);
241
+ if (!n2) continue;
242
+ walker.fireEvent("attributeName", [n2.ns, n2.name]);
243
+ walker.fireEvent("attributeValue", [a.value]);
244
+ }
245
+ if (ctx.at === "attribute") {
246
+ for (const ev of walker.possible()) {
247
+ if (ev.name !== "attributeName") continue;
248
+ for (const n2 of names(ev.param, resolver, true)) if (!written.has(n2.label)) add("attribute", n2.label, n2.doc);
249
+ }
250
+ return { from: at - ctx.typed.length, inTag: true, suggestions };
251
+ }
252
+ const n = resolver.resolveName(ctx.attr, true);
253
+ if (!n) return null;
254
+ walker.fireEvent("attributeName", [n.ns, n.name]);
255
+ for (const ev of walker.possible()) {
256
+ if (ev.name === "attributeValue" && typeof ev.param === "string") add("value", ev.param, ev.documentation);
257
+ }
258
+ return { from: at - ctx.typed.length, inTag: true, suggestions };
259
+ }
260
+
261
+ // src/core/wellformed.ts
262
+ import { SaxesParser as SaxesParser3 } from "saxes";
263
+ function wellFormed(xml) {
264
+ const parser = new SaxesParser3({ xmlns: true, position: true });
265
+ const problems = [];
266
+ parser.on("error", (e) => {
267
+ if (problems.length) return;
268
+ const at = Math.min(parser.position, xml.length);
269
+ problems.push({ from: Math.max(0, at - 1), to: at, message: e.message.replace(/^(?:[^:\n]*:)?\d+:\d+: /, "") });
270
+ });
271
+ try {
272
+ parser.write(xml).close();
273
+ } catch {
274
+ }
275
+ return problems;
276
+ }
277
+
278
+ // src/core/schema.ts
279
+ import { convertRNGToPattern } from "salve-annos";
280
+ var Grammars = class {
281
+ entries = /* @__PURE__ */ new Map();
282
+ readText;
283
+ constructor(readText) {
284
+ this.readText = readText;
285
+ }
286
+ /** The grammar of the RNG at url, compiled once. */
287
+ get(url) {
288
+ const known = this.entries.get(url);
289
+ if (known) return known.grammar;
290
+ const files = /* @__PURE__ */ new Set();
291
+ const resourceLoader = {
292
+ load: async (u) => {
293
+ files.add(u.href);
294
+ const text = await this.readText(u);
295
+ return { url: u, getText: async () => text };
296
+ }
297
+ };
298
+ const grammar = convertRNGToPattern(new URL(url), { resourceLoader }).then((r) => r.pattern);
299
+ const entry = { grammar, files };
300
+ this.entries.set(url, entry);
301
+ grammar.catch(() => {
302
+ if (this.entries.get(url) === entry) this.entries.delete(url);
303
+ });
304
+ return grammar;
305
+ }
306
+ /** Forget every grammar read from url, or all of them. Returns whether any was dropped. */
307
+ invalidate(url) {
308
+ if (url === void 0) {
309
+ const any = this.entries.size > 0;
310
+ this.entries.clear();
311
+ return any;
312
+ }
313
+ let dropped = false;
314
+ for (const [key, e] of this.entries) {
315
+ if (key === url || e.files.has(url)) {
316
+ this.entries.delete(key);
317
+ dropped = true;
318
+ }
319
+ }
320
+ return dropped;
321
+ }
322
+ };
323
+
324
+ // src/core/toml.ts
325
+ import { parse } from "smol-toml";
326
+ var q = (s) => JSON.stringify(s);
327
+ var sectionEnd = (lines, head) => {
328
+ for (let i = head + 1; i < lines.length; i++) if (/^\s*\[/.test(lines[i])) return i;
329
+ return lines.length;
330
+ };
331
+ function setToml(text, section, key, value) {
332
+ const line = `${key} = ${q(value)}`, lines = text ? text.split("\n") : [];
333
+ const head = lines.findIndex((l) => l.trim() === `[${section}]`);
334
+ if (head < 0) return (text && !text.endsWith("\n") ? text + "\n" : text) + (text ? "\n" : "") + `[${section}]
335
+ ${line}
336
+ `;
337
+ const end = sectionEnd(lines, head), re = new RegExp(`^\\s*${key}\\s*=`);
338
+ for (let i = head + 1; i < end; i++) if (re.test(lines[i])) {
339
+ lines[i] = line;
340
+ return lines.join("\n");
341
+ }
342
+ lines.splice(head + 1, 0, line);
343
+ return lines.join("\n");
344
+ }
345
+ function unsetToml(text, section, key) {
346
+ const lines = text.split("\n"), head = lines.findIndex((l) => l.trim() === `[${section}]`);
347
+ if (head < 0) return text;
348
+ const end = sectionEnd(lines, head), re = new RegExp(`^\\s*${key}\\s*=`);
349
+ for (let i = head + 1; i < end; i++) if (re.test(lines[i])) {
350
+ lines.splice(i, 1);
351
+ break;
352
+ }
353
+ return lines.join("\n");
354
+ }
355
+ function readToml(text) {
356
+ let doc;
357
+ try {
358
+ doc = parse(text);
359
+ } catch {
360
+ return {};
361
+ }
362
+ const cfg = {};
363
+ const walk = (table, path) => {
364
+ for (const [key, v] of Object.entries(table)) {
365
+ if (typeof v === "string" || Array.isArray(v) && v.length && v.every((x) => typeof x === "string")) {
366
+ (cfg[path.join(".")] ||= {})[key] = v;
367
+ } else if (Array.isArray(v) && !v.length) {
368
+ (cfg[path.join(".")] ||= {})[key] = [];
369
+ } else if (v && typeof v === "object" && !Array.isArray(v) && !(v instanceof Date)) {
370
+ walk(v, [...path, key]);
371
+ }
372
+ }
373
+ };
374
+ walk(doc, []);
375
+ return cfg;
376
+ }
377
+ var tomlString = (cfg, section, key) => {
378
+ const v = cfg[section]?.[key];
379
+ return typeof v === "string" ? v : "";
380
+ };
381
+
382
+ // src/core/association.ts
383
+ var RNG_NS = "http://relaxng.org/ns/structure/1.0";
384
+ var isOdd = (url) => /\.odd$/i.test(new URL(url).pathname);
385
+ var DEFAULT_SCHEMA_FILES = {
386
+ odd: "odd/teipublisher_odds.rng",
387
+ tei: "tei/tei_all.rng",
388
+ docbook: "docbook/docbook.rng",
389
+ jats: "jats/JATS-archivearticle1-3-mathml3.rng"
390
+ };
391
+ var PUBLIC_SCHEMA_URLS = {
392
+ tei: "https://tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng",
393
+ docbook: "https://cdn.docbook.org/schema/5.2/rng/docbook.rng",
394
+ jats: "https://jats.nlm.nih.gov/archiving/1.3/rng/JATS-archivearticle1-3-mathml3.rng"
395
+ };
396
+ function publicSchema(url) {
397
+ if (/^https?:\/\/(www\.)?tei-c\.org\/.*\/tei_all\.rng$/i.test(url)) return "tei";
398
+ if (/^https?:\/\/([\w-]+\.)?docbook\.org\/.*\/docbook\.rng$/i.test(url)) return "docbook";
399
+ if (/^https?:\/\/jats\.nlm\.nih\.gov\/.*\.rng$/i.test(url)) return "jats";
400
+ return void 0;
401
+ }
402
+ function vocabulary(text) {
403
+ const head = text.slice(0, 5e3);
404
+ if (head.includes("http://www.tei-c.org/ns/1.0") || /<(TEI|teiCorpus)[\s>]/.test(head)) return "tei";
405
+ if (head.includes("http://docbook.org/ns/docbook")) return "docbook";
406
+ if (/<!DOCTYPE\s+article\s+PUBLIC\s+"-\/\/NLM\/\/DTD/.test(head)) return "jats";
407
+ const article = head.match(/<article(?=[\s>])[^>]*>/)?.[0];
408
+ if (article && !/\sxmlns\s*=/.test(article) && (/\s(dtd-version|article-type)\s*=/.test(article) || /<front[\s>]/.test(head))) return "jats";
409
+ return "";
410
+ }
411
+ function xmlModels(text) {
412
+ const out = [];
413
+ for (const m of text.slice(0, 5e3).matchAll(/<\?xml-model\s([^?]*)\?>/g)) {
414
+ const pseudo = (name) => m[1].match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']*)["']`))?.[1];
415
+ out.push({ from: m.index, to: m.index + m[0].length, href: pseudo("href"), schematypens: pseudo("schematypens"), raw: m[0] });
416
+ }
417
+ return out;
418
+ }
419
+ var isRngModel = (pi) => pi.schematypens === RNG_NS || !pi.schematypens && !!pi.href && /\.rng$/i.test(pi.href) && !/schematron/i.test(pi.raw);
420
+ function projectRoot(url, files, stops = []) {
421
+ let dir = new URL("./", url);
422
+ for (; ; ) {
423
+ if (files.exists(new URL("opm.toml", dir).href)) return dir.href;
424
+ const parent = new URL("../", dir);
425
+ if (parent.href === dir.href || stops.some((s) => sameDir(s, dir.href))) return void 0;
426
+ dir = parent;
427
+ }
428
+ }
429
+ var sameDir = (a, b) => a.replace(/\/?$/, "/") === b.replace(/\/?$/, "/");
430
+ function schemaFor(url, text, files, defaults, stops = []) {
431
+ for (const pi of xmlModels(text)) {
432
+ if (!isRngModel(pi) || !pi.href) continue;
433
+ if (/^(https?|ftp):/i.test(pi.href)) {
434
+ const bundled = defaults[publicSchema(pi.href) ?? ""];
435
+ if (bundled) return { url: bundled, via: "xml-model" };
436
+ continue;
437
+ }
438
+ const target = new URL(pi.href, url).href;
439
+ if (files.exists(target)) return { url: target, via: "xml-model" };
440
+ }
441
+ const odd = isOdd(url);
442
+ if (!odd) {
443
+ const root = projectRoot(url, files, stops);
444
+ const toml = root && files.read(new URL("opm.toml", root).href);
445
+ const configured = toml ? tomlString(readToml(toml), "editor", "schema") : "";
446
+ if (configured && /\.rng$/i.test(configured)) {
447
+ const bundled = defaults[publicSchema(configured) ?? ""];
448
+ if (bundled) return { url: bundled, via: "project" };
449
+ const target = new URL(configured, root).href;
450
+ if (files.exists(target)) return { url: target, via: "project" };
451
+ }
452
+ }
453
+ const fallback = defaults[odd ? "odd" : vocabulary(text)];
454
+ return fallback ? { url: fallback, via: "default" } : null;
455
+ }
456
+ function relativeHref(from, to) {
457
+ const a = new URL(from), b = new URL(to);
458
+ if (a.protocol !== b.protocol || a.host !== b.host) return to;
459
+ const dir = a.pathname.split("/").slice(0, -1), target = b.pathname.split("/");
460
+ let i = 0;
461
+ while (i < dir.length && i < target.length - 1 && dir[i] === target[i]) i++;
462
+ return [...Array(dir.length - i).fill(".."), ...target.slice(i)].join("/");
463
+ }
464
+ function xmlModelEdits(text, href) {
465
+ const nl = text.includes("\r\n") ? "\r\n" : "\n";
466
+ const models = xmlModels(text).filter(isRngModel);
467
+ const pi = href && `<?xml-model href="${href.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}" type="application/xml" schematypens="${RNG_NS}"?>`;
468
+ const removal = (m) => {
469
+ const after = text.slice(m.to).match(/^\r?\n/)?.[0].length ?? 0;
470
+ return { from: m.from, to: m.to + after, insert: "" };
471
+ };
472
+ if (!pi) return models.map(removal);
473
+ if (models.length) return [{ from: models[0].from, to: models[0].to, insert: pi }, ...models.slice(1).map(removal)];
474
+ const decl = text.match(/^?<\?xml\s[^?]*\?>/);
475
+ if (decl) return [{ from: decl[0].length, to: decl[0].length, insert: nl + pi }];
476
+ const bom = text.startsWith("\uFEFF") ? 1 : 0;
477
+ return [{ from: bom, to: bom, insert: pi + nl }];
478
+ }
479
+
480
+ // src/core/tags.ts
481
+ var SKIP = [["<!--", "-->"], ["<![CDATA[", "]]>"], ["<?", "?>"], ["<!", ">"]];
482
+ function scanTags(text) {
483
+ const tags = [];
484
+ let i = 0;
485
+ while ((i = text.indexOf("<", i)) >= 0) {
486
+ const skip = SKIP.find(([open]) => text.startsWith(open, i));
487
+ if (skip) {
488
+ const end = text.indexOf(skip[1], i + skip[0].length);
489
+ if (end < 0) break;
490
+ i = end + skip[1].length;
491
+ continue;
492
+ }
493
+ const closing = text[i + 1] === "/";
494
+ const nameFrom = i + (closing ? 2 : 1);
495
+ const name = text.slice(nameFrom).match(/^[^\s<>/="']*/)[0];
496
+ let j = nameFrom + name.length, quote = "";
497
+ for (; j < text.length; j++) {
498
+ const c = text[j];
499
+ if (quote) {
500
+ if (c === quote) quote = "";
501
+ } else if (c === '"' || c === "'") quote = c;
502
+ else if (c === ">" || c === "<") break;
503
+ }
504
+ const finished = text[j] === ">";
505
+ const to = finished ? j + 1 : j;
506
+ const kind = closing ? "close" : finished && text[j - 1] === "/" ? "empty" : "open";
507
+ tags.push({ kind, name, from: i, nameFrom, nameTo: nameFrom + name.length, to });
508
+ i = finished ? to : Math.max(j, i + 1);
509
+ }
510
+ return tags;
511
+ }
512
+ function pairs(tags) {
513
+ const stack = [];
514
+ const pair = /* @__PURE__ */ new Map();
515
+ tags.forEach((t, i) => {
516
+ if (t.kind === "open") stack.push(i);
517
+ else if (t.kind === "close") {
518
+ const k = stack.map((s) => tags[s].name).lastIndexOf(t.name);
519
+ if (k < 0) return;
520
+ pair.set(stack[k], i);
521
+ pair.set(i, stack[k]);
522
+ stack.length = k;
523
+ }
524
+ });
525
+ return pair;
526
+ }
527
+ function matchingTags(text, offset) {
528
+ const tags = scanTags(text);
529
+ const at = tags.findIndex((t) => t.kind !== "empty" && t.nameFrom <= offset && offset <= t.nameTo);
530
+ if (at < 0) return null;
531
+ const other = pairs(tags).get(at);
532
+ if (other === void 0) return null;
533
+ return [at, other].sort((a, b) => a - b).map((i) => ({ from: tags[i].nameFrom, to: tags[i].nameTo }));
534
+ }
535
+ function openElementAt(text, offset) {
536
+ const tags = scanTags(text.slice(0, offset));
537
+ const pair = pairs(tags);
538
+ for (let i = tags.length - 1; i >= 0; i--) {
539
+ if (tags[i].kind === "open" && !pair.has(i) && tags[i].to <= offset && text[tags[i].to - 1] === ">") return tags[i].name;
540
+ }
541
+ return void 0;
542
+ }
543
+ function closeTagAt(text, offset) {
544
+ const before = text.slice(0, offset);
545
+ if (before.endsWith("</")) {
546
+ const name = openElementAt(text, offset - 2);
547
+ if (!name) return void 0;
548
+ return text.slice(offset).startsWith(">") ? name : `${name}>`;
549
+ }
550
+ if (!before.endsWith(">") || before.endsWith("/>")) return void 0;
551
+ const tags = scanTags(before);
552
+ const last = tags[tags.length - 1];
553
+ if (!last || last.kind !== "open" || last.to !== offset || !last.name) return void 0;
554
+ const end = `</${last.name}>`;
555
+ if (text.slice(offset).startsWith(end)) return void 0;
556
+ return end;
557
+ }
558
+
559
+ // src/core/outline.ts
560
+ import { parse as parse2 } from "@xml-tools/parser";
561
+ import { buildAst } from "@xml-tools/ast";
562
+ var Kind = {
563
+ Module: 2,
564
+ Namespace: 3,
565
+ Package: 4,
566
+ Class: 5,
567
+ Method: 6,
568
+ Property: 7,
569
+ Interface: 11,
570
+ Constant: 14,
571
+ Array: 18,
572
+ Object: 19,
573
+ Struct: 23,
574
+ TypeParameter: 26
575
+ };
576
+ var localName = (name) => (name ?? "").replace(/^[^:]*:/, "");
577
+ var unescape = (v) => v.replace(/&(?:#(\d+)|#x([0-9a-fA-F]+)|(quot|lt|gt|apos|amp));/g, (_, d, h, n) => d ? String.fromCharCode(Number(d)) : h ? String.fromCharCode(parseInt(h, 16)) : { quot: '"', lt: "<", gt: ">", apos: "'", amp: "&" }[n]);
578
+ function attr(el, key) {
579
+ const raw = el.attributes.find((a) => a.key === key && a.value !== null)?.value;
580
+ return raw != null ? unescape(raw) : void 0;
581
+ }
582
+ function children(root, name) {
583
+ const out = [];
584
+ const walk = (el) => {
585
+ if (localName(el.name) === name) out.push(el);
586
+ el.subElements.forEach(walk);
587
+ };
588
+ ("rootElement" in root ? root.rootElement ? [root.rootElement] : [] : [root]).forEach(walk);
589
+ return out;
590
+ }
591
+ function symbol(el, name, detail, kind, kids = []) {
592
+ const p = el.position, open = el.syntax?.openName;
593
+ const from = p && p.startOffset >= 0 ? p.startOffset : 0, to = p && p.startOffset >= 0 ? p.endOffset + 1 : 0;
594
+ const named = open && open.startOffset >= 0;
595
+ return { name, detail, kind, from, to, nameFrom: named ? open.startOffset : from, nameTo: named ? open.endOffset + 1 : to, children: kids };
596
+ }
597
+ function ast(text) {
598
+ const { cst, tokenVector } = parse2(text);
599
+ return buildAst(cst, tokenVector);
600
+ }
601
+ function oddOutline(text) {
602
+ const doc = ast(text);
603
+ return [
604
+ ...children(doc, "tagsDecl").map(tagsDecl),
605
+ ...children(doc, "schemaSpec").map(schemaSpec)
606
+ ];
607
+ }
608
+ function tagsDecl(el) {
609
+ const kids = el.subElements.flatMap((c) => {
610
+ switch (localName(c.name)) {
611
+ case "behaviour": {
612
+ const ident = attr(c, "ident") ?? "(no ident)", output = attr(c, "output");
613
+ return [symbol(c, output ? `${ident} \xB7 ${output}` : ident, "", Kind.Method)];
614
+ }
615
+ case "rendition":
616
+ return [symbol(c, attr(c, "xml:id") ?? attr(c, "source") ?? "(rendition)", "", Kind.Property)];
617
+ case "namespace":
618
+ return [symbol(c, attr(c, "name") ?? "(namespace)", "", Kind.Namespace)];
619
+ default:
620
+ return [];
621
+ }
622
+ });
623
+ return symbol(el, "tagsDecl", "", Kind.Namespace, kids);
624
+ }
625
+ function schemaSpec(el) {
626
+ const source = attr(el, "source");
627
+ const kids = el.subElements.flatMap((c) => {
628
+ const ident = attr(c, "ident") ?? "(no ident)", mode = attr(c, "mode") ?? "";
629
+ switch (localName(c.name)) {
630
+ case "moduleRef": {
631
+ const include = attr(c, "include"), except = attr(c, "except");
632
+ const detail = [include && `include: ${include}`, except && `except: ${except}`].filter(Boolean).join(" \xB7 ");
633
+ return [symbol(c, attr(c, "key") ?? "(no key)", detail, Kind.Module)];
634
+ }
635
+ case "dataSpec":
636
+ return [symbol(c, ident, mode, Kind.TypeParameter)];
637
+ case "macroSpec":
638
+ return [symbol(c, ident, mode, Kind.Constant)];
639
+ case "classSpec":
640
+ return [symbol(c, ident, [attr(c, "type"), attr(c, "mode")].filter(Boolean).join(" \xB7 "), Kind.Interface)];
641
+ case "elementSpec":
642
+ return [symbol(c, ident, mode, Kind.Class, rules(c))];
643
+ default:
644
+ return [];
645
+ }
646
+ });
647
+ return symbol(el, attr(el, "ident") ?? "(no ident)", source ? `source: ${source}` : "", Kind.Package, kids);
648
+ }
649
+ function rules(parent) {
650
+ return parent.subElements.flatMap((c) => {
651
+ const type = localName(c.name);
652
+ if (type !== "model" && type !== "modelGrp" && type !== "modelSequence") return [];
653
+ const label = [attr(c, "output"), attr(c, "predicate"), type === "model" ? attr(c, "behaviour") ?? "(no behaviour)" : type].filter(Boolean).join(" \xB7 ");
654
+ const kind = type === "modelGrp" ? Kind.Namespace : type === "modelSequence" ? Kind.Array : Kind.Method;
655
+ return [symbol(c, label, "", kind, type === "model" ? [] : rules(c))];
656
+ });
657
+ }
658
+ var STRUCTURE = /* @__PURE__ */ new Set([
659
+ "teiCorpus",
660
+ "TEI",
661
+ "teiHeader",
662
+ "text",
663
+ "front",
664
+ "body",
665
+ "back",
666
+ "group",
667
+ "div",
668
+ "div1",
669
+ "div2",
670
+ "div3",
671
+ "div4",
672
+ "div5",
673
+ "div6",
674
+ "div7",
675
+ "floatingText"
676
+ ]);
677
+ function textOf(el) {
678
+ const parts = [];
679
+ const walk = (e) => {
680
+ for (const t of e.textContents) parts.push({ at: t.position.startOffset, text: t.text ?? "" });
681
+ e.subElements.forEach(walk);
682
+ };
683
+ walk(el);
684
+ return parts.sort((a, b) => a.at - b.at).map((p) => p.text).join("").replace(/\s+/g, " ").trim();
685
+ }
686
+ var MAX_LABEL = 60;
687
+ function teiOutline(text) {
688
+ const root = ast(text).rootElement;
689
+ if (!root) return [];
690
+ const walk = (el) => {
691
+ const name = localName(el.name);
692
+ const kids = el.subElements.flatMap(walk);
693
+ if (!STRUCTURE.has(name)) return kids;
694
+ if (name === "teiHeader") return [symbol(el, "teiHeader", "", Kind.Object)];
695
+ const head = el.subElements.find((c) => localName(c.name) === "head");
696
+ let label = head ? textOf(head) : "";
697
+ if (label.length > MAX_LABEL) label = label.slice(0, MAX_LABEL).replace(/\s\S*$/, "") + "\u2026";
698
+ const type = attr(el, "type"), n = attr(el, "n"), id = attr(el, "xml:id");
699
+ const title = label || [type, n].filter(Boolean).join(" ") || name;
700
+ const detail = [label ? name : "", id ? `#${id}` : ""].filter(Boolean).join(" ");
701
+ return [symbol(el, title, detail, name.startsWith("div") ? Kind.Struct : Kind.Namespace, kids)];
702
+ };
703
+ return walk(root);
704
+ }
705
+ function elementOutline(text, max = 2e3) {
706
+ const root = ast(text).rootElement;
707
+ let count = 0;
708
+ const walk = (el) => {
709
+ count++;
710
+ const kids = count < max ? el.subElements.slice(0, max - count).map(walk) : [];
711
+ const id = attr(el, "xml:id") ?? attr(el, "id");
712
+ return symbol(el, el.name ?? "?", id ? `#${id}` : "", Kind.Object, kids);
713
+ };
714
+ return root ? [walk(root)] : [];
715
+ }
716
+
717
+ // src/core/elements.ts
718
+ function elements(text) {
719
+ const tags = scanTags(text), pair = pairs(tags), out = [];
720
+ tags.forEach((t, i) => {
721
+ if (t.kind === "empty") out.push({ name: t.name, from: t.from, to: t.to, open: t });
722
+ else if (t.kind === "open" && pair.has(i)) {
723
+ const close = tags[pair.get(i)];
724
+ out.push({ name: t.name, from: t.from, to: close.to, open: t, close });
725
+ }
726
+ });
727
+ return out;
728
+ }
729
+ function elementsAround(text, from, to = from) {
730
+ return elements(text).filter((e) => e.from <= from && e.to >= to).sort((a, b) => a.to - a.from - (b.to - b.from));
731
+ }
732
+ function elementAround(text, from, to, outer) {
733
+ return elementsAround(text, from, to).find((e) => !outer || from === to || e.from < from || e.to > to);
734
+ }
735
+ function selectElement(text, from, to) {
736
+ const e = elementAround(text, from, to, true);
737
+ return e ? { changes: [], selection: { anchor: e.from, head: e.to } } : null;
738
+ }
739
+ function removeElementTags(text, from, to) {
740
+ const e = elementAround(text, from, to, false);
741
+ if (!e) return null;
742
+ const { open, close } = e;
743
+ if (!close) return { changes: [{ from: open.from, to: open.to, insert: "" }], selection: { anchor: open.from, head: open.from } };
744
+ const length = open.to - open.from;
745
+ return {
746
+ changes: [{ from: open.from, to: open.to, insert: "" }, { from: close.from, to: close.to, insert: "" }],
747
+ selection: { anchor: open.from, head: close.from - length }
748
+ };
749
+ }
750
+ function splitElement(text, pos) {
751
+ const e = elementsAround(text, pos).find((x) => x.close && pos >= x.open.to && pos <= x.close.from);
752
+ if (!e) return null;
753
+ const start = text.slice(e.open.from, e.open.to).replace(/\s(xml:)?id\s*=\s*("[^"]*"|'[^']*')/g, "");
754
+ const insert = `</${e.name}>${start}`;
755
+ return { changes: [{ from: pos, to: pos, insert }], selection: { anchor: pos + insert.length, head: pos + insert.length } };
756
+ }
757
+ function surroundWithElement(from, to, tag) {
758
+ const start = `<${tag.trim()}>`, end = `</${tag.trim().split(/\s/)[0]}>`;
759
+ return {
760
+ changes: [{ from, to: from, insert: start }, { from: to, to, insert: end }],
761
+ selection: { anchor: from + start.length, head: to + start.length }
762
+ };
763
+ }
764
+ export {
765
+ DEFAULT_SCHEMA_FILES,
766
+ Grammars,
767
+ Kind,
768
+ PUBLIC_SCHEMA_URLS,
769
+ RNG_NS,
770
+ closeTagAt,
771
+ described,
772
+ elementAround,
773
+ elementOutline,
774
+ elements,
775
+ elementsAround,
776
+ isOdd,
777
+ isRngModel,
778
+ matchingTags,
779
+ oddOutline,
780
+ openElementAt,
781
+ pairs,
782
+ possibleAt,
783
+ projectRoot,
784
+ publicSchema,
785
+ readToml,
786
+ relativeHref,
787
+ removeElementTags,
788
+ scanTags,
789
+ schemaFor,
790
+ selectElement,
791
+ setToml,
792
+ splitElement,
793
+ surroundWithElement,
794
+ teiOutline,
795
+ tomlString,
796
+ unsetToml,
797
+ validate,
798
+ vocabulary,
799
+ wellFormed,
800
+ xmlModelEdits,
801
+ xmlModels
802
+ };
803
+ //# sourceMappingURL=index.js.map