@dita-viewer/core 0.2.3 → 0.2.5

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 (42) hide show
  1. package/dist/bookRender.d.ts +8 -0
  2. package/dist/bookRender.js +2 -0
  3. package/dist/editor/conkeyref.d.ts +12 -2
  4. package/dist/editor/conkeyref.js +32 -0
  5. package/dist/editor/keySpace.d.ts +57 -3
  6. package/dist/editor/keySpace.js +112 -5
  7. package/dist/editor/refResolvers.d.ts +28 -1
  8. package/dist/editor/refResolvers.js +68 -4
  9. package/dist/editor/renderContext.d.ts +28 -0
  10. package/dist/editor/renderContext.js +38 -3
  11. package/dist/editor/topicRender.d.ts +24 -1
  12. package/dist/editor/topicRender.js +20 -6
  13. package/dist/index.d.ts +6 -4
  14. package/dist/index.js +12 -3
  15. package/dist/parser/ditaParser.js +76 -18
  16. package/dist/parser/domTypes.d.ts +9 -1
  17. package/dist/render/baseTypeMap.js +39 -3
  18. package/dist/render/mapTypeMap.d.ts +6 -0
  19. package/dist/render/mapTypeMap.js +11 -5
  20. package/dist/render/refErrorTexts.d.ts +27 -0
  21. package/dist/render/refErrorTexts.js +43 -0
  22. package/dist/render/refTargets.d.ts +12 -0
  23. package/dist/render/refTargets.js +31 -0
  24. package/dist/render/renderer.d.ts +38 -0
  25. package/dist/render/renderer.js +139 -4
  26. package/dist/siteRender.js +2 -0
  27. package/dist-esm/bookRender.js +2 -0
  28. package/dist-esm/editor/conkeyref.js +31 -0
  29. package/dist-esm/editor/keySpace.js +107 -7
  30. package/dist-esm/editor/refResolvers.js +64 -1
  31. package/dist-esm/editor/renderContext.js +41 -6
  32. package/dist-esm/editor/topicRender.js +20 -6
  33. package/dist-esm/index.js +4 -3
  34. package/dist-esm/parser/ditaParser.js +76 -18
  35. package/dist-esm/render/baseTypeMap.js +39 -3
  36. package/dist-esm/render/mapTypeMap.js +11 -5
  37. package/dist-esm/render/refErrorTexts.js +38 -0
  38. package/dist-esm/render/refTargets.js +25 -0
  39. package/dist-esm/render/renderer.js +139 -4
  40. package/dist-esm/siteRender.js +2 -0
  41. package/package.json +1 -1
  42. package/styles/dita-content.css +69 -0
@@ -1,4 +1,5 @@
1
1
  import type { MapEntry, RoleLabelFormatter } from './render/mapTypeMap';
2
+ import type { RefErrorTexts } from './render/refErrorTexts';
2
3
  import type { ProfileFilter } from './profiling';
3
4
  export interface BookXmlRenderInput {
4
5
  /** The map's source text. */
@@ -45,6 +46,13 @@ export interface BookXmlRenderInput {
45
46
  * render without touching the disk.
46
47
  */
47
48
  readFile?: (absPath: string) => string;
49
+ /**
50
+ * Localized wording for the broken-reference hints (see
51
+ * BuildRenderContextInput.refErrorTexts). Book/site rendering always
52
+ * surfaces the hints (refErrors is forced on, like markConrefs); a host
53
+ * that shows another language passes its own strings here.
54
+ */
55
+ refErrorTexts?: Partial<RefErrorTexts>;
48
56
  }
49
57
  export interface BookXmlRenderResult {
50
58
  html: string;
@@ -130,6 +130,8 @@ function renderBookXml(input) {
130
130
  bookMembers: members,
131
131
  docFile: absPath,
132
132
  markConrefs: true,
133
+ refErrors: true,
134
+ refErrorTexts: input.refErrorTexts,
133
135
  });
134
136
  if (result.error !== undefined) {
135
137
  sections.push(`<p class="dita-book-error">${escapeHtml(result.error)}</p>`);
@@ -1,5 +1,5 @@
1
1
  import { DitaNode } from '../parser/domTypes';
2
- import { KeyHrefDef } from './keySpace';
2
+ import { KeyDefLookup } from './keySpace';
3
3
  /**
4
4
  * Resolve a conkeyref to its target element.
5
5
  *
@@ -16,4 +16,14 @@ import { KeyHrefDef } from './keySpace';
16
16
  * `baseDir`), returning its root, or undefined when the file
17
17
  * is missing or unparseable.
18
18
  */
19
- export declare function resolveConkeyref(conkeyref: string, defs: ReadonlyMap<string, KeyHrefDef>, loadTopic: (baseDir: string, href: string) => DitaNode | undefined): DitaNode | undefined;
19
+ export declare function resolveConkeyref(conkeyref: string, defs: KeyDefLookup, loadTopic: (baseDir: string, href: string) => DitaNode | undefined): DitaNode | undefined;
20
+ export type ConkeyrefFailure = 'missingKey' | 'missingFile' | 'parseError' | 'missingId';
21
+ /**
22
+ * Why a conkeyref pulls nothing, in the order resolveConkeyref checks:
23
+ * the key is undefined or has no href; its file is missing or not
24
+ * well-formed (`fileExists` tells the two apart, as loadTopic cannot); the
25
+ * addressed id is absent. Undefined when the reference resolves. Kept next
26
+ * to resolveConkeyref and built on the same steps so the two cannot
27
+ * disagree about what "resolves" means.
28
+ */
29
+ export declare function diagnoseConkeyref(conkeyref: string, defs: KeyDefLookup, loadTopic: (baseDir: string, href: string) => DitaNode | undefined, fileExists: (baseDir: string, href: string) => boolean): ConkeyrefFailure | undefined;
@@ -25,6 +25,8 @@
25
25
  // switches conkeyref targets for free.
26
26
  Object.defineProperty(exports, "__esModule", { value: true });
27
27
  exports.resolveConkeyref = resolveConkeyref;
28
+ exports.diagnoseConkeyref = diagnoseConkeyref;
29
+ const refTargets_1 = require("../render/refTargets");
28
30
  /**
29
31
  * Addressing inside the key's target topic: the whole topic when the value has
30
32
  * only the key name, otherwise the last path segment (the element id, for both
@@ -105,4 +107,34 @@ function resolveConkeyref(conkeyref, defs, loadTopic) {
105
107
  return root;
106
108
  return findElementById(root, targetId);
107
109
  }
110
+ /**
111
+ * Why a conkeyref pulls nothing, in the order resolveConkeyref checks:
112
+ * the key is undefined or has no href; its file is missing or not
113
+ * well-formed (`fileExists` tells the two apart, as loadTopic cannot); the
114
+ * addressed id is absent. Undefined when the reference resolves. Kept next
115
+ * to resolveConkeyref and built on the same steps so the two cannot
116
+ * disagree about what "resolves" means.
117
+ */
118
+ function diagnoseConkeyref(conkeyref, defs, loadTopic, fileExists) {
119
+ const { keyName, elementId } = parseConkeyref(conkeyref);
120
+ if (!keyName)
121
+ return undefined;
122
+ const def = defs.get(keyName);
123
+ if (!def || !def.href)
124
+ return 'missingKey';
125
+ // A keydef may name a non-local or non-DITA resource (scope="external"
126
+ // href="https://...", format="pdf" href="manual.pdf"): keySpace records
127
+ // hrefs without filtering scope/format, so the exclusion lives here, from
128
+ // the same rule makeRefErrorResolver applies to a direct ref. The fragment
129
+ // is stripped first -- it is the target format's own, not a DITA id.
130
+ if ((0, refTargets_1.isNonDitaTarget)(def.href.split('#')[0]))
131
+ return undefined;
132
+ const root = loadTopic(def.baseDir, def.href);
133
+ if (!root)
134
+ return fileExists(def.baseDir, def.href) ? 'parseError' : 'missingFile';
135
+ const targetId = elementId ?? hrefFragmentTarget(def.href);
136
+ if (!targetId)
137
+ return undefined;
138
+ return findElementById(root, targetId) ? undefined : 'missingId';
139
+ }
108
140
  //# sourceMappingURL=conkeyref.js.map
@@ -5,6 +5,21 @@ export declare function splitKeyNames(keys: string): string[];
5
5
  export declare function qualifiedNames(name: string, scopeChain: string[]): string[];
6
6
  /** Like qualifiedNames, for a definition that lives in several scope chains at once. */
7
7
  export declare function qualifiedNamesMulti(name: string, scopeChains: string[][]): string[];
8
+ /** The key of one (scope, name) entry in a scope index; `scopeId` is the chain joined with "/" ("" is the root). */
9
+ export declare function scopeKeyIndexKey(scopeId: string, name: string): string;
10
+ /**
11
+ * Resolves a key written at a place that sits in the given scope chains, against an
12
+ * index of `scopeKeyIndexKey(scope, name)` entries: its own scope first, then each
13
+ * enclosing one, the nearest definition winning (DITA's scope precedence). A name with
14
+ * scope qualifiers (`a.k`, or `x.a.k` for nested scopes) is looked up below the scope
15
+ * the search starts from, so a key defined inside a scope is bare only within it and
16
+ * reachable from outside only by its qualified name. A place in several chains (a
17
+ * `keyscope` listing several names) resolves in the first chain that finds the key.
18
+ *
19
+ * The one rule behind both the completeness checks and the preview, so the two cannot
20
+ * disagree about which definition a reference reaches.
21
+ */
22
+ export declare function resolveKeyInScope<T>(key: string, chains: string[][], index: ReadonlyMap<string, T>): T | undefined;
8
23
  /**
9
24
  * A key's resource target, captured alongside its text value so conkeyref can
10
25
  * resolve `keyname/elementid` to a file. `href` is relative to `baseDir` (the
@@ -18,20 +33,55 @@ export interface KeyHrefDef {
18
33
  href?: string;
19
34
  baseDir: string;
20
35
  }
36
+ /**
37
+ * The keys of a key space by scope, kept beside the flat name map (which answers to
38
+ * bare and qualified names alike and cannot tell scopes apart). Built by the same walk
39
+ * as the flat map, so the two never disagree about what is defined, only about where a
40
+ * lookup may find it.
41
+ */
42
+ export interface KeyScopeIndex {
43
+ /** `scopeKeyIndexKey(scope, name)` -> the key's text value. First definition wins. */
44
+ values: Map<string, string>;
45
+ /** `scopeKeyIndexKey(scope, name)` -> the key's resource target, from the same definition as the value. */
46
+ defs: Map<string, KeyHrefDef>;
47
+ /**
48
+ * A topic's absolute path (see getTopicScopeChains) -> the scope chains each topicref that
49
+ * publishes it sits in, one entry per publishing scope, in document order, no repeats.
50
+ * A topic nothing publishes has no entry.
51
+ */
52
+ topicScopes: Map<string, string[][][]>;
53
+ }
54
+ export declare function createKeyScopeIndex(): KeyScopeIndex;
55
+ /** The scope chains of the topicrefs that publish `absPath`, or undefined when no topicref does. */
56
+ export declare function getTopicScopeChains(scopes: KeyScopeIndex, absPath: string): string[][][] | undefined;
57
+ /**
58
+ * The scope chains a topic is read in when nothing says where it sits: the first
59
+ * topicref in the map that publishes it, or the root scope when none does (a topic
60
+ * no map publishes belongs to no keyscope).
61
+ */
62
+ export declare function defaultTopicScopeChains(scopes: KeyScopeIndex, absPath: string): string[][];
63
+ /** What a definition lookup needs; a Map satisfies it, and so does a scope-bound view of one. */
64
+ export interface KeyDefLookup {
65
+ get(name: string): KeyHrefDef | undefined;
66
+ }
21
67
  /**
22
68
  * Parses one ditamap, expands the ditamaps it references, and adds every
23
69
  * key it defines to `into` (first definition wins, in document order).
24
70
  * When `hrefs` is supplied, each newly defined key also records its resource
25
71
  * target there (same first-definition-wins gate as the value), keyed by the
26
- * individual name. Throws if the map itself cannot be read or parsed; the
27
- * caller decides whether that is fatal.
72
+ * individual name. When `scopes` is supplied, every definition is also recorded
73
+ * under the scope it sits in, and every topic a topicref publishes under the scope
74
+ * of that topicref (same first-definition-wins gate). Throws if the map itself
75
+ * cannot be read or parsed; the caller decides whether that is fatal.
28
76
  */
29
- export declare function collectMapKeys(mapPath: string, into: Map<string, string>, read: FileReader, hrefs?: Map<string, KeyHrefDef>): void;
77
+ export declare function collectMapKeys(mapPath: string, into: Map<string, string>, read: FileReader, hrefs?: Map<string, KeyHrefDef>, scopes?: KeyScopeIndex): void;
30
78
  export type KeyContextStatus = 'none' | 'active' | 'missing';
31
79
  export interface KeySpace {
32
80
  keys: Map<string, string>;
33
81
  /** Each key's resource target (href + defining map dir), for conkeyref. */
34
82
  defs: Map<string, KeyHrefDef>;
83
+ /** The same definitions filed by key scope, and the scopes that publish each topic. */
84
+ scopes: KeyScopeIndex;
35
85
  /** Every file the key values were derived from (for cache stamping). */
36
86
  files: string[];
37
87
  /** 'none': no context set. 'active': keys come from the context map alone.
@@ -70,3 +120,7 @@ export declare function registerKeyDefs(keys: Map<string, string>, defs: Readonl
70
120
  /** The href defs paired with a given values map, or undefined if it was not
71
121
  * produced by buildKeySpace (e.g. a hand-built map in a test). */
72
122
  export declare function getKeyDefs(keys: Map<string, string>): ReadonlyMap<string, KeyHrefDef> | undefined;
123
+ export declare function registerKeyScopes(keys: Map<string, string>, scopes: KeyScopeIndex): void;
124
+ /** The scope index paired with a given values map, or undefined if it was not
125
+ * produced by buildKeySpace (e.g. a hand-built map in a test). */
126
+ export declare function getKeyScopes(keys: Map<string, string>): KeyScopeIndex | undefined;
@@ -9,14 +9,22 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.splitKeyNames = splitKeyNames;
10
10
  exports.qualifiedNames = qualifiedNames;
11
11
  exports.qualifiedNamesMulti = qualifiedNamesMulti;
12
+ exports.scopeKeyIndexKey = scopeKeyIndexKey;
13
+ exports.resolveKeyInScope = resolveKeyInScope;
14
+ exports.createKeyScopeIndex = createKeyScopeIndex;
15
+ exports.getTopicScopeChains = getTopicScopeChains;
16
+ exports.defaultTopicScopeChains = defaultTopicScopeChains;
12
17
  exports.collectMapKeys = collectMapKeys;
13
18
  exports.isKeyContextAvailable = isKeyContextAvailable;
14
19
  exports.keySourceMaps = keySourceMaps;
15
20
  exports.buildKeySpace = buildKeySpace;
16
21
  exports.registerKeyDefs = registerKeyDefs;
17
22
  exports.getKeyDefs = getKeyDefs;
23
+ exports.registerKeyScopes = registerKeyScopes;
24
+ exports.getKeyScopes = getKeyScopes;
18
25
  const path_1 = require("path");
19
26
  const ditaParser_1 = require("../parser/ditaParser");
27
+ const mapTypeMap_1 = require("../render/mapTypeMap");
20
28
  const refResolvers_1 = require("./refResolvers");
21
29
  const sourceText_1 = require("./sourceText");
22
30
  function extractTextFromNode(node) {
@@ -77,15 +85,83 @@ function qualifiedNamesMulti(name, scopeChains) {
77
85
  out.add(q);
78
86
  return [...out];
79
87
  }
88
+ /** The key of one (scope, name) entry in a scope index; `scopeId` is the chain joined with "/" ("" is the root). */
89
+ function scopeKeyIndexKey(scopeId, name) {
90
+ return `${scopeId}\u0000${name}`;
91
+ }
92
+ /**
93
+ * Resolves a key written at a place that sits in the given scope chains, against an
94
+ * index of `scopeKeyIndexKey(scope, name)` entries: its own scope first, then each
95
+ * enclosing one, the nearest definition winning (DITA's scope precedence). A name with
96
+ * scope qualifiers (`a.k`, or `x.a.k` for nested scopes) is looked up below the scope
97
+ * the search starts from, so a key defined inside a scope is bare only within it and
98
+ * reachable from outside only by its qualified name. A place in several chains (a
99
+ * `keyscope` listing several names) resolves in the first chain that finds the key.
100
+ *
101
+ * The one rule behind both the completeness checks and the preview, so the two cannot
102
+ * disagree about which definition a reference reaches.
103
+ */
104
+ function resolveKeyInScope(key, chains, index) {
105
+ const parts = key.split('.');
106
+ for (const chain of chains) {
107
+ for (let depth = chain.length; depth >= 0; depth--) {
108
+ const prefix = chain.slice(0, depth);
109
+ for (let j = 0; j < parts.length; j++) {
110
+ const scope = prefix.concat(parts.slice(0, j)).join('/');
111
+ const def = index.get(scopeKeyIndexKey(scope, parts.slice(j).join('.')));
112
+ if (def !== undefined)
113
+ return def;
114
+ }
115
+ }
116
+ }
117
+ return undefined;
118
+ }
119
+ function createKeyScopeIndex() {
120
+ return { values: new Map(), defs: new Map(), topicScopes: new Map() };
121
+ }
122
+ function topicScopeKey(absPath) {
123
+ const p = (0, path_1.resolve)(absPath);
124
+ return process.platform === 'win32' ? p.toLowerCase() : p;
125
+ }
126
+ /** The scope chains of the topicrefs that publish `absPath`, or undefined when no topicref does. */
127
+ function getTopicScopeChains(scopes, absPath) {
128
+ return scopes.topicScopes.get(topicScopeKey(absPath));
129
+ }
130
+ function noteTopicScope(scopes, absPath, chains) {
131
+ const k = topicScopeKey(absPath);
132
+ const known = scopes.topicScopes.get(k);
133
+ const sig = JSON.stringify(chains);
134
+ if (!known)
135
+ scopes.topicScopes.set(k, [chains]);
136
+ else if (!known.some((c) => JSON.stringify(c) === sig))
137
+ known.push(chains);
138
+ }
139
+ /**
140
+ * The scope chains a topic is read in when nothing says where it sits: the first
141
+ * topicref in the map that publishes it, or the root scope when none does (a topic
142
+ * no map publishes belongs to no keyscope).
143
+ */
144
+ function defaultTopicScopeChains(scopes, absPath) {
145
+ return getTopicScopeChains(scopes, absPath)?.[0] ?? [[]];
146
+ }
147
+ /** A topicref href that names a file of this project: no scheme, not marked external. */
148
+ function localTopicPath(href, scope) {
149
+ if (!href || scope === 'external' || /^[a-z][a-z0-9+.-]*:/i.test(href))
150
+ return undefined;
151
+ const path = href.split('#')[0];
152
+ return path || undefined;
153
+ }
80
154
  /**
81
155
  * Parses one ditamap, expands the ditamaps it references, and adds every
82
156
  * key it defines to `into` (first definition wins, in document order).
83
157
  * When `hrefs` is supplied, each newly defined key also records its resource
84
158
  * target there (same first-definition-wins gate as the value), keyed by the
85
- * individual name. Throws if the map itself cannot be read or parsed; the
86
- * caller decides whether that is fatal.
159
+ * individual name. When `scopes` is supplied, every definition is also recorded
160
+ * under the scope it sits in, and every topic a topicref publishes under the scope
161
+ * of that topicref (same first-definition-wins gate). Throws if the map itself
162
+ * cannot be read or parsed; the caller decides whether that is fatal.
87
163
  */
88
- function collectMapKeys(mapPath, into, read, hrefs) {
164
+ function collectMapKeys(mapPath, into, read, hrefs, scopes) {
89
165
  const content = read(mapPath, 'utf-8');
90
166
  const doc = (0, ditaParser_1.parseDitamap)((0, ditaParser_1.preprocessEntities)(content));
91
167
  const mapRoot = doc.root;
@@ -121,8 +197,26 @@ function collectMapKeys(mapPath, into, read, hrefs) {
121
197
  hrefs?.set(name, { href: node.attributes?.href, baseDir: mapDir });
122
198
  }
123
199
  }
200
+ if (scopes) {
201
+ // The same definition, filed by scope: a lookup that knows where it is
202
+ // asking from finds the nearest one instead of the first in the file.
203
+ for (const chain of chains) {
204
+ const at = scopeKeyIndexKey(chain.join('/'), keyName);
205
+ if (!scopes.values.has(at)) {
206
+ scopes.values.set(at, value || keyName);
207
+ scopes.defs.set(at, { href: node.attributes?.href, baseDir: mapDir });
208
+ }
209
+ }
210
+ }
124
211
  }
125
212
  }
213
+ // A topicref publishes its topic in the scopes it sits in. A keydef does not (it
214
+ // is resource-only), and a submap reference was expanded into its children above.
215
+ if (scopes && baseType === 'map/topicref' && !(0, mapTypeMap_1.isDitamapRef)(node)) {
216
+ const path = localTopicPath(node.attributes?.href, node.attributes?.scope);
217
+ if (path)
218
+ noteTopicScope(scopes, (0, path_1.resolve)(mapDir, (0, refResolvers_1.decodeHrefPart)(path)), chains);
219
+ }
126
220
  for (const child of node.children || [])
127
221
  walk(child, chains);
128
222
  }
@@ -174,9 +268,10 @@ function buildKeySpace(contextMap, ancestorMaps, read, onError = () => undefined
174
268
  }
175
269
  const keys = new Map();
176
270
  const defs = new Map();
271
+ const scopes = createKeyScopeIndex();
177
272
  for (const mf of sources) {
178
273
  try {
179
- collectMapKeys(mf, keys, recordingRead, defs);
274
+ collectMapKeys(mf, keys, recordingRead, defs, scopes);
180
275
  }
181
276
  catch (e) {
182
277
  onError(mf, e);
@@ -190,7 +285,8 @@ function buildKeySpace(contextMap, ancestorMaps, read, onError = () => undefined
190
285
  // tests drive -- gets it, and so renderContext.ts can read it without
191
286
  // importing the vscode-dependent keyMap.ts.
192
287
  registerKeyDefs(keys, defs);
193
- return { keys, defs, files: [...new Set(files)], status };
288
+ registerKeyScopes(keys, scopes);
289
+ return { keys, defs, scopes, files: [...new Set(files)], status };
194
290
  }
195
291
  // ── values map -> href defs, by instance identity ──
196
292
  //
@@ -210,4 +306,15 @@ function registerKeyDefs(keys, defs) {
210
306
  function getKeyDefs(keys) {
211
307
  return defsByKeyMap.get(keys);
212
308
  }
309
+ // The scope index travels with the values map the same way, for the same reason: the
310
+ // render paths hand around `keyMap` and nothing else.
311
+ const scopesByKeyMap = new WeakMap();
312
+ function registerKeyScopes(keys, scopes) {
313
+ scopesByKeyMap.set(keys, scopes);
314
+ }
315
+ /** The scope index paired with a given values map, or undefined if it was not
316
+ * produced by buildKeySpace (e.g. a hand-built map in a test). */
317
+ function getKeyScopes(keys) {
318
+ return scopesByKeyMap.get(keys);
319
+ }
213
320
  //# sourceMappingURL=keySpace.js.map
@@ -1,4 +1,6 @@
1
1
  import { DitaNode } from '../parser/domTypes';
2
+ import { RefErrorTexts } from '../render/refErrorTexts';
3
+ import { URL_SCHEME_RE } from '../render/refTargets';
2
4
  export declare const IMAGE_DIMENSIONS_CACHE_MAX = 1000;
3
5
  export declare function clearImageDimensionsCache(): void;
4
6
  export declare function readImageDimensions(filePath: string): {
@@ -22,6 +24,31 @@ export declare function makeFileCache(docDir: string): {
22
24
  };
23
25
  export declare function makeConrefResolver(docDir: string, ownRoot?: DitaNode, sharedCache?: ReturnType<typeof makeFileCache>): (conref: string, from?: DitaNode) => DitaNode | undefined;
24
26
  export declare function makeConrefRangeResolver(docDir: string, ownRoot?: DitaNode, sharedCache?: ReturnType<typeof makeFileCache>): (conref: string, conrefend: string) => DitaNode[] | undefined;
27
+ /**
28
+ * Default broken-reference diagnosis for RenderContext.refError: the
29
+ * three-state reason a local reference can fail with, in the order the
30
+ * resolver chain itself checks --
31
+ * missing file -- nothing at the referenced path in the closure;
32
+ * parse error -- the file is there but is not well-formed XML (the
33
+ * common review case: an author broke a DIFFERENT file);
34
+ * missing id -- the file parses but #topicId/elementId names no id.
35
+ * Returns undefined for a reference that resolves, and for ones it will
36
+ * not diagnose at all: external URLs, absolute paths, and hrefs that are
37
+ * neither a fragment nor a DITA-shaped file path (a bare id is not a
38
+ * filename to probe). Same-document fragments (#id, #./topicId/id) are
39
+ * checked against ownRoot without touching the filesystem.
40
+ *
41
+ * Rides the shared file cache so a target already loaded for conref/title
42
+ * resolution is not parsed twice, and every probed path -- missing ones
43
+ * included -- lands in touchedFiles() for the caller's dependency set:
44
+ * creating the missing target is exactly the change that must invalidate
45
+ * a cached render. The cache memoizes missing and unparsable alike as
46
+ * undefined, so existsSync is what tells the two apart.
47
+ *
48
+ * The renderer only presents the returned reason (see refErrorTexts.ts);
49
+ * a host with its own diagnostic rules supplies its own callback instead.
50
+ */
51
+ export declare function makeRefErrorResolver(docDir: string, ownRoot?: DitaNode, sharedCache?: ReturnType<typeof makeFileCache>, texts?: RefErrorTexts): (ref: string) => string | undefined;
25
52
  export declare function makeFileTitleResolver(docDir: string, sharedCache?: ReturnType<typeof makeFileCache>, resolveKey?: (key: string) => string | undefined): (href: string) => string | undefined;
26
53
  export declare const DEFAULT_NOTE_LABELS: Record<string, string>;
27
54
  export declare const ZH_NOTE_LABELS: Record<string, string>;
@@ -32,7 +59,7 @@ export declare function detectNoteLabels(root: DitaNode, uiLanguage?: string): R
32
59
  * its own (much smaller) two-language set. */
33
60
  export declare function detectIndexLabel(root: DitaNode, uiLanguage?: string): string;
34
61
  export type FileReader = (path: string, encoding: 'utf-8') => string;
35
- export declare const URL_SCHEME_RE: RegExp;
62
+ export { URL_SCHEME_RE };
36
63
  /**
37
64
  * Builds the render context's isInCurrentBook resolver: given a cross-file
38
65
  * xref's raw href, return the absolute path of the target IF it is one of
@@ -6,6 +6,7 @@ exports.readImageDimensions = readImageDimensions;
6
6
  exports.makeFileCache = makeFileCache;
7
7
  exports.makeConrefResolver = makeConrefResolver;
8
8
  exports.makeConrefRangeResolver = makeConrefRangeResolver;
9
+ exports.makeRefErrorResolver = makeRefErrorResolver;
9
10
  exports.makeFileTitleResolver = makeFileTitleResolver;
10
11
  exports.detectNoteLabels = detectNoteLabels;
11
12
  exports.detectIndexLabel = detectIndexLabel;
@@ -27,6 +28,9 @@ const fs_1 = require("fs");
27
28
  const path_1 = require("path");
28
29
  const ditaParser_1 = require("../parser/ditaParser");
29
30
  const mapTypeMap_1 = require("../render/mapTypeMap");
31
+ const refErrorTexts_1 = require("../render/refErrorTexts");
32
+ const refTargets_1 = require("../render/refTargets");
33
+ Object.defineProperty(exports, "URL_SCHEME_RE", { enumerable: true, get: function () { return refTargets_1.URL_SCHEME_RE; } });
30
34
  const sourceText_1 = require("./sourceText");
31
35
  // ── Image dimensions (for reserving layout space before the image loads) ──
32
36
  //
@@ -438,13 +442,74 @@ function makeConrefRangeResolver(docDir, ownRoot, sharedCache) {
438
442
  return run;
439
443
  };
440
444
  }
445
+ /**
446
+ * Default broken-reference diagnosis for RenderContext.refError: the
447
+ * three-state reason a local reference can fail with, in the order the
448
+ * resolver chain itself checks --
449
+ * missing file -- nothing at the referenced path in the closure;
450
+ * parse error -- the file is there but is not well-formed XML (the
451
+ * common review case: an author broke a DIFFERENT file);
452
+ * missing id -- the file parses but #topicId/elementId names no id.
453
+ * Returns undefined for a reference that resolves, and for ones it will
454
+ * not diagnose at all: external URLs, absolute paths, and hrefs that are
455
+ * neither a fragment nor a DITA-shaped file path (a bare id is not a
456
+ * filename to probe). Same-document fragments (#id, #./topicId/id) are
457
+ * checked against ownRoot without touching the filesystem.
458
+ *
459
+ * Rides the shared file cache so a target already loaded for conref/title
460
+ * resolution is not parsed twice, and every probed path -- missing ones
461
+ * included -- lands in touchedFiles() for the caller's dependency set:
462
+ * creating the missing target is exactly the change that must invalidate
463
+ * a cached render. The cache memoizes missing and unparsable alike as
464
+ * undefined, so existsSync is what tells the two apart.
465
+ *
466
+ * The renderer only presents the returned reason (see refErrorTexts.ts);
467
+ * a host with its own diagnostic rules supplies its own callback instead.
468
+ */
469
+ function makeRefErrorResolver(docDir, ownRoot, sharedCache, texts = refErrorTexts_1.DEFAULT_REF_ERROR_TEXTS) {
470
+ const cache = sharedCache ?? makeFileCache(docDir);
471
+ return (ref) => {
472
+ if (!ref)
473
+ return undefined;
474
+ const hashIdx = ref.indexOf('#');
475
+ const filePath = hashIdx >= 0 ? ref.substring(0, hashIdx) : ref;
476
+ // "#./topicId/elementId" shorthand: strip the same-document marker
477
+ // before splitting, the same rule makeConrefRangeResolver applies.
478
+ const idPart = hashIdx >= 0 ? ref.substring(hashIdx + 1).replace(/^\.\/+/, '') : '';
479
+ const parts = idPart.split('/');
480
+ const elementId = parts.length > 1 ? parts[1] : parts[0];
481
+ // URL, absolute path, or a web document (guide.html#sec): not a local
482
+ // DITA target, so never probed -- see isNonDitaTarget.
483
+ if ((0, refTargets_1.isNonDitaTarget)(filePath))
484
+ return undefined;
485
+ if (!filePath) {
486
+ // Same-document fragment: the id must exist in the document itself.
487
+ if (!idPart || !elementId || !ownRoot)
488
+ return undefined;
489
+ return cache.findElementById(ownRoot, elementId) ? undefined : texts.missingId;
490
+ }
491
+ // No fragment: only a DITA-shaped file path is a file-level reference
492
+ // worth probing (a bare word is not a filename). With a fragment the
493
+ // file part is always checked, whatever its extension -- conref/xref
494
+ // targets are .dita/.xml in practice but the resolver loads any path.
495
+ if (hashIdx < 0 && !/\.(dita|xml|ditamap)$/i.test(filePath))
496
+ return undefined;
497
+ const abs = (0, path_1.resolve)(docDir, decodeHrefPart(filePath));
498
+ const root = cache.loadAbsPath(abs);
499
+ if (!root)
500
+ return (0, fs_1.existsSync)(abs) ? texts.parseError : texts.missingFile;
501
+ if (!elementId)
502
+ return undefined;
503
+ return cache.findElementById(root, elementId) ? undefined : texts.missingId;
504
+ };
505
+ }
441
506
  function makeFileTitleResolver(docDir, sharedCache, resolveKey) {
442
507
  const cache = sharedCache ?? makeFileCache(docDir);
443
508
  return (href) => {
444
509
  // Only local relative references can be resolved from disk — never probe
445
510
  // the filesystem for external URLs or absolute paths (on Windows an
446
511
  // https:// href would otherwise resolve to a junk docDir\https:\ path).
447
- if (!href || exports.URL_SCHEME_RE.test(href) || (0, path_1.isAbsolute)(href))
512
+ if (!href || refTargets_1.URL_SCHEME_RE.test(href) || (0, path_1.isAbsolute)(href))
448
513
  return undefined;
449
514
  const hashIdx = href.indexOf('#');
450
515
  if (hashIdx < 0) {
@@ -524,7 +589,6 @@ function detectIndexLabel(root, uiLanguage) {
524
589
  const lang = root.attributes?.['xml:lang'] || uiLanguage || '';
525
590
  return lang.startsWith('zh') ? '\u7d22\u5f15' : 'Index';
526
591
  }
527
- exports.URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
528
592
  /**
529
593
  * Builds the render context's isInCurrentBook resolver: given a cross-file
530
594
  * xref's raw href, return the absolute path of the target IF it is one of
@@ -537,7 +601,7 @@ exports.URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
537
601
  */
538
602
  function makeIsInCurrentBook(docDir, bookMembers) {
539
603
  return (href) => {
540
- if (!href || exports.URL_SCHEME_RE.test(href) || (0, path_1.isAbsolute)(href))
604
+ if (!href || refTargets_1.URL_SCHEME_RE.test(href) || (0, path_1.isAbsolute)(href))
541
605
  return undefined;
542
606
  const pathPart = href.split('#')[0];
543
607
  if (!pathPart)
@@ -567,7 +631,7 @@ function isLocalHref(href, scope) {
567
631
  return false;
568
632
  if (scope === 'external' || scope === 'peer')
569
633
  return false;
570
- if (exports.URL_SCHEME_RE.test(href))
634
+ if (refTargets_1.URL_SCHEME_RE.test(href))
571
635
  return false;
572
636
  if ((0, path_1.isAbsolute)(href))
573
637
  return false;
@@ -1,5 +1,6 @@
1
1
  import { DitaNode } from '../parser/domTypes';
2
2
  import { RenderContext } from '../render/renderer';
3
+ import { RefErrorTexts } from '../render/refErrorTexts';
3
4
  import { KeyHrefDef } from './keySpace';
4
5
  export interface BuildRenderContextInput {
5
6
  /** Directory hrefs in this document resolve against (== RenderContext.documentDir). */
@@ -18,6 +19,16 @@ export interface BuildRenderContextInput {
18
19
  * explicitly only to drive conkeyref with a hand-built keyMap (tests).
19
20
  */
20
21
  keyDefs?: ReadonlyMap<string, KeyHrefDef>;
22
+ /**
23
+ * The key scope chains the document is read in (a keyscope listing several names
24
+ * gives several chains; `[[]]` is the root scope). A keyref / conkeyref resolves
25
+ * in the nearest scope that defines the key, as DITA says, instead of by name alone.
26
+ * Book / site rendering passes the scope of the topicref that put the topic on the
27
+ * page. Left undefined, the scope comes from `docFile` (the first topicref that
28
+ * publishes it); with neither, or with a `keyMap` that carries no scope index (one
29
+ * built by hand), keys resolve by name only, as they always did.
30
+ */
31
+ keyScope?: string[][];
21
32
  /**
22
33
  * Absolute path of the document being rendered. Together with `markConrefs`
23
34
  * it lets same-file conrefs be marked too (their target file is this one).
@@ -48,6 +59,23 @@ export interface BuildRenderContextInput {
48
59
  clickableExternalXrefs?: boolean;
49
60
  /** Book / site only: sink that records every file the render read. */
50
61
  collectDependencies?: Set<string>;
62
+ /**
63
+ * Opt-in: wire RenderContext.refError with the default three-state
64
+ * diagnosis (makeRefErrorResolver) so a conref that pulls nothing renders
65
+ * as a placeholder chip and an empty xref with a broken target as a
66
+ * .xref-broken marker, instead of silently empty/link-shaped output.
67
+ * Preview and diff paths set this; "Export as HTML" does not -- a shipped
68
+ * document has no editing context for the hints, the same rule
69
+ * suppressIndexterm and markConrefs follow.
70
+ */
71
+ refErrors?: boolean;
72
+ /**
73
+ * Localized wording for the refError hints, merged over the English
74
+ * defaults (DEFAULT_REF_ERROR_TEXTS). The host fills these from its own
75
+ * string catalog -- the VS Code extension via vscode.l10n.t -- so the
76
+ * factory itself stays free of locale logic, like noteLabels.
77
+ */
78
+ refErrorTexts?: Partial<RefErrorTexts>;
51
79
  }
52
80
  export interface BuiltRenderContext {
53
81
  ctx: RenderContext;
@@ -23,8 +23,10 @@
23
23
  // - suppressIndexterm: only the export path sets it.
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
25
  exports.buildRenderContext = buildRenderContext;
26
+ const fs_1 = require("fs");
26
27
  const path_1 = require("path");
27
28
  const refResolvers_1 = require("./refResolvers");
29
+ const refErrorTexts_1 = require("../render/refErrorTexts");
28
30
  const keySpace_1 = require("./keySpace");
29
31
  const conkeyref_1 = require("./conkeyref");
30
32
  function buildRenderContext(input) {
@@ -36,13 +38,22 @@ function buildRenderContext(input) {
36
38
  const conrefResolver = (0, refResolvers_1.makeConrefResolver)(docDir, ownRoot, fileCache);
37
39
  const conrefRangeResolver = (0, refResolvers_1.makeConrefRangeResolver)(docDir, ownRoot, fileCache);
38
40
  const fileTitleResolver = (0, refResolvers_1.makeFileTitleResolver)(docDir, fileCache);
41
+ // Which scope a reference is read in, and the lookups bound to it. The preview's key
42
+ // space also keeps a flat name map (first definition wins, bare names visible
43
+ // everywhere); a lookup that knows where it sits reads the scope index instead, so it
44
+ // finds the nearest definition the way the completeness checks do.
45
+ const scopeIndex = (0, keySpace_1.getKeyScopes)(keyMap);
46
+ const keyChains = scopeIndex
47
+ ? (input.keyScope ?? (input.docFile ? (0, keySpace_1.defaultTopicScopeChains)(scopeIndex, input.docFile) : undefined))
48
+ : undefined;
49
+ const lookupKey = (key) => scopeIndex && keyChains ? (0, keySpace_1.resolveKeyInScope)(key, keyChains, scopeIndex.values) : keyMap.get(key);
39
50
  const ctx = {
40
51
  headingLevel,
41
52
  asWebviewUri,
42
53
  documentDir: docDir,
43
54
  // Local id match first, then cross-file ("file.dita#topicId" or "file.dita").
44
55
  resolveTitle: (id) => titleMap.get(id) || fileTitleResolver(id),
45
- resolveKey: (key) => keyMap.get(key),
56
+ resolveKey: lookupKey,
46
57
  resolveConref: (conref) => conrefResolver(conref),
47
58
  resolveConrefRange: (conref, conrefend) => conrefRangeResolver(conref, conrefend),
48
59
  noteLabels: (0, refResolvers_1.detectNoteLabels)(ownRoot, uiLanguage),
@@ -74,13 +85,27 @@ function buildRenderContext(input) {
74
85
  ctx.isInCurrentBook = (0, refResolvers_1.makeIsInCurrentBook)(docDir, input.bookMembers);
75
86
  if (input.clickableExternalXrefs)
76
87
  ctx.clickableExternalXrefs = true;
88
+ if (input.refErrors) {
89
+ const texts = { ...refErrorTexts_1.DEFAULT_REF_ERROR_TEXTS, ...input.refErrorTexts };
90
+ ctx.refErrorTexts = texts;
91
+ // Same shared cache as the conref/title resolvers: a target probed here
92
+ // is usually one they already loaded, and every probe (missing files
93
+ // included) joins touchedFiles for the caller's dependency set.
94
+ ctx.refError = (0, refResolvers_1.makeRefErrorResolver)(docDir, ownRoot, fileCache, texts);
95
+ }
77
96
  // conkeyref rides on the same file cache: a key's href resolves against the
78
97
  // map that defined it (baseDir), not the topic being rendered, so it needs
79
98
  // the absolute-path loader rather than the docDir-relative conref resolver.
80
99
  // Discovered from keyMap by identity unless the caller passed defs directly.
81
100
  let lastLoaded;
82
- const keyDefs = input.keyDefs ?? (0, keySpace_1.getKeyDefs)(keyMap);
83
- if (keyDefs && keyDefs.size > 0) {
101
+ const flatDefs = input.keyDefs ?? (0, keySpace_1.getKeyDefs)(keyMap);
102
+ // Definitions come from the same scope as the text, so a conkeyref or an xref keyref
103
+ // cannot reach one scope's file while the text shows another's. Defs handed in
104
+ // explicitly (tests) are used as given.
105
+ const keyDefs = flatDefs && !input.keyDefs && scopeIndex && keyChains
106
+ ? { get: (name) => (0, keySpace_1.resolveKeyInScope)(name, keyChains, scopeIndex.defs) }
107
+ : flatDefs;
108
+ if (keyDefs && flatDefs && flatDefs.size > 0) {
84
109
  // A keyref on a link-shaped element (topic/xref) resolves to the key's
85
110
  // resource target as its effective href. The keydef's href is relative
86
111
  // to the map that defined it, but every href the renderer consumes
@@ -122,6 +147,16 @@ function buildRenderContext(input) {
122
147
  fileCache.noteOrigin(el, lastLoaded);
123
148
  return el;
124
149
  };
150
+ // Only with a key space (this block): a topic previewed with no map has
151
+ // no keys at all, and "key is not defined" there would flag every
152
+ // conkeyref for a reason the author cannot act on.
153
+ if (input.refErrors) {
154
+ const texts = { ...refErrorTexts_1.DEFAULT_REF_ERROR_TEXTS, ...input.refErrorTexts };
155
+ ctx.conkeyrefError = (conkeyref) => {
156
+ const failure = (0, conkeyref_1.diagnoseConkeyref)(conkeyref, keyDefs, loadTopic, (baseDir, href) => (0, fs_1.existsSync)((0, path_1.resolve)(baseDir, (0, refResolvers_1.decodeHrefPart)(href.split('#')[0]))));
157
+ return failure === undefined ? undefined : texts[failure];
158
+ };
159
+ }
125
160
  }
126
161
  // One hop further along a reference chain, resolved relative to the file
127
162
  // that holds `from`. conkeyref wins over conref when it resolves, the same