truemap-cli 0.2.0 → 0.5.0

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/src/server.js CHANGED
@@ -1,12 +1,16 @@
1
1
  // The local truemap server: one per repo, started on demand by the CLI, invisible to the user.
2
2
  // Serves the workspace UI, the .truemap pages (with the SDK injected), a chat queue between
3
3
  // the browser and the agent's CLI (listen/reply), and live updates over Server-Sent Events.
4
- import { createServer } from 'node:http';
4
+ import { createServer, request as httpRequest } from 'node:http';
5
5
  import { randomBytes } from 'node:crypto';
6
- import { existsSync, lstatSync, readFileSync, realpathSync, rmSync, statSync, watch } from 'node:fs';
7
- import { extname, join, resolve, sep } from 'node:path';
8
- import { FOLDER, PKG_DIR, VERSION, appendPrivate, historyPath, serverStatePath, writePrivate } from './common.js';
6
+ import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch } from 'node:fs';
7
+ import { basename, extname, join, resolve, sep } from 'node:path';
8
+ import { FOLDER, PKG_DIR, VERSION, appendPrivate, historyPath, serverStatePath, serversDir, snapshotsPath, writePrivate } from './common.js';
9
+ import { changes, fileDiff, snapshotTree } from './changes.js';
10
+ import { cleanPlan, currentPlan, parseReport, planCheck, planMessage, planWarnings, readPlan, savePlan, srcOfBox, stepCheck } from './plan.js';
9
11
  import { checkAll, listPages } from './check.js';
12
+ import { exportPage, kitCss } from './export.js';
13
+ import { snippet } from './snippet.js';
10
14
 
11
15
  const root = resolve(process.argv[2] || process.cwd());
12
16
  const folder = join(root, FOLDER);
@@ -33,8 +37,13 @@ let listener = null; // { res, timer } – the single active `lis
33
37
  let agentState = 'offline'; // offline (never seen) | listening | working | idle (back in the terminal)
34
38
  let agentName = ''; // claude-code | codex | ''
35
39
  let agentSince = 0; // when the current state began
40
+ let endRequested = false; // the user pressed End conversation while the agent wasn't listening
36
41
  let annotateWish; // set by `truemap <page> --annotate` before a tab is open
37
42
  let lastAgentActivity = 0;
43
+ let lastSeenAt = Date.now(); // when a person last had this project open
44
+ let lastReplyAt = 0; // when the agent last wrote in the chat
45
+ let everConnected = false; // a tab has been open since this server started
46
+ const asking = () => { const a = [...history].reverse().find((h) => h.role === 'agent'); return !!(a?.ask && !history.some((h) => h.kind === 'answer' && h.at > a.at)); };
38
47
  let currentPage = null;
39
48
  let closeTimer = null;
40
49
  let idleTimer = null;
@@ -42,6 +51,49 @@ let seq = 0;
42
51
  let lastCheck = { gitRepo: false, results: [] };
43
52
  const history = loadHistory();
44
53
 
54
+ // ---------- change review: where "what changed" is measured from ----------
55
+ const snapshots = (() => { try { return JSON.parse(readFileSync(snapshotsPath(root), 'utf8')); } catch { return {}; } })();
56
+ function saveSnapshots() { try { writePrivate(snapshotsPath(root), JSON.stringify(snapshots)); } catch { /* ignore */ } }
57
+ async function takeSnapshot(kind, extra = {}) {
58
+ const tree = await snapshotTree(root).catch(() => null);
59
+ if (!tree) return null;
60
+ snapshots[kind] = { tree, at: new Date().toISOString(), ...extra };
61
+ saveSnapshots(); changeCache.clear();
62
+ broadcast({ type: 'changes-base', kind });
63
+ return snapshots[kind];
64
+ }
65
+ const changeCache = new Map(); // base -> { at, promise }
66
+
67
+ // ---------- plans ----------
68
+ let plan = (() => { try { return currentPlan(root); } catch { return null; } })();
69
+ function setPlan(p) {
70
+ plan = p;
71
+ if (p) { try { savePlan(root, p); } catch { /* ignore */ } }
72
+ broadcast({ type: 'plan', plan: p && p.status !== 'done' ? p : null });
73
+ }
74
+ async function approvePlan(by) {
75
+ if (!plan || plan.status === 'done') return false;
76
+ setPlan({ ...plan, status: 'approved', approvedAt: new Date().toISOString() });
77
+ await takeSnapshot('plan', { slug: plan.slug });
78
+ if (by === 'user') {
79
+ const msg = { id: `m${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), kind: 'approval', from: 'user', page: plan.page, text: `Approved the plan: ${plan.title}`, context: [], plan: plan.slug };
80
+ queue.push(msg); remember({ role: 'user', ...msg }); deliverQueue();
81
+ }
82
+ return true;
83
+ }
84
+ function changesFor(base, fresh = false) {
85
+ const hit = changeCache.get(base);
86
+ if (!fresh && hit && Date.now() - hit.at < 3000) return hit.promise;
87
+ const promise = changes(root, base, snapshots).then((r) => {
88
+ // measured from the plan's approval: say how the work compares with the plan
89
+ const p = plan && snapshots.plan?.slug === plan.slug ? plan : snapshots.plan?.slug ? readPlan(root, snapshots.plan.slug) : null;
90
+ if (!r.error && r.base?.kind === 'plan' && p) { r.plan = planCheck(root, p, r); r.plan.steps = stepCheck(root, p, r); r.plan.status = p.status; }
91
+ return r;
92
+ }).catch((e) => ({ error: String(e?.message || e) }));
93
+ changeCache.set(base, { at: Date.now(), promise });
94
+ return promise;
95
+ }
96
+
45
97
  function loadHistory() {
46
98
  try {
47
99
  return readFileSync(historyPath(root), 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)).slice(-200);
@@ -101,6 +153,7 @@ function deliverQueue() {
101
153
  if (listener && (listener.res.destroyed || listener.res.writableEnded)) { clearTimeout(listener.timer); listener = null; setAgentState('idle'); }
102
154
  if (!listener || queue.length === 0) return;
103
155
  const messages = queue.splice(0, queue.length);
156
+ takeSnapshot('turn');
104
157
  setAgentState('working');
105
158
  lastAgentActivity = Date.now();
106
159
  broadcast({ type: 'delivered', ids: messages.map((m) => m.id) });
@@ -112,7 +165,7 @@ function scheduleCloseCheck() {
112
165
  if (!listener || clients.size > 0) return;
113
166
  closeTimer = setTimeout(() => {
114
167
  if (listener && clients.size === 0 && queue.length === 0) {
115
- finishListen({ status: 'browser_closed' });
168
+ finishListen({ status: everConnected ? 'browser_closed' : 'no_tab' });
116
169
  setAgentState('idle');
117
170
  }
118
171
  }, CLOSE_GRACE_MS);
@@ -142,6 +195,7 @@ function startWatching() {
142
195
  watchTimer = setTimeout(() => {
143
196
  const files = [...changedPages];
144
197
  changedPages.clear();
198
+ changeCache.clear();
145
199
  broadcast({ type: 'pages', pages: safePages() });
146
200
  broadcast({ type: 'changed', files });
147
201
  scheduleChecks();
@@ -157,6 +211,35 @@ function safePages() {
157
211
  try { return listPages(root); } catch { return []; }
158
212
  }
159
213
 
214
+ const cleanFocus = (f) => (Array.isArray(f) ? f : []).map((x) => String(x).trim().slice(0, 300)).filter(Boolean).slice(0, 20);
215
+
216
+ // ---------- every truemap project running on this machine (one server each) ----------
217
+ function peek(state) {
218
+ return new Promise((ok) => {
219
+ const r = httpRequest({ host: '127.0.0.1', port: state.port, path: '/api/agent/status', method: 'GET', headers: { 'X-Truemap-Token': state.token } }, (res) => {
220
+ const chunks = []; res.on('data', (c) => chunks.push(c));
221
+ res.on('end', () => { try { ok(JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch { ok(null); } });
222
+ });
223
+ r.setTimeout(800, () => r.destroy()); r.on('error', () => ok(null)); r.end();
224
+ });
225
+ }
226
+ async function projects() {
227
+ let files = [];
228
+ try { files = readdirSync(serversDir()).filter((x) => x.endsWith('.json')); } catch { return []; }
229
+ const list = await Promise.all(files.map(async (name) => {
230
+ let st; try { st = JSON.parse(readFileSync(join(serversDir(), name), 'utf8')); } catch { return null; }
231
+ if (!st?.port || !st.token) return null;
232
+ const self = st.pid === process.pid;
233
+ const s = self ? { root, name: basename(root), agent: agentState, agentName, plan: plan && plan.status !== 'done' ? { title: plan.title, status: plan.status } : null, unread: false, asking: false, clients: clients.size } : await peek(st);
234
+ if (!s?.root) return null;
235
+ return { self, name: s.name || basename(s.root), root: s.root, agent: s.agent, agentName: s.agentName || '', plan: s.plan || null, unread: !!s.unread, asking: !!s.asking, url: `http://127.0.0.1:${st.port}/?t=${encodeURIComponent(st.token)}` };
236
+ }));
237
+ // one entry per project, even when two state files (old path spellings) point at the same server
238
+ const seen = new Set();
239
+ return list.filter(Boolean).sort((a, b) => (b.self - a.self) || a.name.localeCompare(b.name))
240
+ .filter((x) => { const k = String(x.root).toLowerCase().replace(/[\\/]+$/, ''); if (seen.has(k)) return false; seen.add(k); return true; });
241
+ }
242
+
160
243
  // ---------- http helpers ----------
161
244
  function sendJson(res, status, body) {
162
245
  res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
@@ -245,12 +328,7 @@ function serveStatic(res, dir, name, cache = 'no-store') {
245
328
  // The page kit comes from truemap itself, so every repo gets kit updates. A repo may still keep its own
246
329
  // assets/truemap.css (older setups, or a hand-tuned copy): that copy wins. assets/theme.css is appended.
247
330
  function serveKit(res) {
248
- const own = folderIsSafe() ? safeFile(folder, 'assets/truemap.css') : null;
249
- let css = readFileSync(own || join(KIT_DIR, 'truemap.css'), 'utf8');
250
- const theme = folderIsSafe() ? safeFile(folder, 'assets/theme.css') : null;
251
- if (theme) css += `
252
- /* .truemap/assets/theme.css */
253
- ${readFileSync(theme, 'utf8')}`;
331
+ const css = kitCss(root);
254
332
  res.writeHead(200, { 'Content-Type': 'text/css; charset=utf-8', 'Cache-Control': 'no-store' });
255
333
  res.end(css);
256
334
  }
@@ -291,13 +369,13 @@ const server = createServer(async (req, res) => {
291
369
  res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' });
292
370
  res.write(`data: ${JSON.stringify({
293
371
  type: 'hello', version: VERSION, root, cmd: CMD, agent: agentInfo(), pages: safePages(), check: lastCheck,
294
- history, current: currentPage, pending: queue.map((m) => m.id), ...(annotateWish !== undefined ? { annotate: annotateWish } : {}),
372
+ history, current: currentPage, pending: queue.map((m) => m.id), plan: plan && plan.status !== 'done' ? plan : null, ...(annotateWish !== undefined ? { annotate: annotateWish } : {}),
295
373
  })}\n\n`);
296
374
  annotateWish = undefined;
297
- clients.add(res);
375
+ clients.add(res); everConnected = true;
298
376
  clearTimeout(closeTimer);
299
377
  const ping = setInterval(() => res.write(': ping\n\n'), 20_000);
300
- req.on('close', () => { clearInterval(ping); clients.delete(res); scheduleCloseCheck(); touchIdle(); });
378
+ req.on('close', () => { clearInterval(ping); clients.delete(res); lastSeenAt = Date.now(); scheduleCloseCheck(); touchIdle(); });
301
379
  return;
302
380
  }
303
381
  if (p === '/api/send' && req.method === 'POST') {
@@ -324,7 +402,9 @@ const server = createServer(async (req, res) => {
324
402
  context,
325
403
  ...(answer ? { answer } : {}),
326
404
  };
405
+ if (b.plan === 'request' && plan && plan.status !== 'done') { msg.kind = 'plan_changes'; msg.plan = plan.slug; setPlan({ ...plan, status: 'revise' }); }
327
406
  queue.push(msg);
407
+ endRequested = false; // a new message means the conversation goes on
328
408
  remember({ role: 'user', ...msg });
329
409
  deliverQueue();
330
410
  return sendJson(res, 200, { ok: true, id: msg.id, delivered: !queue.includes(msg) });
@@ -336,10 +416,54 @@ const server = createServer(async (req, res) => {
336
416
  return sendJson(res, 200, { ok: true });
337
417
  }
338
418
  if (p === '/api/check' && req.method === 'POST') return sendJson(res, 200, runChecks());
419
+ if (p === '/api/export' && req.method === 'GET') {
420
+ const page = url.searchParams.get('page') || '';
421
+ let html;
422
+ try { html = exportPage(root, page); } catch (e) { return sendText(res, 404, String(e.message || e)); }
423
+ const name = page.split('/').pop().replace(/\.html?$/i, '') || 'page';
424
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Disposition': `attachment; filename="${name.replace(/[^\w.-]/g, '_')}-truemap.html"` });
425
+ return res.end(html);
426
+ }
427
+ if (p === '/api/snippet' && req.method === 'GET') {
428
+ try { return sendJson(res, 200, snippet(root, url.searchParams.get('src') || '')); } catch (e) { return sendJson(res, 200, { error: String(e.message || e) }); }
429
+ }
430
+ if (p === '/api/changes' && req.method === 'GET') {
431
+ return sendJson(res, 200, await changesFor(url.searchParams.get('base') || 'auto'));
432
+ }
433
+ if (p === '/api/diff' && req.method === 'GET') {
434
+ return sendJson(res, 200, await fileDiff(root, url.searchParams.get('base') || 'auto', snapshots, String(url.searchParams.get('path') || '')));
435
+ }
436
+ if (p === '/api/plan' && req.method === 'POST') {
437
+ const b = await readBody(req);
438
+ if (b.action === 'approve') return sendJson(res, 200, { ok: await approvePlan('user') });
439
+ return sendJson(res, 400, { error: 'unknown action' });
440
+ }
441
+ if (p === '/api/drift' && req.method === 'GET') {
442
+ const path = String(url.searchParams.get('path') || '').replace(/\\/g, '/');
443
+ const since = String(url.searchParams.get('since') || '');
444
+ if (!path || path.includes('..')) return sendJson(res, 400, { error: 'bad path' });
445
+ const { execFileSync } = await import('node:child_process');
446
+ const g = (args) => { try { return execFileSync('git', args, { cwd: root, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); } catch { return null; } };
447
+ const commit = (since && g(['rev-list', '-1', `--before=${since}`, 'HEAD'])?.trim()) || 'HEAD';
448
+ const text = g(['diff', '--no-color', '-U3', commit, '--', path]);
449
+ if (text === null) return sendJson(res, 200, { error: 'git diff failed' });
450
+ return sendJson(res, 200, { path, from: commit.slice(0, 8), text: text.length > 200_000 ? `${text.slice(0, 200_000)}\n… (cut)` : text });
451
+ }
452
+ if (p === '/api/projects' && req.method === 'GET') return sendJson(res, 200, { projects: await projects() });
453
+ if (p === '/api/end' && req.method === 'POST') {
454
+ // The user is done talking on the page: free the agent to go back to the terminal.
455
+ if (listener) finishListen({ status: 'ended' }); else if (agentState === 'working' || agentState === 'listening') endRequested = true;
456
+ setAgentState('idle');
457
+ return sendJson(res, 200, { ok: true });
458
+ }
339
459
 
340
460
  // ----- agent (CLI) side -----
341
461
  if (p === '/api/agent/status' && req.method === 'GET') {
342
- return sendJson(res, 200, { version: VERSION, pid: process.pid, root, clients: clients.size, agent: agentState, queued: queue.length, current: currentPage });
462
+ return sendJson(res, 200, {
463
+ version: VERSION, pid: process.pid, root, name: basename(root), clients: clients.size, agent: agentState, agentName, queued: queue.length, current: currentPage,
464
+ plan: plan && plan.status !== 'done' ? { title: plan.title, status: plan.status } : null,
465
+ unread: !clients.size && lastReplyAt > lastSeenAt, asking: asking(),
466
+ });
343
467
  }
344
468
  if (p === '/api/agent/listen' && req.method === 'POST') {
345
469
  const b = await readBody(req);
@@ -354,6 +478,7 @@ const server = createServer(async (req, res) => {
354
478
  if (listener && listener.res === res) { clearTimeout(listener.timer); listener = null; setAgentState('idle'); }
355
479
  });
356
480
  if (queue.length) return deliverQueue();
481
+ if (endRequested) { endRequested = false; finishListen({ status: 'ended' }); setAgentState('idle'); return; }
357
482
  setAgentState('listening');
358
483
  if (clients.size === 0) scheduleCloseCheck();
359
484
  return;
@@ -364,7 +489,12 @@ const server = createServer(async (req, res) => {
364
489
  if (!text.trim()) return sendJson(res, 400, { error: 'empty reply' });
365
490
  lastAgentActivity = Date.now();
366
491
  noteAgent(b.agent);
367
- remember({ role: 'agent', id: `a${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), agent: agentName, text });
492
+ const focus = cleanFocus(b.focus);
493
+ const ask = b.ask && typeof b.ask === 'object' && Array.isArray(b.ask.options) && b.ask.options.length >= 2
494
+ ? { question: String(b.ask.question ?? '').slice(0, 500), options: b.ask.options.slice(0, 6).map((o) => ({ label: String(o.label ?? '').slice(0, 200), why: String(o.why ?? '').slice(0, 400) })) }
495
+ : null;
496
+ remember({ role: 'agent', id: `a${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), agent: agentName, text, ...(focus.length ? { focus } : {}), ...(ask ? { ask } : {}) });
497
+ lastReplyAt = Date.now(); if (clients.size) lastSeenAt = lastReplyAt;
368
498
  if (!listener) setAgentState(b.keepWorking || b.willListen ? 'working' : 'idle');
369
499
  return sendJson(res, 200, { ok: true, browsers: clients.size });
370
500
  }
@@ -377,6 +507,65 @@ const server = createServer(async (req, res) => {
377
507
  scheduleChecks();
378
508
  return sendJson(res, 200, { ok: true, browsers: clients.size });
379
509
  }
510
+ if (p === '/api/agent/show' && req.method === 'POST') {
511
+ // The agent points at the map: light up boxes (by id or data-src), optionally with a note.
512
+ const b = await readBody(req);
513
+ lastAgentActivity = Date.now();
514
+ noteAgent(b.agent);
515
+ broadcast({ type: 'show', page: typeof b.page === 'string' ? b.page : '', focus: cleanFocus(b.focus), note: String(b.note ?? '').slice(0, 2000), clear: !!b.clear, agent: agentName });
516
+ return sendJson(res, 200, { ok: true, browsers: clients.size });
517
+ }
518
+ if (p === '/api/agent/changes' && req.method === 'POST') {
519
+ // `truemap changes`: the summary for the agent, and the Changes view for the user.
520
+ const b = await readBody(req);
521
+ noteAgent(b.agent);
522
+ const base = ['turn', 'plan', 'head', 'main'].includes(b.base) ? b.base : 'auto';
523
+ const r = await changesFor(base, true);
524
+ if (b.open !== false) broadcast({ type: 'view', view: 'changes', base });
525
+ return sendJson(res, 200, { ...r, browsers: clients.size });
526
+ }
527
+ if (p === '/api/agent/plan' && req.method === 'POST') {
528
+ const b = await readBody(req);
529
+ noteAgent(b.agent);
530
+ lastAgentActivity = Date.now();
531
+ if (b.status) {
532
+ if (!plan) return sendJson(res, 404, { error: 'no plan in play' });
533
+ if (b.status === 'approved') await approvePlan('agent');
534
+ let check = null;
535
+ if (b.status === 'done') {
536
+ // closing a plan takes the agent's account of every step
537
+ let rep2;
538
+ try { rep2 = parseReport(plan, Array.isArray(b.steps) ? b.steps : []); } catch (e) { return sendJson(res, 400, { error: String(e.message || e) }); }
539
+ // the account of steps is optional; when given, every report is kept
540
+ if (rep2.report.some(Boolean)) plan = { ...plan, report: rep2.report, reports: [...(plan.reports || []), { at: new Date().toISOString(), report: rep2.report }] };
541
+ if (snapshots.plan?.slug === plan.slug) { await takeSnapshot('planEnd', { slug: plan.slug }); const r = await changesFor('plan', true); check = r.plan || null; }
542
+ setPlan({ ...plan, status: 'done', doneAt: new Date().toISOString() });
543
+ const sts = check?.steps || [];
544
+ const rpt = plan.report || [];
545
+ const tally = ['done', 'partly', 'not_built', 'dropped'].map((k) => [k, rpt.filter((x) => x?.status === k).length]).filter(([, n]) => n).map(([k, n]) => `${n} ${k.replace('_', ' ')}`).join(', ');
546
+ const conflicts = sts.filter((x) => x.conflict || x.rewritten);
547
+ remember({ role: 'agent', id: `a${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), agent: agentName, plan: plan.slug,
548
+ text: [`**Plan closed: ${plan.title}.**${tally ? ` Steps: ${tally}.` : ''}`, ...rpt.map((x, i) => x && x.status !== 'done' ? `- Step ${i + 1} ${x.status.replace('_', ' ')}: ${x.note}` : null).filter(Boolean),
549
+ ...(conflicts.length ? ['', '**Check before you trust this report:**', ...conflicts.map((x) => `- Step ${x.n}: ${[x.conflict, x.rewritten].filter(Boolean).join(' ')}`)] : []),
550
+ '', 'Open the Changes tab to see each step beside its diff.'].join('\n') });
551
+ }
552
+ return sendJson(res, 200, { ok: true, plan: plan.slug, status: plan.status, check });
553
+ }
554
+ let p2;
555
+ try { p2 = cleanPlan(b.plan); } catch (e) { return sendJson(res, 400, { error: String(e.message || e) }); }
556
+ const prev = readPlan(root, p2.slug);
557
+ p2.revision = prev && prev.status !== 'done' ? (prev.revision || 1) + 1 : 1;
558
+ p2.status = 'review'; p2.at = new Date().toISOString();
559
+ if (prev && prev.status !== 'done') {
560
+ const was = new Map(prev.touch.map((t) => [t.box, t.what]));
561
+ const wasAdd = new Map(prev.add.map((a) => [a.id, JSON.stringify(a)]));
562
+ p2.revised = [...p2.touch.filter((t) => was.get(t.box) !== t.what).map((t) => t.box), ...p2.add.filter((a) => wasAdd.get(a.id) !== JSON.stringify(a)).map((a) => a.id)];
563
+ }
564
+ setPlan(p2);
565
+ remember({ role: 'agent', id: `a${Date.now().toString(36)}${(seq++).toString(36)}`, at: p2.at, agent: agentName, text: planMessage(p2, p2.revision > 1 ? prev : null, (box) => srcOfBox(root, p2.page, box, 'data-name') || box), plan: p2.slug });
566
+ broadcast({ type: 'navigate', page: p2.page, pages: safePages() });
567
+ return sendJson(res, 200, { ok: true, slug: p2.slug, revision: p2.revision, page: p2.page, browsers: clients.size, warnings: planWarnings(root, p2) });
568
+ }
380
569
  if (p === '/api/agent/progress' && req.method === 'POST') {
381
570
  const b = await readBody(req);
382
571
  broadcast({ type: 'progress', text: String(b.text ?? '').slice(0, 300) });
@@ -400,7 +589,8 @@ const content = createServer((req, res) => {
400
589
  const p = new URL(req.url, `http://127.0.0.1:${contentPort}`).pathname;
401
590
  try {
402
591
  if (p === '/__truemap/sdk.js') {
403
- const js = readFileSync(join(UI_DIR, 'sdk.js'), 'utf8').replace('__TRUEMAP_PARENT__', `http://127.0.0.1:${port}`);
592
+ const js = [join(UI_DIR, 'wires.js'), join(UI_DIR, 'diagram.js')].map((f) => readFileSync(f, 'utf8')).join('\n;\n')
593
+ + '\n' + readFileSync(join(UI_DIR, 'sdk.js'), 'utf8').replace('__TRUEMAP_PARENT__', `http://127.0.0.1:${port}`);
404
594
  res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store' });
405
595
  return res.end(js);
406
596
  }
package/src/snippet.js ADDED
@@ -0,0 +1,63 @@
1
+ // The real code behind a box: a few lines around `name` in `path`, read from the repo.
2
+ // Only files git tracks (or, without git, files inside the repo that aren't hidden) are served, so a
3
+ // page can never pull out .env or anything ignored.
4
+ import { execFileSync } from 'node:child_process';
5
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
6
+ import { join, resolve, sep } from 'node:path';
7
+ import { gitExe } from './common.js';
8
+ import { parseAnchor } from './check.js';
9
+
10
+ const MAX_BYTES = 2 * 1024 * 1024;
11
+
12
+ function git(root, args) {
13
+ try {
14
+ return execFileSync(gitExe(), args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, maxBuffer: 8 * 1024 * 1024 });
15
+ } catch { return null; }
16
+ }
17
+
18
+ export function snippet(root, src, around = 10) {
19
+ const { path, name } = parseAnchor(String(src || ''));
20
+ if (!path || path.endsWith('/')) return { path, kind: 'folder' };
21
+ const full = resolve(root, '.' + sep + path.replace(/\//g, sep));
22
+ if (!full.startsWith(resolve(root) + sep) || !existsSync(full)) return { path, error: 'not found' };
23
+ try { if (!realpathSync(full).startsWith(realpathSync(root) + sep)) return { path, error: 'outside the repo' }; } catch { return { path, error: 'not found' }; }
24
+ const tracked = git(root, ['ls-files', '--error-unmatch', '--', path]);
25
+ if (tracked === null) {
26
+ if (git(root, ['rev-parse', '--is-inside-work-tree']) !== null) return { path, error: 'not tracked by git' };
27
+ if (path.split('/').some((p) => p.startsWith('.'))) return { path, error: 'hidden file' };
28
+ }
29
+ const st = statSync(full);
30
+ if (st.isDirectory()) return { path, kind: 'folder' };
31
+ if (st.size > MAX_BYTES) return { path, error: 'file too large to show' };
32
+ const text = readFileSync(join(full), 'utf8');
33
+ if (text.includes('\0')) return { path, error: 'binary file' };
34
+ const lines = text.split(/\r?\n/);
35
+ let line = 0;
36
+ if (name) {
37
+ const esc = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
38
+ const re = new RegExp(`(?<![\\p{L}\\p{N}_$])${esc}(?![\\p{L}\\p{N}_$])`, 'u');
39
+ // Prefer the line that defines the name over lines that merely use it:
40
+ // 1. a keyword right before it (function x, class X, def x, const x = …), or x: / x = a function,
41
+ // or a method header at the start of a line (async x(…) {) that is not a call (this.x(…))
42
+ // 2. any line with a defining keyword 3. the first mention
43
+ const strong = [
44
+ new RegExp(`\\b(function\\*?|class|def|fn|func|interface|type|struct|enum|trait|impl|module|const|let|var|val)\\s+${esc}(?![\\p{L}\\p{N}_$])`, 'u'),
45
+ new RegExp(`(?<![.\\p{L}\\p{N}_$])${esc}\\s*[:=]\\s*(async\\s*)?(function|\\(|[\\p{L}_$][\\p{L}\\p{N}_$]*\\s*=>)`, 'u'),
46
+ // a method header: name(…) { or name(…): Type { on one line, or name( with the parameters continuing below
47
+ new RegExp(`^\\s*((public|private|protected|static|async|override|readonly|get|set)\\s+)*${esc}\\s*(<[^>]*>)?\\s*\\((.*\\)\\s*(:[^=]*?)?\\s*\\{\\s*$|[^)]*$)`, 'u'),
48
+ ];
49
+ const weak = /\b(function|class|def|fn|func|const|let|var|type|interface|export|struct|enum|router\.\w+|app\.\w+)\b/;
50
+ const hits = lines.map((l, i) => (re.test(l) ? i : -1)).filter((i) => i >= 0);
51
+ if (!hits.length) return { path, name, missing: true, total: lines.length };
52
+ line = hits.find((i) => strong.some((s) => s.test(lines[i]))) ?? hits.find((i) => weak.test(lines[i])) ?? hits[0] ?? 0;
53
+ }
54
+ const start = Math.max(0, line - 3);
55
+ const end = Math.min(lines.length, start + around * 2 + 1);
56
+ const dirty = (git(root, ['status', '--porcelain', '--', path]) || '').trim();
57
+ const changed = dirty ? 'uncommitted changes' : git(root, ['log', '-1', '--format=%cr', '--', path]);
58
+ return {
59
+ path, name, line: line + 1, start: start + 1, total: lines.length,
60
+ lines: lines.slice(start, end).map((l) => (l.length > 220 ? `${l.slice(0, 220)}…` : l)),
61
+ lastChange: changed ? changed.trim() : '',
62
+ };
63
+ }