@dita-viewer/core 0.2.1 → 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.
Files changed (41) hide show
  1. package/README.md +20 -7
  2. package/dist/editor/renderContext.d.ts +7 -0
  3. package/dist/editor/renderContext.js +24 -0
  4. package/dist/editor/topicRender.d.ts +9 -0
  5. package/dist/editor/topicRender.js +4 -2
  6. package/dist/language/ditaLanguageUtils.js +2 -0
  7. package/dist/profiling.d.ts +7 -1
  8. package/dist/profiling.js +9 -3
  9. package/dist/render/baseTypeMap.js +28 -2
  10. package/dist/render/renderer.d.ts +24 -0
  11. package/dist/render/renderer.js +36 -9
  12. package/dist-esm/bookRender.js +145 -0
  13. package/dist-esm/completion.js +142 -0
  14. package/dist-esm/completionData.js +155 -0
  15. package/dist-esm/diagnostics.js +378 -0
  16. package/dist-esm/editor/conkeyref.js +104 -0
  17. package/dist-esm/editor/keySpace.js +201 -0
  18. package/dist-esm/editor/refResolvers.js +633 -0
  19. package/dist-esm/editor/renderContext.js +138 -0
  20. package/dist-esm/editor/sourceText.js +142 -0
  21. package/dist-esm/editor/topicRender.js +328 -0
  22. package/dist-esm/index.js +66 -0
  23. package/dist-esm/keyMapForDocument.js +23 -0
  24. package/dist-esm/language/ditaLanguageUtils.js +659 -0
  25. package/dist-esm/language/referenceableFiles.js +108 -0
  26. package/dist-esm/mapRender.js +24 -0
  27. package/dist-esm/package.json +1 -0
  28. package/dist-esm/parser/ditaParser.js +409 -0
  29. package/dist-esm/parser/domTypes.js +1 -0
  30. package/dist-esm/parser/mapTagMap.js +77 -0
  31. package/dist-esm/parser/namedEntities.js +321 -0
  32. package/dist-esm/parser/standardTagMap.js +393 -0
  33. package/dist-esm/profiling.js +224 -0
  34. package/dist-esm/render/baseTypeMap.js +1057 -0
  35. package/dist-esm/render/cjkSpacing.js +94 -0
  36. package/dist-esm/render/mapTypeMap.js +568 -0
  37. package/dist-esm/render/renderer.js +519 -0
  38. package/dist-esm/siteRender.js +261 -0
  39. package/package.json +4 -2
  40. package/styles/TOKENS.md +21 -0
  41. package/styles/dita-content.css +31 -17
@@ -0,0 +1,155 @@
1
+ // What the completion engine knows about DITA, as data.
2
+ //
3
+ // CHILD_HINTS says which elements are the usual children of a parent. It is a
4
+ // ranking aid, not a content model: every known element is still offered
5
+ // everywhere, and a hinted one is merely listed first. A wrong or missing
6
+ // entry therefore costs a suggestion's position, never its availability, which
7
+ // is why this can be a curated table rather than a copy of the DTDs.
8
+ //
9
+ // Entries follow the DITA 1.3 technical-content and map vocabularies. Order is
10
+ // the order the suggestions appear in.
11
+ const INLINE = [
12
+ 'ph', 'codeph', 'keyword', 'term', 'xref', 'b', 'i', 'u', 'tt', 'sup', 'sub',
13
+ 'uicontrol', 'menucascade', 'userinput', 'systemoutput', 'varname', 'filepath',
14
+ 'cmdname', 'apiname', 'parmname', 'option', 'image', 'q', 'indexterm', 'fn',
15
+ 'data', 'tm', 'cite', 'abbreviated-form', 'xmlelement', 'xmlatt', 'msgph',
16
+ 'wintitle', 'shortcut', 'synph',
17
+ ];
18
+ const BLOCKS = [
19
+ 'p', 'ul', 'ol', 'dl', 'note', 'table', 'simpletable', 'fig', 'codeblock',
20
+ 'pre', 'lines', 'lq', 'sl', 'image', 'object', 'div', 'hazardstatement',
21
+ 'draft-comment', 'required-cleanup', 'foreign', 'data',
22
+ ];
23
+ const BODY = ['p', 'section', 'example', 'ul', 'ol', 'dl', 'note', 'table', 'simpletable', 'fig', 'codeblock', 'pre', 'lines', 'lq', 'sl', 'image', 'div', 'bodydiv', 'sectiondiv', 'hazardstatement', 'object', 'foreign', 'data', 'draft-comment', 'required-cleanup', 'fn', 'indexterm'];
24
+ const MIXED = [...new Set([...BLOCKS, ...INLINE])];
25
+ const TITLED_SECTION = ['title', ...BLOCKS];
26
+ const TOPIC_PARTS = ['title', 'titlealts', 'shortdesc', 'abstract', 'prolog'];
27
+ const MAP_REF_CHILDREN = ['topicmeta', 'topicref', 'keydef', 'mapref', 'topicgroup', 'topichead'];
28
+ export const CHILD_HINTS = {
29
+ // Topic roots
30
+ concept: [...TOPIC_PARTS, 'conbody', 'related-links'],
31
+ task: [...TOPIC_PARTS, 'taskbody', 'related-links'],
32
+ reference: [...TOPIC_PARTS, 'refbody', 'related-links'],
33
+ topic: [...TOPIC_PARTS, 'body', 'related-links'],
34
+ glossentry: ['glossterm', 'glossdef', 'glossBody', 'prolog'],
35
+ troubleshooting: [...TOPIC_PARTS, 'troublebody', 'related-links'],
36
+ // Bodies
37
+ body: BODY,
38
+ conbody: BODY,
39
+ refbody: ['section', 'refsyn', 'properties', 'table', 'simpletable', 'example', 'dl', 'p', 'ul', 'ol', 'note', 'codeblock'],
40
+ taskbody: ['prereq', 'context', 'steps', 'steps-unordered', 'steps-informal', 'result', 'example', 'postreq', 'section'],
41
+ troublebody: ['condition', 'troubleSolution', 'section', 'example'],
42
+ section: TITLED_SECTION,
43
+ example: TITLED_SECTION,
44
+ sectiondiv: BLOCKS,
45
+ bodydiv: BODY,
46
+ div: MIXED,
47
+ prereq: BLOCKS,
48
+ context: BLOCKS,
49
+ result: BLOCKS,
50
+ postreq: BLOCKS,
51
+ // Task steps
52
+ steps: ['step', 'stepsection'],
53
+ 'steps-unordered': ['step', 'stepsection'],
54
+ step: ['cmd', 'info', 'substeps', 'stepxmp', 'choices', 'choicetable', 'stepresult', 'steptroubleshooting', 'tutorialinfo'],
55
+ substeps: ['substep'],
56
+ substep: ['cmd', 'info', 'stepxmp', 'choices', 'choicetable', 'stepresult'],
57
+ choices: ['choice'],
58
+ // Lists
59
+ ul: ['li'],
60
+ ol: ['li'],
61
+ sl: ['sli'],
62
+ dl: ['dlhead', 'dlentry'],
63
+ dlentry: ['dt', 'dd'],
64
+ dlhead: ['dthd', 'ddhd'],
65
+ li: MIXED,
66
+ dd: MIXED,
67
+ sli: INLINE,
68
+ // Tables
69
+ table: ['title', 'desc', 'tgroup'],
70
+ tgroup: ['colspec', 'thead', 'tbody'],
71
+ thead: ['row'],
72
+ tbody: ['row'],
73
+ row: ['entry'],
74
+ entry: MIXED,
75
+ simpletable: ['sthead', 'strow'],
76
+ sthead: ['stentry'],
77
+ strow: ['stentry'],
78
+ stentry: MIXED,
79
+ // Figures and blocks that hold mixed content
80
+ fig: ['title', 'desc', 'image', 'figgroup', 'codeblock', 'pre', 'lines', 'simpletable', 'table'],
81
+ note: MIXED,
82
+ p: INLINE,
83
+ title: INLINE,
84
+ shortdesc: INLINE,
85
+ desc: INLINE,
86
+ cmd: INLINE,
87
+ info: MIXED,
88
+ lq: MIXED,
89
+ // Metadata
90
+ prolog: ['author', 'source', 'publisher', 'copyright', 'critdates', 'permissions', 'metadata', 'resourceid', 'data'],
91
+ metadata: ['audience', 'category', 'keywords', 'prodinfo', 'othermeta', 'data'],
92
+ keywords: ['keyword', 'indexterm'],
93
+ prodinfo: ['prodname', 'vrmlist', 'brand', 'component', 'featnum', 'prognum', 'platform', 'series'],
94
+ 'related-links': ['link', 'linklist', 'linkpool'],
95
+ link: ['linktext', 'desc'],
96
+ linklist: ['title', 'desc', 'link', 'linklist'],
97
+ // Maps
98
+ map: ['title', 'topicmeta', 'topicref', 'topichead', 'topicgroup', 'keydef', 'mapref', 'reltable', 'anchor', 'navref', 'topicset', 'data'],
99
+ bookmap: ['booktitle', 'bookmeta', 'frontmatter', 'chapter', 'part', 'appendices', 'appendix', 'backmatter', 'reltable'],
100
+ booktitle: ['mainbooktitle', 'booktitlealt'],
101
+ topicref: MAP_REF_CHILDREN,
102
+ topichead: MAP_REF_CHILDREN,
103
+ topicgroup: ['topicref', 'topichead', 'keydef', 'mapref', 'topicmeta'],
104
+ chapter: MAP_REF_CHILDREN,
105
+ part: [...MAP_REF_CHILDREN, 'chapter'],
106
+ appendix: MAP_REF_CHILDREN,
107
+ appendices: ['appendix', 'topicmeta'],
108
+ keydef: ['topicmeta', 'topicref'],
109
+ mapref: ['topicmeta'],
110
+ topicmeta: ['navtitle', 'linktext', 'shortdesc', 'keywords', 'data', 'othermeta', 'searchtitle', 'resourceid', 'author'],
111
+ reltable: ['relheader', 'relrow'],
112
+ relheader: ['relcolspec'],
113
+ relrow: ['relcell'],
114
+ relcolspec: ['topicref'],
115
+ relcell: ['topicref'],
116
+ };
117
+ /** Roots offered where no element is open yet. */
118
+ export const ROOT_HINTS = {
119
+ topic: ['concept', 'task', 'reference', 'topic', 'glossentry', 'troubleshooting'],
120
+ map: ['map', 'bookmap'],
121
+ };
122
+ /** Values for enumerated attributes. A `tag:attr` key outranks a bare `attr`. */
123
+ export const ENUM_VALUES = {
124
+ 'note:type': ['note', 'tip', 'important', 'caution', 'warning', 'danger', 'attention', 'remember', 'restriction', 'fastpath', 'trouble', 'notice', 'other'],
125
+ scope: ['local', 'peer', 'external'],
126
+ format: ['dita', 'ditamap', 'html', 'pdf', 'xml', 'txt'],
127
+ 'processing-role': ['normal', 'resource-only'],
128
+ toc: ['yes', 'no'],
129
+ print: ['yes', 'no', 'printonly'],
130
+ search: ['yes', 'no'],
131
+ locktitle: ['yes', 'no'],
132
+ linking: ['normal', 'targetonly', 'sourceonly', 'none'],
133
+ 'collection-type': ['unordered', 'sequence', 'choice', 'family'],
134
+ type: ['fn', 'section', 'table', 'fig', 'li', 'step', 'topic', 'concept', 'task', 'reference'],
135
+ placement: ['inline', 'break'],
136
+ align: ['left', 'right', 'center', 'current', 'justify'],
137
+ valign: ['top', 'middle', 'bottom'],
138
+ frame: ['all', 'bottom', 'none', 'sides', 'top', 'topbot'],
139
+ colsep: ['0', '1'],
140
+ rowsep: ['0', '1'],
141
+ pgwide: ['0', '1'],
142
+ importance: ['obsolete', 'deprecated', 'optional', 'default', 'low', 'normal', 'high', 'recommended', 'required', 'urgent'],
143
+ status: ['new', 'changed', 'deleted', 'unchanged'],
144
+ translate: ['yes', 'no', '-dita-use-conref-target'],
145
+ 'xml:lang': ['en-US', 'en-GB', 'zh-CN', 'zh-TW', 'ja-JP', 'ko-KR', 'de-DE', 'fr-FR', 'es-ES', 'ru-RU'],
146
+ };
147
+ /** Attributes whose value is a path, and which kind of file it names. */
148
+ export const FILE_ATTRS = {
149
+ href: 'topic',
150
+ conref: 'topic',
151
+ conrefend: 'topic',
152
+ };
153
+ /** Elements whose `href` points at an image or other binary rather than a topic. */
154
+ export const IMAGE_HREF_TAGS = new Set(['image', 'object', 'imagemap']);
155
+ export const IMAGE_EXT = /\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|emf)$/i;
@@ -0,0 +1,378 @@
1
+ // Authoring problems in one DITA source file, for a host's editor.
2
+ //
3
+ // Project-owned, not one of the verbatim VS Code files: the viewer's own
4
+ // diagnostics are built on `vscode.Diagnostic`, and this is the part a host
5
+ // without that type needs. Positions are 0-based line/column pairs with an
6
+ // exclusive end, the same convention as the parser's SourceRange.
7
+ //
8
+ // Two passes. The source must first be well-formed XML; a broken document gets
9
+ // that one error and nothing else, because every element position after the
10
+ // error would be a guess. Only then is the tree walked for the mistakes that
11
+ // read fine as XML: references to nothing and ids used twice.
12
+ import { existsSync } from 'fs';
13
+ import { dirname, isAbsolute, resolve } from 'path';
14
+ import sax from 'sax';
15
+ import { parseDita, parseDitamap } from './parser/ditaParser';
16
+ import { decodeHrefPart } from './editor/refResolvers';
17
+ import { splitRefFragment } from './language/ditaLanguageUtils';
18
+ /** A file whose #id anchors can be checked with idsIn. */
19
+ const DITA_FILE = /\.(dita|ditamap|xml)$/i;
20
+ /** `http:`, `mailto:`, `C:` — a reference the vault cannot resolve by path. */
21
+ const URL_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
22
+ /** Attributes that point at a file or an element. */
23
+ const FILE_ATTRIBUTES = ['href', 'conref', 'conrefend'];
24
+ /** Attributes that point at a key. conkeyref adds an element id after a '/'. */
25
+ const KEY_ATTRIBUTES = ['keyref', 'conkeyref'];
26
+ // ── line/column helpers ──
27
+ /** Offsets of every line start, so a source position and an offset convert both ways. */
28
+ function lineStarts(text) {
29
+ const starts = [0];
30
+ for (let i = 0; i < text.length; i++)
31
+ if (text.charCodeAt(i) === 10)
32
+ starts.push(i + 1);
33
+ return starts;
34
+ }
35
+ function offsetOf(starts, text, line, col) {
36
+ const start = starts[Math.min(Math.max(0, line), starts.length - 1)];
37
+ return Math.min(text.length, start + Math.max(0, col));
38
+ }
39
+ function positionOf(starts, offset) {
40
+ let lo = 0;
41
+ let hi = starts.length - 1;
42
+ while (lo < hi) {
43
+ const mid = (lo + hi + 1) >> 1;
44
+ if (starts[mid] <= offset)
45
+ lo = mid;
46
+ else
47
+ hi = mid - 1;
48
+ }
49
+ return { line: lo, col: offset - starts[lo] };
50
+ }
51
+ /**
52
+ * Index just past the '>' that closes the tag opening at `start`, skipping
53
+ * quoted attribute values (a conref can contain '>'), or `start + 1` when the
54
+ * tag is unterminated.
55
+ */
56
+ function openingTagEnd(text, start) {
57
+ let quote;
58
+ for (let i = start + 1; i < text.length; i++) {
59
+ const ch = text[i];
60
+ if (quote) {
61
+ if (ch === quote)
62
+ quote = undefined;
63
+ }
64
+ else if (ch === '"' || ch === "'") {
65
+ quote = ch;
66
+ }
67
+ else if (ch === '>') {
68
+ return i + 1;
69
+ }
70
+ }
71
+ return start + 1;
72
+ }
73
+ /**
74
+ * The range to underline for an element: its opening tag. The parser records
75
+ * the whole element (open through close), which for a container would paint
76
+ * half the screen for one bad attribute.
77
+ */
78
+ function openingTagRange(text, starts, node) {
79
+ const start = offsetOf(starts, text, node.sourceRange.startLine, node.sourceRange.startCol);
80
+ const end = openingTagEnd(text, start);
81
+ const endPos = positionOf(starts, end);
82
+ return {
83
+ startLine: node.sourceRange.startLine,
84
+ startCol: node.sourceRange.startCol,
85
+ endLine: endPos.line,
86
+ endCol: endPos.col,
87
+ };
88
+ }
89
+ // ── well-formedness ──
90
+ /**
91
+ * Replaces the DOCTYPE declaration with spaces instead of deleting it, so the
92
+ * line and column SAX reports still match the editor. A DITA DOCTYPE is often
93
+ * two lines long; deleting it (as preprocessEntities does) would shift every
94
+ * position after it up by one.
95
+ */
96
+ function blankDoctype(xml) {
97
+ const start = xml.indexOf('<!DOCTYPE');
98
+ if (start < 0)
99
+ return xml;
100
+ let i = start + '<!DOCTYPE'.length;
101
+ let quote;
102
+ let subset = false;
103
+ for (; i < xml.length; i++) {
104
+ const ch = xml[i];
105
+ if (quote) {
106
+ if (ch === quote)
107
+ quote = undefined;
108
+ }
109
+ else if (ch === '"' || ch === "'") {
110
+ quote = ch;
111
+ }
112
+ else if (ch === '[') {
113
+ subset = true;
114
+ }
115
+ else if (ch === ']') {
116
+ subset = false;
117
+ }
118
+ else if (ch === '>' && !subset) {
119
+ i++;
120
+ break;
121
+ }
122
+ }
123
+ const blanked = xml.slice(start, i).replace(/[^\n]/g, ' ');
124
+ return xml.slice(0, start) + blanked + xml.slice(i);
125
+ }
126
+ /** CDATA and comments are skipped; what is left is a named entity reference. */
127
+ const CDATA_COMMENT_OR_ENTITY = /(<!\[CDATA\[[\s\S]*?\]\]>|<!--[\s\S]*?-->)|&([A-Za-z_][\w.-]*);/g;
128
+ const XML_BUILTIN = new Set(['amp', 'lt', 'gt', 'quot', 'apos']);
129
+ /**
130
+ * Makes a DITA source parseable without changing where anything is.
131
+ *
132
+ * DITA sources use `&nbsp;` and friends with no DTD loaded to declare them, so
133
+ * a strict XML parser would stop at the first one. preprocessEntities (the
134
+ * renderer's answer) swaps each for its character, which is right for
135
+ * rendering but moves every later column on that line: an underline placed by
136
+ * the parser's position would land on the wrong tag. Here each named
137
+ * reference becomes the same number of spaces instead, so line and column
138
+ * still match the editor. The result is only ever parsed, never shown.
139
+ */
140
+ function parseableSource(xml) {
141
+ return blankDoctype(xml).replace(CDATA_COMMENT_OR_ENTITY, (full, verbatim, name) => verbatim !== undefined || XML_BUILTIN.has(name) ? full : ' '.repeat(full.length));
142
+ }
143
+ /**
144
+ * The first XML error, with the tag it belongs to underlined where one can be
145
+ * found.
146
+ */
147
+ function checkWellFormed(xml) {
148
+ const source = parseableSource(xml);
149
+ const parser = sax.parser(true, { trim: false, normalize: false });
150
+ let failure;
151
+ parser.onerror = (err) => {
152
+ failure = { line: parser.line, column: parser.column, message: err.message };
153
+ // Abort: SAX would otherwise keep parsing whatever follows the error.
154
+ throw err;
155
+ };
156
+ try {
157
+ parser.write(source).close();
158
+ }
159
+ catch {
160
+ // onerror recorded it; the throw above is only the abort mechanism.
161
+ }
162
+ if (!failure)
163
+ return undefined;
164
+ const message = failure.message.split('\n')[0].trim() || failure.message;
165
+ const starts = lineStarts(xml);
166
+ const at = offsetOf(starts, xml, failure.line, Math.max(0, failure.column - 1));
167
+ // The error points just past the offending character (often a tag's '>').
168
+ // Widening to the enclosing tag underlines `</para>` rather than one char
169
+ // after it; at end of file there is no tag, so the position stays as is.
170
+ const tagStart = Math.max(xml.lastIndexOf('<', at), xml.lastIndexOf('<', at - 1));
171
+ const tagEnd = tagStart >= 0 ? openingTagEnd(xml, tagStart) : -1;
172
+ const insideTag = tagStart >= 0 && at < tagEnd;
173
+ // A tag whose '>' is missing swallows the next one, and the parser only
174
+ // notices at that next tag. Blame the tag that was left open.
175
+ const previous = insideTag ? xml.lastIndexOf('<', tagStart - 1) : -1;
176
+ if (previous >= 0 && /[A-Za-z_:]/.test(xml[previous + 1] ?? '') && openingTagEnd(xml, previous) > tagStart) {
177
+ const name = /^<([^\s/>]+)/.exec(xml.slice(previous))?.[1] ?? '';
178
+ const end = previous + xml.slice(previous, tagStart).trimEnd().length;
179
+ const a = positionOf(starts, previous);
180
+ const b = positionOf(starts, end);
181
+ return {
182
+ severity: 'error',
183
+ message: `The <${name}> tag is missing its closing ">"`,
184
+ startLine: a.line,
185
+ startCol: a.col,
186
+ endLine: b.line,
187
+ endCol: b.col,
188
+ };
189
+ }
190
+ const from = insideTag ? positionOf(starts, tagStart) : positionOf(starts, at);
191
+ const to = insideTag ? positionOf(starts, tagEnd) : positionOf(starts, Math.min(xml.length, at + 1));
192
+ return {
193
+ severity: 'error',
194
+ message,
195
+ startLine: from.line,
196
+ startCol: from.col,
197
+ endLine: to.line,
198
+ endCol: to.col,
199
+ };
200
+ }
201
+ // ── document walk ──
202
+ function elementChildren(node) {
203
+ return (node.children ?? []).filter((c) => c.type === 'element');
204
+ }
205
+ function walk(root, visit) {
206
+ visit(root);
207
+ for (const child of elementChildren(root))
208
+ walk(child, visit);
209
+ }
210
+ /** Every id in the document, mapped to the 0-based line it is first used on. */
211
+ function idsWithLines(root) {
212
+ const ids = new Map();
213
+ walk(root, (node) => {
214
+ const id = node.attributes?.id;
215
+ if (id && !ids.has(id))
216
+ ids.set(id, node.sourceRange.startLine);
217
+ });
218
+ return ids;
219
+ }
220
+ /**
221
+ * The first id a `#fragment` names that `has` does not know. A fragment is
222
+ * `topicid` or `topicid/elementid` (DITA's two-part form), so both halves must
223
+ * exist; a single id may be a topic's or an element's.
224
+ */
225
+ export function missingFragmentId(fragment, has) {
226
+ const { topicId, elementId } = splitRefFragment(fragment);
227
+ const wanted = topicId ? [topicId, elementId] : [elementId];
228
+ return wanted.filter((id) => id !== '').find((id) => !has(id));
229
+ }
230
+ /**
231
+ * The key a keyref/conkeyref names: everything before the first '/' (the rest,
232
+ * if any, is an element id inside the target topic).
233
+ */
234
+ function keyNameOf(value) {
235
+ const slash = value.indexOf('/');
236
+ return (slash < 0 ? value : value.slice(0, slash)).trim();
237
+ }
238
+ function report(state, node, message) {
239
+ state.out.push({ severity: 'warning', message, ...openingTagRange(state.text, state.starts, node) });
240
+ }
241
+ /**
242
+ * True when the href names a file this vault can open: no scheme, no absolute
243
+ * path, and not marked external or peer (a peer is in another deliverable, so
244
+ * it need not exist next to this file).
245
+ */
246
+ function isLocalRef(node, value) {
247
+ const scope = node.attributes?.scope;
248
+ if (scope === 'external' || scope === 'peer')
249
+ return false;
250
+ if (URL_SCHEME.test(value) || isAbsolute(value))
251
+ return false;
252
+ return true;
253
+ }
254
+ function checkFileRef(state, node, attribute) {
255
+ const raw = (node.attributes?.[attribute] ?? '').trim();
256
+ if (!raw || raw === '#')
257
+ return;
258
+ const hash = raw.indexOf('#');
259
+ const pathPart = (hash < 0 ? raw : raw.slice(0, hash)).split('?')[0];
260
+ const fragment = hash < 0 ? '' : raw.slice(hash + 1);
261
+ if (!pathPart) {
262
+ // "#id": a target in this file. An id the document does not define is a
263
+ // broken link even though the file it "points at" trivially exists.
264
+ const missing = fragment ? missingFragmentId(decodeHrefPart(fragment), (id) => state.ownIds.has(id)) : undefined;
265
+ if (missing !== undefined)
266
+ report(state, node, `No element with id "${missing}" in this file`);
267
+ return;
268
+ }
269
+ if (!isLocalRef(node, raw))
270
+ return;
271
+ const target = resolve(state.docDir, decodeHrefPart(pathPart));
272
+ // Watched even when it does not exist: creating the file is exactly the
273
+ // fix for "File not found", and must clear the warning without reopening.
274
+ state.deps?.add(target);
275
+ if (!state.fileExists(target)) {
276
+ report(state, node, `File not found: ${pathPart}`);
277
+ return;
278
+ }
279
+ if (!fragment || !state.idsIn || !DITA_FILE.test(target))
280
+ return;
281
+ const ids = state.idsIn(target);
282
+ const missing = ids ? missingFragmentId(decodeHrefPart(fragment), (id) => ids.includes(id)) : undefined;
283
+ if (missing !== undefined)
284
+ report(state, node, `No element with id "${missing}" in ${pathPart}`);
285
+ }
286
+ function checkKeyRef(state, node, attribute) {
287
+ const raw = (node.attributes?.[attribute] ?? '').trim();
288
+ if (!raw)
289
+ return;
290
+ const name = keyNameOf(raw);
291
+ // No key space at all means no map was found near the document, not that
292
+ // every key is missing: a topic opened on its own would otherwise warn on
293
+ // each keyref it has.
294
+ if (state.keys.size === 0)
295
+ return;
296
+ if (name && !state.keys.has(name)) {
297
+ report(state, node, `Key "${name}" is not defined by the maps near this document`);
298
+ }
299
+ }
300
+ /**
301
+ * Duplicate ids, within each topic. DITA only requires an id to be unique in
302
+ * its own topic, so the same id in a nested topic is legal; a topic's own id
303
+ * belongs to the scope it sits in. A map has no topics and is one scope.
304
+ */
305
+ function checkDuplicateIds(state, root) {
306
+ const visit = (node, scope) => {
307
+ const id = node.attributes?.id;
308
+ if (id) {
309
+ const first = scope.get(id);
310
+ // The first use is the definition; every later one is the mistake.
311
+ // Tracked per id rather than by position so two tags on one line clash.
312
+ if (first === undefined)
313
+ scope.set(id, node.sourceRange.startLine);
314
+ else
315
+ report(state, node, `Duplicate id "${id}"; first used on line ${first + 1}`);
316
+ }
317
+ const inner = node.baseType === 'topic/topic' ? new Map() : scope;
318
+ for (const child of elementChildren(node))
319
+ visit(child, inner);
320
+ };
321
+ visit(root, new Map());
322
+ }
323
+ /**
324
+ * What is wrong with this source, sorted by position. An empty array means the
325
+ * document is well formed and every reference it makes can be resolved.
326
+ */
327
+ export function collectDiagnostics(input) {
328
+ const { xml, absPath, keys, keyFiles, fileExists = existsSync, idsIn, collectDependencies } = input;
329
+ // Key maps are dependencies whatever the document turns out to contain: a
330
+ // keyref that resolves today can stop resolving when the map changes, and
331
+ // no other file is read to find that out.
332
+ if (collectDependencies)
333
+ for (const map of keyFiles ?? [])
334
+ collectDependencies.add(map);
335
+ const wellFormed = checkWellFormed(xml);
336
+ if (wellFormed)
337
+ return [wellFormed];
338
+ const isMap = input.isMap ?? /\.ditamap$/i.test(absPath);
339
+ let root;
340
+ try {
341
+ root = (isMap ? parseDitamap : parseDita)(parseableSource(xml)).root;
342
+ }
343
+ catch (e) {
344
+ // Well-formed, but not something the renderer can walk (an empty root,
345
+ // say). Report it at the top rather than pretending the file is clean.
346
+ return [{
347
+ severity: 'error',
348
+ message: e instanceof Error ? e.message : String(e),
349
+ startLine: 0,
350
+ startCol: 0,
351
+ endLine: 0,
352
+ endCol: 0,
353
+ }];
354
+ }
355
+ const state = {
356
+ text: xml,
357
+ starts: lineStarts(xml),
358
+ docDir: dirname(absPath),
359
+ keys: keys ?? new Map(),
360
+ fileExists,
361
+ idsIn,
362
+ deps: collectDependencies,
363
+ ownIds: idsWithLines(root),
364
+ out: [],
365
+ };
366
+ checkDuplicateIds(state, root);
367
+ walk(root, (node) => {
368
+ for (const attribute of KEY_ATTRIBUTES)
369
+ checkKeyRef(state, node, attribute);
370
+ // keyref wins over href when both are present (DITA's indirect-first
371
+ // rule), so a co-located href is a fallback and not worth a warning.
372
+ if (node.attributes?.keyref)
373
+ return;
374
+ for (const attribute of FILE_ATTRIBUTES)
375
+ checkFileRef(state, node, attribute);
376
+ });
377
+ return state.out.sort((a, b) => a.startLine - b.startLine || a.startCol - b.startCol);
378
+ }
@@ -0,0 +1,104 @@
1
+ // conkeyref resolution (P3) -- the DITA "content reference by key".
2
+ //
3
+ // A conkeyref value ("keyname", "keyname/elementid" or
4
+ // "keyname/topicid/elementid") is an indirect content reference: the leading
5
+ // segment is a key, resolved through the map key space to the target topic's
6
+ // href, and the remaining segments address an element inside that topic. It is
7
+ // the key-based analogue of a direct conref -- once the target element is
8
+ // found, the renderer substitutes it exactly as it would a conref target
9
+ // (same-type merge, cross-type replacement, cycle guard).
10
+ //
11
+ // This module is pure: no vscode, no filesystem, no parser. It takes the key
12
+ // space's href definitions plus an injected `loadTopic` (the caller owns file
13
+ // IO, caching and parsing) and returns the resolved target element or
14
+ // undefined. Returning undefined is how the caller learns to fall back: per the
15
+ // DITA 1.3 spec (and DITA-OT's DOTJ046E behaviour), when a conkeyref cannot be
16
+ // resolved -- key not defined, key with no href, target file missing, addressed
17
+ // id not present -- an element that also carries a direct @conref uses that
18
+ // instead, and when there is no conref the element renders its own literal
19
+ // content.
20
+ //
21
+ // Key-space precedence is inherited unchanged from the definitions it is given
22
+ // (first definition wins; a context map fully replaces the ancestor scan) --
23
+ // this function only reads the map it is handed, so switching the key context
24
+ // switches conkeyref targets for free.
25
+ /**
26
+ * Addressing inside the key's target topic: the whole topic when the value has
27
+ * only the key name, otherwise the last path segment (the element id, for both
28
+ * the "key/elemid" and the "key/topicid/elemid" forms -- the intermediate topic
29
+ * id is redundant for a by-id lookup).
30
+ */
31
+ function parseConkeyref(conkeyref) {
32
+ const segments = conkeyref.split('/').filter((s) => s !== '');
33
+ const keyName = segments[0];
34
+ const elementId = segments.length > 1 ? segments[segments.length - 1] : undefined;
35
+ return { keyName, elementId };
36
+ }
37
+ /**
38
+ * The element id a key's own href addresses: the last path segment of its
39
+ * fragment ("file.dita#topicid/elemid" -> "elemid"; "file.dita#topicid" ->
40
+ * "topicid"), or undefined when the href has no fragment. This is what a bare
41
+ * conkeyref="keyname" points at when the key was defined against an element.
42
+ */
43
+ function hrefFragmentTarget(href) {
44
+ const hash = href.indexOf('#');
45
+ if (hash < 0)
46
+ return undefined;
47
+ const segments = href.slice(hash + 1).split('/').filter((s) => s !== '');
48
+ if (segments.length === 0)
49
+ return undefined;
50
+ const last = segments[segments.length - 1];
51
+ try {
52
+ return decodeURIComponent(last);
53
+ }
54
+ catch {
55
+ return last;
56
+ }
57
+ }
58
+ function findElementById(root, targetId) {
59
+ if (root.attributes?.id === targetId)
60
+ return root;
61
+ for (const child of root.children || []) {
62
+ const found = findElementById(child, targetId);
63
+ if (found)
64
+ return found;
65
+ }
66
+ return undefined;
67
+ }
68
+ /**
69
+ * Resolve a conkeyref to its target element.
70
+ *
71
+ * Cycle protection is deliberately NOT done here. A conkeyref that resolves
72
+ * back into an already-rendered chain (A -> B -> A) is caught one level up, by
73
+ * the renderer: resolveConrefForNode only calls this when the value is not
74
+ * already on its conrefChain, mirroring direct-conref cycle protection. Keeping
75
+ * the guard out of this pure function means one owner for the rule and no dead
76
+ * parameter at the call sites (buildRenderContext never threads a chain in).
77
+ *
78
+ * @param conkeyref the raw @conkeyref value.
79
+ * @param defs the key space's href definitions (from KeySpace.defs).
80
+ * @param loadTopic loads and parses the topic at `href` (relative to
81
+ * `baseDir`), returning its root, or undefined when the file
82
+ * is missing or unparseable.
83
+ */
84
+ export function resolveConkeyref(conkeyref, defs, loadTopic) {
85
+ if (!conkeyref)
86
+ return undefined;
87
+ const { keyName, elementId } = parseConkeyref(conkeyref);
88
+ if (!keyName)
89
+ return undefined;
90
+ const def = defs.get(keyName);
91
+ // Key not defined, or defined without a resource target: nothing to pull.
92
+ if (!def || !def.href)
93
+ return undefined;
94
+ const root = loadTopic(def.baseDir, def.href);
95
+ if (!root)
96
+ return undefined;
97
+ // An id in the conkeyref itself wins; otherwise the key's own href may name
98
+ // the element ("file.dita#topicid/elemid"); with neither, the reference
99
+ // targets the key's whole topic.
100
+ const targetId = elementId ?? hrefFragmentTarget(def.href);
101
+ if (!targetId)
102
+ return root;
103
+ return findElementById(root, targetId);
104
+ }