@dita-viewer/core 0.2.0 → 0.2.2
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 -21
- package/README.md +90 -58
- package/dist/editor/renderContext.d.ts +7 -0
- package/dist/editor/renderContext.js +24 -0
- package/dist/editor/topicRender.d.ts +9 -0
- package/dist/editor/topicRender.js +4 -2
- package/dist/index.js +3 -3
- package/dist/language/ditaLanguageUtils.js +2 -0
- package/dist/profiling.d.ts +9 -3
- package/dist/profiling.js +12 -6
- package/dist/render/baseTypeMap.js +28 -2
- package/dist/render/mapTypeMap.js +23 -23
- package/dist/render/renderer.d.ts +24 -0
- package/dist/render/renderer.js +36 -9
- package/dist-esm/bookRender.js +145 -0
- package/dist-esm/completion.js +142 -0
- package/dist-esm/completionData.js +155 -0
- package/dist-esm/diagnostics.js +378 -0
- package/dist-esm/editor/conkeyref.js +104 -0
- package/dist-esm/editor/keySpace.js +201 -0
- package/dist-esm/editor/refResolvers.js +633 -0
- package/dist-esm/editor/renderContext.js +138 -0
- package/dist-esm/editor/sourceText.js +142 -0
- package/dist-esm/editor/topicRender.js +328 -0
- package/dist-esm/index.js +66 -0
- package/dist-esm/keyMapForDocument.js +23 -0
- package/dist-esm/language/ditaLanguageUtils.js +659 -0
- package/dist-esm/language/referenceableFiles.js +108 -0
- package/dist-esm/mapRender.js +24 -0
- package/dist-esm/package.json +1 -0
- package/dist-esm/parser/ditaParser.js +409 -0
- package/dist-esm/parser/domTypes.js +1 -0
- package/dist-esm/parser/mapTagMap.js +77 -0
- package/dist-esm/parser/namedEntities.js +321 -0
- package/dist-esm/parser/standardTagMap.js +393 -0
- package/dist-esm/profiling.js +224 -0
- package/dist-esm/render/baseTypeMap.js +1057 -0
- package/dist-esm/render/cjkSpacing.js +94 -0
- package/dist-esm/render/mapTypeMap.js +568 -0
- package/dist-esm/render/renderer.js +519 -0
- package/dist-esm/siteRender.js +261 -0
- package/package.json +55 -53
- package/styles/TOKENS.md +59 -38
- package/styles/dita-content.css +1171 -1157
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// Which files completion offers for an href/conref value, and how the folder
|
|
2
|
+
// tree is walked to find them.
|
|
3
|
+
//
|
|
4
|
+
// Its own module for the same reason mapTreeRefresh.ts exists: this walk used
|
|
5
|
+
// to live inside the completion provider, which imports vscode, so none of its
|
|
6
|
+
// rules were reachable from plain mocha -- and the rules are the whole
|
|
7
|
+
// behaviour. Depth limit, pruned directory names, which extensions count, the
|
|
8
|
+
// result cap: every one of them is a trade-off that looks identical in a
|
|
9
|
+
// screenshot and differs in whether completion stays usable in a large
|
|
10
|
+
// document set.
|
|
11
|
+
//
|
|
12
|
+
// The reader is injected rather than called here. That is what keeps the
|
|
13
|
+
// module loadable without the vscode API (the unit tests run without it) and
|
|
14
|
+
// what let the runtime version switch from readdirSync to
|
|
15
|
+
// workspace.fs.readDirectory without touching a single rule below.
|
|
16
|
+
import { join, normalize, relative } from 'path';
|
|
17
|
+
/**
|
|
18
|
+
* Directory names never worth descending into. `out` is where DITA-OT writes
|
|
19
|
+
* generated .dita/.xml, which are real files matching the extension rule but
|
|
20
|
+
* are copies of sources the user would never mean to reference; `node_modules`
|
|
21
|
+
* is here because a document set that lives next to a build tree otherwise
|
|
22
|
+
* spends its whole result cap on it.
|
|
23
|
+
*
|
|
24
|
+
* Checked against the entry name at every level, not just the top one, and
|
|
25
|
+
* against directories and files alike -- matching the walk this was extracted
|
|
26
|
+
* from, which tested the name before it knew what the entry was.
|
|
27
|
+
*/
|
|
28
|
+
const PRUNED_ENTRY_NAMES = new Set(['node_modules', 'out']);
|
|
29
|
+
/**
|
|
30
|
+
* Extensions completion offers. Case-insensitive on purpose: document sets do
|
|
31
|
+
* contain `TOPIC.DITA`, and a glob-based search would match that only on the
|
|
32
|
+
* case-insensitive file systems -- this project's CI runs the same code on
|
|
33
|
+
* ubuntu, windows and macos.
|
|
34
|
+
*/
|
|
35
|
+
const REFERENCEABLE_EXT = /\.(dita|ditamap|xml)$/i;
|
|
36
|
+
/** How many directory levels below the document's own folder are searched. */
|
|
37
|
+
export const REFERENCEABLE_MAX_DEPTH = 3;
|
|
38
|
+
/**
|
|
39
|
+
* Soft bound on the result list.
|
|
40
|
+
*
|
|
41
|
+
* Deliberately soft, and deliberately unchanged: the walk this replaces checked
|
|
42
|
+
* the count once per directory rather than once per file, so a single directory
|
|
43
|
+
* holding more matching files than the cap yields all of them (a measurement of
|
|
44
|
+
* a 30 x 60 document set returned 240, not 200). Tightening that would change
|
|
45
|
+
* which files completion offers, and this change is about not blocking the
|
|
46
|
+
* extension host -- not about re-deciding the cap. Pinned by a test so the
|
|
47
|
+
* behaviour is a choice on the record rather than an accident.
|
|
48
|
+
*/
|
|
49
|
+
export const REFERENCEABLE_MAX_RESULTS = 200;
|
|
50
|
+
/**
|
|
51
|
+
* Lists referenceable files under `baseDir`, as href strings relative to it.
|
|
52
|
+
*
|
|
53
|
+
* Depth-first, in the order the reader yields entries -- both preserved from
|
|
54
|
+
* the recursive version this replaces, because the soft result cap makes order
|
|
55
|
+
* observable: whichever files are reached first are the ones offered when the
|
|
56
|
+
* cap binds.
|
|
57
|
+
*/
|
|
58
|
+
export async function collectReferenceableFiles(baseDir, readDir, options = {}) {
|
|
59
|
+
const maxDepth = options.maxDepth ?? REFERENCEABLE_MAX_DEPTH;
|
|
60
|
+
const maxResults = options.maxResults ?? REFERENCEABLE_MAX_RESULTS;
|
|
61
|
+
const isCancelled = options.isCancelled ?? (() => false);
|
|
62
|
+
const results = [];
|
|
63
|
+
async function walk(dir, depth) {
|
|
64
|
+
if (depth > maxDepth || results.length >= maxResults || isCancelled())
|
|
65
|
+
return;
|
|
66
|
+
let entries;
|
|
67
|
+
try {
|
|
68
|
+
entries = await readDir(dir);
|
|
69
|
+
}
|
|
70
|
+
catch (e) {
|
|
71
|
+
// Unreadable, missing or just-deleted directory: skip this subtree and
|
|
72
|
+
// keep the rest. Completion degrading to "fewer suggestions" beats
|
|
73
|
+
// throwing into VS Code's completion pipeline, and the synchronous walk
|
|
74
|
+
// this replaces swallowed readdirSync failures the same way.
|
|
75
|
+
console.warn(`Failed to read directory ${dir}:`, e instanceof Error ? e.message : e);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
for (const entry of entries) {
|
|
79
|
+
if (isCancelled())
|
|
80
|
+
return;
|
|
81
|
+
if (entry.name.startsWith('.') || PRUNED_ENTRY_NAMES.has(entry.name))
|
|
82
|
+
continue;
|
|
83
|
+
const full = join(dir, entry.name);
|
|
84
|
+
if (entry.isDirectory) {
|
|
85
|
+
await walk(full, depth + 1);
|
|
86
|
+
}
|
|
87
|
+
else if (REFERENCEABLE_EXT.test(entry.name)) {
|
|
88
|
+
results.push(toRelativeHref(baseDir, full));
|
|
89
|
+
}
|
|
90
|
+
// No per-entry try/catch any more: the only thing that used to throw per
|
|
91
|
+
// entry was the statSync that decided file-vs-directory, and the injected
|
|
92
|
+
// reader now supplies that answer up front.
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
await walk(baseDir, 0);
|
|
96
|
+
return results;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Turns an absolute path into the string completion inserts.
|
|
100
|
+
*
|
|
101
|
+
* Relative because href/conref values are resolved against the referencing
|
|
102
|
+
* document's folder, and forward-slashed because they are XML attribute values
|
|
103
|
+
* in a DITA document, not Windows paths -- a `\` in an href would be a literal
|
|
104
|
+
* backslash to every consumer of that document.
|
|
105
|
+
*/
|
|
106
|
+
export function toRelativeHref(baseDir, fullPath) {
|
|
107
|
+
return normalize(relative(baseDir, fullPath)).replace(/\\/g, '/');
|
|
108
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Render a .ditamap's text to the outline tree HTML.
|
|
2
|
+
//
|
|
3
|
+
// The same steps the VS Code viewer's tree mode runs (parse, splice in
|
|
4
|
+
// referenced submaps, render), as one host-neutral call. Nothing here is new
|
|
5
|
+
// rendering logic -- it only sequences the copied parser and renderer.
|
|
6
|
+
import { resolve } from 'path';
|
|
7
|
+
import { parseDitamap, preprocessEntities } from './parser/ditaParser';
|
|
8
|
+
import { expandDitamapRefs } from './editor/refResolvers';
|
|
9
|
+
import { readSourceText } from './editor/sourceText';
|
|
10
|
+
import { renderMapDocument } from './render/mapTypeMap';
|
|
11
|
+
export function renderMapXml(input) {
|
|
12
|
+
const doc = parseDitamap(preprocessEntities(input.xml));
|
|
13
|
+
const read = (path, enc) => {
|
|
14
|
+
input.collectDependencies?.add(resolve(path));
|
|
15
|
+
return readSourceText(path, enc);
|
|
16
|
+
};
|
|
17
|
+
expandDitamapRefs(doc.root, input.docDir, read);
|
|
18
|
+
return renderMapDocument(doc.root, {
|
|
19
|
+
docDir: input.docDir,
|
|
20
|
+
resolveKey: (k) => input.keyMap?.get(k),
|
|
21
|
+
roleFormat: input.roleFormat,
|
|
22
|
+
treeLabel: input.treeLabel,
|
|
23
|
+
});
|
|
24
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "type": "module" }
|
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
import sax from 'sax';
|
|
2
|
+
import { STANDARD_TAG_TO_BASETYPE } from './standardTagMap';
|
|
3
|
+
import { MAP_STANDARD_TAG_TO_BASETYPE } from './mapTagMap';
|
|
4
|
+
import { lookupNamedEntity } from './namedEntities';
|
|
5
|
+
const TOPIC_PATTERN = /^(topic|map)\//;
|
|
6
|
+
// Modules whose elements the standard tag tables cover. A class token from one of
|
|
7
|
+
// these ("hi-d/b", "task/step") names a standard element, so its local name can
|
|
8
|
+
// be looked up in the tag table; a token from any other module is a custom
|
|
9
|
+
// specialization and must not be matched by name (my-d/b is not hi-d/b).
|
|
10
|
+
const STANDARD_MODULES = new Set([
|
|
11
|
+
'topic', 'task', 'concept', 'reference', 'glossentry', 'glossgroup', 'troubleshooting',
|
|
12
|
+
'hi-d', 'pr-d', 'sw-d', 'ui-d', 'ut-d', 'abbrev-d', 'xml-d', 'markup-d', 'delay-d',
|
|
13
|
+
'equation-d', 'hazard-d', 'taskreq-d', 'svg-d', 'mathml-d',
|
|
14
|
+
'map', 'mapgroup-d', 'bookmap', 'glossref-d', 'ditavalref-d',
|
|
15
|
+
]);
|
|
16
|
+
function makeParseBaseType(tagMap) {
|
|
17
|
+
const known = new Set(Object.values(tagMap));
|
|
18
|
+
return function parseBaseType(tagName, classAttr) {
|
|
19
|
+
const fromTag = tagMap[tagName];
|
|
20
|
+
if (fromTag) {
|
|
21
|
+
return fromTag;
|
|
22
|
+
}
|
|
23
|
+
if (classAttr) {
|
|
24
|
+
const tokens = classAttr.trim().split(/\s+/);
|
|
25
|
+
// A @class lists ancestors from the most general to the most specific
|
|
26
|
+
// ("- topic/ph hi-d/b my-d/mybold "). Without a DTD the best answer is the
|
|
27
|
+
// most specific token that is a standard element or a known base type.
|
|
28
|
+
for (let i = tokens.length - 1; i >= 0; i--) {
|
|
29
|
+
const token = tokens[i];
|
|
30
|
+
const slash = token.indexOf('/');
|
|
31
|
+
if (slash > 0) {
|
|
32
|
+
if (STANDARD_MODULES.has(token.slice(0, slash))) {
|
|
33
|
+
const viaName = tagMap[token.slice(slash + 1)];
|
|
34
|
+
if (viaName)
|
|
35
|
+
return viaName;
|
|
36
|
+
}
|
|
37
|
+
if (known.has(token))
|
|
38
|
+
return token;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
// Nothing recognisable: keep the first topic/map token, as before.
|
|
42
|
+
for (const token of tokens) {
|
|
43
|
+
if (TOPIC_PATTERN.test(token)) {
|
|
44
|
+
return token;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return undefined;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function makeRange() {
|
|
52
|
+
return { startLine: 0, startCol: 0, endLine: 0, endCol: 0 };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Walks the raw source and lists every element tag with its exact offsets.
|
|
56
|
+
* sax's parser.line/column only update on newlines and at onopentag describe
|
|
57
|
+
* the position AFTER the tag's '>', and parser.position is unreliable once
|
|
58
|
+
* text has been reported — so tag ranges come from this scan instead. SAX
|
|
59
|
+
* consumes tags in source order, so the parser's onopentag/onclosetag
|
|
60
|
+
* handlers shift this queue one event at a time; `>` inside quoted attribute
|
|
61
|
+
* values (conref="a>b.dita#t/id") is skipped like a real XML parser does,
|
|
62
|
+
* `<` inside them is rejected by strict-mode sax outright.
|
|
63
|
+
*/
|
|
64
|
+
function scanTagEvents(xml) {
|
|
65
|
+
const events = [];
|
|
66
|
+
let i = 0;
|
|
67
|
+
while (i < xml.length) {
|
|
68
|
+
const lt = xml.indexOf('<', i);
|
|
69
|
+
if (lt < 0)
|
|
70
|
+
break;
|
|
71
|
+
if (xml.startsWith('<!--', lt)) {
|
|
72
|
+
const end = xml.indexOf('-->', lt + 4);
|
|
73
|
+
i = end < 0 ? xml.length : end + 3;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (xml.startsWith('<![CDATA[', lt)) {
|
|
77
|
+
const end = xml.indexOf(']]>', lt + 9);
|
|
78
|
+
i = end < 0 ? xml.length : end + 3;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (xml.startsWith('<?', lt) || xml.startsWith('<!', lt)) {
|
|
82
|
+
// processing instruction / DOCTYPE: find the terminating '>' outside quotes
|
|
83
|
+
let j = lt + 2;
|
|
84
|
+
while (j < xml.length) {
|
|
85
|
+
const ch = xml[j];
|
|
86
|
+
if (ch === '"' || ch === "'") {
|
|
87
|
+
const close = xml.indexOf(ch, j + 1);
|
|
88
|
+
if (close < 0)
|
|
89
|
+
break;
|
|
90
|
+
j = close + 1;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (ch === '>')
|
|
94
|
+
break;
|
|
95
|
+
j++;
|
|
96
|
+
}
|
|
97
|
+
i = j + 1;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const m = /^([A-Za-z_:][\w.:-]*)/.exec(xml.slice(lt + 1));
|
|
101
|
+
if (!m) {
|
|
102
|
+
i = lt + 1;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const name = m[1];
|
|
106
|
+
let j = lt + 1 + name.length;
|
|
107
|
+
let selfClosing = false;
|
|
108
|
+
let gt = -1;
|
|
109
|
+
while (j < xml.length) {
|
|
110
|
+
const ch = xml[j];
|
|
111
|
+
if (ch === '"' || ch === "'") {
|
|
112
|
+
const close = xml.indexOf(ch, j + 1);
|
|
113
|
+
if (close < 0)
|
|
114
|
+
break;
|
|
115
|
+
j = close + 1;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (ch === '>') {
|
|
119
|
+
selfClosing = xml[j - 1] === '/';
|
|
120
|
+
gt = j;
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
j++;
|
|
124
|
+
}
|
|
125
|
+
if (gt < 0)
|
|
126
|
+
break; // unterminated tag: leave the rest to sax's error handling
|
|
127
|
+
const isClose = xml[lt + 1] === '/';
|
|
128
|
+
events.push({ name, selfClosing, isClose, start: lt, end: gt + 1 });
|
|
129
|
+
i = gt + 1;
|
|
130
|
+
}
|
|
131
|
+
return events;
|
|
132
|
+
}
|
|
133
|
+
function makeParser(tagMap) {
|
|
134
|
+
const parseBaseType = makeParseBaseType(tagMap);
|
|
135
|
+
return function parseXml(xml) {
|
|
136
|
+
const parser = sax.parser(true, { trim: false, normalize: false });
|
|
137
|
+
const root = {
|
|
138
|
+
type: 'element',
|
|
139
|
+
children: [],
|
|
140
|
+
sourceRange: makeRange(),
|
|
141
|
+
};
|
|
142
|
+
const stack = [root];
|
|
143
|
+
let currentText = '';
|
|
144
|
+
let currentTextStartLine = 0;
|
|
145
|
+
let currentTextStartCol = 0;
|
|
146
|
+
// Range end stashed by onopentag for a self-closing tag, consumed by the
|
|
147
|
+
// onclosetag sax fires immediately after for it.
|
|
148
|
+
let selfClosingEnd;
|
|
149
|
+
// The source scan feeding exact tag offsets to the handlers below.
|
|
150
|
+
const tagEvents = scanTagEvents(xml);
|
|
151
|
+
let q = 0;
|
|
152
|
+
// (line, col) of a raw offset, via an ever-forward line-start cursor.
|
|
153
|
+
// Tag offsets are consumed in document order, so it never rewinds.
|
|
154
|
+
let lastLineStart = 0;
|
|
155
|
+
let currentLine = 0;
|
|
156
|
+
function locAt(pos) {
|
|
157
|
+
let i = lastLineStart;
|
|
158
|
+
let line = currentLine;
|
|
159
|
+
let nl = xml.indexOf('\n', i);
|
|
160
|
+
while (nl !== -1 && nl < pos) {
|
|
161
|
+
i = nl + 1;
|
|
162
|
+
line++;
|
|
163
|
+
nl = xml.indexOf('\n', i);
|
|
164
|
+
}
|
|
165
|
+
lastLineStart = i;
|
|
166
|
+
currentLine = line;
|
|
167
|
+
return { line, col: pos - i };
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Pops the queue's next tag of the given kind, trusting sax as the
|
|
171
|
+
* authority on order but the scan as the authority on position. sax
|
|
172
|
+
* lower-cases names by default, so the scan's raw spelling is compared
|
|
173
|
+
* the same way. A head mismatch means the two disagree on something
|
|
174
|
+
* exotic (a comment form neither skips identically); re-sync within a
|
|
175
|
+
* small window and otherwise fall back to sax's own line/column, so
|
|
176
|
+
* parsing never fails over a bookkeeping disagreement.
|
|
177
|
+
*/
|
|
178
|
+
function nextTag(name, isClose) {
|
|
179
|
+
const want = name.toLowerCase();
|
|
180
|
+
for (let k = q; k < Math.min(q + 8, tagEvents.length); k++) {
|
|
181
|
+
const e = tagEvents[k];
|
|
182
|
+
if (e.isClose !== isClose || e.name.toLowerCase() !== want)
|
|
183
|
+
continue;
|
|
184
|
+
// Skip the entries between q and k: whatever they were, sax has not
|
|
185
|
+
// reported them, so they don't correspond to this parser's stream.
|
|
186
|
+
q = k + 1;
|
|
187
|
+
return e;
|
|
188
|
+
}
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
function saxFallbackEnd() {
|
|
192
|
+
return { line: parser.line, col: parser.column };
|
|
193
|
+
}
|
|
194
|
+
function flushText() {
|
|
195
|
+
if (currentText.length > 0) {
|
|
196
|
+
const parent = stack[stack.length - 1];
|
|
197
|
+
if (parent) {
|
|
198
|
+
parent.children.push({
|
|
199
|
+
type: 'text',
|
|
200
|
+
text: currentText,
|
|
201
|
+
children: [],
|
|
202
|
+
sourceRange: {
|
|
203
|
+
startLine: currentTextStartLine,
|
|
204
|
+
startCol: currentTextStartCol,
|
|
205
|
+
endLine: parser.line,
|
|
206
|
+
endCol: parser.column,
|
|
207
|
+
},
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
currentText = '';
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
parser.onopentag = (node) => {
|
|
214
|
+
flushText();
|
|
215
|
+
const tagName = node.name;
|
|
216
|
+
const classAttr = node.attributes['class'];
|
|
217
|
+
const baseType = parseBaseType(tagName, classAttr);
|
|
218
|
+
const classTokens = classAttr
|
|
219
|
+
? classAttr.trim().split(/\s+/).filter(Boolean)
|
|
220
|
+
: undefined;
|
|
221
|
+
// The range spans the tag's own source text, from its '<' to just past
|
|
222
|
+
// its '>' — not sax's after-'>' position — so cursor positions
|
|
223
|
+
// anywhere inside the tag's text (the common case of clicking a line
|
|
224
|
+
// to locate it in the preview) resolve to this element, and a
|
|
225
|
+
// self-closing element no longer records a zero-width range sitting
|
|
226
|
+
// beyond its own end.
|
|
227
|
+
const open = nextTag(tagName, false);
|
|
228
|
+
const start = open ? locAt(open.start) : { line: parser.line, col: Math.max(0, parser.column - 1) };
|
|
229
|
+
if (open?.selfClosing) {
|
|
230
|
+
// sax fires onclosetag for self-closing tags too, immediately after
|
|
231
|
+
// onopentag, with the parser position unmoved: consume that queue
|
|
232
|
+
// entry here and let the close carry the range end below.
|
|
233
|
+
selfClosingEnd = open ? locAt(open.end) : saxFallbackEnd();
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
selfClosingEnd = undefined;
|
|
237
|
+
}
|
|
238
|
+
const element = {
|
|
239
|
+
type: 'element',
|
|
240
|
+
tagName,
|
|
241
|
+
classTokens,
|
|
242
|
+
baseType,
|
|
243
|
+
attributes: node.attributes,
|
|
244
|
+
children: [],
|
|
245
|
+
sourceRange: {
|
|
246
|
+
startLine: start.line,
|
|
247
|
+
startCol: start.col,
|
|
248
|
+
endLine: 0,
|
|
249
|
+
endCol: 0,
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
const parent = stack[stack.length - 1];
|
|
253
|
+
if (parent) {
|
|
254
|
+
parent.children.push(element);
|
|
255
|
+
}
|
|
256
|
+
stack.push(element);
|
|
257
|
+
};
|
|
258
|
+
parser.onclosetag = () => {
|
|
259
|
+
flushText();
|
|
260
|
+
const element = stack.pop();
|
|
261
|
+
if (element) {
|
|
262
|
+
// Self-closing: onopentag already consumed the scan entry and stashed
|
|
263
|
+
// the end. Real close tag: its '>' ends the element's range.
|
|
264
|
+
let end;
|
|
265
|
+
if (selfClosingEnd) {
|
|
266
|
+
end = selfClosingEnd;
|
|
267
|
+
selfClosingEnd = undefined;
|
|
268
|
+
}
|
|
269
|
+
else {
|
|
270
|
+
const close = nextTag(element.tagName || '', true);
|
|
271
|
+
end = close && close.end >= 0 ? locAt(close.end) : saxFallbackEnd();
|
|
272
|
+
}
|
|
273
|
+
element.sourceRange.endLine = end.line;
|
|
274
|
+
element.sourceRange.endCol = end.col;
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
parser.ontext = (text) => {
|
|
278
|
+
if (currentText.length === 0) {
|
|
279
|
+
currentTextStartLine = parser.line;
|
|
280
|
+
currentTextStartCol = parser.column;
|
|
281
|
+
}
|
|
282
|
+
currentText += text;
|
|
283
|
+
};
|
|
284
|
+
// CDATA sections fire a separate sax event (not ontext) — without this
|
|
285
|
+
// handler, <![CDATA[...]]> content (common in codeblocks) is dropped.
|
|
286
|
+
parser.oncdata = (text) => {
|
|
287
|
+
if (currentText.length === 0) {
|
|
288
|
+
currentTextStartLine = parser.line;
|
|
289
|
+
currentTextStartCol = parser.column;
|
|
290
|
+
}
|
|
291
|
+
currentText += text;
|
|
292
|
+
};
|
|
293
|
+
parser.onerror = (err) => {
|
|
294
|
+
throw new Error(`SAX parse error at line ${parser.line}:${parser.column}: ${err.message}`);
|
|
295
|
+
};
|
|
296
|
+
parser.write(xml).close();
|
|
297
|
+
const docRoot = root.children.find((c) => c.type === 'element');
|
|
298
|
+
if (!docRoot) {
|
|
299
|
+
throw new Error('No root element found in DITA document');
|
|
300
|
+
}
|
|
301
|
+
return {
|
|
302
|
+
root: docRoot,
|
|
303
|
+
sourceRange: docRoot.sourceRange,
|
|
304
|
+
};
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Common ISO/HTML character entities that DITA DTDs normally declare in
|
|
309
|
+
* external subsets. The DOCTYPE (and with it those declarations) is
|
|
310
|
+
* stripped before parsing, so map the frequent ones to literal characters
|
|
311
|
+
* instead of silently deleting the text.
|
|
312
|
+
*/
|
|
313
|
+
const ISO_ENTITIES = {
|
|
314
|
+
nbsp: '\u00a0', copy: '©', reg: '®', trade: '™', deg: '°', plusmn: '±',
|
|
315
|
+
micro: 'µ', middot: '·', laquo: '«', raquo: '»', sect: '§', para: '¶',
|
|
316
|
+
times: '×', divide: '÷', frac12: '½', frac14: '¼', frac34: '¾',
|
|
317
|
+
sup1: '¹', sup2: '²', sup3: '³', cent: '¢', pound: '£', yen: '¥', euro: '€',
|
|
318
|
+
ndash: '–', mdash: '—', lsquo: '\u2018', rsquo: '\u2019', ldquo: '\u201c', rdquo: '\u201d',
|
|
319
|
+
hellip: '…', bull: '•', dagger: '†', Dagger: '‡', prime: '′', Prime: '″',
|
|
320
|
+
larr: '←', uarr: '↑', rarr: '→', darr: '↓', harr: '↔',
|
|
321
|
+
};
|
|
322
|
+
const BUILTIN_ENTITIES = new Set(['amp', 'lt', 'gt', 'quot', 'apos']);
|
|
323
|
+
/** Nested-entity expansion cap; also what stops a self-referential declaration. */
|
|
324
|
+
const MAX_ENTITY_DEPTH = 8;
|
|
325
|
+
/** A CDATA section or comment (left verbatim) or a named entity reference. */
|
|
326
|
+
const CDATA_COMMENT_OR_ENTITY_REF = /(<!\[CDATA\[[\s\S]*?\]\]>|<!--[\s\S]*?-->)|&([a-zA-Z_][a-zA-Z0-9_.-]*);/g;
|
|
327
|
+
const XML_ESCAPES = { '&': '&', '<': '<', '>': '>' };
|
|
328
|
+
/**
|
|
329
|
+
* Preprocess XML to avoid SAX parse errors:
|
|
330
|
+
* 1. Extract general entity declarations from the DOCTYPE (single- or
|
|
331
|
+
* double-quoted; parameter entities `<!ENTITY % ...>` are ignored)
|
|
332
|
+
* 2. Strip the entire DOCTYPE declaration
|
|
333
|
+
* 3. Replace entity references outside CDATA sections and comments:
|
|
334
|
+
* declared entities (first declaration wins; values may reference other
|
|
335
|
+
* entities, expanded up to MAX_ENTITY_DEPTH) take precedence over the
|
|
336
|
+
* ISO/HTML character tables; built-in XML entities are kept as-is
|
|
337
|
+
* 4. Any reference that still can't be resolved (e.g. declared in an
|
|
338
|
+
* external DTD subset that is never loaded) is kept as the literal
|
|
339
|
+
* text "&name;" rather than deleted -- deleting it made the text vanish
|
|
340
|
+
* without a trace, and a bare reference would make SAX throw
|
|
341
|
+
*
|
|
342
|
+
* CDATA sections and comments are left exactly as written: inside them
|
|
343
|
+
* " " is just characters (e.g. a codeblock showing HTML), not a reference.
|
|
344
|
+
*/
|
|
345
|
+
export function preprocessEntities(xml) {
|
|
346
|
+
// 1. Extract simple entity declarations: <!ENTITY name "value"> / 'value'.
|
|
347
|
+
// `[^\s%]` as the first name character rejects parameter entities
|
|
348
|
+
// (<!ENTITY % name ...>), which are not referenced as &name;.
|
|
349
|
+
const entityRegex = /<!ENTITY\s+([^\s%]\S*)\s+(?:"([^"]*)"|'([^']*)')\s*>/g;
|
|
350
|
+
const declared = new Map();
|
|
351
|
+
let match;
|
|
352
|
+
while ((match = entityRegex.exec(xml)) !== null) {
|
|
353
|
+
if (!declared.has(match[1]))
|
|
354
|
+
declared.set(match[1], match[2] ?? match[3]);
|
|
355
|
+
}
|
|
356
|
+
// 2. Strip the entire DOCTYPE declaration
|
|
357
|
+
const stripped = stripDoctype(xml);
|
|
358
|
+
// 3./4. One pass over everything that is not a CDATA section or comment.
|
|
359
|
+
// Values are substituted via a callback so '$&'/'$$' sequences in an
|
|
360
|
+
// entity value stay literal, and names are looked up in a Map so ones
|
|
361
|
+
// containing regex metacharacters (e.g. '.') match exactly.
|
|
362
|
+
const expand = (text, depth) => text.replace(CDATA_COMMENT_OR_ENTITY_REF, (full, verbatim, name) => {
|
|
363
|
+
if (verbatim !== undefined)
|
|
364
|
+
return full;
|
|
365
|
+
if (BUILTIN_ENTITIES.has(name))
|
|
366
|
+
return full;
|
|
367
|
+
const declaredValue = declared.get(name);
|
|
368
|
+
if (declaredValue !== undefined) {
|
|
369
|
+
// Declared values are markup and are inserted as written.
|
|
370
|
+
return depth < MAX_ENTITY_DEPTH ? expand(declaredValue, depth + 1) : `&${name};`;
|
|
371
|
+
}
|
|
372
|
+
const chars = ISO_ENTITIES[name] ?? lookupNamedEntity(name);
|
|
373
|
+
// Table values are plain characters: escape the markup-significant
|
|
374
|
+
// ones (e.g. the HTML5 aliases & and <).
|
|
375
|
+
if (chars !== undefined)
|
|
376
|
+
return chars.replace(/[&<>]/g, (c) => XML_ESCAPES[c]);
|
|
377
|
+
return `&${name};`;
|
|
378
|
+
});
|
|
379
|
+
return expand(stripped, 0);
|
|
380
|
+
}
|
|
381
|
+
/** Strips the entire <!DOCTYPE ...> declaration, including internal subset [...]. */
|
|
382
|
+
function stripDoctype(xml) {
|
|
383
|
+
const start = xml.indexOf('<!DOCTYPE');
|
|
384
|
+
if (start < 0)
|
|
385
|
+
return xml;
|
|
386
|
+
// Check for an internal subset marked by [ ... ]>
|
|
387
|
+
const bracketStart = xml.indexOf('[', start);
|
|
388
|
+
const firstGt = xml.indexOf('>', start);
|
|
389
|
+
if (bracketStart >= 0 && (firstGt < 0 || bracketStart < firstGt)) {
|
|
390
|
+
// Has internal subset — find the closing ]>
|
|
391
|
+
const end = xml.indexOf(']>', bracketStart);
|
|
392
|
+
if (end >= 0) {
|
|
393
|
+
return xml.substring(0, start) + xml.substring(end + 2);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
// No internal subset — just strip up to and including the first >
|
|
397
|
+
if (firstGt >= 0) {
|
|
398
|
+
return xml.substring(0, start) + xml.substring(firstGt + 1);
|
|
399
|
+
}
|
|
400
|
+
return xml;
|
|
401
|
+
}
|
|
402
|
+
const _parseDita = makeParser(STANDARD_TAG_TO_BASETYPE);
|
|
403
|
+
const _parseDitamap = makeParser(MAP_STANDARD_TAG_TO_BASETYPE);
|
|
404
|
+
export function parseDita(xml) {
|
|
405
|
+
return _parseDita(xml);
|
|
406
|
+
}
|
|
407
|
+
export function parseDitamap(xml) {
|
|
408
|
+
return _parseDitamap(xml);
|
|
409
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
export const MAP_STANDARD_TAG_TO_BASETYPE = {
|
|
2
|
+
// Root
|
|
3
|
+
map: 'map/map',
|
|
4
|
+
// BookMap root (specializes map)
|
|
5
|
+
bookmap: 'map/map',
|
|
6
|
+
// Metadata within topicmeta
|
|
7
|
+
title: 'map/map-title',
|
|
8
|
+
topicmeta: 'map/topicmeta',
|
|
9
|
+
navtitle: 'map/navtitle',
|
|
10
|
+
linktext: 'map/linktext',
|
|
11
|
+
shortdesc: 'map/shortdesc',
|
|
12
|
+
keywords: 'map/keywords',
|
|
13
|
+
keyword: 'map/keyword',
|
|
14
|
+
// BookMap title structure (specializes map/title)
|
|
15
|
+
booktitle: 'map/map-title',
|
|
16
|
+
mainbooktitle: 'map/map-title',
|
|
17
|
+
booktitlealt: 'map/map-title',
|
|
18
|
+
subtitle: 'map/map-title',
|
|
19
|
+
// BookMap metadata (specializes topicmeta)
|
|
20
|
+
bookmeta: 'map/topicmeta',
|
|
21
|
+
// Topic references
|
|
22
|
+
topicref: 'map/topicref',
|
|
23
|
+
topichead: 'map/topichead',
|
|
24
|
+
topicgroup: 'map/topicgroup',
|
|
25
|
+
keydef: 'map/keydef',
|
|
26
|
+
// BookMap topicref specializations
|
|
27
|
+
chapter: 'map/topicref',
|
|
28
|
+
appendix: 'map/topicref',
|
|
29
|
+
part: 'map/topicref',
|
|
30
|
+
preface: 'map/topicref',
|
|
31
|
+
notices: 'map/topicref',
|
|
32
|
+
draftintro: 'map/topicref',
|
|
33
|
+
glossaryref: 'map/topicref',
|
|
34
|
+
dedication: 'map/topicref',
|
|
35
|
+
colophon: 'map/topicref',
|
|
36
|
+
bookabstract: 'map/topicref',
|
|
37
|
+
amendments: 'map/topicref',
|
|
38
|
+
// BookMap structural containers — rendered as visible labels in tree view,
|
|
39
|
+
// children pass through at same depth for book view entry collection
|
|
40
|
+
frontmatter: 'map/bookmap-structural',
|
|
41
|
+
backmatter: 'map/bookmap-structural',
|
|
42
|
+
booklists: 'map/bookmap-structural',
|
|
43
|
+
toc: 'map/bookmap-structural',
|
|
44
|
+
figurelist: 'map/bookmap-structural',
|
|
45
|
+
tablelist: 'map/bookmap-structural',
|
|
46
|
+
indexlist: 'map/bookmap-structural',
|
|
47
|
+
glossarylist: 'map/bookmap-structural',
|
|
48
|
+
abbrevlist: 'map/bookmap-structural',
|
|
49
|
+
bibliolist: 'map/bookmap-structural',
|
|
50
|
+
trademarklist: 'map/bookmap-structural',
|
|
51
|
+
// Reltable
|
|
52
|
+
reltable: 'map/reltable',
|
|
53
|
+
relheader: 'map/relheader',
|
|
54
|
+
relrow: 'map/relrow',
|
|
55
|
+
relcell: 'map/relcell',
|
|
56
|
+
relcolspec: 'map/relcolspec',
|
|
57
|
+
// Other
|
|
58
|
+
anchor: 'map/anchor',
|
|
59
|
+
navref: 'map/navref',
|
|
60
|
+
mapref: 'map/mapref',
|
|
61
|
+
// ── ditavalref domain ── Evidence: base/dtd/ditavalrefDomain.mod ──
|
|
62
|
+
// class "+ map/topicref ditavalref-d/ditavalref" → first pair map/topicref
|
|
63
|
+
ditavalref: 'map/topicref',
|
|
64
|
+
// class "+ map/topicmeta ditavalref-d/ditavalmeta" → map/topicmeta
|
|
65
|
+
ditavalmeta: 'map/topicmeta',
|
|
66
|
+
// ── mapGroup domain ── Evidence: base/dtd/mapGroup.mod ──
|
|
67
|
+
anchorref: 'map/topicref',
|
|
68
|
+
topicset: 'map/topicref',
|
|
69
|
+
topicsetref: 'map/topicref',
|
|
70
|
+
// ── glossref domain ── Evidence: technicalContent/dtd/glossrefDomain.mod ──
|
|
71
|
+
// class "+ map/topicref glossref-d/glossref" → map/topicref
|
|
72
|
+
glossref: 'map/topicref',
|
|
73
|
+
// ── BookMap division/list wrappers (topicref specializations) ──
|
|
74
|
+
// Evidence: bookmap/dtd/bookmap.mod — class "- map/topicref bookmap/..."
|
|
75
|
+
appendices: 'map/topicref',
|
|
76
|
+
booklist: 'map/topicref',
|
|
77
|
+
};
|