cornfield 0.51.6 → 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,15 @@ 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, 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, 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)
81
82
  * @property {(rel: string) => boolean} inside whether a path is in the repo once its symlinks are followed
82
83
  */
83
84
 
@@ -295,7 +296,7 @@ export async function runDeriver(deriver, { root, files, options = {}, config =
295
296
  topology,
296
297
  changes,
297
298
  schemaProblems: validateTopology(topology),
298
- 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))),
299
300
  validateProblems,
300
301
  driftProblems,
301
302
  unowned,
package/core/repo.js CHANGED
@@ -18,45 +18,81 @@ 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) => {
24
- try { return fs.statSync(abs(rel)).isDirectory(); } catch { return false; }
25
- };
26
- const list = (rel) => (isDir(rel) ? fs.readdirSync(abs(rel)).sort() : []);
27
- const realRoot = (() => { try { return fs.realpathSync(root); } catch { return path.resolve(root); } })();
21
+ const realpath = fs.realpathSync.native;
22
+ const realRoot = (() => { try { return realpath(root); } catch { return path.resolve(root); } })();
28
23
  /** Whether real path `real` is `dir` or under it (by whole segments: `/x/repo-other` is not under `/x/repo`) */
29
24
  const under = (dir, real) => { const r = path.relative(dir, real); return r === '' || (r !== '..' && !r.startsWith(`..${path.sep}`) && !path.isAbsolute(r)); };
30
25
  const within = (real) => under(realRoot, real);
31
26
  /**
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.
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.
34
30
  */
35
- const inside = (rel) => {
36
- if (String(rel).includes('\0')) return false;
37
- let at = abs(rel);
31
+ const insideAbs = (at) => {
32
+ if (at.includes('\0')) return false;
38
33
  let rest = '';
39
34
  for (;;) {
40
- try { return within(path.resolve(fs.realpathSync(at), rest)); } catch { /* not there, or a link loop: try its folder */ }
35
+ try { return within(path.resolve(realpath(at), rest)); } catch { /* not there, or a link loop: try its folder */ }
41
36
  const up = path.dirname(at);
42
37
  if (up === at) return false;
43
38
  rest = path.join(path.basename(at), rest);
44
39
  at = up;
45
40
  }
46
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) => {
79
+ try { return fs.statSync(abs(rel)).isDirectory(); } catch { return false; }
80
+ };
81
+ const isDir = (rel) => { const m = look(rel); return !!m && m.ok && (m.link ? rawIsDir(rel) : m.st.isDirectory()); };
82
+ const list = (rel) => (isDir(rel) ? fs.readdirSync(abs(rel)).sort() : []);
47
83
  /**
48
84
  * Every file under `rel` that `test` accepts, sorted by folder, skipping SKIP_DIRS. A symlink is followed only while
49
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,
50
86
  * and of two links to one other folder the first wins. `onSkip(path, reason)` hears of each link left out: 'outside'
51
87
  * (out of the repo, to a folder or to a file `test` accepts), 'walked' (to a folder already walked) or 'missing' (to
52
88
  * 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`.
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`.
55
91
  */
56
- const walk = (rel, test = () => true, onSkip = () => {}, seen = new Set()) => {
92
+ const walk = (rel, test = () => true, onSkip = () => {}, seen = new Set(), skipDir = null) => {
57
93
  const start = rel && rel !== '.' ? rel : '';
58
94
  let startReal;
59
- try { startReal = fs.realpathSync(abs(start)); } catch { return []; }
95
+ try { startReal = realpath(abs(start)); } catch { return []; }
60
96
  if (!within(startReal)) { onSkip(start, 'outside'); return []; }
61
97
  const linked = startReal !== path.join(realRoot, start);
62
98
  if (seen.has(startReal)) { if (linked) onSkip(start, 'walked'); return []; }
@@ -71,25 +107,68 @@ export function repoReader(root) {
71
107
  const child = dir ? `${dir}/${e.name}` : e.name;
72
108
  if (!e.isSymbolicLink()) {
73
109
  if (!e.isDirectory()) return test(child) ? [child] : [];
110
+ if (skipDir && skipDir(e.name)) return [];
74
111
  const childReal = path.join(real, e.name);
75
112
  if (seen.has(childReal)) { if (viaLink) onSkip(child, 'walked'); return []; }
76
113
  return go(child, childReal, viaLink);
77
114
  }
78
115
  let target;
79
- try { target = fs.realpathSync(abs(child)); } catch { if (test(child)) onSkip(child, 'missing'); return []; }
80
- const folder = isDir(child);
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 [];
81
119
  if (!within(target)) { if (folder || test(child)) onSkip(child, 'outside'); return []; }
82
120
  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));
121
+ const ownRoute = under(startReal, target) && !path.relative(startReal, target).split(path.sep).some((s) => SKIP_DIRS.has(s) || (skipDir && skipDir(s)));
84
122
  if (ownRoute || seen.has(target)) { onSkip(child, 'walked'); return []; }
85
123
  return go(child, target, true);
86
124
  });
87
125
  };
88
- return go(start, startReal, linked);
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;
89
129
  };
90
130
  return { root, read, exists, isDir, list, walk, inside };
91
131
  }
92
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
+
93
172
  /**
94
173
  * Every file and folder path under the root (relative, forward slashes), for checking the paths a map cites.
95
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.6",
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,6 +18,7 @@
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
 
@@ -44,7 +45,7 @@ export function docFiles(io, paths, refuse = () => {}) {
44
45
  const told = new Set();
45
46
  for (const p of paths) {
46
47
  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 (leavesRepo({ inside }, p)) { refuse(outsideProblem('docs', p), 'problem'); continue; }
48
49
  if (io.isDir(rel)) {
49
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));
50
51
  } else if (isMarkdown(rel) && io.exists(rel)) out.add(rel);
@@ -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;