@teipublisher/oddity-language-server 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +58 -2
- package/dist/edit.js +1211 -0
- package/dist/edit.js.map +7 -0
- package/dist/index.js +1701 -0
- package/dist/index.js.map +7 -0
- package/dist/node.cjs +45925 -0
- package/dist/node.cjs.map +7 -0
- package/package.json +74 -4
- package/schema/README.md +45 -0
- package/schema/docbook/docbook.rng +18457 -0
- package/schema/jats/BITS-embedded-index2.ent.rng +340 -0
- package/schema/jats/BITS-question-answer2.ent.rng +795 -0
- package/schema/jats/JATS-XHTMLtablesetup1-3.ent.rng +614 -0
- package/schema/jats/JATS-ali-namespace1-3.ent.rng +284 -0
- package/schema/jats/JATS-archivearticle1-3-mathml3.rng +1277 -0
- package/schema/jats/JATS-archivecustom-classes1-3.ent.rng +427 -0
- package/schema/jats/JATS-archivecustom-mixes1-3.ent.rng +630 -0
- package/schema/jats/JATS-archivecustom-models1-3.ent.rng +2205 -0
- package/schema/jats/JATS-articlemeta1-3.ent.rng +3138 -0
- package/schema/jats/JATS-backmatter1-3.ent.rng +601 -0
- package/schema/jats/JATS-chars1-3.ent.rng +715 -0
- package/schema/jats/JATS-common-atts1-3.ent.rng +367 -0
- package/schema/jats/JATS-common1-3.ent.rng +6007 -0
- package/schema/jats/JATS-default-classes1-3.ent.rng +1953 -0
- package/schema/jats/JATS-default-mixes1-3.ent.rng +583 -0
- package/schema/jats/JATS-display1-3.ent.rng +1669 -0
- package/schema/jats/JATS-format1-3.ent.rng +1256 -0
- package/schema/jats/JATS-funding1-3.ent.rng +1389 -0
- package/schema/jats/JATS-journalmeta1-3.ent.rng +691 -0
- package/schema/jats/JATS-link1-3.ent.rng +664 -0
- package/schema/jats/JATS-list1-3.ent.rng +747 -0
- package/schema/jats/JATS-math1-3.ent.rng +620 -0
- package/schema/jats/JATS-mathml3-mathmlsetup1-3.ent.rng +459 -0
- package/schema/jats/JATS-nlmcitation1-3.ent.rng +522 -0
- package/schema/jats/JATS-para1-3.ent.rng +780 -0
- package/schema/jats/JATS-phrase1-3.ent.rng +725 -0
- package/schema/jats/JATS-references1-3.ent.rng +1713 -0
- package/schema/jats/JATS-related-object1-3.ent.rng +453 -0
- package/schema/jats/JATS-section1-3.ent.rng +482 -0
- package/schema/jats/mathml3-qname1.mod.rng +61 -0
- package/schema/jats/mathml3.rng +4094 -0
- package/schema/jats/xhtml-inlstyle-1.mod.rng +37 -0
- package/schema/jats/xhtml-table-1.mod.rng +426 -0
- package/schema/odd/teipublisher_odds.rng +12769 -0
- package/schema/opm/opm.schema.json +402 -0
- package/schema/tei/tei_all.rng +23212 -0
- package/src/core/association.ts +155 -0
- package/src/core/complete.ts +147 -0
- package/src/core/elements.ts +86 -0
- package/src/core/opmToml.ts +432 -0
- package/src/core/outline.ts +156 -0
- package/src/core/schema.ts +55 -0
- package/src/core/tags.ts +104 -0
- package/src/core/toml.ts +64 -0
- package/src/core/tomlScan.ts +155 -0
- package/src/core/validate.ts +128 -0
- package/src/core/wellformed.ts +16 -0
- package/src/edit.ts +12 -0
- package/src/index.ts +17 -0
- package/src/node.ts +39 -0
- package/src/server/server.ts +322 -0
package/src/core/tags.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// ── start and end tags: matching pairs and closing tags ──────────────────
|
|
2
|
+
// A light scanner rather than a parser: it has to work on half-typed documents.
|
|
3
|
+
|
|
4
|
+
export interface Tag {
|
|
5
|
+
kind: 'open' | 'close' | 'empty';
|
|
6
|
+
name: string;
|
|
7
|
+
/** Offset of the '<'. */
|
|
8
|
+
from: number;
|
|
9
|
+
nameFrom: number;
|
|
10
|
+
nameTo: number;
|
|
11
|
+
/** Offset just after the '>', or the end of the text for an unfinished tag. */
|
|
12
|
+
to: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const SKIP: [string, string][] = [['<!--', '-->'], ['<![CDATA[', ']]>'], ['<?', '?>'], ['<!', '>']];
|
|
16
|
+
|
|
17
|
+
/** Every tag in text, skipping comments, CDATA, processing instructions and declarations. */
|
|
18
|
+
export function scanTags(text: string): Tag[] {
|
|
19
|
+
const tags: Tag[] = [];
|
|
20
|
+
let i = 0;
|
|
21
|
+
while ((i = text.indexOf('<', i)) >= 0) {
|
|
22
|
+
const skip = SKIP.find(([open]) => text.startsWith(open, i));
|
|
23
|
+
if (skip) {
|
|
24
|
+
const end = text.indexOf(skip[1], i + skip[0].length);
|
|
25
|
+
if (end < 0) break;
|
|
26
|
+
i = end + skip[1].length;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
const closing = text[i + 1] === '/';
|
|
30
|
+
const nameFrom = i + (closing ? 2 : 1);
|
|
31
|
+
const name = text.slice(nameFrom).match(/^[^\s<>/="']*/)![0];
|
|
32
|
+
// the end of the tag: the first '>' outside a quoted value
|
|
33
|
+
let j = nameFrom + name.length, quote = '';
|
|
34
|
+
for (; j < text.length; j++) {
|
|
35
|
+
const c = text[j];
|
|
36
|
+
if (quote) { if (c === quote) quote = ''; } else if (c === '"' || c === "'") quote = c; else if (c === '>' || c === '<') break;
|
|
37
|
+
}
|
|
38
|
+
const finished = text[j] === '>';
|
|
39
|
+
const to = finished ? j + 1 : j;
|
|
40
|
+
const kind = closing ? 'close' : finished && text[j - 1] === '/' ? 'empty' : 'open';
|
|
41
|
+
tags.push({ kind, name, from: i, nameFrom, nameTo: nameFrom + name.length, to });
|
|
42
|
+
i = finished ? to : Math.max(j, i + 1);
|
|
43
|
+
}
|
|
44
|
+
return tags;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Pairs of open and close tags, by index into tags, matched like a parser would. */
|
|
48
|
+
export function pairs(tags: Tag[]): Map<number, number> {
|
|
49
|
+
const stack: number[] = [];
|
|
50
|
+
const pair = new Map<number, number>();
|
|
51
|
+
tags.forEach((t, i) => {
|
|
52
|
+
if (t.kind === 'open') stack.push(i);
|
|
53
|
+
else if (t.kind === 'close') {
|
|
54
|
+
// close the nearest open tag of the same name; anything above it was left open
|
|
55
|
+
const k = stack.map(s => tags[s].name).lastIndexOf(t.name);
|
|
56
|
+
if (k < 0) return;
|
|
57
|
+
pair.set(stack[k], i);
|
|
58
|
+
pair.set(i, stack[k]);
|
|
59
|
+
stack.length = k;
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
return pair;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The name ranges of the tag whose name holds offset and its partner, for renaming both at once. */
|
|
66
|
+
export function matchingTags(text: string, offset: number): { from: number; to: number }[] | null {
|
|
67
|
+
const tags = scanTags(text);
|
|
68
|
+
const at = tags.findIndex(t => t.kind !== 'empty' && t.nameFrom <= offset && offset <= t.nameTo);
|
|
69
|
+
if (at < 0) return null;
|
|
70
|
+
const other = pairs(tags).get(at);
|
|
71
|
+
if (other === undefined) return null;
|
|
72
|
+
return [at, other].sort((a, b) => a - b).map(i => ({ from: tags[i].nameFrom, to: tags[i].nameTo }));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The innermost element still open at offset. */
|
|
76
|
+
export function openElementAt(text: string, offset: number): string | undefined {
|
|
77
|
+
const tags = scanTags(text.slice(0, offset));
|
|
78
|
+
const pair = pairs(tags);
|
|
79
|
+
for (let i = tags.length - 1; i >= 0; i--) {
|
|
80
|
+
if (tags[i].kind === 'open' && !pair.has(i) && tags[i].to <= offset && text[tags[i].to - 1] === '>') return tags[i].name;
|
|
81
|
+
}
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* What to insert at offset, just after the user typed a character, to close a tag:
|
|
87
|
+
* after the '>' of a start tag its end tag, after '</' the name of the open element.
|
|
88
|
+
*/
|
|
89
|
+
export function closeTagAt(text: string, offset: number): string | undefined {
|
|
90
|
+
const before = text.slice(0, offset);
|
|
91
|
+
if (before.endsWith('</')) {
|
|
92
|
+
const name = openElementAt(text, offset - 2);
|
|
93
|
+
if (!name) return undefined;
|
|
94
|
+
return text.slice(offset).startsWith('>') ? name : `${name}>`;
|
|
95
|
+
}
|
|
96
|
+
if (!before.endsWith('>') || before.endsWith('/>')) return undefined;
|
|
97
|
+
const tags = scanTags(before);
|
|
98
|
+
const last = tags[tags.length - 1];
|
|
99
|
+
if (!last || last.kind !== 'open' || last.to !== offset || !last.name) return undefined;
|
|
100
|
+
const end = `</${last.name}>`;
|
|
101
|
+
// already closed right after the cursor, e.g. when a '>' is retyped
|
|
102
|
+
if (text.slice(offset).startsWith(end)) return undefined;
|
|
103
|
+
return end;
|
|
104
|
+
}
|
package/src/core/toml.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// ── opm.toml: write the keys the page controls, read the few it needs ─────
|
|
2
|
+
// Reading parses the whole file with smol-toml (TOML 1.0). Writing does not
|
|
3
|
+
// serialize: the edits leave every other line of the file, comments included, as it is.
|
|
4
|
+
import { parse } from 'smol-toml';
|
|
5
|
+
|
|
6
|
+
export type TomlValue = string | string[];
|
|
7
|
+
export type TomlConfig = Record<string, Record<string, TomlValue>>;
|
|
8
|
+
|
|
9
|
+
const q = (s: string) => JSON.stringify(s);
|
|
10
|
+
const sectionEnd = (lines: string[], head: number) => {
|
|
11
|
+
for (let i = head + 1; i < lines.length; i++) if (/^\s*\[/.test(lines[i])) return i;
|
|
12
|
+
return lines.length;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Set section.key = value in place, keeping everything else in the file as it is. */
|
|
16
|
+
export function setToml(text: string, section: string, key: string, value: string): string {
|
|
17
|
+
const line = `${key} = ${q(value)}`, lines = text ? text.split('\n') : [];
|
|
18
|
+
const head = lines.findIndex(l => l.trim() === `[${section}]`);
|
|
19
|
+
if (head < 0) return (text && !text.endsWith('\n') ? text + '\n' : text) + (text ? '\n' : '') + `[${section}]\n${line}\n`;
|
|
20
|
+
const end = sectionEnd(lines, head), re = new RegExp(`^\\s*${key}\\s*=`);
|
|
21
|
+
for (let i = head + 1; i < end; i++) if (re.test(lines[i])) { lines[i] = line; return lines.join('\n'); }
|
|
22
|
+
lines.splice(head + 1, 0, line);
|
|
23
|
+
return lines.join('\n');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Drop section.key, leaving the rest of the file as it is. */
|
|
27
|
+
export function unsetToml(text: string, section: string, key: string): string {
|
|
28
|
+
const lines = text.split('\n'), head = lines.findIndex(l => l.trim() === `[${section}]`);
|
|
29
|
+
if (head < 0) return text;
|
|
30
|
+
const end = sectionEnd(lines, head), re = new RegExp(`^\\s*${key}\\s*=`);
|
|
31
|
+
for (let i = head + 1; i < end; i++) if (re.test(lines[i])) { lines.splice(i, 1); break; }
|
|
32
|
+
return lines.join('\n');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The string and string-array values of a TOML file, by table: `[transform.web] template = …`,
|
|
37
|
+
* `[transform] web.template = …` and `transform.web.template = …` all end up under
|
|
38
|
+
* cfg['transform.web'].template. Other values and arrays of tables are left out.
|
|
39
|
+
* A file that is not valid TOML gives no values, as opm would not run with it either.
|
|
40
|
+
*/
|
|
41
|
+
export function readToml(text: string): TomlConfig {
|
|
42
|
+
let doc: Record<string, unknown>;
|
|
43
|
+
try { doc = parse(text); } catch { return {}; }
|
|
44
|
+
const cfg: TomlConfig = {};
|
|
45
|
+
const walk = (table: Record<string, unknown>, path: string[]) => {
|
|
46
|
+
for (const [key, v] of Object.entries(table)) {
|
|
47
|
+
if (typeof v === 'string' || (Array.isArray(v) && v.length && v.every(x => typeof x === 'string'))) {
|
|
48
|
+
(cfg[path.join('.')] ||= {})[key] = v as TomlValue;
|
|
49
|
+
} else if (Array.isArray(v) && !v.length) {
|
|
50
|
+
(cfg[path.join('.')] ||= {})[key] = [];
|
|
51
|
+
} else if (v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date)) {
|
|
52
|
+
walk(v as Record<string, unknown>, [...path, key]);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
walk(doc, []);
|
|
57
|
+
return cfg;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A string value from the config, or '' when it is missing or not a string. */
|
|
61
|
+
export const tomlString = (cfg: TomlConfig, section: string, key: string): string => {
|
|
62
|
+
const v = cfg[section]?.[key];
|
|
63
|
+
return typeof v === 'string' ? v : '';
|
|
64
|
+
};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// ── where things are in a TOML file ───────────────────────────────────────
|
|
2
|
+
// smol-toml tells whether a file is valid and what it holds, but not where a
|
|
3
|
+
// key or table is written. This scanner finds the headers and key/value lines
|
|
4
|
+
// with their offsets, and resolves each to the path its value has in the parsed
|
|
5
|
+
// document: [[chunking]] tables count up, so the fragments of the second run are
|
|
6
|
+
// chunking[1].fragments. It never throws: a line it cannot read is skipped.
|
|
7
|
+
|
|
8
|
+
export type Seg = string | number;
|
|
9
|
+
|
|
10
|
+
export interface TomlTable {
|
|
11
|
+
/** Path of the table in the parsed document, e.g. ['chunking', 1, 'fragments', 0]. */
|
|
12
|
+
path: Seg[];
|
|
13
|
+
/** The header, brackets included. */
|
|
14
|
+
from: number;
|
|
15
|
+
to: number;
|
|
16
|
+
/** Whether it is an array-of-tables header, [[…]]. */
|
|
17
|
+
array: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface TomlKey {
|
|
21
|
+
/** Path of the value, e.g. ['transform', 'web', 'template']. */
|
|
22
|
+
path: Seg[];
|
|
23
|
+
/** The whole (possibly dotted) key. */
|
|
24
|
+
from: number;
|
|
25
|
+
to: number;
|
|
26
|
+
/** The value, trimmed. */
|
|
27
|
+
valueFrom: number;
|
|
28
|
+
valueTo: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface TomlScan { tables: TomlTable[]; keys: TomlKey[] }
|
|
32
|
+
|
|
33
|
+
const isBare = (c: string) => /[A-Za-z0-9_-]/.test(c);
|
|
34
|
+
const isSpace = (c: string) => c === ' ' || c === '\t';
|
|
35
|
+
|
|
36
|
+
/** A dotted key starting at i: its parts and where it ends, or null. */
|
|
37
|
+
export function readKey(text: string, i: number, stop: (c: string) => boolean): { parts: string[]; end: number } | null {
|
|
38
|
+
const parts: string[] = [];
|
|
39
|
+
for (;;) {
|
|
40
|
+
while (isSpace(text[i])) i++;
|
|
41
|
+
const c = text[i];
|
|
42
|
+
if (c === '"' || c === "'") {
|
|
43
|
+
let j = i + 1, part = '';
|
|
44
|
+
while (j < text.length && text[j] !== c && text[j] !== '\n') {
|
|
45
|
+
if (c === '"' && text[j] === '\\' && j + 1 < text.length) { part += text[j + 1]; j += 2; continue; }
|
|
46
|
+
part += text[j++];
|
|
47
|
+
}
|
|
48
|
+
if (text[j] !== c) return null;
|
|
49
|
+
parts.push(part);
|
|
50
|
+
i = j + 1;
|
|
51
|
+
} else if (c !== undefined && isBare(c)) {
|
|
52
|
+
const start = i;
|
|
53
|
+
while (i < text.length && isBare(text[i])) i++;
|
|
54
|
+
parts.push(text.slice(start, i));
|
|
55
|
+
} else {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
while (isSpace(text[i])) i++;
|
|
59
|
+
if (text[i] === '.') { i++; continue; }
|
|
60
|
+
return i < text.length && stop(text[i]) ? { parts, end: i } : null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A value starting at i, past strings, arrays and inline tables, which may span lines:
|
|
66
|
+
* where its text ends (before a trailing comment and blanks) and where scanning goes on.
|
|
67
|
+
*/
|
|
68
|
+
export function skipValue(text: string, i: number): { valueTo: number; next: number } {
|
|
69
|
+
let depth = 0, contentEnd = -1;
|
|
70
|
+
while (i < text.length) {
|
|
71
|
+
const c = text[i];
|
|
72
|
+
if (c === '"' || c === "'") {
|
|
73
|
+
if (text.startsWith(c.repeat(3), i)) {
|
|
74
|
+
const end = text.indexOf(c.repeat(3), i + 3);
|
|
75
|
+
i = end < 0 ? text.length : end + 3;
|
|
76
|
+
while (text[i] === c) i++;
|
|
77
|
+
} else {
|
|
78
|
+
i++;
|
|
79
|
+
while (i < text.length && text[i] !== c && text[i] !== '\n') i += c === '"' && text[i] === '\\' ? 2 : 1;
|
|
80
|
+
if (text[i] === c) i++;
|
|
81
|
+
}
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (c === '#') {
|
|
85
|
+
if (depth === 0 && contentEnd < 0) contentEnd = i;
|
|
86
|
+
while (i < text.length && text[i] !== '\n') i++;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (c === '\n' && depth === 0) break;
|
|
90
|
+
if (c === '[' || c === '{') depth++;
|
|
91
|
+
else if ((c === ']' || c === '}') && depth) depth--;
|
|
92
|
+
i++;
|
|
93
|
+
}
|
|
94
|
+
let valueTo = contentEnd < 0 ? i : contentEnd;
|
|
95
|
+
while (valueTo > 0 && /\s/.test(text[valueTo - 1])) valueTo--;
|
|
96
|
+
return { valueTo, next: i };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function scanToml(text: string): TomlScan {
|
|
100
|
+
const tables: TomlTable[] = [], keys: TomlKey[] = [];
|
|
101
|
+
const counts = new Map<string, number>();
|
|
102
|
+
const id = (p: Seg[]) => JSON.stringify(p);
|
|
103
|
+
// resolve a header's parts: a prefix that names an array of tables means its last element
|
|
104
|
+
const resolve = (parts: string[], array: boolean): Seg[] => {
|
|
105
|
+
const path: Seg[] = [];
|
|
106
|
+
parts.forEach((part, n) => {
|
|
107
|
+
path.push(part);
|
|
108
|
+
const last = n === parts.length - 1;
|
|
109
|
+
if (last && array) {
|
|
110
|
+
const count = counts.get(id(path)) ?? 0;
|
|
111
|
+
counts.set(id(path), count + 1);
|
|
112
|
+
path.push(count);
|
|
113
|
+
} else if (!last && counts.has(id(path))) {
|
|
114
|
+
path.push(counts.get(id(path))! - 1);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
return path;
|
|
118
|
+
};
|
|
119
|
+
let table: Seg[] = [];
|
|
120
|
+
let i = 0;
|
|
121
|
+
while (i < text.length) {
|
|
122
|
+
const c = text[i];
|
|
123
|
+
if (c === '\n' || isSpace(c) || c === '\r') { i++; continue; }
|
|
124
|
+
const eol = () => { const n = text.indexOf('\n', i); return n < 0 ? text.length : n; };
|
|
125
|
+
if (c === '#') { i = eol(); continue; }
|
|
126
|
+
if (c === '[') {
|
|
127
|
+
const array = text[i + 1] === '[';
|
|
128
|
+
const key = readKey(text, i + (array ? 2 : 1), ch => ch === ']');
|
|
129
|
+
if (key && (!array || text[key.end + 1] === ']')) {
|
|
130
|
+
const end = key.end + (array ? 2 : 1);
|
|
131
|
+
table = resolve(key.parts, array);
|
|
132
|
+
tables.push({ path: table, from: i, to: end, array });
|
|
133
|
+
}
|
|
134
|
+
i = eol();
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
const key = readKey(text, i, ch => ch === '=');
|
|
138
|
+
if (!key) { i = eol(); continue; }
|
|
139
|
+
let keyTo = key.end;
|
|
140
|
+
while (keyTo > i && isSpace(text[keyTo - 1])) keyTo--;
|
|
141
|
+
let v = key.end + 1;
|
|
142
|
+
while (isSpace(text[v])) v++;
|
|
143
|
+
const { valueTo, next } = skipValue(text, v);
|
|
144
|
+
keys.push({ path: [...table, ...key.parts], from: i, to: keyTo, valueFrom: v, valueTo: Math.max(v, valueTo) });
|
|
145
|
+
i = Math.max(next, i + 1);
|
|
146
|
+
}
|
|
147
|
+
return { tables, keys };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The table a position belongs to: the path of the last header before it, [] before any. */
|
|
151
|
+
export function tableAt(scan: TomlScan, offset: number): TomlTable | undefined {
|
|
152
|
+
let found: TomlTable | undefined;
|
|
153
|
+
for (const t of scan.tables) if (t.from <= offset) found = t; else break;
|
|
154
|
+
return found;
|
|
155
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// ── RELAX NG validation of one XML text with salve, errors as text ranges ──
|
|
2
|
+
// Pure, so tests run it without a worker; runtime/validator.ts is the worker around it.
|
|
3
|
+
import {
|
|
4
|
+
AnyName, AttributeNameError, AttributeValueError, ChoiceError, DefaultNameResolver, Name, NameChoice, NsName,
|
|
5
|
+
type BaseName, type Grammar, type ValidationError,
|
|
6
|
+
} from 'salve-annos';
|
|
7
|
+
import { SaxesParser, type SaxesTagNS } from 'saxes';
|
|
8
|
+
|
|
9
|
+
export interface Problem { from: number; to: number; message: string }
|
|
10
|
+
|
|
11
|
+
/** More would only slow the editor down; the first ones are what needs fixing. */
|
|
12
|
+
const MAX = 200;
|
|
13
|
+
|
|
14
|
+
/** A name as the document would write it: prefixed where it declares one for the namespace. */
|
|
15
|
+
function nameText(n: BaseName, resolver: DefaultNameResolver, attribute: boolean): string {
|
|
16
|
+
if (n instanceof Name) {
|
|
17
|
+
if (!n.ns || (attribute && n.ns === '')) return n.name;
|
|
18
|
+
const q = resolver.unresolveName(n.ns, n.name);
|
|
19
|
+
return q ?? `${n.name} (${n.ns})`;
|
|
20
|
+
}
|
|
21
|
+
if (n instanceof NameChoice) return `${nameText(n.a, resolver, attribute)} or ${nameText(n.b, resolver, attribute)}`;
|
|
22
|
+
if (n instanceof NsName) return `any name in ${n.ns}`;
|
|
23
|
+
if (n instanceof AnyName) return 'any name';
|
|
24
|
+
return String(n);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** salve's messages, worded as the editor shows them; `value` is the attribute value just checked. */
|
|
28
|
+
function messageOf(e: ValidationError, resolver: DefaultNameResolver, value?: string): string {
|
|
29
|
+
const attribute = e instanceof AttributeNameError || e instanceof AttributeValueError;
|
|
30
|
+
const names = e.getNames().map(n => nameText(n, resolver, attribute));
|
|
31
|
+
const one = names.join(', ');
|
|
32
|
+
switch (e.msg) {
|
|
33
|
+
case 'tag not allowed here': return `<${one}> is not allowed here`;
|
|
34
|
+
case 'tag required': return `<${one}> is required here`;
|
|
35
|
+
case 'unexpected end tag': return `</${one}> was not expected here`;
|
|
36
|
+
case 'attribute not allowed here': return `@${one} is not allowed here`;
|
|
37
|
+
case 'attribute missing': return `Required attribute @${one} is missing`;
|
|
38
|
+
case 'invalid attribute value': return value === undefined ? `Invalid value for @${one}` : `"${value}" is not a valid value for @${one}`;
|
|
39
|
+
case 'text not allowed here': return 'Text is not allowed here';
|
|
40
|
+
}
|
|
41
|
+
if (e instanceof ChoiceError) return `Expected one of: ${names.map(n => `<${n}>`).join(', ')}`;
|
|
42
|
+
const text = e.toStringWithNames(names);
|
|
43
|
+
return text.charAt(0).toUpperCase() + text.slice(1);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Validate xml against grammar: well-formedness first, then the schema, stopping at the first syntax error. */
|
|
47
|
+
export function validate(grammar: Grammar, xml: string): Problem[] {
|
|
48
|
+
const resolver = new DefaultNameResolver();
|
|
49
|
+
const walker = grammar.newWalker(resolver);
|
|
50
|
+
const parser = new SaxesParser({ xmlns: true, position: true });
|
|
51
|
+
const problems: Problem[] = [];
|
|
52
|
+
let broken = false;
|
|
53
|
+
|
|
54
|
+
// where the parser last was: tags are located from there, backwards to their '<'
|
|
55
|
+
let tagFrom = 0, tagTo = 0, textFrom = 0;
|
|
56
|
+
let text = '';
|
|
57
|
+
const report = (r: ReturnType<typeof walker.fireEvent>, from: number, to: number, value?: string) => {
|
|
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
|
+
// whitespace between elements is never an error worth showing
|
|
64
|
+
if (text.trim() !== '') report(walker.fireEvent('text', [text]), textFrom, tagFrom);
|
|
65
|
+
text = '';
|
|
66
|
+
};
|
|
67
|
+
/** The span of a tag's name, given where its '<' is. */
|
|
68
|
+
const nameSpan = (from: number, name: string, closing: boolean) => {
|
|
69
|
+
const start = from + (closing ? 2 : 1);
|
|
70
|
+
return [start, start + name.length] as const;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
parser.on('opentag', (node: SaxesTagNS) => {
|
|
74
|
+
if (broken) return;
|
|
75
|
+
tagTo = parser.position;
|
|
76
|
+
tagFrom = xml.lastIndexOf('<', tagTo - 1);
|
|
77
|
+
flush();
|
|
78
|
+
resolver.enterContext();
|
|
79
|
+
for (const [qn, a] of Object.entries(node.attributes)) {
|
|
80
|
+
if (qn === 'xmlns') resolver.definePrefix('', a.value);
|
|
81
|
+
else if (a.prefix === 'xmlns') resolver.definePrefix(a.local, a.value);
|
|
82
|
+
}
|
|
83
|
+
const [nf, nt] = nameSpan(tagFrom, node.name, false);
|
|
84
|
+
report(walker.fireEvent('enterStartTag', [node.uri, node.local]), nf, nt);
|
|
85
|
+
const tag = xml.slice(tagFrom, tagTo);
|
|
86
|
+
for (const [qn, a] of Object.entries(node.attributes)) {
|
|
87
|
+
if (qn === 'xmlns' || a.prefix === 'xmlns') continue;
|
|
88
|
+
const at = tag.search(new RegExp(`\\s${qn.replace(/[.*+?^${}()|[\]\\-]/g, '\\$&')}\\s*=`));
|
|
89
|
+
const af = at < 0 ? nf : tagFrom + at + 1, aend = at < 0 ? nt : af + qn.length;
|
|
90
|
+
report(walker.fireEvent('attributeName', [a.uri, a.local]), af, aend);
|
|
91
|
+
report(walker.fireEvent('attributeValue', [a.value]), af, aend, a.value);
|
|
92
|
+
}
|
|
93
|
+
report(walker.fireEvent('leaveStartTag', []), nf, nt);
|
|
94
|
+
if (node.isSelfClosing) return;
|
|
95
|
+
textFrom = tagTo;
|
|
96
|
+
});
|
|
97
|
+
parser.on('closetag', (node: SaxesTagNS) => {
|
|
98
|
+
if (broken) return;
|
|
99
|
+
if (node.isSelfClosing) {
|
|
100
|
+
// the start tag was the whole element
|
|
101
|
+
report(walker.fireEvent('endTag', [node.uri, node.local]), ...nameSpan(tagFrom, node.name, false));
|
|
102
|
+
} else {
|
|
103
|
+
tagTo = parser.position;
|
|
104
|
+
tagFrom = xml.lastIndexOf('</', tagTo - 1);
|
|
105
|
+
flush();
|
|
106
|
+
report(walker.fireEvent('endTag', [node.uri, node.local]), ...nameSpan(tagFrom, node.name, true));
|
|
107
|
+
}
|
|
108
|
+
resolver.leaveContext();
|
|
109
|
+
textFrom = tagTo;
|
|
110
|
+
});
|
|
111
|
+
parser.on('text', s => { text += s; });
|
|
112
|
+
parser.on('cdata', s => { text += s; });
|
|
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
|
+
|
|
120
|
+
// saxes keeps going after an error, but the walker would only report the fallout:
|
|
121
|
+
// the handlers above stop, and what came before the error stays reported
|
|
122
|
+
try { parser.write(xml).close(); } catch { /* reported through 'error' */ }
|
|
123
|
+
if (broken) return problems;
|
|
124
|
+
|
|
125
|
+
const end = walker.end();
|
|
126
|
+
report(end, tagFrom, tagTo);
|
|
127
|
+
return problems;
|
|
128
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// ── well-formedness alone, for documents without a schema ─────────────────
|
|
2
|
+
import { SaxesParser } from 'saxes';
|
|
3
|
+
import type { Problem } from './validate.ts';
|
|
4
|
+
|
|
5
|
+
/** The first syntax error in xml, if any, as validate() reports it. */
|
|
6
|
+
export function wellFormed(xml: string): Problem[] {
|
|
7
|
+
const parser = new SaxesParser({ xmlns: true, position: true });
|
|
8
|
+
const problems: Problem[] = [];
|
|
9
|
+
parser.on('error', e => {
|
|
10
|
+
if (problems.length) return;
|
|
11
|
+
const at = Math.min(parser.position, xml.length);
|
|
12
|
+
problems.push({ from: Math.max(0, at - 1), to: at, message: e.message.replace(/^(?:[^:\n]*:)?\d+:\d+: /, '') });
|
|
13
|
+
});
|
|
14
|
+
try { parser.write(xml).close(); } catch { /* reported through 'error' */ }
|
|
15
|
+
return problems;
|
|
16
|
+
}
|
package/src/edit.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Light helpers for editors, without salve: tag matching and closing, schema association, xml-model and opm.toml edits.
|
|
2
|
+
export { scanTags, pairs, matchingTags, openElementAt, closeTagAt, type Tag } from './core/tags.ts';
|
|
3
|
+
export {
|
|
4
|
+
schemaFor, projectRoot, isOdd, xmlModels, isRngModel, xmlModelEdits, relativeHref, RNG_NS, DEFAULT_SCHEMA_FILES, PUBLIC_SCHEMA_URLS, publicSchema, vocabulary,
|
|
5
|
+
type Files, type Defaults, type SchemaChoice, type TextEdit,
|
|
6
|
+
} from './core/association.ts';
|
|
7
|
+
export { checkOpmToml, completeOpmToml, describeOpmToml, isOpmToml, schemaAt, OPM_SCHEMA, type TomlProblem, type TomlOption, type TomlCompletions, type TomlHover, type Schema } from './core/opmToml.ts';
|
|
8
|
+
export { readToml, setToml, unsetToml, tomlString, type TomlConfig, type TomlValue } from './core/toml.ts';
|
|
9
|
+
export {
|
|
10
|
+
elements, elementsAround, elementAround, selectElement, removeElementTags, splitElement, surroundWithElement,
|
|
11
|
+
type Element, type ElementEdit, type Selection,
|
|
12
|
+
} from './core/elements.ts';
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Editor-independent core: what opm studio and ODDity share.
|
|
2
|
+
export { validate, type Problem } from './core/validate.ts';
|
|
3
|
+
export { possibleAt, described, type Possible, type Suggestion } from './core/complete.ts';
|
|
4
|
+
export { wellFormed } from './core/wellformed.ts';
|
|
5
|
+
export { Grammars, type ReadText } from './core/schema.ts';
|
|
6
|
+
export {
|
|
7
|
+
schemaFor, projectRoot, vocabulary, isOdd, xmlModels, isRngModel, xmlModelEdits, relativeHref, RNG_NS, DEFAULT_SCHEMA_FILES, PUBLIC_SCHEMA_URLS, publicSchema,
|
|
8
|
+
type Files, type Defaults, type SchemaChoice, type TextEdit,
|
|
9
|
+
} from './core/association.ts';
|
|
10
|
+
export { scanTags, pairs, matchingTags, openElementAt, closeTagAt, type Tag } from './core/tags.ts';
|
|
11
|
+
export { oddOutline, teiOutline, elementOutline, Kind, type OutlineSymbol } from './core/outline.ts';
|
|
12
|
+
export { checkOpmToml, completeOpmToml, describeOpmToml, isOpmToml, schemaAt, OPM_SCHEMA, type TomlProblem, type TomlOption, type TomlCompletions, type TomlHover, type Schema } from './core/opmToml.ts';
|
|
13
|
+
export { readToml, setToml, unsetToml, tomlString, type TomlConfig, type TomlValue } from './core/toml.ts';
|
|
14
|
+
export {
|
|
15
|
+
elements, elementsAround, elementAround, selectElement, removeElementTags, splitElement, surroundWithElement,
|
|
16
|
+
type Element, type ElementEdit, type Selection,
|
|
17
|
+
} from './core/elements.ts';
|
package/src/node.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Node entry: run with --node-ipc (VS Code) or --stdio.
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { readFile } from 'node:fs/promises';
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
|
+
import { createConnection, ProposedFeatures } from 'vscode-languageserver/node';
|
|
7
|
+
import { startServer, type Host } from './server/server.ts';
|
|
8
|
+
import { DEFAULT_SCHEMA_FILES } from './core/association.ts';
|
|
9
|
+
|
|
10
|
+
const local = (url: string | URL) => {
|
|
11
|
+
const u = typeof url === 'string' ? new URL(url) : url;
|
|
12
|
+
return u.protocol === 'file:' ? fileURLToPath(u) : undefined;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const host: Host = {
|
|
16
|
+
files: {
|
|
17
|
+
exists: url => { const p = local(url); return !!p && existsSync(p); },
|
|
18
|
+
read: url => {
|
|
19
|
+
const p = local(url);
|
|
20
|
+
try { return p ? readFileSync(p, 'utf8') : undefined; } catch { return undefined; }
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
async readText(url) {
|
|
24
|
+
const p = local(url);
|
|
25
|
+
if (p) return readFile(p, 'utf8');
|
|
26
|
+
const r = await fetch(url);
|
|
27
|
+
if (!r.ok) throw new Error(`${url} could not be loaded: ${r.status}`);
|
|
28
|
+
return r.text();
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// The schemas shipped with the package, beside dist/ (or the bundle that includes this file).
|
|
33
|
+
const schemaDir = process.env.ODDITY_LS_SCHEMAS;
|
|
34
|
+
if (schemaDir) {
|
|
35
|
+
const base = pathToFileURL(schemaDir.endsWith('/') ? schemaDir : `${schemaDir}/`);
|
|
36
|
+
host.defaults = Object.fromEntries(Object.entries(DEFAULT_SCHEMA_FILES).map(([k, f]) => [k, new URL(f, base).href]));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
startServer(createConnection(ProposedFeatures.all), host);
|