cornfield 0.51.5 → 0.51.7

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.
@@ -26,7 +26,7 @@ import { pathToFileURL } from 'node:url';
26
26
  import { DERIVER_CONTRACT, deriveTopology, deriverProblems } from './derive.js';
27
27
  import { planSync, missingPaths } from './sync.js';
28
28
  import { validateTopology } from './validate.js';
29
- import { repoReader, repoPaths } from './repo.js';
29
+ import { reachable, repoReader, repoPaths } from './repo.js';
30
30
  import { BUILTIN_DERIVERS, CORNFIELD_DIR, DEFAULTS } from './config.js';
31
31
 
32
32
  export { DERIVER_CONTRACT, deriverProblems };
@@ -70,14 +70,16 @@ export { DERIVER_CONTRACT, deriverProblems };
70
70
 
71
71
  /**
72
72
  * The readers a deriver gets, rooted at the repo (core/repo.js). Paths are relative, with forward slashes;
73
- * text is read with LF line ends.
73
+ * text is read with LF line ends. A path whose real path (symlinks followed) is outside the repo is not there: `read` throws,
74
+ * `exists` and `isDir` say no, `list` is empty.
74
75
  * @typedef {object} RepoReader
75
76
  * @property {string} root the repo's absolute folder
76
77
  * @property {(rel: string) => string} read
77
78
  * @property {(rel: string) => boolean} exists
78
79
  * @property {(rel: string) => boolean} isDir
79
80
  * @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
81
+ * @property {(rel: string, test?: (file: string) => boolean, onSkip?: (rel: string, reason: 'outside' | 'walked' | 'missing') => void, seen?: Set<string>, skipDir?: (name: string) => boolean) => 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; `skipDir` names more folders to leave out)
82
+ * @property {(rel: string) => boolean} inside whether a path is in the repo once its symlinks are followed
81
83
  */
82
84
 
83
85
  /**
@@ -294,7 +296,7 @@ export async function runDeriver(deriver, { root, files, options = {}, config =
294
296
  topology,
295
297
  changes,
296
298
  schemaProblems: validateTopology(topology),
297
- pathProblems: missingPaths({ nodes: topology.nodes.filter((n) => (own.nodes || []).some((m) => m.id === n.id)), edges: [] }, repoPaths(dir)),
299
+ pathProblems: missingPaths({ nodes: topology.nodes.filter((n) => (own.nodes || []).some((m) => m.id === n.id)), edges: [] }, repoPaths(dir), reachable(repoReader(dir))),
298
300
  validateProblems,
299
301
  driftProblems,
300
302
  unowned,
package/core/repo.js CHANGED
@@ -18,21 +18,157 @@ export const SKIP_DIRS = new Set(['node_modules', '.git', '.claude', '.worktrees
18
18
  */
19
19
  export function repoReader(root) {
20
20
  const abs = (rel) => path.join(root, rel);
21
- const read = (rel) => fs.readFileSync(abs(rel), 'utf8').replace(/\r\n/g, '\n');
22
- const exists = (rel) => fs.existsSync(abs(rel));
23
- const isDir = (rel) => {
21
+ const realpath = fs.realpathSync.native;
22
+ const realRoot = (() => { try { return realpath(root); } catch { return path.resolve(root); } })();
23
+ /** Whether real path `real` is `dir` or under it (by whole segments: `/x/repo-other` is not under `/x/repo`) */
24
+ const under = (dir, real) => { const r = path.relative(dir, real); return r === '' || (r !== '..' && !r.startsWith(`..${path.sep}`) && !path.isAbsolute(r)); };
25
+ const within = (real) => under(realRoot, real);
26
+ /**
27
+ * Whether the path `at` (absolute) lies in the repo once every symlink on its way is followed. A path that is not
28
+ * there is judged by the nearest folder on its way that is, with the rest as written (a `..` included): nothing can
29
+ * be read from it.
30
+ */
31
+ const insideAbs = (at) => {
32
+ if (at.includes('\0')) return false;
33
+ let rest = '';
34
+ for (;;) {
35
+ try { return within(path.resolve(realpath(at), rest)); } catch { /* not there, or a link loop: try its folder */ }
36
+ const up = path.dirname(at);
37
+ if (up === at) return false;
38
+ rest = path.join(path.basename(at), rest);
39
+ at = up;
40
+ }
41
+ };
42
+ const inside = (rel) => insideAbs(abs(String(rel)));
43
+ // The readers below are the one place a path is held to the repo: whatever a deriver is told to read, and whatever a
44
+ // symlink points at, a file whose real path is outside is not there (`read` throws, `exists` and `isDir` say no,
45
+ // `list` is empty). A folder's verdict is kept for the reader's life, so a plain file costs one `lstat`, not a
46
+ // `realpath` walk of its whole way; only a symlink is resolved each time. A file `walk` returned was judged by its
47
+ // real path there, and is read without a second look. Both are kept for the reader's life: make a reader per run, not
48
+ // one that outlives changes to the repo's links.
49
+ const folders = new Map();
50
+ const walked = new Set();
51
+ const pending = []; // what `walk` returned since a read last looked: only a reader of those files pays to list them
52
+ const folderInside = (dir) => {
53
+ let v = folders.get(dir);
54
+ if (v === undefined) { v = insideAbs(dir); folders.set(dir, v); }
55
+ return v;
56
+ };
57
+ // A trailing separator would make `lstat` follow a link it names (`ext/` for `ext`), so a path is looked at without one
58
+ const bare = (p) => { let q = p; while (q.length > 1 && (q.endsWith('/') || q.endsWith(path.sep))) q = q.slice(0, -1); return q; };
59
+ const rootAt = bare(path.join(root));
60
+ /** `null` when there is nothing at `rel`; else whether it is a symlink, whether it lies in the repo, and (not a link) what it is */
61
+ const look = (rel) => {
62
+ const at = bare(abs(rel));
63
+ let st;
64
+ try { st = fs.lstatSync(at); } catch { return null; }
65
+ if (st.isSymbolicLink()) return { link: true, ok: insideAbs(at), st };
66
+ return { link: false, ok: at === rootAt || folderInside(path.dirname(at)), st };
67
+ };
68
+ const outside = (rel) => Object.assign(new Error(`${JSON.stringify(String(rel))} is outside the repo.`), { code: 'EOUTSIDE' });
69
+ const read = (rel) => {
70
+ while (pending.length) for (const f of pending.pop()) walked.add(f);
71
+ if (!walked.has(rel)) {
72
+ const m = look(rel);
73
+ if (m && !m.ok) throw outside(rel);
74
+ }
75
+ return fs.readFileSync(abs(rel), 'utf8').replace(/\r\n/g, '\n');
76
+ };
77
+ const exists = (rel) => { const m = look(rel); return !!m && m.ok && (!m.link || fs.existsSync(abs(rel))); };
78
+ const rawIsDir = (rel) => {
24
79
  try { return fs.statSync(abs(rel)).isDirectory(); } catch { return false; }
25
80
  };
81
+ const isDir = (rel) => { const m = look(rel); return !!m && m.ok && (m.link ? rawIsDir(rel) : m.st.isDirectory()); };
26
82
  const list = (rel) => (isDir(rel) ? fs.readdirSync(abs(rel)).sort() : []);
27
- /** Every file under `rel` that `test` accepts, skipping SKIP_DIRS */
28
- const walk = (rel, test = () => true) => list(rel).flatMap((name) => {
29
- if (SKIP_DIRS.has(name)) return [];
30
- const child = rel && rel !== '.' ? `${rel}/${name}` : name;
31
- return isDir(child) ? walk(child, test) : test(child) ? [child] : [];
32
- });
33
- return { root, read, exists, isDir, list, walk };
83
+ /**
84
+ * Every file under `rel` that `test` accepts, sorted by folder, skipping SKIP_DIRS. A symlink is followed only while
85
+ * 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,
86
+ * and of two links to one other folder the first wins. `onSkip(path, reason)` hears of each link left out: 'outside'
87
+ * (out of the repo, to a folder or to a file `test` accepts), 'walked' (to a folder already walked) or 'missing' (to
88
+ * nothing, or a loop of links, named like a file `test` accepts). Walks that share `seen` (a set of real folders) read
89
+ * each folder once between them, a folder two of them name in the repo's own words in silence. `skipDir(name)` leaves
90
+ * out, beside SKIP_DIRS, each folder (or link to one) it accepts. Only links pay a `realpath`.
91
+ */
92
+ const walk = (rel, test = () => true, onSkip = () => {}, seen = new Set(), skipDir = null) => {
93
+ const start = rel && rel !== '.' ? rel : '';
94
+ let startReal;
95
+ try { startReal = realpath(abs(start)); } catch { return []; }
96
+ if (!within(startReal)) { onSkip(start, 'outside'); return []; }
97
+ const linked = startReal !== path.join(realRoot, start);
98
+ if (seen.has(startReal)) { if (linked) onSkip(start, 'walked'); return []; }
99
+ // `viaLink`: `dir` is reached through a link, so a real folder in it may be one walked by its own name
100
+ const go = (dir, real, viaLink) => {
101
+ seen.add(real);
102
+ let entries;
103
+ try { entries = fs.readdirSync(abs(dir), { withFileTypes: true }); } catch { return []; }
104
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
105
+ return entries.flatMap((e) => {
106
+ if (SKIP_DIRS.has(e.name)) return [];
107
+ const child = dir ? `${dir}/${e.name}` : e.name;
108
+ if (!e.isSymbolicLink()) {
109
+ if (!e.isDirectory()) return test(child) ? [child] : [];
110
+ if (skipDir && skipDir(e.name)) return [];
111
+ const childReal = path.join(real, e.name);
112
+ if (seen.has(childReal)) { if (viaLink) onSkip(child, 'walked'); return []; }
113
+ return go(child, childReal, viaLink);
114
+ }
115
+ let target;
116
+ try { target = realpath(abs(child)); } catch { if (test(child)) onSkip(child, 'missing'); return []; }
117
+ const folder = rawIsDir(child);
118
+ if (folder && skipDir && skipDir(e.name)) return [];
119
+ if (!within(target)) { if (folder || test(child)) onSkip(child, 'outside'); return []; }
120
+ if (!folder) return test(child) ? [child] : [];
121
+ const ownRoute = under(startReal, target) && !path.relative(startReal, target).split(path.sep).some((s) => SKIP_DIRS.has(s) || (skipDir && skipDir(s)));
122
+ if (ownRoute || seen.has(target)) { onSkip(child, 'walked'); return []; }
123
+ return go(child, target, true);
124
+ });
125
+ };
126
+ const found = go(start, startReal, linked);
127
+ pending.push(found.slice()); // a copy: what a caller adds to the list it gets back is not taken for a walked file
128
+ return found;
129
+ };
130
+ return { root, read, exists, isDir, list, walk, inside };
34
131
  }
35
132
 
133
+ /**
134
+ * Whether a path a config names (a file or folder option of a deriver) leaves the repo: it is absolute, climbs out
135
+ * with `..`, or a symlink on its way leads out. `io` is a repo reader (`inside`).
136
+ * @param {{ inside: (rel: string) => boolean }} io
137
+ * @param {unknown} p
138
+ */
139
+ export function leavesRepo(io, p) {
140
+ if (typeof p !== 'string') return false;
141
+ const rel = path.posix.normalize(p.replace(/^\.\/+/, '').replace(/\/+$/, '') || '.');
142
+ return path.isAbsolute(p) || path.win32.isAbsolute(p) || rel === '..' || rel.startsWith('../') || !io.inside(rel);
143
+ }
144
+
145
+ /**
146
+ * The problem `validate` fails on for a config path that leaves the repo, naming the path as written (a JSON string, so
147
+ * nothing in it can break the line) and never where it leads.
148
+ * @param {string} who the deriver's name
149
+ * @param {unknown} p
150
+ */
151
+ export const outsideProblem = (who, p) => `${who}: ${JSON.stringify(p)} is outside the repo; only files and folders of the repo are read.`;
152
+
153
+ /**
154
+ * For `missingPaths`: whether a path `repoPaths` does not list is in the repo all the same, because a symlink on its way
155
+ * stays in the repo (`repoPaths` does not follow links; the walk does, and makes nodes at such paths). The path must be
156
+ * written plainly (relative, no empty, `.` or `..` segment, no folder the walks skip), a symlink must be on its way (so a
157
+ * repo without one is checked exactly as `repoPaths` says), and `exists` holds it to its real path.
158
+ * @param {{ root: string, exists: (rel: string) => boolean }} io a repo reader
159
+ * @returns {(p: string) => boolean}
160
+ */
161
+ export const reachable = (io) => (p) => {
162
+ if (typeof p !== 'string' || p === '' || p.includes('\0') || path.posix.isAbsolute(p) || path.win32.isAbsolute(p)) return false;
163
+ const segments = p.split('/');
164
+ if (segments.some((s) => s === '' || s === '.' || s === '..' || SKIP_DIRS.has(s))) return false;
165
+ if (!io.exists(p)) return false; // first, so a path that is not there costs one look
166
+ for (let i = 1; i <= segments.length; i++) {
167
+ try { if (fs.lstatSync(path.join(io.root, ...segments.slice(0, i))).isSymbolicLink()) return true; } catch { return false; }
168
+ }
169
+ return false;
170
+ };
171
+
36
172
  /**
37
173
  * Every file and folder path under the root (relative, forward slashes), for checking the paths a map cites.
38
174
  * @param {string} root
package/core/sync.js CHANGED
@@ -75,11 +75,12 @@ const CITED_PATH = /(?:^|[\s(`'"[])((?:[\w@.-]+\/)+[\w@-]+\.(?:json|js|ts|mjs|md
75
75
  * (`lib/outbox.ts`), so it counts when it is a path suffix of anything in the repo.
76
76
  * @param {{ nodes: any[], edges: any[] }} topology
77
77
  * @param {Set<string>} paths every path in the repo (core/repo.js `repoPaths`)
78
+ * @param {(p: string) => boolean} [reach] whether a path `paths` does not list is still in the repo, by a symlink that stays in it (core/repo.js `reachable`)
78
79
  * @returns {string[]}
79
80
  */
80
- export function missingPaths(topology, paths) {
81
+ export function missingPaths(topology, paths, reach = () => false) {
81
82
  const all = [...paths];
82
- const exists = (p) => paths.has(p) || all.some((q) => q.endsWith(`/${p}`));
83
+ const exists = (p) => paths.has(p) || all.some((q) => q.endsWith(`/${p}`)) || reach(p);
83
84
  const found = [];
84
85
  const check = (where, text) => {
85
86
  for (const m of String(text || '').matchAll(CITED_PATH)) {
@@ -89,7 +90,7 @@ export function missingPaths(topology, paths) {
89
90
  };
90
91
  for (const n of topology.nodes) {
91
92
  for (const f of String(n.file || '').split(/,\s*/).filter(Boolean)) {
92
- if (!paths.has(f)) found.push(`Node "${n.id}" has file "${f}", which is not in the repo`);
93
+ if (!paths.has(f) && !reach(f)) found.push(`Node "${n.id}" has file "${f}", which is not in the repo`);
93
94
  }
94
95
  check(`Node "${n.id}" description`, n.desc);
95
96
  check(`Node "${n.id}" summary`, n.summary);
package/core/validate.js CHANGED
@@ -22,7 +22,7 @@ import { PERSONAS_FILE, validatePersonas } from './personas.js';
22
22
  import { CLOUD_FILE, cloudNodeProblems } from './cloud.js';
23
23
  import { deriveTopology } from './derive.js';
24
24
  import { missingPaths, planSync } from './sync.js';
25
- import { repoPaths, repoReader } from './repo.js';
25
+ import { reachable, repoPaths, repoReader } from './repo.js';
26
26
  import { checkThemeContrast } from './contrast.js';
27
27
  import { layerTokenWarnings, mapTokenWarnings, nodeColorNotes, nodeColorWarnings, quoted } from './map-tokens.js';
28
28
  import { layersMapWarnings } from './layers.js';
@@ -214,11 +214,11 @@ export function validateProposalFiles(topology, dir, root = path.dirname(dir)) {
214
214
  * @returns {string[]}
215
215
  */
216
216
  export function validatePersonasFile(root, roles = null) {
217
- const file = path.join(root, PERSONAS_FILE);
218
- if (!fs.existsSync(file)) return [];
217
+ const io = repoReader(root); // a file that leads out of the repo is not there, as for the personas deriver
218
+ if (!io.exists(PERSONAS_FILE)) return [];
219
219
  let parsed;
220
220
  try {
221
- parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
221
+ parsed = JSON.parse(io.read(PERSONAS_FILE));
222
222
  } catch (err) {
223
223
  return [`${PERSONAS_FILE} is not valid JSON: ${err.message}`];
224
224
  }
@@ -232,11 +232,11 @@ export function validatePersonasFile(root, roles = null) {
232
232
  * @returns {string[]}
233
233
  */
234
234
  export function validateCloudNodes(topology, root) {
235
- const file = path.join(root, CLOUD_FILE);
235
+ const io = repoReader(root); // a file that leads out of the repo is not there, as for the cloud deriver
236
236
  let parsed = null;
237
- if (fs.existsSync(file)) {
237
+ if (io.exists(CLOUD_FILE)) {
238
238
  try {
239
- parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
239
+ parsed = JSON.parse(io.read(CLOUD_FILE));
240
240
  } catch (err) {
241
241
  return [`${CLOUD_FILE} is not valid JSON: ${err.message}`];
242
242
  }
@@ -260,7 +260,7 @@ export async function validateRepo({ config, derivers, topology = readTopology(c
260
260
  if (!topology) return { errors: [`${config.topology} is missing: run cornfield sync to make it.`], warnings: [], derived: null, notes: [] };
261
261
  const errors = validateTopology(topology);
262
262
  try {
263
- errors.push(...missingPaths(topology, repoPaths(config.root)));
263
+ errors.push(...missingPaths(topology, repoPaths(config.root), reachable(repoReader(config.root))));
264
264
  } catch (err) {
265
265
  errors.push(`Checking the paths the map cites failed: ${err.message}`);
266
266
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.51.5",
3
+ "version": "0.51.7",
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)",
@@ -31,6 +31,7 @@
31
31
 
32
32
  import { CLOUD_FILE, deriveCloud, EVIDENCE_KINDS } from '../../core/cloud.js';
33
33
  import { hostsIn } from './hosts.js';
34
+ import { leavesRepo, outsideProblem } from '../../core/repo.js';
34
35
  import { caddyEvidence, dockerfileSources, imageRef, workflowSources } from './sources.js';
35
36
 
36
37
  const WORKFLOW_DIRS = ['.github/workflows', '.forgejo/workflows'];
@@ -75,6 +76,7 @@ export default {
75
76
  const known = [...ctx.nodes, ...((ctx.map && ctx.map.nodes) || []).filter((n) => !ctx.nodes.some((d) => d.id === n.id))];
76
77
  const evidence = [];
77
78
  const warnings = [];
79
+ const problems = [];
78
80
  const nodes = [];
79
81
  const edges = [];
80
82
  const add = (piece) => evidence.push(piece);
@@ -89,7 +91,7 @@ export default {
89
91
  };
90
92
 
91
93
  // Hosts in code and pages
92
- const roots = Array.isArray(options.code) ? options.code
94
+ const roots = Array.isArray(options.code) ? options.code.filter((dir) => !(leavesRepo(ctx, dir) && problems.push(outsideProblem('cloud', dir))))
93
95
  : (ctx.info.starter?.packages || []).map((p) => p.dir);
94
96
  const files = [...new Set(roots.flatMap((dir) => ctx.walk(dir === '.' ? '' : dir, (f) => (CODE_FILE.test(f) || PAGE_FILE.test(f)) && !NOT_SHIPPED.test(f))))].sort();
95
97
  for (const file of files) {
@@ -123,7 +125,12 @@ export default {
123
125
  }
124
126
 
125
127
  // CI workflows
126
- const workflowFiles = WORKFLOW_DIRS.flatMap((dir) => ctx.list(dir).filter((f) => /\.ya?ml$/.test(f)).map((f) => `${dir}/${f}`));
128
+ // A workflow file that is a link out of the repo, or to nothing, is not read (core/repo.js): said, and left out
129
+ const workflowFiles = WORKFLOW_DIRS.flatMap((dir) => ctx.list(dir).filter((f) => /\.ya?ml$/.test(f)).map((f) => `${dir}/${f}`)).filter((file) => {
130
+ if (ctx.exists(file)) return true;
131
+ warnings.push(`cloud: ${file} ${ctx.inside(file) ? 'is a link to nothing' : 'is a link to somewhere outside the repo'}; it is not read.`);
132
+ return false;
133
+ });
127
134
  if (workflowFiles.length) {
128
135
  const yaml = await loadYaml();
129
136
  if (!yaml) warnings.push(`cloud: ${workflowFiles.length} CI workflow file(s) not read: install the optional dependency js-yaml to draw what CI pulls.`);
@@ -145,6 +152,7 @@ export default {
145
152
 
146
153
  // Caddyfiles the config names
147
154
  for (const { file, from } of options.caddyfiles || []) {
155
+ if (leavesRepo(ctx, file)) { problems.push(outsideProblem('cloud', file)); continue; }
148
156
  if (!ctx.exists(file)) { warnings.push(`cloud: caddyfile ${file} does not exist.`); continue; }
149
157
  for (const e of caddyEvidence(ctx.read(file))) add({ ...e, from, when: 'renew', file });
150
158
  }
@@ -152,7 +160,7 @@ export default {
152
160
  if (!ctx.exists(CLOUD_FILE)) {
153
161
  const hosts = new Set(evidence.filter((e) => e.match.kind === 'host').map((e) => e.match.value));
154
162
  if (evidence.length) warnings.push(`cloud: the code reaches ${hosts.size} outside host(s) and ${evidence.length - [...evidence].filter((e) => e.match.kind === 'host').length} other outside source(s); add ${CLOUD_FILE} to draw them (docs/cloud.md).`);
155
- return { nodes: [], edges: [], warnings, evidence: [] };
163
+ return { nodes: [], edges: [], warnings, problems, evidence: [] };
156
164
  }
157
165
  // What the derivers before this one found (a repo's own deriver may add `lib`, `route`, `env` … evidence)
158
166
  const all = [...(ctx.evidence || []), ...evidence];
@@ -170,6 +178,7 @@ export default {
170
178
  nodes: [...nodes, ...cloud.nodes],
171
179
  edges: [...edges, ...cloud.edges],
172
180
  warnings: [...warnings, ...cloud.warnings],
181
+ problems,
173
182
  ownedIds: [...nodes.map((n) => n.id), ...cloud.ownedIds],
174
183
  evidence,
175
184
  info: { unknownPlans: cloud.unknown },
@@ -35,6 +35,7 @@
35
35
  */
36
36
 
37
37
  import { caddyRoutes, labelsOf, traefikRoutes } from './routes.js';
38
+ import { leavesRepo, outsideProblem } from '../../core/repo.js';
38
39
 
39
40
  export const COMPOSE_NAMES = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml'];
40
41
  const CADDYFILE = /(?:^|\/)(?:Caddyfile|[\w.-]+\.caddyfile)$/i;
@@ -86,10 +87,11 @@ const targetPort = (p) => {
86
87
  };
87
88
 
88
89
  /** The compose files: the config's, else the first compose name in each folder */
89
- function composeFiles(ctx, options) {
90
+ function composeFiles(ctx, options, problems) {
90
91
  if (Array.isArray(options.files)) {
91
- for (const f of options.files) if (!ctx.exists(f)) throw new Error(`compose file ${f} does not exist.`);
92
- return [...options.files];
92
+ const named = options.files.filter((f) => !(leavesRepo(ctx, f) && problems.push(outsideProblem('compose', f))));
93
+ for (const f of named) if (!ctx.exists(f)) throw new Error(`compose file ${f} does not exist.`);
94
+ return named;
93
95
  }
94
96
  const found = ctx.walk('', (f) => COMPOSE_NAMES.includes(f.slice(f.lastIndexOf('/') + 1)));
95
97
  const byDir = new Map();
@@ -109,9 +111,10 @@ const compose = {
109
111
  async derive(ctx) {
110
112
  const options = ctx.options || {};
111
113
  const parent = options.parent || 'root';
112
- const files = composeFiles(ctx, options);
114
+ const problems = [];
115
+ const files = composeFiles(ctx, options, problems);
113
116
  const warnings = [];
114
- if (!files.length) return { nodes: [], edges: [], warnings, info: { stacks: [] } };
117
+ if (!files.length) return { nodes: [], edges: [], warnings, problems, info: { stacks: [] } };
115
118
  const yaml = await loadYaml();
116
119
  if (!yaml) throw new Error(`${files.length} compose file(s) and no YAML reader: install the optional dependency js-yaml (npm install js-yaml).`);
117
120
 
@@ -170,6 +173,7 @@ const compose = {
170
173
  const caddyfiles = Array.isArray(options.caddyfiles) ? options.caddyfiles : ctx.walk('', (f) => CADDYFILE.test(f));
171
174
  const outside = new Set();
172
175
  for (const file of caddyfiles) {
176
+ if (leavesRepo(ctx, file)) { problems.push(outsideProblem('compose', file)); continue; }
173
177
  if (!ctx.exists(file)) { warnings.push(`compose: caddyfile ${file} does not exist.`); continue; }
174
178
  const here = dirOf(file);
175
179
  for (const r of caddyRoutes(ctx.read(file))) {
@@ -217,7 +221,7 @@ const compose = {
217
221
  }
218
222
 
219
223
  return {
220
- nodes, edges, warnings, ownedIds,
224
+ nodes, edges, warnings, problems, ownedIds,
221
225
  info: { stacks: stacks.map((s) => ({ id: s.id, name: s.name, dir: s.dir, file: s.file, containers: s.services.map((x) => containerId(s, x)) })) },
222
226
  };
223
227
  },
@@ -18,23 +18,37 @@
18
18
 
19
19
  import path from 'node:path';
20
20
  import { markdownLinks, renderMarkdown } from './markdown.js';
21
+ import { leavesRepo, outsideProblem } from '../../core/repo.js';
21
22
 
22
23
  export const DEFAULT_PATHS = ['README.md', 'docs'];
23
24
 
24
25
  const isMarkdown = (f) => /\.md$/i.test(f);
25
26
  const isReadme = (f) => /^readme\.md$/i.test(path.posix.basename(f));
26
27
 
28
+ /** What a docs warning says of a link the walk leaves out (core/repo.js `walk`) */
29
+ 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' };
30
+
31
+ /** The files the site writes itself: a doc's page may not land on one (see `docOutputs`) */
32
+ export const SITE_OUTPUTS = ['map.html', 'site.css', '.cornfield-site'];
33
+
27
34
  /**
28
- * The Markdown files the paths name, sorted, each once.
29
- * @param {{ exists: Function, isDir: Function, walk: Function }} io
35
+ * The Markdown files the paths name, sorted, each once. A path that leaves the repo (`..`, an absolute path, a
36
+ * symlink to somewhere else), and a file or folder under one that does, is left out and said by `refuse`.
37
+ * @param {{ exists: Function, isDir: Function, walk: Function, inside?: Function }} io
30
38
  * @param {string[]} paths
39
+ * @param {(message: string, severity: 'problem' | 'warning') => void} [refuse]
31
40
  */
32
- export function docFiles(io, paths) {
41
+ export function docFiles(io, paths, refuse = () => {}) {
33
42
  const out = new Set();
43
+ const inside = io.inside || (() => true);
44
+ const seen = new Set(); // the real folders read so far: two paths that reach one folder read it once
45
+ const told = new Set();
34
46
  for (const p of paths) {
35
- const rel = p.replace(/^\.\/+/, '').replace(/\/+$/, '');
36
- if (io.isDir(rel)) io.walk(rel, isMarkdown).forEach((f) => out.add(f));
37
- else if (isMarkdown(rel) && io.exists(rel)) out.add(rel);
47
+ const rel = path.posix.normalize(p.replace(/^\.\/+/, '').replace(/\/+$/, '') || '.');
48
+ if (leavesRepo({ inside }, p)) { refuse(outsideProblem('docs', p), 'problem'); continue; }
49
+ if (io.isDir(rel)) {
50
+ 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));
51
+ } else if (isMarkdown(rel) && io.exists(rel)) out.add(rel);
38
52
  }
39
53
  return [...out].sort();
40
54
  }
@@ -54,6 +68,31 @@ export function docOutput(file) {
54
68
  return route.endsWith('/') ? `${route.slice(1)}index.html` : `${route.slice(1)}.html`;
55
69
  }
56
70
 
71
+ /**
72
+ * Where each doc lands, by file. A doc whose page would land on a file the site writes itself (`map.md` → `map.html`),
73
+ * or on another doc's page (`index.md` beside a README), goes to the next free `-doc` name (`map-doc.html`), so no
74
+ * page is written over; `renamed` lists `[file, output, other]` for each. A README keeps the folder's `index.html`,
75
+ * and the first of two docs keeps its name. A doc with no clash keeps `docOutput(file)`.
76
+ * @param {string[]} files
77
+ */
78
+ export function docOutputs(files) {
79
+ const taken = new Map(SITE_OUTPUTS.map((o) => [o, null]));
80
+ const outputs = new Map();
81
+ const renamed = [];
82
+ for (const file of [...files].sort((a, b) => Number(isReadme(b)) - Number(isReadme(a)))) {
83
+ let out = docOutput(file);
84
+ if (taken.has(out)) {
85
+ const other = taken.get(out);
86
+ const stem = out.replace(/\.html$/, '');
87
+ for (let n = 1; taken.has(out); n++) out = `${stem}-doc${n > 1 ? `-${n}` : ''}.html`;
88
+ renamed.push([file, out, other]);
89
+ }
90
+ taken.set(out, file);
91
+ outputs.set(file, out);
92
+ }
93
+ return { outputs, renamed };
94
+ }
95
+
57
96
  /** The page node id of a doc: `page-doc-` and its path, in kebab case */
58
97
  export const docPageId = (file) => `page-doc-${file.replace(/\.md$/i, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`;
59
98
 
@@ -84,13 +123,18 @@ export default {
84
123
  derive(ctx) {
85
124
  const { paths = DEFAULT_PATHS, app: appId = 'app-docs', label = 'docs', parent = 'root' } = ctx.options || {};
86
125
  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
126
  const warnings = [];
92
127
  const problems = [];
93
- const nodes = [{ id: appId, type: 'app', label, file: paths.map((p) => p.replace(/^\.\/+/, '').replace(/\/+$/, '')).find((p) => ctx.exists(p)) }];
128
+ const refuse = (message, severity) => (severity === 'problem' ? problems : warnings).push(message);
129
+ const files = docFiles(ctx, paths, refuse);
130
+ const empty = { nodes: [], edges: [], info: { pages: [] } };
131
+ if (!files.length) return { ...empty, warnings: [...warnings, ...(ctx.options?.paths ? [`docs: no Markdown in ${paths.join(', ')}.`] : [])], problems };
132
+
133
+ // Two docs that would be one page id are a problem (below); only the first is placed, and only its name can clash
134
+ const ids = new Set();
135
+ const { outputs, renamed } = docOutputs(files.filter((f) => !ids.has(docPageId(f)) && ids.add(docPageId(f))));
136
+ 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}.`);
137
+ const nodes = [{ id: appId, type: 'app', label, file: paths.map((p) => p.replace(/^\.\/+/, '').replace(/\/+$/, '')).find((p) => ctx.exists(p) && ctx.inside(p)) }];
94
138
  const edges = [];
95
139
  if (ctx.nodes.some((n) => n.id === parent)) edges.push({ from: parent, to: appId });
96
140
 
@@ -102,7 +146,7 @@ export default {
102
146
  if (clash) { problems.push(`docs: ${file} and ${clash.file} would both be page "${id}"; rename one.`); continue; }
103
147
  const text = ctx.read(file);
104
148
  const { title, headings } = renderMarkdown(text);
105
- const page = { id, file, route: docRoute(file), output: docOutput(file), title: title || path.posix.basename(file, '.md'), anchors: headings.map((h) => h.id), text };
149
+ 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
150
  pages.push(page);
107
151
  byFile.set(file, page);
108
152
  nodes.push({ id, type: 'page', label: page.route, file, summary: page.title });
@@ -126,6 +170,7 @@ export default {
126
170
  if (t.external) continue;
127
171
  if (t.outside) { warnings.push(`docs: ${page.file} links to "${href}", outside the repo.`); continue; }
128
172
  const target = t.path === '' ? page.file : t.path;
173
+ if (!ctx.inside(target)) { warnings.push(`docs: ${page.file} links to "${href}", which leads outside the repo.`); continue; }
129
174
  if (!ctx.exists(target)) { problems.push(`docs: ${page.file} links to "${href}", but ${target} is not in the repo.`); continue; }
130
175
  const readme = ctx.isDir(target) ? files.find((f) => path.posix.dirname(f) === target && isReadme(f)) : null;
131
176
  const doc = byFile.get(readme || target);
@@ -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 = '.cornfield-site';
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
- const read = (rel) => fs.readFileSync(path.join(root, rel), 'utf8');
222
- const exists = (rel) => fs.existsSync(path.join(root, rel));
223
- const isDir = (rel) => { try { return fs.statSync(path.join(root, rel)).isDirectory(); } catch { return false; } };
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: Object.keys(files).sort(), warnings: derived.warnings, problems: derived.problems };
248
+ return { pages: pages.length, files: written.sort(), warnings: derived.warnings, problems };
236
249
  }
237
250
 
238
251
  const SITE_CSS = `:root {
@@ -25,6 +25,8 @@
25
25
  * hand-written page under that app is removed. YAML needs the optional dependency js-yaml.
26
26
  */
27
27
 
28
+ import { leavesRepo, outsideProblem } from '../../core/repo.js';
29
+
28
30
  const SPEC_FILE = /(?:^|\/)(?:openapi|swagger|[\w.-]+\.openapi|opencollection)\.(?:json|ya?ml)$/i;
29
31
  const METHOD_ORDER = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE'];
30
32
  export const DEFAULT_APP = 'app-api';
@@ -127,9 +129,10 @@ export function specKind(doc) {
127
129
  }
128
130
 
129
131
  /** The specs to read: `[{ file, app, prefix }]` */
130
- function specsOf(ctx, options, warnings) {
131
- if (Array.isArray(options.specs)) return options.specs.map((s) => ({ app: DEFAULT_APP, ...s }));
132
- if (typeof options.file === 'string') return [{ file: options.file, app: options.app || DEFAULT_APP, prefix: options.prefix }];
132
+ function specsOf(ctx, options, warnings, problems) {
133
+ const inRepo = (s) => !(leavesRepo(ctx, s.file) && problems.push(outsideProblem('openapi', s.file)));
134
+ if (Array.isArray(options.specs)) return options.specs.map((s) => ({ app: DEFAULT_APP, ...s })).filter(inRepo);
135
+ if (typeof options.file === 'string') return [{ file: options.file, app: options.app || DEFAULT_APP, prefix: options.prefix }].filter(inRepo);
133
136
  const found = ctx.walk('', (f) => SPEC_FILE.test(f));
134
137
  if (found.length > 1) {
135
138
  warnings.push(`openapi: ${found.length} API description files (${found.join(', ')}); name the ones to draw: { use: 'openapi', options: { specs: [{ file, app }] } }.`);
@@ -145,7 +148,8 @@ const openapi = {
145
148
  async derive(ctx) {
146
149
  const options = ctx.options || {};
147
150
  const warnings = [];
148
- const specs = specsOf(ctx, options, warnings);
151
+ const problems = [];
152
+ const specs = specsOf(ctx, options, warnings, problems);
149
153
  const nodes = [];
150
154
  const edges = [];
151
155
  const ownedIds = [];
@@ -191,7 +195,7 @@ const openapi = {
191
195
  }
192
196
  if (!endpoints.length) warnings.push(`openapi: ${spec.file} describes no endpoints.`);
193
197
  }
194
- return { nodes, edges, warnings, ownedIds, pageOwners, info: { specs: specs.map((s) => ({ file: s.file, app: s.app })) } };
198
+ return { nodes, edges, warnings, problems, ownedIds, pageOwners, info: { specs: specs.map((s) => ({ file: s.file, app: s.app })) } };
195
199
  },
196
200
  };
197
201
 
@@ -35,6 +35,7 @@
35
35
  */
36
36
 
37
37
  import { LANGUAGES, TEST_FILES, docSummary, expandMembers, goImports, goManifest, goWorkDirs, manifestLanguage, pyName, pythonImports, pythonManifest, rustManifest, rustName, rustUses } from './languages.js';
38
+ import { leavesRepo, outsideProblem } from '../../core/repo.js';
38
39
 
39
40
  const DEFAULT_EXTENSIONS = LANGUAGES.js.extensions;
40
41
  const TEST_DIRS = new Set(['test', 'tests', '__tests__', '__fixtures__', 'fixtures']);
@@ -105,17 +106,10 @@ const readJson = (io, rel) => {
105
106
  };
106
107
  const join = (dir, name) => (dir ? `${dir}/${name}` : name);
107
108
 
108
- /** Every file under `dir` that `test` accepts, not going into the folders `prune` names */
109
- function walkPruned(io, dir, prune, test) {
110
- if (!prune.length) return io.walk(dir, test);
111
- const skip = new Set(prune);
112
- return io.list(dir).flatMap((name) => {
113
- const child = join(dir, name);
114
- if (!io.isDir(child)) return test(child) ? [child] : [];
115
- if (skip.has(name) || name.endsWith('.egg-info')) return [];
116
- return walkPruned(io, child, prune, test);
117
- }).filter((f) => !f.split('/').some((s) => s === 'node_modules' || s === '.git'));
118
- }
109
+ /** Every file under `dir` that `test` accepts, not going into the folders `prune` names: the repo's own walk, so a symlink out of the repo or a loop of links is not followed */
110
+ const walkPruned = (io, dir, prune, test) => (prune.length
111
+ ? io.walk(dir, test, undefined, undefined, (name) => prune.includes(name) || name.endsWith('.egg-info'))
112
+ : io.walk(dir, test));
119
113
 
120
114
  /** The language most of a folder's source files are in (JavaScript when there are none) */
121
115
  function languageOf(io, dir) {
@@ -178,10 +172,13 @@ function uvMembers(io) {
178
172
  }
179
173
 
180
174
  /** The repo's packages: `[{ dir, lang, name, summary, manifest, deps }]` */
181
- function findPackages(io, options) {
175
+ function findPackages(io, options, problems) {
182
176
  const rootManifest = readJson(io, 'package.json') || {};
183
177
  const ws = Array.isArray(rootManifest.workspaces) ? rootManifest.workspaces : rootManifest.workspaces?.packages;
184
- if (Array.isArray(options.packages)) return expandPatterns(options.packages, io).map((dir) => packageAt(io, dir, languageOf(io, dir)));
178
+ if (Array.isArray(options.packages)) {
179
+ const named = options.packages.filter((p) => !(leavesRepo(io, String(p).replace(/\\/g, '/').replace(/\/\*$/, '')) && problems.push(outsideProblem('starter', p))));
180
+ return expandPatterns(named, io).map((dir) => packageAt(io, dir, languageOf(io, dir)));
181
+ }
185
182
  const others = otherPackages(io);
186
183
  let js = [];
187
184
  if (Array.isArray(ws) && ws.length) js = expandPatterns(ws, io);
@@ -248,7 +245,8 @@ const starter = {
248
245
  const isTest = (f, lang) => (TEST_FILES[lang] || TEST_FILES.js).test(f) || TEST_FILES.js.test(f) || f.split('/').some((s) => TEST_DIRS.has(s));
249
246
  const isSourceOf = (lang) => (f) => extOf(lang).some((e) => f.endsWith(e)) && (options.tests || !isTest(f, lang));
250
247
  const rootManifest = readJson(ctx, 'package.json') || {};
251
- const packages = findPackages(ctx, options);
248
+ const problems = [];
249
+ const packages = findPackages(ctx, options, problems);
252
250
  const nodes = [{ id: 'root', label: rootManifest.name || ctx.config?.title || 'repo', type: 'root', ...(ctx.exists('package.json') ? { file: 'package.json' } : {}) }];
253
251
  const edges = [];
254
252
  const warnings = [];
@@ -363,7 +361,7 @@ const starter = {
363
361
  edges.push({ from: moduleId(a), to: moduleId(b), dashed: true, label: 'imports' });
364
362
  }
365
363
  if (!packages.length) warnings.push('starter: no packages found (no npm workspaces, Go modules, Rust crates or Python packages, and no top-level folder with source files). Set derivers: [{ use: "starter", options: { packages: ["src"] } }].');
366
- return { nodes, edges, warnings, info: { packages: packages.map((p) => ({ id: pid(p.dir), dir: p.dir, name: p.name, language: p.lang })) } };
364
+ return { nodes, edges, warnings, problems, info: { packages: packages.map((p) => ({ id: pid(p.dir), dir: p.dir, name: p.name, language: p.lang })) } };
367
365
  },
368
366
  };
369
367
 
@@ -33,6 +33,7 @@
33
33
  */
34
34
 
35
35
  import { slug } from '../compose/index.js';
36
+ import { leavesRepo, outsideProblem } from '../../core/repo.js';
36
37
 
37
38
  export const WORLD_FILE = 'stacks/world.json';
38
39
  const FILE_KEYS = ['version', 'hosts', 'runs'];
@@ -63,6 +64,7 @@ const world = {
63
64
  const options = ctx.options || {};
64
65
  const file = options.file || WORLD_FILE;
65
66
  const parent = options.parent || 'root';
67
+ if (leavesRepo(ctx, file)) return { nodes: [], edges: [], warnings: [], problems: [outsideProblem('world', file)], info: { machines: [] } };
66
68
  if (!ctx.exists(file)) return { nodes: [], edges: [], warnings: [], problems: [], info: { machines: [] } };
67
69
 
68
70
  let doc;