cornfield 0.12.0 → 0.13.1

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/config.js CHANGED
@@ -17,7 +17,7 @@
17
17
  * port: 3350,
18
18
  * host: '127.0.0.1', // loopback, unless sign-in is configured with an https publicUrl (server/bind.js)
19
19
  * publicUrl: null, // the origin people open it at; sign-in needs it (server/auth.js)
20
- * worktrees: '.claude/worktrees', // a folder of git worktrees whose unpushed proposals are listed too
20
+ * worktrees: '.claude/worktrees', // a folder of git worktrees whose unpushed proposals are listed too; or { dir, maxAgeDays } to leave out worktrees untouched that long (docs/config.md#worktrees)
21
21
  * proposals: 'docs/specs/proposals', // where proposal files live, in the checkout and in each worktree; or { dir, approveLands } (docs/config.md#proposals)
22
22
  * topology: 'topology.json',
23
23
  * personas: { roles: null }, // the roles a persona may have (null: any)
@@ -165,6 +165,9 @@ export const DEFAULTS = Object.freeze({
165
165
  const KEYS = Object.keys(DEFAULTS);
166
166
  /** The keys of `proposals` when it is an object: the folder, and whether an approval also lands the spec PR (opt-in, off unless true) */
167
167
  export const PROPOSALS_KEYS = Object.freeze(['dir', 'approveLands']);
168
+ /** The keys of `worktrees` when it is an object: the folder, and how many days without a change leave a worktree out of the list (default: none is left out) */
169
+ export const WORKTREES_KEYS = Object.freeze(['dir', 'maxAgeDays']);
170
+ const MAX_WORKTREE_AGE_DAYS = 36500;
168
171
  const AGENT_KEYS = ['authors', 'labels', 'branchPrefixes', 'bots', 'transport', 'maxOpen', 'profiles', 'runners', 'quietAfter', 'limits', 'on', 'refuseCollisions'];
169
172
  const PROFILE_NAME = new RegExp(PROFILE_SOURCE);
170
173
  const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -301,8 +304,15 @@ export function configProblems(c) {
301
304
  if (!isObject(c.releaseNotes)) out.push('"releaseNotes" is { breakingLabel }.');
302
305
  else if (c.releaseNotes.breakingLabel !== undefined && (!isText(c.releaseNotes.breakingLabel) || c.releaseNotes.breakingLabel.includes(','))) out.push('releaseNotes.breakingLabel is a label\'s name, like "breaking".');
303
306
  }
304
- for (const key of ['worktrees', 'topology']) {
305
- if (c[key] !== undefined && c[key] !== null && !inRepo(c[key])) out.push(`"${key}" is a folder or file inside the repo, written relative to it.`);
307
+ if (c.topology !== undefined && c.topology !== null && !inRepo(c.topology)) out.push('"topology" is a folder or file inside the repo, written relative to it.');
308
+ // The folder as a string (always so), or { dir?, maxAgeDays? }
309
+ if (c.worktrees !== undefined && c.worktrees !== null) {
310
+ if (isObject(c.worktrees)) {
311
+ for (const k of Object.keys(c.worktrees)) if (!WORKTREES_KEYS.includes(k)) out.push(`worktrees.${k}: the keys are ${WORKTREES_KEYS.join(', ')}.`);
312
+ if (c.worktrees.dir !== undefined && !inRepo(c.worktrees.dir)) out.push('worktrees.dir is the folder of git worktrees, inside the repo and written relative to it.');
313
+ const age = c.worktrees.maxAgeDays;
314
+ if (age !== undefined && !(typeof age === 'number' && Number.isFinite(age) && age > 0 && age <= MAX_WORKTREE_AGE_DAYS)) out.push(`worktrees.maxAgeDays is a number of days above 0 and at most ${MAX_WORKTREE_AGE_DAYS}: a worktree whose newest proposal is older is left out.`);
315
+ } else if (!inRepo(c.worktrees)) out.push('"worktrees" is a folder inside the repo, written relative to it (or { dir, maxAgeDays }).');
306
316
  }
307
317
  // The folder as a string (always so), or { dir?, approveLands? }: the object form is how the folder's options are set
308
318
  if (c.proposals !== undefined && c.proposals !== null) {
@@ -453,6 +463,9 @@ export async function loadConfig(root, { env = process.env, file } = {}) {
453
463
  // `proposals` is the folder to everything downstream, whichever way the file wrote it; the options are read from `approveLands`
454
464
  config.approveLands = isObject(raw.proposals) && raw.proposals.approveLands === true;
455
465
  config.proposals = (isObject(raw.proposals) ? raw.proposals.dir : raw.proposals) ?? DEFAULTS.proposals;
466
+ // `worktrees` is the folder to everything downstream (null: no worktrees are looked at); the age limit is read from `worktreeMaxAgeDays`
467
+ config.worktreeMaxAgeDays = isObject(raw.worktrees) && raw.worktrees.maxAgeDays !== undefined ? raw.worktrees.maxAgeDays : null;
468
+ config.worktrees = isObject(raw.worktrees) ? (raw.worktrees.dir ?? DEFAULTS.worktrees) : config.worktrees;
456
469
  if (env.CORNFIELD_PORT) config.port = Number(env.CORNFIELD_PORT);
457
470
  if (env.PORT && !env.CORNFIELD_PORT) config.port = Number(env.PORT);
458
471
  if (env.CORNFIELD_HOST) config.host = env.CORNFIELD_HOST;
@@ -304,10 +304,12 @@ export function mentionsOf(refs, nodes) {
304
304
  * @returns {{ nodes: object[], unresolved: string[], changed: Set<string>, failing: Set<string>, perMessage: Map<string, { nodes: object[], unresolved: string[] }> }}
305
305
  */
306
306
  export function litForThread(thread, nodes) {
307
- const all = linksOf(thread.messages.map((m) => m.body));
307
+ // A thread that is not there (not loaded, or an answer without one) lights nothing, and never throws
308
+ const messages = thread && Array.isArray(thread.messages) ? thread.messages.filter((m) => m && typeof m.body === 'string') : [];
309
+ const all = linksOf(messages.map((m) => m.body));
308
310
  const got = mentionsOf(all.refs, nodes);
309
311
  const perMessage = new Map();
310
- for (const m of thread.messages) perMessage.set(m.id, messageNodes(m.body, nodes));
312
+ for (const m of messages) perMessage.set(m.id, messageNodes(m.body, nodes));
311
313
  return { nodes: got.nodes, unresolved: got.unresolved, changed: new Set(got.ids), failing: new Set(), perMessage };
312
314
  }
313
315
 
@@ -130,7 +130,8 @@ function freshNotes() {
130
130
 
131
131
  /** The New idea form: whether it is open, one send in flight, and what the last send came to */
132
132
  function freshIdea() {
133
- return { open: false, busy: false, message: '', bad: false, link: null };
133
+ // `opener` is the id of the node whose panel button that opened the form ('' when the bar's own button did), `node` the node it was about
134
+ return { open: false, busy: false, message: '', bad: false, link: null, opener: '', node: null };
134
135
  }
135
136
 
136
137
  let wired = false;
@@ -338,7 +339,7 @@ function relight() {
338
339
  if (ui.runSel) {
339
340
  const run = runById(ui.runSel);
340
341
  state.forgeLit = run ? litOfRun(run) : null;
341
- } else if (ui.threadDetail) {
342
+ } else if (ui.threadDetail && ui.threadDetail.thread) {
342
343
  ui.litThread = litForThread(ui.threadDetail.thread, state.nodes);
343
344
  state.forgeLit = { changed: ui.litThread.changed, failing: ui.litThread.failing };
344
345
  } else if (ui.deployItem) {
@@ -413,6 +414,9 @@ function dropThread() {
413
414
  }
414
415
 
415
416
  /** Selects a thread: asks for its messages (read-only), then lights the nodes they mention */
417
+ /** The thread a successful answer holds, or null (a failure, or an answer without one) */
418
+ const threadOf = (res) => (res && res.ok && res.body && res.body.thread && typeof res.body.thread === 'object' && Array.isArray(res.body.thread.messages) ? res.body.thread : null);
419
+
416
420
  async function selectThread(n) {
417
421
  const token = ++threadToken;
418
422
  pullToken++;
@@ -435,13 +439,15 @@ async function selectThread(n) {
435
439
  paint();
436
440
  const res = await request(threadUrl(n), false);
437
441
  if (token !== threadToken) return;
438
- if (!res.ok) {
439
- ui.threadError = errorWords(res.status, res.body);
442
+ // An answer without a thread in it is a failure too: nothing to show or light
443
+ const thread = threadOf(res);
444
+ if (!thread) {
445
+ ui.threadError = res.ok ? `Thread ${n} could not be read: the answer had no thread in it. Refresh to ask again.` : errorWords(res.status, res.body);
440
446
  announce(ui.threadError);
441
447
  paint();
442
448
  return;
443
449
  }
444
- ui.threadDetail = { thread: res.body.thread, at: res.body.at, rate: res.body.rate || '', stale: res.body.stale || '' };
450
+ ui.threadDetail = { thread, at: res.body.at, rate: res.body.rate || '', stale: res.body.stale || '' };
445
451
  relight();
446
452
  $('forge-panel').querySelector('.hx-forge-body').scrollTop = 0; // the thread's messages are what was asked for, not the row that was tapped
447
453
  announce(threadSelectionWords());
@@ -507,9 +513,45 @@ function threadsFor(nodeId) {
507
513
  /** Opens or closes the form; the focus goes to the title, or back to the button */
508
514
  function toggleIdea(open) {
509
515
  ui.idea.open = open;
510
- if (open) ui.idea.message = '';
516
+ if (open) { ui.idea.message = ''; ui.idea.opener = ''; ui.idea.node = null; }
511
517
  paintIdea();
512
- if (open) $('idea-title').focus(); else $('idea-open').focus();
518
+ if (open) $('idea-title').focus(); else focusIdeaOpener();
519
+ }
520
+
521
+ /** Puts the focus back on what opened the form: the node panel's button while it is still there, else the New idea button */
522
+ function focusIdeaOpener() {
523
+ const from = ui.idea.opener ? [...document.querySelectorAll('[data-thread-start]')].find((b) => b.dataset.threadStart === ui.idea.opener) : null;
524
+ (from && !from.closest('[inert]') ? from : $('idea-open')).focus();
525
+ }
526
+
527
+ /** A node id that reads back as one mention: no brackets or line breaks, as core/mentions.js parses them */
528
+ const MENTIONABLE = /^[^[\]\r\n]{1,200}$/;
529
+
530
+ /** "Start a thread about this" (a node's panel): the New idea form, with the node's label as the title and its mention in the text */
531
+ function startThread(node) {
532
+ if (!node || ui.idea.busy || !ui.config || ui.config.threads === false) return;
533
+ if (ui.kind !== 'threads') {
534
+ ui.kind = 'threads';
535
+ ui.actNote = null;
536
+ ui.filters = defaultFilters('threads');
537
+ }
538
+ openForge();
539
+ paintFilters();
540
+ ui.idea.open = true;
541
+ ui.idea.message = '';
542
+ ui.idea.bad = false;
543
+ ui.idea.link = null;
544
+ ui.idea.node = { id: node.id, label: node.label };
545
+ ui.idea.opener = node.id;
546
+ // Never lose a draft: a title already typed stays, and text already typed stays under the mention, which is added once (`.value` is
547
+ // text, never markup, so the label and the id need no escaping here)
548
+ const title = $('idea-title');
549
+ if (title.value.trim() === '') title.value = String(node.label || node.id).slice(0, 256);
550
+ const text = $('idea-body');
551
+ const mention = MENTIONABLE.test(node.id) ? `[[${node.id}]]` : '';
552
+ if (mention && !text.value.includes(mention)) text.value = text.value.trim() === '' ? `${mention}\n\n` : `${mention}\n\n${text.value}`;
553
+ paintIdea();
554
+ $('idea-title').focus();
513
555
  }
514
556
 
515
557
  /** The one write: a POST to cornfield's own server, which opens an issue with the label as the maintainer */
@@ -541,13 +583,36 @@ async function sendIdea() {
541
583
  }
542
584
  paintIdea();
543
585
  announce(ui.idea.message);
544
- if (res.ok) {
586
+ if (res.ok) await afterIdea(res);
587
+ else $('idea-title').focus();
588
+ }
589
+
590
+ /**
591
+ * After an idea is opened: the list read again, the new thread selected (so what it mentions lights), the focus back on what opened
592
+ * the form, and all of it said once. The idea is on the forge whatever happens here, so a failure is said, never thrown.
593
+ */
594
+ async function afterIdea(res) {
595
+ const about = ui.idea.node;
596
+ const n = res.body && res.body.number;
597
+ let trouble = '';
598
+ try {
545
599
  ui.lists = {};
546
600
  indexCache = null;
547
601
  await loadList(true, true);
548
602
  ensureThreadsList();
549
- $('idea-open').focus();
550
- } else $('idea-title').focus();
603
+ // The new thread is selected in the list, so what it mentions lights on the map once its messages are in
604
+ if (Number.isInteger(n)) await selectThread(n);
605
+ } catch (err) {
606
+ trouble = ` The list could not be read again (${err instanceof Error ? err.message : err}); Refresh asks for it.`;
607
+ }
608
+ // Then the focus goes back to what opened the form: after the selection, which draws the node's panel (and its button) again
609
+ try { focusIdeaOpener(); } catch { /* the page moved on */ }
610
+ ui.idea.opener = '';
611
+ ui.idea.node = null;
612
+ const shown = ui.thread === n && ui.threadDetail && ui.threadDetail.thread ? ` ${threadSelectionWords()}` : ui.thread === n && ui.threadError ? ` ${ui.threadError}` : '';
613
+ // Opened from a node: say that its "Mentioned in" lists the new thread
614
+ const listed = about && (threadsFor(about.id) || []).some((t) => t.number === n);
615
+ announce(`${ui.idea.message}${shown}${listed ? ` It is listed under Mentioned in for ${about.label}.` : ''}${trouble}`);
551
616
  }
552
617
 
553
618
  /** The New idea bar and form, from `ui.idea`; typed text and the focus are left alone */
@@ -1518,8 +1583,9 @@ export async function refreshForge({ quiet = false } = {}) {
1518
1583
  const at = ui.thread;
1519
1584
  const token = ++threadToken;
1520
1585
  const res = await request(threadUrl(at), true);
1521
- if (token !== threadToken || !res.ok) return;
1522
- ui.threadDetail = { thread: res.body.thread, at: res.body.at, rate: res.body.rate || '', stale: res.body.stale || '' };
1586
+ const thread = threadOf(res);
1587
+ if (token !== threadToken || !thread) return;
1588
+ ui.threadDetail = { thread, at: res.body.at, rate: res.body.rate || '', stale: res.body.stale || '' };
1523
1589
  relight();
1524
1590
  return;
1525
1591
  }
@@ -1620,7 +1686,16 @@ function onClick(e) {
1620
1686
  else if (action.dataset.action === 'clear-forge-deploy') { clearDeploy(); $('forge-title').focus(); }
1621
1687
  else if (action.dataset.action === 'clear-forge-thread') { clearThread(); $('forge-title').focus(); }
1622
1688
  else if (action.dataset.action === 'idea-open') toggleIdea(!ui.idea.open);
1623
- else if (action.dataset.action === 'idea-send') sendIdea();
1689
+ else if (action.dataset.action === 'idea-send') {
1690
+ // Nothing of it may escape as an unhandled rejection: what went wrong is said, and the form is usable again
1691
+ sendIdea().catch((err) => {
1692
+ ui.idea.busy = false;
1693
+ ui.idea.message = `Something went wrong in the page: ${err instanceof Error ? err.message : err}`;
1694
+ ui.idea.bad = true;
1695
+ paintIdea();
1696
+ announce(ui.idea.message);
1697
+ });
1698
+ }
1624
1699
  else if (action.dataset.action === 'idea-cancel') { toggleIdea(false); announce('Cancelled. Nothing was opened.'); }
1625
1700
  }
1626
1701
 
@@ -1690,7 +1765,7 @@ export function initForgePanel(config, opts = {}) {
1690
1765
  const threadsOn = config.threads !== false;
1691
1766
  const tab = panel.querySelector('[data-forge-kind="threads"]');
1692
1767
  if (tab) tab.hidden = !threadsOn;
1693
- state.threadIndex = threadsOn ? { for: threadsFor, ensure: ensureThreadsList, open: openThread } : null;
1768
+ state.threadIndex = threadsOn ? { for: threadsFor, ensure: ensureThreadsList, open: openThread, start: startThread, forge: forgeName } : null;
1694
1769
  registerSheet('forge', panel);
1695
1770
  paintFilters();
1696
1771
  paint();
@@ -1725,7 +1800,9 @@ export function initForgePanel(config, opts = {}) {
1725
1800
  const drawer = $('spec-drawer');
1726
1801
  if (drawer) drawer.addEventListener('click', (e) => {
1727
1802
  const open = e.target.closest && e.target.closest('[data-thread-open]');
1728
- if (open && state.threadIndex) openThread(Number(open.dataset.threadOpen));
1803
+ if (open && state.threadIndex) { openThread(Number(open.dataset.threadOpen)); return; }
1804
+ const start = e.target.closest && e.target.closest('[data-thread-start]');
1805
+ if (start && state.threadIndex && state.selectedNode) startThread(state.selectedNode);
1729
1806
  });
1730
1807
  }
1731
1808
  return true;
@@ -132,10 +132,13 @@ function dataSummary(node) {
132
132
  /** "Mentioned in": the threads whose text names the node (an idea, or a spec PR's conversation); each opens in the issues and PRs panel */
133
133
  function threadsSection(node) {
134
134
  const index = state.threadIndex;
135
- const threads = index ? index.for(node.id) : null;
136
- if (!threads || !threads.length) return '';
135
+ if (!index) return '';
136
+ const threads = index.for(node.id);
137
+ // "Start a thread about this" shows whenever threads are on and a maintainer is signed in (the panel only sets `start` then)
138
+ const start = index.start ? `<div class="hx-line"><button type="button" class="hx-btn" data-thread-start="${escHtml(node.id)}" aria-label="Start a thread about this: opens the New idea form for ${escHtml(index.forge())}, with this node mentioned">Start a thread about this</button></div>` : '';
139
+ if (!threads || !threads.length) return start;
137
140
  const rows = threads.map((t) => `<div class="hx-line"><span class="hx-glyph" style="--glyph:#fbbf24">◆</span><span><button type="button" class="hx-btn hx-thread-open" data-thread-open="${t.number}" aria-label="Open thread #${t.number}, ${escHtml(t.title)}, in the issues and pull requests panel">#${t.number} ${escHtml(t.title)}</button> <span class="hx-faint">${t.kind === 'proposal' ? 'proposal' : 'idea'}</span></span></div>`);
138
- return section(`Mentioned in ${threads.length} ${threads.length === 1 ? 'thread' : 'threads'}:`, rows);
141
+ return section(`Mentioned in ${threads.length} ${threads.length === 1 ? 'thread' : 'threads'}:`, rows) + start;
139
142
  }
140
143
 
141
144
  /** Draws "Mentioned in" again in the open panel (the list was just read, or the map changed); nothing else in the panel moves */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.12.0",
3
+ "version": "0.13.1",
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/server/files.js CHANGED
@@ -6,14 +6,16 @@
6
6
  * repo's map and registry, and the folders of the browser modules its config names. Everything else in
7
7
  * the checkout (.env files, databases, sources) is not reachable.
8
8
  *
9
- * Proposals are found here too: `<proposals>/*.json` in the checkout and the same under each folder of
10
- * the configured worktrees folder (git worktrees with unpushed drafts). A request can only name one the
11
- * listing found itself; what it says is never joined into a path.
9
+ * Proposals are found here too (server/proposal-walk.js does the walking, asynchronously): `<proposals>/*.json` in the
10
+ * checkout and the same under each folder of the configured worktrees folder (git worktrees with unpushed drafts, those
11
+ * that differ from the checkout's). A request can only name one the listing found itself; what it says is never joined
12
+ * into a path.
12
13
  */
13
14
 
14
15
  import fs from 'node:fs';
15
16
  import path from 'node:path';
16
17
  import { createHash } from 'node:crypto';
18
+ import { PROPOSAL_FILE, createProposalLister } from './proposal-walk.js';
17
19
 
18
20
  /** Content-Type by lower-case file extension (with the dot) */
19
21
  export const MIME_TYPES = {
@@ -112,64 +114,40 @@ export function sendFile(req, res, filePath, reqPath) {
112
114
  // Proposals: listed from the checkout and its worktrees, served read-only
113
115
  // ---------------------------------------------------------------------------
114
116
 
115
- /** A proposal's file name: letters, digits, `.`, `_`, `-`; never a leading dot or dash. The slug is the name without `.json` */
116
- export const PROPOSAL_FILE = /^([A-Za-z0-9][A-Za-z0-9._-]*)\.json$/;
117
+ export { PROPOSAL_FILE };
117
118
 
118
- /**
119
- * The folders to look in: the checkout first, then each worktree (a real directory, never a link).
120
- * @param {{ root: string, proposals: string, worktrees?: string|null }} where
121
- */
122
- function proposalFolders({ root, proposals, worktrees }) {
123
- const base = path.resolve(root);
124
- const folders = [{ source: 'checkout', dir: path.join(base, proposals) }];
125
- if (!worktrees) return folders;
126
- let entries = [];
127
- try {
128
- entries = fs.readdirSync(path.join(base, worktrees), { withFileTypes: true });
129
- } catch { /* no worktrees here */ }
130
- for (const w of entries) {
131
- // A worktree called "checkout" would be taken for the checkout itself: not listed
132
- if (w.isDirectory() && w.name !== 'checkout') folders.push({ source: w.name, dir: path.join(base, worktrees, w.name, proposals) });
133
- }
134
- return folders;
119
+ /** The listers by the `fs` they use: the real one, or a fake a test hands in as `where.fs`. Each keeps its own cache. */
120
+ const listers = new WeakMap();
121
+ const realLister = createProposalLister();
122
+
123
+ function listerOf(where) {
124
+ if (!where.fs) return realLister;
125
+ if (!listers.has(where.fs)) listers.set(where.fs, createProposalLister({ fs: where.fs }));
126
+ return listers.get(where.fs);
135
127
  }
136
128
 
137
129
  /**
138
- * Every proposal the server may serve. A review (`*.review.json`), a link, a directory and a name that is
139
- * not a plain file name are left out. When a slug is in several places each is listed, the worktree copies
140
- * first, as that is where it is being written.
141
- * @param {{ root: string, proposals: string, worktrees?: string|null }} where
142
- * @returns {{ slug: string, source: string, file: string }[]} `source` is `checkout` or the worktree's name
130
+ * Every proposal the server may serve (server/proposal-walk.js has how: async, cached, without the worktree files
131
+ * that are copies of the checkout's). A review (`*.review.json`), a link, a directory and a name that is not a plain
132
+ * file name are left out. When a slug is in several places each is listed, the worktree copies first, as that is
133
+ * where it is being written. Each entry carries `parsed`, `{ proposal }` or `{ error }`: what the file holds.
134
+ * @param {{ root: string, proposals: string, worktrees?: string|null, worktreeMaxAgeDays?: number|null }} where
135
+ * @param {{ only?: string|null }} [opts] `only`: walk just this source (`checkout` or a worktree's name)
136
+ * @returns {Promise<{ slug: string, source: string, file: string, parsed: { proposal?: unknown, error?: string } }[]>} `source` is `checkout` or the worktree's name
143
137
  */
144
- export function listProposalFiles(where) {
145
- const out = [];
146
- for (const { source, dir } of proposalFolders(where)) {
147
- let names = [];
148
- try {
149
- names = fs.readdirSync(dir);
150
- } catch { continue; }
151
- for (const name of names) {
152
- const m = PROPOSAL_FILE.exec(name);
153
- if (!m || name.endsWith('.review.json')) continue;
154
- const file = path.join(dir, name);
155
- try {
156
- if (!fs.lstatSync(file).isFile()) continue; // a directory, or a symlink to somewhere else
157
- } catch { continue; }
158
- out.push({ slug: m[1], source, file });
159
- }
160
- }
161
- const rank = (e) => (e.source === 'checkout' ? 1 : 0);
162
- return out.sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : rank(a) - rank(b) || (a.source < b.source ? -1 : a.source > b.source ? 1 : 0)));
138
+ export function listProposalFiles(where, opts) {
139
+ return listerOf(where).list(where, opts);
163
140
  }
164
141
 
165
142
  /**
166
143
  * The listed proposal a request names, matched against the listing. No `source` means the first one
167
- * listed for the slug (the worktree copy).
168
- * @param {{ root: string, proposals: string, worktrees?: string|null }} where
144
+ * listed for the slug (the worktree copy). With a `source`, only that one place is walked.
145
+ * @param {{ root: string, proposals: string, worktrees?: string|null, worktreeMaxAgeDays?: number|null }} where
169
146
  * @param {unknown} slug
170
147
  * @param {unknown} [source]
171
148
  */
172
- export function findProposalFile(where, slug, source) {
149
+ export async function findProposalFile(where, slug, source) {
173
150
  if (typeof slug !== 'string' || (source !== undefined && source !== null && typeof source !== 'string')) return null;
174
- return listProposalFiles(where).find((e) => e.slug === slug && (source === undefined || source === null || e.source === source)) || null;
151
+ const only = typeof source === 'string' && source !== '' ? source : null;
152
+ return (await listProposalFiles(where, { only })).find((e) => e.slug === slug && (only === null || e.source === only)) || null;
175
153
  }
package/server/mockups.js CHANGED
@@ -30,7 +30,7 @@
30
30
  * `unreviewed` (or `missing`).
31
31
  */
32
32
 
33
- import fs from 'node:fs';
33
+ import fsp from 'node:fs/promises';
34
34
  import path from 'node:path';
35
35
  import { createHash } from 'node:crypto';
36
36
  import { mockupsOf } from '../core/proposal.js';
@@ -70,33 +70,40 @@ function sendJson(res, status, body) {
70
70
  }
71
71
  const refuse = (res, status, message) => sendJson(res, status, { error: message });
72
72
 
73
- /** The proposal's parsed JSON for a local entry, or null */
74
- function readLocalProposal(entry) {
73
+ /** The proposal's parsed JSON for a local entry, or null: what the listing parsed, else the file read without blocking */
74
+ async function readLocalProposal(entry) {
75
+ if (entry.parsed) return entry.parsed.error === undefined ? entry.parsed.proposal ?? null : null;
75
76
  try {
76
- return JSON.parse(fs.readFileSync(entry.file, 'utf8'));
77
+ return JSON.parse(await fsp.readFile(entry.file, 'utf8'));
77
78
  } catch {
78
79
  return null;
79
80
  }
80
81
  }
81
82
 
82
83
  /** The bytes of a mockup of a local proposal, or null: the path is resolved with links followed and must stay in the proposal's folder, be a plain file, and be at most MOCKUP_MAX_BYTES */
83
- export function readLocalMockup(entry, rel) {
84
+ export async function readLocalMockup(entry, rel) {
84
85
  try {
85
- const dir = fs.realpathSync(path.dirname(entry.file));
86
- const real = fs.realpathSync(path.join(dir, ...rel.split('/')));
86
+ const dir = await fsp.realpath(path.dirname(entry.file));
87
+ const real = await fsp.realpath(path.join(dir, ...rel.split('/')));
87
88
  if (!real.startsWith(dir + path.sep)) return null;
88
- const stats = fs.statSync(real);
89
+ const stats = await fsp.stat(real);
89
90
  if (!stats.isFile() || stats.size > MOCKUP_MAX_BYTES) return null;
90
- return fs.readFileSync(real);
91
+ return await fsp.readFile(real);
91
92
  } catch {
92
93
  return null;
93
94
  }
94
95
  }
95
96
 
96
- const hashItems = (entry, items) => items.map((m) => {
97
- const bytes = readLocalMockup(entry, m.path);
97
+ /** One mockup at a time: a worktree on a slow mount is not hammered */
98
+ const hashItems = async (entry, items) => {
99
+ const out = [];
100
+ for (const m of items) out.push(await hashItem(entry, m));
101
+ return out;
102
+ };
103
+ const hashItem = async (entry, m) => {
104
+ const bytes = await readLocalMockup(entry, m.path);
98
105
  return { node: m.node, path: m.path, sha256: bytes ? sha256(bytes) : null };
99
- });
106
+ };
100
107
 
101
108
  /**
102
109
  * Whether each mockup is what was approved.
@@ -209,18 +216,18 @@ export async function serveMockups(req, res, match, url, where, forgeFor) {
209
216
  const slug = match[1];
210
217
  const position = match[2] === undefined ? null : Number(match[2]);
211
218
  const source = url.searchParams.get('source') || null;
212
- const entry = findProposalFile(where, slug, source);
219
+ const entry = await findProposalFile(where, slug, source);
213
220
  if (!entry) {
214
221
  if (forgeFor && pullNumber(source) !== null) return servePull(req, res, where, forgeFor, slug, /** @type {string} */ (source), position);
215
222
  return refuse(res, 404, 'No such proposal');
216
223
  }
217
- const proposal = readLocalProposal(entry);
224
+ const proposal = await readLocalProposal(entry);
218
225
  if (!proposal) return refuse(res, 422, 'The proposal could not be read');
219
226
  const items = mockupsOf(proposal);
220
227
  // A proposal here has no PR to be reviewed on: nothing it lists has been approved
221
- if (position === null) return sendJson(res, 200, describe(slug, entry.source, items, hashItems(entry, items), null));
228
+ if (position === null) return sendJson(res, 200, describe(slug, entry.source, items, await hashItems(entry, items), null));
222
229
  const item = items.find((m) => m.index === position);
223
- const bytes = item ? readLocalMockup(entry, item.path) : null;
230
+ const bytes = item ? await readLocalMockup(entry, item.path) : null;
224
231
  if (!item || !bytes) return refuse(res, 404, 'No such mockup');
225
232
  return sendBytes(req, res, item.path, bytes);
226
233
  }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * @module server/proposal-walk
3
+ *
4
+ * Finding the proposal files of the checkout and of its worktrees without ever holding up the server.
5
+ *
6
+ * A worktrees folder can be huge and slow (147 worktrees of 50 proposals each on a Windows drive seen through WSL's 9p:
7
+ * minutes of reads). So the walk is:
8
+ *
9
+ * - **async**: only `fs.promises` calls, at most `CONCURRENCY` in flight at once across all walks (a slow mount is not hammered with
10
+ * thousands of opens), and a turn of the event loop given back every `YIELD_EVERY` calls, so `/healthz` and the
11
+ * other routes are answered meanwhile. No worker thread: nothing in it is CPU-bound, only waiting on the disk;
12
+ * - **cached by path, mtime and size**: a file whose stamp is unchanged is not read again, so a listing with nothing
13
+ * changed does a `readdir` per folder and an `lstat` per file, and no `readFile`;
14
+ * - **without copies**: a worktree starts as a copy of the checkout, so a worktree file whose contents equal the
15
+ * checkout's file of the same name (line endings ignored) is not a draft and is left out. The comparison is by
16
+ * SHA-256 of the contents with `\r\n` read as `\n`, and the hashes are cached with the files. The file's size
17
+ * says first whether it can be equal at all: only then is it hashed;
18
+ * - **single-flight**: listings asked for while one is under way share it;
19
+ * - **optionally pruned by age**: with `where.worktreeMaxAgeDays`, a worktree whose newest proposal is older than
20
+ * that is left out.
21
+ *
22
+ * The cache is bounded (`MAX_ENTRIES` files) and forgets the files that are gone.
23
+ */
24
+
25
+ import fsp from 'node:fs/promises';
26
+ import path from 'node:path';
27
+ import { createHash } from 'node:crypto';
28
+
29
+ /** A proposal's file name: letters, digits, `.`, `_`, `-`; never a leading dot or dash. The slug is the name without `.json` */
30
+ export const PROPOSAL_FILE = /^([A-Za-z0-9][A-Za-z0-9._-]*)\.json$/;
31
+
32
+ export const CONCURRENCY = 8;
33
+ export const YIELD_EVERY = 32;
34
+ export const MAX_ENTRIES = 20000;
35
+ const MAX_WALKS = 16;
36
+ const DAY_MS = 86_400_000;
37
+
38
+ const sha256 = (text) => createHash('sha256').update(text).digest('hex');
39
+ const countNewlines = (text) => { let n = 0; for (let i = text.indexOf('\n'); i !== -1; i = text.indexOf('\n', i + 1)) n++; return n; };
40
+ const turn = () => new Promise((resolve) => setImmediate(resolve));
41
+
42
+ /** Runs the calls it is given at most `limit` at a time, and lets the event loop breathe now and then */
43
+ function gateOf(limit) {
44
+ let active = 0;
45
+ let calls = 0;
46
+ const waiting = [];
47
+ return async (fn) => {
48
+ if (active < limit) active++;
49
+ else await new Promise((resolve) => waiting.push(resolve)); // the slot is handed over, not freed, so the limit holds
50
+ try {
51
+ return await fn();
52
+ } finally {
53
+ if (++calls % YIELD_EVERY === 0) await turn();
54
+ const next = waiting.shift();
55
+ if (next) next();
56
+ else active--;
57
+ }
58
+ };
59
+ }
60
+
61
+ /** What a file's text is as a proposal: `{ proposal }` or `{ error }` (listed with the error rather than breaking the list) */
62
+ function parseProposal(text) {
63
+ try {
64
+ return { proposal: JSON.parse(text) };
65
+ } catch (err) {
66
+ return { error: `Not valid JSON: ${err.message}` };
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Makes a lister, which keeps the cache of what it walked. `fs` is the `fs.promises` surface it needs
72
+ * (`readdir`, `lstat`, `readFile`); tests pass a counting fake.
73
+ * @param {{ fs?: Pick<typeof fsp, 'readdir'|'lstat'|'readFile'>, concurrency?: number, maxEntries?: number, now?: () => number }} [opts]
74
+ */
75
+ export function createProposalLister({ fs = fsp, concurrency = CONCURRENCY, maxEntries = MAX_ENTRIES, now = Date.now } = {}) {
76
+ /** One state per place walked: its cache (path -> record) and the walk under way */
77
+ const states = new Map();
78
+ /** One gate for every walk of this lister: two walks at once (a listing, and a lookup of one source) share the limit */
79
+ const io = gateOf(concurrency);
80
+
81
+ function stateOf(key) {
82
+ let state = states.get(key);
83
+ if (state) {
84
+ states.delete(key); // most recently used last
85
+ } else {
86
+ state = { cache: new Map(), flights: new Map() };
87
+ if (states.size >= MAX_WALKS) states.delete(states.keys().next().value);
88
+ }
89
+ states.set(key, state);
90
+ return state;
91
+ }
92
+
93
+ async function walk(where, state, only) {
94
+ const { cache } = state;
95
+ const seen = new Set();
96
+ const base = path.resolve(where.root);
97
+ const maxAgeMs = where.worktreeMaxAgeDays > 0 ? where.worktreeMaxAgeDays * DAY_MS : null;
98
+ const clock = where.now || now;
99
+
100
+ /** The proposal files directly in `dir`, each with its lstat; a folder that is not there has none */
101
+ async function scan(dir) {
102
+ let names;
103
+ try {
104
+ names = await io(() => fs.readdir(dir));
105
+ } catch { return []; }
106
+ const wanted = names.filter((name) => PROPOSAL_FILE.test(name) && !name.endsWith('.review.json'));
107
+ const found = await Promise.all(wanted.map(async (name) => {
108
+ const file = path.join(dir, name);
109
+ try {
110
+ const st = await io(() => fs.lstat(file));
111
+ return st.isFile() ? { name, slug: PROPOSAL_FILE.exec(name)[1], file, mtimeMs: st.mtimeMs, size: st.size } : null; // not a directory, nor a link to somewhere else
112
+ } catch { return null; }
113
+ }));
114
+ return found.filter(Boolean);
115
+ }
116
+
117
+ /** Whether the cached record still answers for this file against the checkout's copy (`against`: its hash, or null) */
118
+ const usable = (rec, f, against) => !!rec && rec.mtimeMs === f.mtimeMs && rec.size === f.size
119
+ && (rec.hash === null ? rec.against === against : rec.hash === against || rec.parsed !== undefined);
120
+
121
+ /**
122
+ * The record of a file: read, hashed and parsed only when the cache cannot answer. `checkout` is the checkout's
123
+ * record of the same name for a worktree file (null when the checkout has none), undefined for the checkout's own file.
124
+ */
125
+ async function recordOf(f, checkout) {
126
+ seen.add(f.file);
127
+ const against = checkout ? checkout.hash : null;
128
+ const hit = cache.get(f.file);
129
+ if (usable(hit, f, against)) return hit;
130
+ let text;
131
+ try {
132
+ text = await io(() => fs.readFile(f.file, 'utf8'));
133
+ } catch (err) {
134
+ return { mtimeMs: f.mtimeMs, size: f.size, hash: null, against, parsed: { error: `Not valid JSON: ${err.message}` } }; // not kept: asked again next time
135
+ }
136
+ const normal = text.replace(/\r\n/g, '\n');
137
+ const bytes = Buffer.byteLength(normal);
138
+ let hash = null;
139
+ // A copy can only be as long as the checkout's file with its line ends read as \r\n or \n
140
+ if (checkout === undefined || (checkout && f.size >= checkout.bytes && f.size <= checkout.bytes + checkout.newlines)) hash = sha256(normal);
141
+ const rec = { mtimeMs: f.mtimeMs, size: f.size, hash, against, bytes, newlines: checkout === undefined ? countNewlines(normal) : 0 };
142
+ if (!checkout || hash !== against) rec.parsed = parseProposal(text);
143
+ cache.delete(f.file);
144
+ cache.set(f.file, rec);
145
+ return rec;
146
+ }
147
+
148
+ const out = [];
149
+ const proposals = where.proposals;
150
+ const checkoutFiles = await scan(path.join(base, proposals));
151
+ const checkoutRecs = new Map();
152
+ await Promise.all(checkoutFiles.map(async (f) => checkoutRecs.set(f.name, await recordOf(f))));
153
+ if (!only || only === 'checkout') for (const f of checkoutFiles) out.push({ slug: f.slug, source: 'checkout', file: f.file, parsed: checkoutRecs.get(f.name).parsed });
154
+
155
+ if (where.worktrees && only !== 'checkout') {
156
+ const dir = path.join(base, where.worktrees);
157
+ let entries = [];
158
+ try {
159
+ entries = await io(() => fs.readdir(dir, { withFileTypes: true }));
160
+ } catch { /* no worktrees here */ }
161
+ // A worktree called "checkout" would be taken for the checkout itself: not listed
162
+ const names = entries.filter((w) => w.isDirectory() && w.name !== 'checkout' && (!only || w.name === only)).map((w) => w.name).sort();
163
+ await Promise.all(names.map(async (name) => {
164
+ const files = await scan(path.join(dir, name, proposals));
165
+ if (maxAgeMs !== null && files.length && clock() - Math.max(...files.map((f) => f.mtimeMs)) > maxAgeMs) return;
166
+ await Promise.all(files.map(async (f) => {
167
+ const rec = await recordOf(f, checkoutRecs.get(f.name) || null);
168
+ const peer = checkoutRecs.get(f.name);
169
+ const copy = !!peer && rec.hash !== null && rec.hash === peer.hash;
170
+ if (!copy) out.push({ slug: f.slug, source: name, file: f.file, parsed: rec.parsed });
171
+ }));
172
+ }));
173
+ }
174
+
175
+ // Forget what is gone (only after a whole walk: a walk of one source says nothing of the others), and keep the cache bounded
176
+ if (!only) for (const file of cache.keys()) if (!seen.has(file)) cache.delete(file);
177
+ while (cache.size > maxEntries) cache.delete(cache.keys().next().value);
178
+
179
+ const rank = (e) => (e.source === 'checkout' ? 1 : 0);
180
+ return out.sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : rank(a) - rank(b) || (a.source < b.source ? -1 : a.source > b.source ? 1 : 0)));
181
+ }
182
+
183
+ /**
184
+ * Every proposal the server may serve (a review, a link, a directory and a name that is not a plain file name are left
185
+ * out): the checkout's, then each worktree's that differs from the checkout's. When a slug is in several places each
186
+ * is listed, the worktree copies first, as that is where it is being written. `only` limits the walk to one source.
187
+ * @param {{ root: string, proposals: string, worktrees?: string|null, worktreeMaxAgeDays?: number|null, now?: () => number }} where
188
+ * @param {{ only?: string|null }} [opts]
189
+ * @returns {Promise<{ slug: string, source: string, file: string, parsed: { proposal?: unknown, error?: string } }[]>}
190
+ */
191
+ async function list(where, { only = null } = {}) {
192
+ const state = stateOf(JSON.stringify([path.resolve(where.root), where.proposals, where.worktrees || null, where.worktreeMaxAgeDays || null]));
193
+ const flightKey = only || '';
194
+ let flight = state.flights.get(flightKey);
195
+ if (!flight) {
196
+ flight = walk(where, state, only).finally(() => state.flights.delete(flightKey));
197
+ state.flights.set(flightKey, flight);
198
+ }
199
+ return [...(await flight)];
200
+ }
201
+
202
+ return { list };
203
+ }
@@ -26,7 +26,8 @@
26
26
  * the review in the data folder; `migrateStage1Reviews` carries those over once, when the menu is opened.
27
27
  *
28
28
  * Which files exist, and that a request can only name one the server itself listed, is server/files.js
29
- * (`listProposalFiles`, `findProposalFile`); this module reads the files, checks each
29
+ * (`listProposalFiles`, `findProposalFile`, server/proposal-walk.js: async and cached by path and mtime, so a slow
30
+ * worktrees folder never holds up the server); this module checks each
30
31
  * against the checkout's topology.json and answers. Every function takes `where`:
31
32
  * `{ root, proposals, worktrees, topology, dataDir, publicHost? }` (core/config.js names them). A file that does not
32
33
  * parse is listed with an `error` instead of breaking the list. The listing's `review` is always null: a review lives on
@@ -39,7 +40,7 @@
39
40
  * (percent-encoded) says why the PRs are not. Without `forgeFor` nothing is asked of a forge and the routes answer as they always have.
40
41
  */
41
42
 
42
- import fs from 'node:fs';
43
+ import fsp from 'node:fs/promises';
43
44
  import path from 'node:path';
44
45
  import { findProposalFile, listProposalFiles } from './files.js';
45
46
  import { summarize, proposalProblems } from '../core/proposal.js';
@@ -60,14 +61,24 @@ function send(res, status, body, extra = {}) {
60
61
  }
61
62
 
62
63
  /** The map the proposals are checked against: the checkout's topology.json, or null when it cannot be read */
63
- function readTopology(where) {
64
+ async function readTopology(where) {
65
+ const file = path.join(where.root, where.topology || 'topology.json');
64
66
  try {
65
- const topology = JSON.parse(fs.readFileSync(path.join(where.root, where.topology || 'topology.json'), 'utf8'));
66
- return Array.isArray(topology.nodes) && Array.isArray(topology.edges) ? topology : null;
67
+ const st = await fsp.stat(file);
68
+ const stamp = `${st.mtimeMs}:${st.size}`;
69
+ const known = topologies.get(file);
70
+ if (known && known.stamp === stamp) return known.topology;
71
+ const topology = JSON.parse(await fsp.readFile(file, 'utf8'));
72
+ const checked = Array.isArray(topology.nodes) && Array.isArray(topology.edges) ? topology : null;
73
+ topologies.set(file, { stamp, topology: checked });
74
+ if (topologies.size > 32) topologies.delete(topologies.keys().next().value);
75
+ return checked;
67
76
  } catch {
68
77
  return null;
69
78
  }
70
79
  }
80
+ /** The maps read, by file and the size and mtime they were read at: an unchanged map is not read or parsed again */
81
+ const topologies = new Map();
71
82
 
72
83
  /** A host name that is the machine's own: localhost, an address, a tailnet name, a bare name, or the configured public host. Not an outside domain pointed here. */
73
84
  function ownHostName(host, publicHost) {
@@ -136,15 +147,16 @@ export function readBody(req, limit) {
136
147
  * a file that does not parse has `error` instead and no counts. `review` is null (see the module's head).
137
148
  */
138
149
  function describeEntry(entry, topology) {
139
- const { slug, source } = entry;
140
- let proposal;
141
- try {
142
- proposal = JSON.parse(fs.readFileSync(entry.file, 'utf8'));
143
- } catch (err) {
144
- return { slug, title: slug, summary: '', spec: null, source, counts: null, errors: null, review: null, error: `Not valid JSON: ${err.message}` };
145
- }
146
- return { ...describeProposal(slug, source, proposal, topology), review: null };
150
+ const { slug, source, parsed } = entry;
151
+ if (parsed.error !== undefined) return { slug, title: slug, summary: '', spec: null, source, counts: null, errors: null, review: null, error: parsed.error };
152
+ // What a file says of itself against the map is kept with its parsed result, until either changes
153
+ const memo = described.get(parsed);
154
+ if (memo && memo.topology === topology && memo.slug === slug && memo.source === source) return { ...memo.value };
155
+ const value = { ...describeProposal(slug, source, parsed.proposal, topology), review: null };
156
+ described.set(parsed, { topology, slug, source, value });
157
+ return { ...value };
147
158
  }
159
+ const described = new WeakMap();
148
160
 
149
161
  /** What a listing entry says of a parsed proposal (the file may hold anything JSON can) */
150
162
  function describeProposal(slug, source, proposal, topology) {
@@ -175,9 +187,9 @@ async function describePull(entry, forge, where, topology) {
175
187
  }
176
188
 
177
189
  /** The listing `GET /proposals` answers with */
178
- export function listProposals(where) {
179
- const topology = readTopology(where);
180
- return listProposalFiles(where).map((entry) => describeEntry(entry, topology));
190
+ export async function listProposals(where) {
191
+ const [topology, files] = await Promise.all([readTopology(where), listProposalFiles(where)]);
192
+ return files.map((entry) => describeEntry(entry, topology));
181
193
  }
182
194
 
183
195
  /**
@@ -189,8 +201,8 @@ export function listProposals(where) {
189
201
  * @returns {Promise<{ list: object[], problem: string | null }>}
190
202
  */
191
203
  async function listWithPulls(where, forgeFor, signedIn) {
192
- const topology = readTopology(where);
193
- const local = listProposalFiles(where).map((entry) => describeEntry(entry, topology));
204
+ const [topology, files] = await Promise.all([readTopology(where), listProposalFiles(where)]);
205
+ const local = files.map((entry) => describeEntry(entry, topology));
194
206
  let forge;
195
207
  try {
196
208
  forge = forgeFor();
@@ -285,7 +297,7 @@ async function putPullReview(req, res, where, forgeFor, signedIn, slug, n) {
285
297
  * @param {{ root: string, proposals: string, worktrees?: string|null, topology?: string, dataDir: string, publicHost?: string|null }} where
286
298
  * @param {(() => import('./forge.js').Forge) | null} [forgeFor] the forge as the signed-in user; null without sign-in
287
299
  * @param {SignedIn | null} [signedIn] who is signed in, and where their actions are recorded; null without sign-in
288
- * @returns {boolean} true when the request was answered
300
+ * @returns {boolean} true when the route is one of the proposals' (the answer may follow: the files are read without blocking the server)
289
301
  */
290
302
  export function serveProposals(req, res, reqPath, url, where, forgeFor = null, signedIn = null) {
291
303
  if (reqPath !== '/proposals' && !reqPath.startsWith('/proposals/')) return false;
@@ -310,7 +322,11 @@ export function serveProposals(req, res, reqPath, url, where, forgeFor = null, s
310
322
  if (!res.headersSent) send(res, 500, { error: 'The review could not be read' });
311
323
  });
312
324
  } else {
313
- send(res, 404, { error: findProposalFile(where, slug, url.searchParams.get('source') || null) ? 'No review yet' : 'No such proposal' });
325
+ findProposalFile(where, slug, url.searchParams.get('source') || null).then((found) => {
326
+ send(res, 404, { error: found ? 'No review yet' : 'No such proposal' });
327
+ }).catch(() => {
328
+ if (!res.headersSent) send(res, 500, { error: 'The proposal could not be looked up' });
329
+ });
314
330
  }
315
331
  } else {
316
332
  req.resume();
@@ -334,7 +350,9 @@ export function serveProposals(req, res, reqPath, url, where, forgeFor = null, s
334
350
 
335
351
  if (reqPath === '/proposals') {
336
352
  if (!forgeFor) {
337
- send(res, 200, listProposals(where));
353
+ listProposals(where).then((list) => send(res, 200, list)).catch(() => {
354
+ if (!res.headersSent) send(res, 500, { error: 'The proposals could not be listed' });
355
+ });
338
356
  return true;
339
357
  }
340
358
  listWithPulls(where, forgeFor, signedIn).then(({ list, problem }) => {
@@ -349,25 +367,25 @@ export function serveProposals(req, res, reqPath, url, where, forgeFor = null, s
349
367
  // listing; it never becomes part of a path.
350
368
  const m = /^\/proposals\/([^/]+)\.json$/.exec(reqPath);
351
369
  const source = url.searchParams.get('source') || null;
352
- const entry = m ? findProposalFile(where, m[1], source) : null;
370
+ serveFile(res, where, forgeFor, m ? m[1] : null, source).catch(() => {
371
+ if (!res.headersSent) send(res, 500, { error: 'The proposal could not be read' });
372
+ });
373
+ return true;
374
+ }
375
+
376
+ /** GET /proposals/<slug>.json: the file the listing found, or (with a forge) the proposal of an open spec PR */
377
+ async function serveFile(res, where, forgeFor, slug, source) {
378
+ const entry = slug ? await findProposalFile(where, slug, source) : null;
353
379
  if (!entry) {
354
- if (m && forgeFor) {
355
- servePull(res, where, forgeFor, m[1], source).catch(() => {
356
- if (!res.headersSent) send(res, 500, { error: 'The proposal could not be read' });
357
- });
358
- return true;
359
- }
360
- send(res, 404, { error: 'No such proposal' });
361
- return true;
380
+ if (slug && forgeFor) return servePull(res, where, forgeFor, slug, source);
381
+ return send(res, 404, { error: 'No such proposal' });
362
382
  }
363
383
  let text;
364
384
  try {
365
- text = fs.readFileSync(entry.file, 'utf8');
385
+ text = await fsp.readFile(entry.file, 'utf8');
366
386
  JSON.parse(text);
367
387
  } catch (err) {
368
- send(res, 422, { error: `Not valid JSON: ${err.message}` });
369
- return true;
388
+ return send(res, 422, { error: `Not valid JSON: ${err.message}` });
370
389
  }
371
- send(res, 200, text, { 'X-Proposal-Source': encodeURIComponent(entry.source) });
372
- return true;
390
+ return send(res, 200, text, { 'X-Proposal-Source': encodeURIComponent(entry.source) });
373
391
  }
package/server/server.js CHANGED
@@ -169,7 +169,7 @@ export function createCornfieldServer(config, opts = {}) {
169
169
  const csp = cspOf(importMap);
170
170
  const repoModules = repoModuleDirs(config);
171
171
  const publicHost = config.publicUrl ? new URL(config.publicUrl).hostname : null;
172
- const where = { root, proposals: config.proposals, worktrees: config.worktrees, topology: config.topology, dataDir: config.dataDir, publicHost };
172
+ const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost };
173
173
  const fixtureCache = new Map();
174
174
  const lander = config.approveLands ? createLander({ config, where, auth, hooks, now: opts.now, timer: opts.landTimer }) : null;
175
175
  if (lander) {