cornfield 0.51.4 → 0.51.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/core/deriver-kit.js +2 -1
- package/core/repo.js +64 -7
- package/package.json +1 -1
- package/plugins/docs/index.js +56 -12
- package/plugins/docs/markdown.js +92 -17
- package/plugins/docs/site.js +19 -6
package/core/deriver-kit.js
CHANGED
|
@@ -77,7 +77,8 @@ export { DERIVER_CONTRACT, deriverProblems };
|
|
|
77
77
|
* @property {(rel: string) => boolean} exists
|
|
78
78
|
* @property {(rel: string) => boolean} isDir
|
|
79
79
|
* @property {(rel: string) => string[]} list a folder's entries, sorted
|
|
80
|
-
* @property {(rel: string, test?: (file: string) => boolean) => string[]} walk every file under a folder that `test` accepts, skipping node_modules, .git and the like
|
|
80
|
+
* @property {(rel: string, test?: (file: string) => boolean, onSkip?: (rel: string, reason: 'outside' | 'walked' | 'missing') => void, seen?: Set<string>) => string[]} walk every file under a folder that `test` accepts, skipping node_modules, .git and the like; a symlink is followed only while it stays in the repo, and a real folder is walked once (`onSkip` hears of each link left out; walks that share `seen` read a folder once between them)
|
|
81
|
+
* @property {(rel: string) => boolean} inside whether a path is in the repo once its symlinks are followed
|
|
81
82
|
*/
|
|
82
83
|
|
|
83
84
|
/**
|
package/core/repo.js
CHANGED
|
@@ -24,13 +24,70 @@ export function repoReader(root) {
|
|
|
24
24
|
try { return fs.statSync(abs(rel)).isDirectory(); } catch { return false; }
|
|
25
25
|
};
|
|
26
26
|
const list = (rel) => (isDir(rel) ? fs.readdirSync(abs(rel)).sort() : []);
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
27
|
+
const realRoot = (() => { try { return fs.realpathSync(root); } catch { return path.resolve(root); } })();
|
|
28
|
+
/** Whether real path `real` is `dir` or under it (by whole segments: `/x/repo-other` is not under `/x/repo`) */
|
|
29
|
+
const under = (dir, real) => { const r = path.relative(dir, real); return r === '' || (r !== '..' && !r.startsWith(`..${path.sep}`) && !path.isAbsolute(r)); };
|
|
30
|
+
const within = (real) => under(realRoot, real);
|
|
31
|
+
/**
|
|
32
|
+
* Whether `rel` lies in the repo once every symlink on its way is followed. A path that is not there is judged by
|
|
33
|
+
* the nearest folder on its way that is, with the rest as written (a `..` included): nothing can be read from it.
|
|
34
|
+
*/
|
|
35
|
+
const inside = (rel) => {
|
|
36
|
+
if (String(rel).includes('\0')) return false;
|
|
37
|
+
let at = abs(rel);
|
|
38
|
+
let rest = '';
|
|
39
|
+
for (;;) {
|
|
40
|
+
try { return within(path.resolve(fs.realpathSync(at), rest)); } catch { /* not there, or a link loop: try its folder */ }
|
|
41
|
+
const up = path.dirname(at);
|
|
42
|
+
if (up === at) return false;
|
|
43
|
+
rest = path.join(path.basename(at), rest);
|
|
44
|
+
at = up;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Every file under `rel` that `test` accepts, sorted by folder, skipping SKIP_DIRS. A symlink is followed only while
|
|
49
|
+
* it stays in the repo, and a real folder is walked once: a link to a folder under `rel` is left to the real folder,
|
|
50
|
+
* and of two links to one other folder the first wins. `onSkip(path, reason)` hears of each link left out: 'outside'
|
|
51
|
+
* (out of the repo, to a folder or to a file `test` accepts), 'walked' (to a folder already walked) or 'missing' (to
|
|
52
|
+
* nothing, or a loop of links, named like a file `test` accepts). Walks that share `seen` (a set of real folders) read
|
|
53
|
+
* each folder once between them, a folder two of them name in the repo's own words in silence. Only links pay a
|
|
54
|
+
* `realpath`.
|
|
55
|
+
*/
|
|
56
|
+
const walk = (rel, test = () => true, onSkip = () => {}, seen = new Set()) => {
|
|
57
|
+
const start = rel && rel !== '.' ? rel : '';
|
|
58
|
+
let startReal;
|
|
59
|
+
try { startReal = fs.realpathSync(abs(start)); } catch { return []; }
|
|
60
|
+
if (!within(startReal)) { onSkip(start, 'outside'); return []; }
|
|
61
|
+
const linked = startReal !== path.join(realRoot, start);
|
|
62
|
+
if (seen.has(startReal)) { if (linked) onSkip(start, 'walked'); return []; }
|
|
63
|
+
// `viaLink`: `dir` is reached through a link, so a real folder in it may be one walked by its own name
|
|
64
|
+
const go = (dir, real, viaLink) => {
|
|
65
|
+
seen.add(real);
|
|
66
|
+
let entries;
|
|
67
|
+
try { entries = fs.readdirSync(abs(dir), { withFileTypes: true }); } catch { return []; }
|
|
68
|
+
entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
69
|
+
return entries.flatMap((e) => {
|
|
70
|
+
if (SKIP_DIRS.has(e.name)) return [];
|
|
71
|
+
const child = dir ? `${dir}/${e.name}` : e.name;
|
|
72
|
+
if (!e.isSymbolicLink()) {
|
|
73
|
+
if (!e.isDirectory()) return test(child) ? [child] : [];
|
|
74
|
+
const childReal = path.join(real, e.name);
|
|
75
|
+
if (seen.has(childReal)) { if (viaLink) onSkip(child, 'walked'); return []; }
|
|
76
|
+
return go(child, childReal, viaLink);
|
|
77
|
+
}
|
|
78
|
+
let target;
|
|
79
|
+
try { target = fs.realpathSync(abs(child)); } catch { if (test(child)) onSkip(child, 'missing'); return []; }
|
|
80
|
+
const folder = isDir(child);
|
|
81
|
+
if (!within(target)) { if (folder || test(child)) onSkip(child, 'outside'); return []; }
|
|
82
|
+
if (!folder) return test(child) ? [child] : [];
|
|
83
|
+
const ownRoute = under(startReal, target) && !path.relative(startReal, target).split(path.sep).some((s) => SKIP_DIRS.has(s));
|
|
84
|
+
if (ownRoute || seen.has(target)) { onSkip(child, 'walked'); return []; }
|
|
85
|
+
return go(child, target, true);
|
|
86
|
+
});
|
|
87
|
+
};
|
|
88
|
+
return go(start, startReal, linked);
|
|
89
|
+
};
|
|
90
|
+
return { root, read, exists, isDir, list, walk, inside };
|
|
34
91
|
}
|
|
35
92
|
|
|
36
93
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cornfield",
|
|
3
|
-
"version": "0.51.
|
|
3
|
+
"version": "0.51.6",
|
|
4
4
|
"description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "popcorn245 (https://github.com/popcorn245)",
|
package/plugins/docs/index.js
CHANGED
|
@@ -24,17 +24,30 @@ export const DEFAULT_PATHS = ['README.md', 'docs'];
|
|
|
24
24
|
const isMarkdown = (f) => /\.md$/i.test(f);
|
|
25
25
|
const isReadme = (f) => /^readme\.md$/i.test(path.posix.basename(f));
|
|
26
26
|
|
|
27
|
+
/** What a docs warning says of a link the walk leaves out (core/repo.js `walk`) */
|
|
28
|
+
const SKIPPED = { outside: 'is a link to somewhere outside the repo; it is not followed', walked: 'leads to a folder already read; it is not read again', missing: 'is a link to nothing; it is not read' };
|
|
29
|
+
|
|
30
|
+
/** The files the site writes itself: a doc's page may not land on one (see `docOutputs`) */
|
|
31
|
+
export const SITE_OUTPUTS = ['map.html', 'site.css', '.cornfield-site'];
|
|
32
|
+
|
|
27
33
|
/**
|
|
28
|
-
* The Markdown files the paths name, sorted, each once.
|
|
29
|
-
*
|
|
34
|
+
* The Markdown files the paths name, sorted, each once. A path that leaves the repo (`..`, an absolute path, a
|
|
35
|
+
* symlink to somewhere else), and a file or folder under one that does, is left out and said by `refuse`.
|
|
36
|
+
* @param {{ exists: Function, isDir: Function, walk: Function, inside?: Function }} io
|
|
30
37
|
* @param {string[]} paths
|
|
38
|
+
* @param {(message: string, severity: 'problem' | 'warning') => void} [refuse]
|
|
31
39
|
*/
|
|
32
|
-
export function docFiles(io, paths) {
|
|
40
|
+
export function docFiles(io, paths, refuse = () => {}) {
|
|
33
41
|
const out = new Set();
|
|
42
|
+
const inside = io.inside || (() => true);
|
|
43
|
+
const seen = new Set(); // the real folders read so far: two paths that reach one folder read it once
|
|
44
|
+
const told = new Set();
|
|
34
45
|
for (const p of paths) {
|
|
35
|
-
const rel = p.replace(/^\.\/+/, '').replace(/\/+$/, '');
|
|
36
|
-
if (
|
|
37
|
-
|
|
46
|
+
const rel = path.posix.normalize(p.replace(/^\.\/+/, '').replace(/\/+$/, '') || '.');
|
|
47
|
+
if (path.isAbsolute(p) || path.win32.isAbsolute(p) || rel === '..' || rel.startsWith('../') || !inside(rel)) { refuse(`docs: ${JSON.stringify(p)} is outside the repo; only files and folders of the repo are read.`, 'problem'); continue; }
|
|
48
|
+
if (io.isDir(rel)) {
|
|
49
|
+
io.walk(rel, isMarkdown, (f, why) => { const m = `docs: ${f || '.'} ${SKIPPED[why]}.`; if (!told.has(m)) { told.add(m); refuse(m, 'warning'); } }, seen).forEach((f) => out.add(f));
|
|
50
|
+
} else if (isMarkdown(rel) && io.exists(rel)) out.add(rel);
|
|
38
51
|
}
|
|
39
52
|
return [...out].sort();
|
|
40
53
|
}
|
|
@@ -54,6 +67,31 @@ export function docOutput(file) {
|
|
|
54
67
|
return route.endsWith('/') ? `${route.slice(1)}index.html` : `${route.slice(1)}.html`;
|
|
55
68
|
}
|
|
56
69
|
|
|
70
|
+
/**
|
|
71
|
+
* Where each doc lands, by file. A doc whose page would land on a file the site writes itself (`map.md` → `map.html`),
|
|
72
|
+
* or on another doc's page (`index.md` beside a README), goes to the next free `-doc` name (`map-doc.html`), so no
|
|
73
|
+
* page is written over; `renamed` lists `[file, output, other]` for each. A README keeps the folder's `index.html`,
|
|
74
|
+
* and the first of two docs keeps its name. A doc with no clash keeps `docOutput(file)`.
|
|
75
|
+
* @param {string[]} files
|
|
76
|
+
*/
|
|
77
|
+
export function docOutputs(files) {
|
|
78
|
+
const taken = new Map(SITE_OUTPUTS.map((o) => [o, null]));
|
|
79
|
+
const outputs = new Map();
|
|
80
|
+
const renamed = [];
|
|
81
|
+
for (const file of [...files].sort((a, b) => Number(isReadme(b)) - Number(isReadme(a)))) {
|
|
82
|
+
let out = docOutput(file);
|
|
83
|
+
if (taken.has(out)) {
|
|
84
|
+
const other = taken.get(out);
|
|
85
|
+
const stem = out.replace(/\.html$/, '');
|
|
86
|
+
for (let n = 1; taken.has(out); n++) out = `${stem}-doc${n > 1 ? `-${n}` : ''}.html`;
|
|
87
|
+
renamed.push([file, out, other]);
|
|
88
|
+
}
|
|
89
|
+
taken.set(out, file);
|
|
90
|
+
outputs.set(file, out);
|
|
91
|
+
}
|
|
92
|
+
return { outputs, renamed };
|
|
93
|
+
}
|
|
94
|
+
|
|
57
95
|
/** The page node id of a doc: `page-doc-` and its path, in kebab case */
|
|
58
96
|
export const docPageId = (file) => `page-doc-${file.replace(/\.md$/i, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`;
|
|
59
97
|
|
|
@@ -84,13 +122,18 @@ export default {
|
|
|
84
122
|
derive(ctx) {
|
|
85
123
|
const { paths = DEFAULT_PATHS, app: appId = 'app-docs', label = 'docs', parent = 'root' } = ctx.options || {};
|
|
86
124
|
if (!Array.isArray(paths) || !paths.every((p) => typeof p === 'string' && p)) throw new Error('options.paths is a list of files and folders, like ["README.md", "docs"].');
|
|
87
|
-
const files = docFiles(ctx, paths);
|
|
88
|
-
const empty = { nodes: [], edges: [], info: { pages: [] } };
|
|
89
|
-
if (!files.length) return { ...empty, warnings: ctx.options?.paths ? [`docs: no Markdown in ${paths.join(', ')}.`] : [] };
|
|
90
|
-
|
|
91
125
|
const warnings = [];
|
|
92
126
|
const problems = [];
|
|
93
|
-
const
|
|
127
|
+
const refuse = (message, severity) => (severity === 'problem' ? problems : warnings).push(message);
|
|
128
|
+
const files = docFiles(ctx, paths, refuse);
|
|
129
|
+
const empty = { nodes: [], edges: [], info: { pages: [] } };
|
|
130
|
+
if (!files.length) return { ...empty, warnings: [...warnings, ...(ctx.options?.paths ? [`docs: no Markdown in ${paths.join(', ')}.`] : [])], problems };
|
|
131
|
+
|
|
132
|
+
// Two docs that would be one page id are a problem (below); only the first is placed, and only its name can clash
|
|
133
|
+
const ids = new Set();
|
|
134
|
+
const { outputs, renamed } = docOutputs(files.filter((f) => !ids.has(docPageId(f)) && ids.add(docPageId(f))));
|
|
135
|
+
for (const [file, output, other] of renamed) warnings.push(`docs: ${file} would be page ${docOutput(file)}, ${other ? `which ${other} has` : 'which the site writes itself'}; it is written to ${output}.`);
|
|
136
|
+
const nodes = [{ id: appId, type: 'app', label, file: paths.map((p) => p.replace(/^\.\/+/, '').replace(/\/+$/, '')).find((p) => ctx.exists(p) && ctx.inside(p)) }];
|
|
94
137
|
const edges = [];
|
|
95
138
|
if (ctx.nodes.some((n) => n.id === parent)) edges.push({ from: parent, to: appId });
|
|
96
139
|
|
|
@@ -102,7 +145,7 @@ export default {
|
|
|
102
145
|
if (clash) { problems.push(`docs: ${file} and ${clash.file} would both be page "${id}"; rename one.`); continue; }
|
|
103
146
|
const text = ctx.read(file);
|
|
104
147
|
const { title, headings } = renderMarkdown(text);
|
|
105
|
-
const page = { id, file, route: docRoute(file), output:
|
|
148
|
+
const page = { id, file, route: docRoute(file), output: outputs.get(file), title: title || path.posix.basename(file, '.md'), anchors: headings.map((h) => h.id), text };
|
|
106
149
|
pages.push(page);
|
|
107
150
|
byFile.set(file, page);
|
|
108
151
|
nodes.push({ id, type: 'page', label: page.route, file, summary: page.title });
|
|
@@ -126,6 +169,7 @@ export default {
|
|
|
126
169
|
if (t.external) continue;
|
|
127
170
|
if (t.outside) { warnings.push(`docs: ${page.file} links to "${href}", outside the repo.`); continue; }
|
|
128
171
|
const target = t.path === '' ? page.file : t.path;
|
|
172
|
+
if (!ctx.inside(target)) { warnings.push(`docs: ${page.file} links to "${href}", which leads outside the repo.`); continue; }
|
|
129
173
|
if (!ctx.exists(target)) { problems.push(`docs: ${page.file} links to "${href}", but ${target} is not in the repo.`); continue; }
|
|
130
174
|
const readme = ctx.isDir(target) ? files.find((f) => path.posix.dirname(f) === target && isReadme(f)) : null;
|
|
131
175
|
const doc = byFile.get(readme || target);
|
package/plugins/docs/markdown.js
CHANGED
|
@@ -562,12 +562,74 @@ function fenceOf(line) {
|
|
|
562
562
|
if (!m || line.includes('`', m[0].length)) return null;
|
|
563
563
|
return [line, m[1], /^\s*([^`\s]*)/.exec(line.slice(m[0].length))[1]];
|
|
564
564
|
}
|
|
565
|
-
const
|
|
565
|
+
const LINE_BREAK = /[\n\r\u2028\u2029]/;
|
|
566
|
+
/**
|
|
567
|
+
* A heading line's `[line, level, text]`, or null: one to six `#`, then a space or tab (or the end of the line), the text
|
|
568
|
+
* and an optional closing run of `#`. (Read by hand: the one expression for it, `/^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/`,
|
|
569
|
+
* tries every split of a long run of spaces. As the expression's `.` did, a line with a line break in it is no heading.)
|
|
570
|
+
*/
|
|
571
|
+
function headingOf(line) {
|
|
572
|
+
let i = 0;
|
|
573
|
+
while (i < 3 && line[i] === ' ') i++;
|
|
574
|
+
const start = i;
|
|
575
|
+
while (line[i] === '#') i++;
|
|
576
|
+
const level = i - start;
|
|
577
|
+
if (level < 1 || level > 6) return null;
|
|
578
|
+
if (i < line.length && line[i] !== ' ' && line[i] !== '\t') return null;
|
|
579
|
+
if (LINE_BREAK.test(line)) return null;
|
|
580
|
+
while (line[i] === ' ' || line[i] === '\t') i++;
|
|
581
|
+
let end = line.length;
|
|
582
|
+
while (end > i && (line[end - 1] === ' ' || line[end - 1] === '\t')) end--;
|
|
583
|
+
// Cut a closing run of `#` that a space or tab sets off from the text
|
|
584
|
+
let j = end;
|
|
585
|
+
while (j > i && line[j - 1] === '#') j--;
|
|
586
|
+
if (j < end && j > i && (line[j - 1] === ' ' || line[j - 1] === '\t')) {
|
|
587
|
+
end = j;
|
|
588
|
+
while (end > i && (line[end - 1] === ' ' || line[end - 1] === '\t')) end--;
|
|
589
|
+
}
|
|
590
|
+
return [line, level, line.slice(i, end)];
|
|
591
|
+
}
|
|
566
592
|
const RULE = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
|
|
567
593
|
const QUOTE = /^ {0,3}> ?/;
|
|
568
|
-
const
|
|
594
|
+
const LIST_MARK = /^( {0,3})([-*+]|\d{1,9}[.)])([ \t]+|$)/;
|
|
595
|
+
/**
|
|
596
|
+
* A list item line's `[line, indent, marker, spaces, rest of the line]`, or null. (The prefix only is matched by the
|
|
597
|
+
* expression; with a `(.*)$` after it, a run of spaces and a line break at the end of the line made it try every split.)
|
|
598
|
+
*/
|
|
599
|
+
function listItem(line) {
|
|
600
|
+
const m = LIST_MARK.exec(line);
|
|
601
|
+
if (!m || LINE_BREAK.test(line)) return null;
|
|
602
|
+
return [line, m[1], m[2], m[3], line.slice(m[0].length)];
|
|
603
|
+
}
|
|
569
604
|
const HTML_START = /^ {0,3}<\/?(p|div|img|br|hr|details|summary|table|picture|center|section|!--)(?=[\s/>]|$)/i;
|
|
570
|
-
const
|
|
605
|
+
const SPACES = /\s*/y;
|
|
606
|
+
const SEP_CELL = /:?-+:?\s*/y;
|
|
607
|
+
/**
|
|
608
|
+
* Whether a line is a table's separator row: cells of dashes with an optional colon at either end, between pipes (the
|
|
609
|
+
* outer two optional). (By hand: the expression for it, `/^ {0,3}\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/`, tries every split of a long run of spaces.)
|
|
610
|
+
*/
|
|
611
|
+
function isTableSep(line) {
|
|
612
|
+
let i = 0;
|
|
613
|
+
while (i < 3 && line[i] === ' ') i++;
|
|
614
|
+
// Up to three spaces and a pipe; with no pipe the spaces are read as the cell's own leading spaces
|
|
615
|
+
if (line[i] !== '|') i = 0; else i++;
|
|
616
|
+
for (;;) {
|
|
617
|
+
SPACES.lastIndex = i;
|
|
618
|
+
SPACES.test(line);
|
|
619
|
+
SEP_CELL.lastIndex = SPACES.lastIndex;
|
|
620
|
+
if (!SEP_CELL.test(line)) return false;
|
|
621
|
+
i = SEP_CELL.lastIndex;
|
|
622
|
+
if (i === line.length) return true;
|
|
623
|
+
if (line[i] !== '|') return false;
|
|
624
|
+
SPACES.lastIndex = i + 1;
|
|
625
|
+
SPACES.test(line);
|
|
626
|
+
i = SPACES.lastIndex;
|
|
627
|
+
if (i === line.length) return true;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** How many empty cells a document's tables may add to rows shorter than their header (see renderBlocks) */
|
|
632
|
+
const MAX_PADDING = 65536;
|
|
571
633
|
|
|
572
634
|
const isBlank = (l) => /^\s*$/.test(l);
|
|
573
635
|
const indentOf = (l) => /^ */.exec(l.replace(/\t/g, ' '))[0].length;
|
|
@@ -592,12 +654,16 @@ function cells(line) {
|
|
|
592
654
|
}
|
|
593
655
|
|
|
594
656
|
/** Whether a line starts a block other than a paragraph (it interrupts a paragraph) */
|
|
595
|
-
const startsBlock = (line) =>
|
|
657
|
+
const startsBlock = (line) => {
|
|
658
|
+
if (fenceOf(line) || headingOf(line) || RULE.test(line) || QUOTE.test(line) || HTML_START.test(line)) return true;
|
|
659
|
+
const item = listItem(line);
|
|
660
|
+
return Boolean(item) && !isBlank(item[4]);
|
|
661
|
+
};
|
|
596
662
|
|
|
597
663
|
/**
|
|
598
664
|
* Lines of Markdown as HTML.
|
|
599
665
|
* @param {string[]} lines
|
|
600
|
-
* @param {{ link: Function, headings: object[], slugs: Map<string, number
|
|
666
|
+
* @param {{ link: Function, headings: object[], slugs: Map<string, number>, padding: number }} ctx (padding: the empty cells a table may still add)
|
|
601
667
|
* @param {boolean} [tight] paragraphs without <p> (a tight list item)
|
|
602
668
|
* @param {number} [depth] how many lists and quotes these lines sit in (from MAX_NEST on, a list or quote is text)
|
|
603
669
|
*/
|
|
@@ -623,10 +689,9 @@ function renderBlocks(lines, ctx, tight = false, depth = 0) {
|
|
|
623
689
|
continue;
|
|
624
690
|
}
|
|
625
691
|
|
|
626
|
-
const heading =
|
|
692
|
+
const heading = headingOf(line);
|
|
627
693
|
if (heading) {
|
|
628
|
-
const level = heading
|
|
629
|
-
const text = heading[2] || '';
|
|
694
|
+
const [, level, text] = heading;
|
|
630
695
|
const base = headingSlug(text);
|
|
631
696
|
const n = ctx.slugs.get(base) || 0;
|
|
632
697
|
ctx.slugs.set(base, n + 1);
|
|
@@ -653,7 +718,7 @@ function renderBlocks(lines, ctx, tight = false, depth = 0) {
|
|
|
653
718
|
continue;
|
|
654
719
|
}
|
|
655
720
|
|
|
656
|
-
if (line.includes('|') && i + 1 < lines.length &&
|
|
721
|
+
if (line.includes('|') && i + 1 < lines.length && isTableSep(lines[i + 1]) && lines[i + 1].includes('-')) {
|
|
657
722
|
const head = cells(line);
|
|
658
723
|
const align = cells(lines[i + 1]).map((c) => (c.startsWith(':') && c.endsWith(':') ? 'center' : c.endsWith(':') ? 'right' : c.startsWith(':') ? 'left' : null));
|
|
659
724
|
const cell = (tag, text, k) => `<${tag}${align[k] ? ` style="text-align:${align[k]}"` : ''}>${renderInline(text, ctx)}</${tag}>`;
|
|
@@ -661,13 +726,20 @@ function renderBlocks(lines, ctx, tight = false, depth = 0) {
|
|
|
661
726
|
const rows = [];
|
|
662
727
|
while (i < lines.length && !isBlank(lines[i]) && lines[i].includes('|')) {
|
|
663
728
|
const row = cells(lines[i++]);
|
|
664
|
-
|
|
729
|
+
// A short row is padded with empty cells to the header's width. A wide header over many short rows would so make output
|
|
730
|
+
// in the square of the input, so a document adds at most MAX_PADDING such cells: a row that would pass that keeps its own
|
|
731
|
+
let width = head.length;
|
|
732
|
+
if (row.length < width) {
|
|
733
|
+
if (width - row.length <= ctx.padding) ctx.padding -= width - row.length;
|
|
734
|
+
else width = row.length;
|
|
735
|
+
}
|
|
736
|
+
rows.push(`<tr>${head.slice(0, width).map((_, k) => cell('td', row[k] ?? '', k)).join('')}</tr>`);
|
|
665
737
|
}
|
|
666
738
|
out.push(`<div class="table"><table>\n<thead><tr>${head.map((h, k) => cell('th', h, k)).join('')}</tr></thead>\n<tbody>\n${rows.join('\n')}\n</tbody>\n</table></div>`);
|
|
667
739
|
continue;
|
|
668
740
|
}
|
|
669
741
|
|
|
670
|
-
const item = depth < MAX_NEST &&
|
|
742
|
+
const item = depth < MAX_NEST && listItem(line);
|
|
671
743
|
if (item) {
|
|
672
744
|
const ordered = /\d/.test(item[2]);
|
|
673
745
|
const kind = ordered ? item[2].slice(-1) : item[2];
|
|
@@ -675,28 +747,31 @@ function renderBlocks(lines, ctx, tight = false, depth = 0) {
|
|
|
675
747
|
const items = [];
|
|
676
748
|
let loose = false;
|
|
677
749
|
while (i < lines.length) {
|
|
678
|
-
const m =
|
|
750
|
+
const m = listItem(lines[i]);
|
|
679
751
|
if (!m || (/\d/.test(m[2]) ? m[2].slice(-1) : m[2]) !== kind) break;
|
|
680
752
|
const contentIndent = m[1].length + m[2].length + Math.min(m[3].length || 1, 4);
|
|
681
753
|
const body = [m[4]];
|
|
682
754
|
i++;
|
|
683
755
|
let sawBlank = false;
|
|
756
|
+
let filled = m[4] === '' ? 0 : 1;
|
|
684
757
|
while (i < lines.length) {
|
|
685
758
|
const l = lines[i];
|
|
686
759
|
if (isBlank(l)) { sawBlank = true; body.push(''); i++; continue; }
|
|
687
760
|
if (indentOf(l) >= contentIndent) {
|
|
688
|
-
if (sawBlank &&
|
|
689
|
-
|
|
761
|
+
if (sawBlank && filled) loose = loose || !listItem(l.slice(contentIndent));
|
|
762
|
+
const text = l.replace(/\t/g, ' ').slice(contentIndent);
|
|
763
|
+
body.push(text);
|
|
764
|
+
if (text !== '') filled++;
|
|
690
765
|
sawBlank = false;
|
|
691
766
|
i++;
|
|
692
767
|
continue;
|
|
693
768
|
}
|
|
694
769
|
// A lazy continuation of the item's paragraph
|
|
695
|
-
if (!sawBlank && !startsBlock(l) && !
|
|
770
|
+
if (!sawBlank && !startsBlock(l) && !listItem(l)) { body.push(l.trim()); i++; filled++; continue; }
|
|
696
771
|
break;
|
|
697
772
|
}
|
|
698
773
|
while (body.length && body[body.length - 1] === '') body.pop();
|
|
699
|
-
if (sawBlank && i < lines.length &&
|
|
774
|
+
if (sawBlank && i < lines.length && listItem(lines[i])) loose = true;
|
|
700
775
|
items.push(body);
|
|
701
776
|
}
|
|
702
777
|
const tag = ordered ? 'ol' : 'ul';
|
|
@@ -723,7 +798,7 @@ function renderBlocks(lines, ctx, tight = false, depth = 0) {
|
|
|
723
798
|
* @returns {{ html: string, title: string | null, headings: { level: number, text: string, id: string }[] }}
|
|
724
799
|
*/
|
|
725
800
|
export function renderMarkdown(text, { link = (href) => href } = {}) {
|
|
726
|
-
const ctx = { link, headings: [], slugs: new Map() };
|
|
801
|
+
const ctx = { link, headings: [], slugs: new Map(), padding: MAX_PADDING };
|
|
727
802
|
const html = renderBlocks(String(text).replace(/\r\n?/g, '\n').split('\n'), ctx);
|
|
728
803
|
const h1 = ctx.headings.find((h) => h.level === 1);
|
|
729
804
|
return { html, title: h1 ? h1.text : null, headings: ctx.headings };
|
package/plugins/docs/site.js
CHANGED
|
@@ -18,10 +18,11 @@ import { escapeHtml as esc } from '../../core/text.js';
|
|
|
18
18
|
import { deriveTopology } from '../../core/derive.js';
|
|
19
19
|
import { readTopology } from '../../core/validate.js';
|
|
20
20
|
import { renderMarkdown, safeUrl } from './markdown.js';
|
|
21
|
-
import docsDeriver, { resolveLink } from './index.js';
|
|
21
|
+
import docsDeriver, { resolveLink, SITE_OUTPUTS } from './index.js';
|
|
22
|
+
import { repoReader } from '../../core/repo.js';
|
|
22
23
|
|
|
23
24
|
/** The file a built site holds, so a rebuild knows the folder is its own */
|
|
24
|
-
export const SITE_MARKER =
|
|
25
|
+
export const SITE_MARKER = SITE_OUTPUTS[2];
|
|
25
26
|
const IMAGE = /\.(png|jpe?g|gif|svg|webp|avif)$/i;
|
|
26
27
|
|
|
27
28
|
/** The forge URL a repo file is shown at, from the config's forge, or null */
|
|
@@ -102,6 +103,7 @@ ${body}
|
|
|
102
103
|
`;
|
|
103
104
|
|
|
104
105
|
for (const page of pages) {
|
|
106
|
+
if (SITE_OUTPUTS.includes(page.output) || pages.some((q) => q !== page && q.output === page.output)) throw new Error(`${page.file} would be written to ${page.output}, which another page or the site itself writes.`);
|
|
105
107
|
const { html } = renderMarkdown(read(page.file), {
|
|
106
108
|
link: (href, { image }) => {
|
|
107
109
|
const t = resolveLink(page.file, href);
|
|
@@ -218,21 +220,32 @@ export async function buildSite({ config, derivers, out, sourceUrl = sourceUrlOf
|
|
|
218
220
|
const derived = await deriveTopology({ root, config, derivers: list, map: readTopology(config) });
|
|
219
221
|
const pages = derived.info.docs?.pages || [];
|
|
220
222
|
if (!pages.length) throw new Error('There are no docs to build: the docs deriver found no Markdown (see its "paths" option).');
|
|
221
|
-
|
|
222
|
-
const
|
|
223
|
-
const
|
|
223
|
+
// What the site reads is the repo's: a path that leads out of it, by `..` or a symlink, is as if it were not there
|
|
224
|
+
const io = repoReader(root);
|
|
225
|
+
const read = (rel) => {
|
|
226
|
+
if (!io.inside(rel)) throw new Error(`${rel} is outside the repo.`);
|
|
227
|
+
return fs.readFileSync(path.join(root, rel), 'utf8');
|
|
228
|
+
};
|
|
229
|
+
const exists = (rel) => io.inside(rel) && io.exists(rel);
|
|
230
|
+
const isDir = (rel) => io.inside(rel) && io.isDir(rel);
|
|
224
231
|
const files = siteFiles({ title: config.title || 'Docs', pages, nodes: derived.nodes, edges: derived.edges, read, exists, isDir, sourceUrl });
|
|
225
232
|
// Only a folder this builds (it leaves a marker) or an empty one is emptied: never a folder of the repo's own files
|
|
226
233
|
if (fs.existsSync(out) && fs.readdirSync(out).length && !fs.existsSync(path.join(out, SITE_MARKER))) throw new Error(`${out} is not empty and is not a site cornfield built: pick another folder, or empty it first.`);
|
|
227
234
|
fs.rmSync(out, { recursive: true, force: true });
|
|
228
235
|
files[SITE_MARKER] = 'Built by cornfield docs. This folder is emptied on every build.\n';
|
|
236
|
+
const problems = [...derived.problems];
|
|
237
|
+
const written = [];
|
|
229
238
|
for (const [rel, content] of Object.entries(files)) {
|
|
230
239
|
const dest = path.join(out, rel);
|
|
240
|
+
// What is written lies in `out`, whatever a doc is called
|
|
241
|
+
if (path.relative(out, dest).split(path.sep)[0] === '..' || path.isAbsolute(path.relative(out, dest))) { problems.push(`docs: ${rel} would be written outside ${path.basename(out)}; it is not.`); continue; }
|
|
242
|
+
if (typeof content !== 'string' && !io.inside(content.copy)) { problems.push(`docs: ${content.copy} leads outside the repo; it is not copied.`); continue; }
|
|
231
243
|
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
232
244
|
if (typeof content === 'string') fs.writeFileSync(dest, content, 'utf8');
|
|
233
245
|
else fs.copyFileSync(path.join(root, content.copy), dest);
|
|
246
|
+
written.push(rel);
|
|
234
247
|
}
|
|
235
|
-
return { pages: pages.length, files:
|
|
248
|
+
return { pages: pages.length, files: written.sort(), warnings: derived.warnings, problems };
|
|
236
249
|
}
|
|
237
250
|
|
|
238
251
|
const SITE_CSS = `:root {
|