@podlite/publisher 0.0.52 → 0.0.54

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 (52) hide show
  1. package/CHANGELOG.podlite +26 -0
  2. package/esm/catalogue.d.ts +17 -0
  3. package/esm/catalogue.js +156 -0
  4. package/esm/catalogue.js.map +1 -0
  5. package/esm/images-plugin.js +3 -1
  6. package/esm/images-plugin.js.map +1 -1
  7. package/esm/include-resolve-plugin.d.ts +16 -1
  8. package/esm/include-resolve-plugin.js +235 -104
  9. package/esm/include-resolve-plugin.js.map +1 -1
  10. package/esm/links-plugin.d.ts +9 -1
  11. package/esm/links-plugin.js +144 -58
  12. package/esm/links-plugin.js.map +1 -1
  13. package/esm/node-utils.d.ts +3 -2
  14. package/esm/node-utils.js +60 -19
  15. package/esm/node-utils.js.map +1 -1
  16. package/esm/react-plugin.js +9 -1
  17. package/esm/react-plugin.js.map +1 -1
  18. package/esm/reading.d.ts +5 -0
  19. package/esm/reading.js +34 -0
  20. package/esm/reading.js.map +1 -0
  21. package/esm/record.d.ts +2 -2
  22. package/esm/record.js +1 -1
  23. package/esm/record.js.map +1 -1
  24. package/esm/site-data-plugin.d.ts +1 -0
  25. package/esm/site-data-plugin.js +12 -1
  26. package/esm/site-data-plugin.js.map +1 -1
  27. package/esm/source.d.ts +6 -0
  28. package/esm/source.js +27 -0
  29. package/esm/source.js.map +1 -1
  30. package/esm/version.d.ts +1 -1
  31. package/esm/version.js +1 -1
  32. package/lib/catalogue.d.ts +17 -0
  33. package/lib/catalogue.js +197 -0
  34. package/lib/images-plugin.js +3 -1
  35. package/lib/include-resolve-plugin.d.ts +16 -1
  36. package/lib/include-resolve-plugin.js +270 -103
  37. package/lib/links-plugin.d.ts +9 -1
  38. package/lib/links-plugin.js +177 -56
  39. package/lib/node-utils.d.ts +3 -2
  40. package/lib/node-utils.js +73 -31
  41. package/lib/react-plugin.js +9 -1
  42. package/lib/reading.d.ts +5 -0
  43. package/lib/reading.js +38 -0
  44. package/lib/record.d.ts +2 -2
  45. package/lib/record.js +2 -1
  46. package/lib/site-data-plugin.d.ts +1 -0
  47. package/lib/site-data-plugin.js +13 -1
  48. package/lib/source.d.ts +6 -0
  49. package/lib/source.js +29 -1
  50. package/lib/version.d.ts +1 -1
  51. package/lib/version.js +1 -1
  52. package/package.json +4 -4
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.catalogueOf = exports.idOfFile = void 0;
40
+ /*
41
+ =begin pod :kind<module>
42
+
43
+ =head2 catalogue
44
+
45
+ This module holds the texts an include on a site can bring. They are the
46
+ records the site read before the plugins ran, and the documents plugins make
47
+ later in the chain. Several records read from one file are one source. The
48
+ current version of a document and its permanent address are one source. A page
49
+ cut out of a file is that file.
50
+
51
+ The id of a source is the absolute path of the file it was read from. A
52
+ document a plugin makes is known by the name it was made under, resolved the
53
+ same way.
54
+
55
+ A path in a C<file:> source is resolved from the directory of the file it is
56
+ written in. A mask is matched against the files of the catalogue. A C<doc:>
57
+ source is the document whose C<=NAME> or C<=TITLE> answers to the name. When two
58
+ sources answer to a name, it resolves to neither, and the answer names both.
59
+ When no document answers to a name yet and the host says it will be made later,
60
+ an include of it is left for a later pass.
61
+
62
+ =end pod
63
+ */
64
+ const path = __importStar(require("path"));
65
+ const gray_matter_1 = __importDefault(require("gray-matter"));
66
+ const schema_1 = require("@podlite/schema");
67
+ const podlite_1 = require("podlite");
68
+ const node_utils_1 = require("./node-utils");
69
+ const source_1 = require("./source");
70
+ const isMask = (written) => /[*?]/.test(written);
71
+ const isUnder = (file, dir) => {
72
+ const relative = path.relative(dir, file);
73
+ return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
74
+ };
75
+ /*
76
+ =begin pod :kind<export>
77
+
78
+ =head2 idOfFile
79
+
80
+ The id of a file as a source: its absolute path, from the working directory.
81
+
82
+ =end pod
83
+ */
84
+ const idOfFile = (file) => path.resolve(file);
85
+ exports.idOfFile = idOfFile;
86
+ // a Markdown text is read without its front matter, as the record was
87
+ const readable = (source) => (0, node_utils_1.getParserTypeforFile)(source.file, source.mime) === node_utils_1.PARSER_TYPES.MARKDOWN ? (0, gray_matter_1.default)(source.text).content : source.text;
88
+ /*
89
+ =begin pod :kind<export>
90
+
91
+ =head2 catalogueOf
92
+
93
+ A catalogue over the readings of the records given. Records added later bring
94
+ the readings it does not hold; a reading it holds already is not taken twice.
95
+
96
+ =end pod
97
+ */
98
+ const catalogueOf = (records = [], options = {}) => {
99
+ const entries = new Map();
100
+ const held = new WeakSet();
101
+ const bounds = (options.bounds ?? []).map(dir => path.resolve(dir));
102
+ let names;
103
+ const add = (list) => {
104
+ for (const record of list) {
105
+ const source = (0, source_1.recordOrigin)(record);
106
+ if (!source || held.has(source))
107
+ continue;
108
+ held.add(source);
109
+ const id = (0, exports.idOfFile)(source.file);
110
+ if (entries.has(id))
111
+ continue;
112
+ const own = (0, source_1.recordSource)(record) === source && (0, source_1.isParsedTree)(record);
113
+ const entry = { id, source, tree: own ? record.node : undefined };
114
+ entries.set(id, entry);
115
+ if (names)
116
+ index(names, entry);
117
+ }
118
+ };
119
+ const index = (into, entry) => {
120
+ const tree = entry.tree ?? options.parse?.(readable(entry.source), entry.source.file);
121
+ if (!tree)
122
+ return;
123
+ const node = Array.isArray(tree) ? (0, schema_1.mkRootBlock)({}, tree) : tree;
124
+ for (const name of new Set((0, schema_1.getDocIDs)({ file: entry.source.file, node }))) {
125
+ into.set(name, [...(into.get(name) ?? []), entry.id]);
126
+ }
127
+ };
128
+ // the names each document answers to, built on the first question
129
+ const namesOf = () => {
130
+ if (names)
131
+ return names;
132
+ names = new Map();
133
+ for (const entry of entries.values())
134
+ index(names, entry);
135
+ return names;
136
+ };
137
+ // the directory a path written in that place does not lead out of
138
+ const boundOf = (dir) => bounds.filter(bound => dir === bound || isUnder(dir, bound)).sort((a, b) => b.length - a.length)[0];
139
+ const sourceAt = (id, name) => {
140
+ const entry = entries.get(id);
141
+ const format = entry?.source.mime ? (0, podlite_1.formatOfType)(entry.source.mime) : (0, podlite_1.formatOfFile)(id);
142
+ return { id, name, context: path.dirname(id), ...(format ? { format } : {}) };
143
+ };
144
+ const locateFile = (written, context, plain) => {
145
+ const dir = path.resolve(String(context ?? ''));
146
+ const bound = boundOf(dir);
147
+ const inside = (id) => bound === undefined || isUnder(id, bound);
148
+ if (plain || !isMask(written)) {
149
+ const id = path.resolve(dir, written);
150
+ if (!inside(id))
151
+ return {
152
+ masked: false,
153
+ sources: [],
154
+ failed: `the path leads out of ${path.relative(process.cwd(), bound) || '.'}`,
155
+ };
156
+ return { masked: false, sources: [sourceAt(id, written)] };
157
+ }
158
+ const pattern = path.resolve(dir, written);
159
+ const found = [...entries.keys()].filter(id => inside(id) && (0, schema_1.filePathMatches)(id, pattern)).sort();
160
+ return {
161
+ masked: true,
162
+ // named the way the mask is written, for the selection to match it back
163
+ sources: found.map(id => sourceAt(id, path.isAbsolute(written) ? id : path.relative(dir, id))),
164
+ };
165
+ };
166
+ const locateDoc = (written) => {
167
+ const ids = namesOf().get(written) ?? [];
168
+ if (!ids.length && options.waits?.(written))
169
+ return undefined;
170
+ if (ids.length > 1) {
171
+ const files = ids.map(id => entries.get(id).source.file).join(', ');
172
+ return { masked: false, sources: [], failed: `more than one document is named ${written}: ${files}` };
173
+ }
174
+ return { masked: false, sources: ids.map(id => ({ ...sourceAt(id, written) })) };
175
+ };
176
+ const sources = {
177
+ schemes: ['file', 'doc'],
178
+ locate: (written, context, plain, _at, scheme) => scheme === 'doc' ? locateDoc(written) : locateFile(written, context, plain),
179
+ read: source => {
180
+ const entry = entries.get(source.id);
181
+ return entry ? readable(entry.source) : null;
182
+ },
183
+ };
184
+ const idOf = (record) => {
185
+ const source = (0, source_1.recordOrigin)(record);
186
+ return source ? (0, exports.idOfFile)(source.file) : undefined;
187
+ };
188
+ const named = (name) => namesOf().get(name) ?? [];
189
+ const textOf = (id) => {
190
+ const entry = entries.get(id);
191
+ return entry ? readable(entry.source) : undefined;
192
+ };
193
+ add(records);
194
+ return { sources, add, idOf, named, textOf };
195
+ };
196
+ exports.catalogueOf = catalogueOf;
197
+ //# sourceMappingURL=catalogue.js.map
@@ -42,6 +42,7 @@ const constants_1 = require("./constants");
42
42
  const path_1 = __importDefault(require("path"));
43
43
  const fs = __importStar(require("fs"));
44
44
  const node_utils_1 = require("./node-utils");
45
+ const source_1 = require("./source");
45
46
  const ORIENTATION_TAG = 0x0112;
46
47
  const readOrientation = (file) => {
47
48
  let bytes;
@@ -122,7 +123,8 @@ export default {}
122
123
  ':image': node => {
123
124
  // process copy files to assets
124
125
  // '../assets/'
125
- const { path } = (0, node_utils_1.getPathToOpen)(node.src, file);
126
+ // a picture an include brought is found from the file it was written in
127
+ const { path } = (0, node_utils_1.getPathToOpen)(node.src, (0, source_1.nodeOrigin)(node)?.file ?? file);
126
128
  const { name, ext, dir } = path_1.default.parse(path);
127
129
  const variable_name = 'i' + path.split('/').slice(1).join('_').replace(/\W+/g, '_').toLowerCase();
128
130
  const newFileName = `${variable_name}${ext}`;
@@ -1,3 +1,18 @@
1
+ import { publishRecord } from './record';
1
2
  import { PodliteWebPlugin } from './plugins';
2
- declare const plugin: () => PodliteWebPlugin;
3
+ export type IncludeResolveOptions = {
4
+ catalogue?: publishRecord[];
5
+ bounds?: string[];
6
+ late?: string[];
7
+ };
8
+ export declare class IncludeError extends Error {
9
+ readonly problems: string[];
10
+ constructor(problems: string[]);
11
+ }
12
+ export declare const includePasses: (options?: IncludeResolveOptions) => {
13
+ first: PodliteWebPlugin;
14
+ last: PodliteWebPlugin;
15
+ documents: (name: string) => string[];
16
+ };
17
+ declare const plugin: (options?: IncludeResolveOptions) => PodliteWebPlugin;
3
18
  export default plugin;
@@ -1,120 +1,287 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.includePasses = exports.IncludeError = void 0;
37
+ const path = __importStar(require("path"));
3
38
  const schema_1 = require("@podlite/schema");
4
- const schema_2 = require("@podlite/schema");
5
- const shared_1 = require("./shared");
6
- // A selector whose source, address or operand does not resolve brings nothing
7
- // in, and says so once, naming the =set assignments lost with it.
8
- const select = (selector, recs, lost = '') => {
9
- // a selector that is not read, or a scheme not resolved here, finds nothing
10
- // without saying why
11
- const parsed = (0, shared_1.parseSelector)(selector);
12
- if (!parsed) {
13
- console.warn(`[plugin: resolve ] selector ${selector} cannot be read${lost}`);
14
- return null;
15
- }
16
- if (parsed.scheme && parsed.scheme !== 'doc' && parsed.scheme !== 'file') {
17
- console.warn(`[plugin: resolve ] selector ${selector}: scheme ${parsed.scheme}: is not supported${lost}`);
18
- return null;
19
- }
20
- try {
21
- return (0, shared_1.runSelector)(selector, recs);
22
- }
23
- catch (e) {
24
- if (!(e instanceof schema_2.SelectorError))
25
- throw e;
26
- console.warn(`[plugin: resolve ] selector ${selector} cannot be read: ${e.message}${lost}`);
27
- return null;
39
+ const podlite_1 = require("podlite");
40
+ const refresh_tocs_1 = require("podlite/lib/refresh-tocs");
41
+ const catalogue_1 = require("./catalogue");
42
+ const node_utils_1 = require("./node-utils");
43
+ const reading_1 = require("./reading");
44
+ const site_data_plugin_1 = require("./site-data-plugin");
45
+ const source_1 = require("./source");
46
+ /*
47
+ =begin pod :kind<export>
48
+
49
+ =head2 IncludeError
50
+
51
+ The build stops when an include cannot place what it names:
52
+
53
+ =item the source or the address is not found;
54
+ =item the selector cannot be read;
55
+ =item the scheme is not one the site reads;
56
+ =item a name answers to two documents;
57
+ =item a file includes itself, directly or through other files.
58
+
59
+ C<problems> holds one line for each, with the file and the line of the directive.
60
+
61
+ =end pod
62
+ */
63
+ class IncludeError extends Error {
64
+ problems;
65
+ constructor(problems) {
66
+ super(`an include is not placed:\n${problems.map(line => ` ${line}`).join('\n')}`);
67
+ this.name = 'IncludeError';
68
+ this.problems = problems;
28
69
  }
70
+ }
71
+ exports.IncludeError = IncludeError;
72
+ // lose what the include names, though the assembler reports them as warnings
73
+ const stopping = new Set(['unsupported-scheme', 'unparsed-selector', 'cycle', 'ambiguous']);
74
+ const shown = (file) => (path.isAbsolute(file) ? path.relative(process.cwd(), file) : file);
75
+ const isNode = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
76
+ const nodesOf = (tree, ...queries) => (0, schema_1.getFromTree)(tree, ...queries).flatMap(node => (isNode(node) ? [node] : []));
77
+ const isToc = (node) => node.type === 'block' && (node.name === 'toc' || node.name === 'Toc');
78
+ const hasToc = (tree) => nodesOf(tree, 'toc', 'Toc').some(isToc);
79
+ // the format a table of contents of the record is built again from; none for Markdown
80
+ const writtenFormat = (source) => {
81
+ const type = (0, node_utils_1.getParserTypeforFile)(source.file, source.mime);
82
+ return type === node_utils_1.PARSER_TYPES.MARKDOWN ? undefined : type === node_utils_1.PARSER_TYPES.PODLITE ? 'podlite' : 'default';
29
83
  };
30
- const names = (set) => set.map(c => c.name).join(', ');
31
- // The =set assignments written before an include go to the first block it
32
- // brings; once placed or lost, the directive no longer carries them. When the
33
- // include brings no block they stay without a target: carrying them on to the
34
- // next block is not done here, nor through an include inside what was brought.
35
- const assignments = (node) => {
36
- const set = node.set || [];
37
- const { set: _, ...rest } = node;
38
- const lost = set.length ? `; =set assignments not applied: ${names(set)}` : '';
39
- const place = (blocks) => {
40
- if (!set.length)
41
- return blocks;
42
- const applied = (0, schema_2.applySetToFirst)(blocks, set, { mode: 'include' });
43
- if (applied.outcome !== 'block') {
44
- console.warn(`[plugin: resolve ] =set before =include has no target block: ${names(set)}`);
45
- }
46
- return applied.outcome === 'block' ? applied.nodes : blocks;
84
+ const passes = (options) => {
85
+ const late = new Set([site_data_plugin_1.SITE_DATA_DOCUMENT, ...(options.late ?? [])]);
86
+ let waiting = false;
87
+ const catalogue = (0, catalogue_1.catalogueOf)(options.catalogue ?? [], {
88
+ bounds: options.bounds,
89
+ parse: (text, file) => (0, reading_1.readRecordText)(text, file),
90
+ waits: name => waiting && late.has(name),
91
+ });
92
+ const parser = (0, podlite_1.podlite)({ importPlugins: true });
93
+ // the file a directive was written in, by the place a problem shares with it
94
+ const fileAt = new WeakMap();
95
+ const describe = (problem) => {
96
+ const steps = problem.chain.map(step => {
97
+ const file = (step.location && fileAt.get(step.location)) || step.file;
98
+ return `${shown(file)}${step.location ? `:${step.location.start.line}` : ''}`;
99
+ });
100
+ const at = steps.pop() ?? '<document>';
101
+ return `${at}: ${problem.message}${steps.length ? ` (included through ${steps.reverse().join(', ')})` : ''}`;
47
102
  };
48
- return { node: rest, lost, place };
49
- };
50
- const plugin = () => {
51
- const outCtx = {};
52
- const docsMap = new Map();
53
- const onExit = ctx => ({ ...ctx, ...outCtx });
54
- const processNode = (node, recs) => {
55
- const rules = {
56
- // TODO: remove 'Include' due to duplicate to 'include'
57
- Include: written => {
58
- const { node, lost, place } = assignments(written);
59
- const { content } = node;
60
- const selector = (0, schema_1.getTextContentFromNode)(content).trim();
61
- console.warn(`[include] start resolve selector: ${selector}`);
62
- if (selector) {
63
- // try to resolve selector
64
- const result = select(selector, recs, lost);
65
- if (!result)
66
- return node;
67
- const [block] = result;
68
- if (typeof block === 'object' && !('file' in block)) {
69
- const updated = { content: place([block])[0] };
70
- return { ...node, ...updated };
71
- }
72
- if (!block) {
73
- console.warn(`[plugin: resolve ] selector ${selector} not found`);
74
- place([]);
103
+ const stampOf = (where) => where.via ? { file: where.file, via: where.via } : { file: where.file };
104
+ // The file each node was written in goes onto the node itself, where a copy
105
+ // keeps it; the assembler's own table is lost on the first copy a plugin makes.
106
+ const stamp = (tree, origin) => {
107
+ const visit = (node) => {
108
+ if (Array.isArray(node))
109
+ return node.forEach(visit);
110
+ if (!isNode(node))
111
+ return;
112
+ const where = origin.get(node);
113
+ if (where && !node[source_1.nodeOriginKey])
114
+ node[source_1.nodeOriginKey] = stampOf(where);
115
+ const file = node[source_1.nodeOriginKey]?.file;
116
+ if (file && isNode(node.location))
117
+ fileAt.set(node.location, file);
118
+ visit(node.content);
119
+ };
120
+ visit(tree);
121
+ };
122
+ // what the nodes say of themselves is told to the assembler, so that a block an
123
+ // earlier pass brought is not taken for one of the record
124
+ const seed = (tree, origin) => {
125
+ const visit = (node) => {
126
+ if (Array.isArray(node))
127
+ return node.forEach(visit);
128
+ if (!isNode(node))
129
+ return;
130
+ const mark = node[source_1.nodeOriginKey];
131
+ if (mark)
132
+ origin.set(node, { file: mark.file, text: '', ...(mark.via ? { via: mark.via } : {}) });
133
+ visit(node.content);
134
+ };
135
+ visit(tree);
136
+ };
137
+ const run = (pass) => {
138
+ const outCtx = {};
139
+ const onExit = ctx => ({ ...ctx, ...outCtx });
140
+ const onProcess = (recs) => {
141
+ if (!options.catalogue && pass !== 'last') {
142
+ console.warn('[plugin: resolve ] no catalogue of the site is given; an include is looked for among the records at hand');
143
+ }
144
+ // a document a plugin made earlier in the chain is a source too
145
+ catalogue.add(recs);
146
+ waiting = pass === 'first';
147
+ const problems = [];
148
+ // directives already said why they are left in place
149
+ const told = new WeakSet();
150
+ const fail = (problem) => {
151
+ const at = problem.chain[problem.chain.length - 1]?.location;
152
+ if (at)
153
+ told.add(at);
154
+ problems.push(describe(problem));
155
+ };
156
+ const warn = (problem) => {
157
+ if (stopping.has(problem.kind))
158
+ fail(problem);
159
+ else
160
+ console.warn(`[plugin: resolve ] ${describe(problem)}`);
161
+ };
162
+ // a document placed last is placed as it is: an include in it would need a third pass
163
+ const lateFiles = new Set();
164
+ if (pass !== 'first') {
165
+ for (const name of late) {
166
+ for (const id of catalogue.named(name)) {
167
+ lateFiles.add(id);
168
+ const text = catalogue.textOf(id);
169
+ if (text !== undefined && nodesOf((0, reading_1.readRecordText)(text, id), 'include').length) {
170
+ problems.push(`${shown(id)}: ${name} is placed after the other plugins, so it may not hold an include`);
171
+ }
75
172
  }
76
173
  }
174
+ if (problems.length)
175
+ throw new IncludeError(problems);
176
+ }
177
+ // one field of a record, read from one file
178
+ const assemble = (tree, record) => {
179
+ if (typeof tree !== 'object' || tree === null)
180
+ return tree;
181
+ // the tables of contents are built again in the passes that place the record's
182
+ // own text; the last one only adds documents plugins made
183
+ if (!nodesOf(tree, 'include').length && (pass === 'last' || !hasToc(tree)))
184
+ return tree;
185
+ const self = catalogue.idOf(record);
186
+ const source = (0, source_1.recordOrigin)(record);
187
+ const file = self ?? (0, catalogue_1.idOfFile)(record.file);
188
+ const origin = new WeakMap();
189
+ seed(tree, origin);
190
+ let node = (0, podlite_1.assembleIncludes)(tree, {
191
+ sources: catalogue.sources,
192
+ context: path.dirname(file),
193
+ parse: reading_1.readRecordText,
194
+ file,
195
+ ...(source ? { text: source.text } : {}),
196
+ self,
197
+ origin,
198
+ reportCycles: true,
199
+ onError: fail,
200
+ onWarning: warn,
201
+ });
202
+ // the record's own tables of contents reach what the includes brought
203
+ const format = source && writtenFormat(source);
204
+ if (source && format && hasToc(node)) {
205
+ node = (0, refresh_tocs_1.refreshTocs)(node, (0, podlite_1.writtenTree)(parser, source.text, format), file, origin);
206
+ }
207
+ stamp(node, origin);
77
208
  return node;
78
- },
79
- include: written => {
80
- const { node, lost, place } = assignments(written);
81
- const { content } = node;
82
- const selector = (0, schema_1.getTextContentFromNode)(content).trim();
83
- console.warn(`[include] start resolve selector: ${selector}`);
84
- if (selector) {
85
- const result = select(selector, recs, lost);
86
- if (!result)
87
- return node;
88
- const blocks = [];
89
- for (const item of result) {
90
- if (typeof item === 'object' && item !== null && !('file' in item)) {
91
- blocks.push(item);
209
+ };
210
+ // two records of one reading share their tree
211
+ const trees = new WeakMap();
212
+ const assembleTree = (record) => {
213
+ const known = trees.get(record.node);
214
+ if (known)
215
+ return known;
216
+ const made = assemble(record.node, record);
217
+ trees.set(record.node, made);
218
+ return made;
219
+ };
220
+ // a template is a record of the chain and is assembled as one; a template a record
221
+ // carries is left as it is, as the plugins of images and links leave it
222
+ const out = recs.map(record => {
223
+ const node = assembleTree(record);
224
+ const description = assemble(record.description, record);
225
+ const header = assemble(record.header, record);
226
+ const footer = assemble(record.footer, record);
227
+ const same = node === record.node &&
228
+ description === record.description &&
229
+ header === record.header &&
230
+ footer === record.footer;
231
+ return same ? record : { ...record, node, description, header, footer };
232
+ });
233
+ if (pass !== 'first') {
234
+ for (const record of out) {
235
+ for (const tree of [record.node, record.description, record.header, record.footer]) {
236
+ for (const left of nodesOf(tree, 'include')) {
237
+ if (left.location && told.has(left.location))
238
+ continue;
239
+ const file = left[source_1.nodeOriginKey]?.file ?? record.file;
240
+ const line = left.location ? `:${left.location.start.line}` : '';
241
+ problems.push(`${shown(file)}${line}: the include is left in place`);
242
+ }
243
+ // a picture or a link placed now comes after the plugins that make them work
244
+ for (const node of nodesOf(tree, () => true)) {
245
+ const from = node[source_1.nodeOriginKey]?.file;
246
+ if (!from || !lateFiles.has(from))
247
+ continue;
248
+ const what = node.type === 'image' ? 'a picture' : node.type === 'fcode' && node.name === 'L' ? 'a link' : '';
249
+ if (what)
250
+ problems.push(`${shown(from)}: ${what} is placed after the plugins that handle it`);
92
251
  }
93
252
  }
94
- if (blocks.length > 0) {
95
- return { ...node, content: place((0, schema_2.outermost)(blocks)) };
96
- }
97
- console.warn(`[plugin: resolve ] selector ${selector} not found`);
98
- place([]);
99
253
  }
100
- else if (lost) {
101
- console.warn(`[plugin: resolve ] include selector cannot be read: (empty)${lost}`);
102
- }
103
- return node;
104
- },
254
+ }
255
+ if (problems.length)
256
+ throw new IncludeError([...new Set(problems)]);
257
+ return out;
105
258
  };
106
- return (0, schema_1.makeInterator)(rules)(node, {});
259
+ return [onProcess, onExit];
107
260
  };
108
- const onProcess = (recs) => {
109
- // convert all doc: links to file:: links
110
- const docsWithIncludesResolves = recs.map(item => {
111
- const node = processNode(item.node, recs);
112
- // const node = item.node
113
- return { ...item, node };
114
- });
115
- return docsWithIncludesResolves;
116
- };
117
- return [onProcess, onExit];
261
+ return { run, documents: (name) => catalogue.named(name) };
262
+ };
263
+ /*
264
+ =begin pod :kind<export>
265
+
266
+ =head2 includePasses
267
+
268
+ Gives the include plugin as two passes over one catalogue. C<first> goes before the
269
+ plugins of images, links and React and places all it can; an include of a
270
+ document a plugin makes later in the chain (the site data, and the names in
271
+ C<late>) waits there. C<last> goes after those plugins and places only such
272
+ documents. An include left after it stops the build. C<documents> gives the files
273
+ of the documents that answer to a name, for the links plugin to find a C<doc:>
274
+ link by the same names.
275
+
276
+ =end pod
277
+ */
278
+ const includePasses = (options = {}) => {
279
+ const { run, documents } = passes(options);
280
+ return { first: run('first'), last: run('last'), documents };
118
281
  };
282
+ exports.includePasses = includePasses;
283
+ // One pass over the records: nothing waits, and an include that does not place
284
+ // what it names stops the build.
285
+ const plugin = (options = {}) => passes(options).run('only');
119
286
  exports.default = plugin;
120
287
  //# sourceMappingURL=include-resolve-plugin.js.map
@@ -1,3 +1,11 @@
1
1
  import { PodliteWebPlugin } from './plugins';
2
- declare const plugin: () => PodliteWebPlugin;
2
+ export type LinksOptions = {
3
+ documents?: (name: string) => string[];
4
+ home?: string;
5
+ };
6
+ export declare class LinkError extends Error {
7
+ readonly problems: string[];
8
+ constructor(problems: string[]);
9
+ }
10
+ declare const plugin: (options?: LinksOptions) => PodliteWebPlugin;
3
11
  export default plugin;