@arshdelight/practi 0.18.0 → 0.20.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/README.md +79 -136
- package/dist/client.js +6 -6
- package/dist/client.js.map +1 -1
- package/dist/cmd/blob.js +21 -24
- package/dist/cmd/blob.js.map +1 -1
- package/dist/cmd/branch.js +5 -7
- package/dist/cmd/branch.js.map +1 -1
- package/dist/cmd/clone.js +29 -23
- package/dist/cmd/clone.js.map +1 -1
- package/dist/cmd/commit.js +97 -0
- package/dist/cmd/commit.js.map +1 -0
- package/dist/cmd/config.js +1 -17
- package/dist/cmd/config.js.map +1 -1
- package/dist/cmd/edit.js +18 -4
- package/dist/cmd/edit.js.map +1 -1
- package/dist/cmd/embed.js +30 -25
- package/dist/cmd/embed.js.map +1 -1
- package/dist/cmd/export.js +43 -0
- package/dist/cmd/export.js.map +1 -0
- package/dist/cmd/fix.js +9 -153
- package/dist/cmd/fix.js.map +1 -1
- package/dist/cmd/gc.js +6 -5
- package/dist/cmd/gc.js.map +1 -1
- package/dist/cmd/history.js +73 -70
- package/dist/cmd/history.js.map +1 -1
- package/dist/cmd/init.js +10 -5
- package/dist/cmd/init.js.map +1 -1
- package/dist/cmd/lint.js +23 -20
- package/dist/cmd/lint.js.map +1 -1
- package/dist/cmd/log.js +2 -4
- package/dist/cmd/log.js.map +1 -1
- package/dist/cmd/merge.js +13 -10
- package/dist/cmd/merge.js.map +1 -1
- package/dist/cmd/new.js +56 -54
- package/dist/cmd/new.js.map +1 -1
- package/dist/cmd/note.js +27 -42
- package/dist/cmd/note.js.map +1 -1
- package/dist/cmd/pull.js +17 -13
- package/dist/cmd/pull.js.map +1 -1
- package/dist/cmd/push.js +27 -12
- package/dist/cmd/push.js.map +1 -1
- package/dist/cmd/search.js +30 -44
- package/dist/cmd/search.js.map +1 -1
- package/dist/cmd/show.js +5 -4
- package/dist/cmd/show.js.map +1 -1
- package/dist/cmd/similar.js +7 -20
- package/dist/cmd/similar.js.map +1 -1
- package/dist/cmd/skill.js +16 -16
- package/dist/cmd/skill.js.map +1 -1
- package/dist/cmd/switch.js +11 -6
- package/dist/cmd/switch.js.map +1 -1
- package/dist/index.js +245 -447
- package/dist/index.js.map +1 -1
- package/dist/practice.js +120 -97
- package/dist/practice.js.map +1 -1
- package/dist/quality.js +2 -2
- package/dist/quality.js.map +1 -1
- package/dist/state.js +13 -73
- package/dist/state.js.map +1 -1
- package/dist/sync.js +6 -48
- package/dist/sync.js.map +1 -1
- package/dist/web.js +259 -481
- package/dist/web.js.map +1 -1
- package/dist/workspace.js +10 -52
- package/dist/workspace.js.map +1 -1
- package/package.json +1 -1
- package/skills/use-practi/SKILL.md +123 -125
- package/web-default/chain.html +39 -0
- package/web-default/chain.js +56 -0
- package/web-default/detail.js +11 -8
- package/web-default/home.html +36 -0
- package/web-default/home.js +49 -0
- package/web-default/lang.js +17 -23
- package/web-default/style.css +1 -1
- package/web-default/app.js +0 -132
- package/web-default/index.html +0 -28
package/dist/web.js
CHANGED
|
@@ -3,16 +3,12 @@ import fs from 'node:fs';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
|
-
import { aggregateView, computeNodeHash, exportSubtree, readBlob, resolveNodeRef
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import { loadNotes, subtreeHashes, insertNote, updateNote, removeNote, NOTES_FILE } from './notes.js';
|
|
11
|
-
import { runNew } from './cmd/new.js';
|
|
6
|
+
import { aggregateView, computeNodeHash, exportSubtree, readBlob, resolveNodeRef } from '@arshdelight/pop-sdk';
|
|
7
|
+
import { chainPathFor, findRepoFromCwd, isRepoDir, loadChain, openPool, practiDirFor, resolveRepo, workingFileFor } from './practice.js';
|
|
8
|
+
import { defaultDataDir } from './state.js';
|
|
9
|
+
import { loadNotes, insertNote, updateNote, removeNote } from './notes.js';
|
|
12
10
|
/** 内置默认前端(随包分发的普通文件):dist/../web-default 与 src/../web-default 都指向 cli/web-default */
|
|
13
11
|
const DEFAULT_WEB_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'web-default');
|
|
14
|
-
/** workspace 里的覆盖目录名:里面的文件按文件级覆盖默认前端(不存在的文件回落默认) */
|
|
15
|
-
const WEB_OVERRIDE_DIR = 'web';
|
|
16
12
|
const STATIC_TYPES = {
|
|
17
13
|
'.html': 'text/html; charset=utf-8',
|
|
18
14
|
'.css': 'text/css; charset=utf-8',
|
|
@@ -23,300 +19,240 @@ const STATIC_TYPES = {
|
|
|
23
19
|
'.png': 'image/png',
|
|
24
20
|
'.ico': 'image/x-icon',
|
|
25
21
|
};
|
|
26
|
-
/**
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
function injectLiveReload(html) {
|
|
30
|
-
const tag = '<script src="/_lr.js" defer></script>';
|
|
31
|
-
return /<\/body>/i.test(html) ? html.replace(/<\/body>/i, `${tag}</body>`) : html + tag;
|
|
22
|
+
/** practices 家目录:配置家下的 practices/(migrate 时代即此布局,实例文件夹聚居地) */
|
|
23
|
+
function practicesHome() {
|
|
24
|
+
return path.join(defaultDataDir(), 'practices');
|
|
32
25
|
}
|
|
33
26
|
export function runWeb(opts) {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
27
|
+
if (opts.dir) {
|
|
28
|
+
// 显式 --dir 定位失败是硬错误(用户点名了一个文件夹)
|
|
29
|
+
const repo = resolveRepo({ dir: opts.dir, verb: 'web' });
|
|
30
|
+
if (repo === null)
|
|
31
|
+
return 1;
|
|
32
|
+
return serve({ kind: 'repo', repo }, opts);
|
|
33
|
+
}
|
|
34
|
+
const fromCwd = findRepoFromCwd(process.cwd());
|
|
35
|
+
if (fromCwd)
|
|
36
|
+
return serve({ kind: 'repo', repo: fromCwd }, opts);
|
|
37
|
+
// cwd 不在任何实例文件夹里 → practices 总览(家目录缺/空也照开,页面给空态)
|
|
38
|
+
return serve({ kind: 'home', homeDir: practicesHome() }, opts);
|
|
39
|
+
}
|
|
40
|
+
function serve(ctx, opts) {
|
|
37
41
|
const url = `http://127.0.0.1:${opts.port}/`;
|
|
38
|
-
// live reload:SSE 客户端池 + 文件/数据监听。监听面 = 整个 data dir(nodes/、
|
|
39
|
-
// 覆盖目录 web/、practi.json 全覆盖:另一终端 practi new 页面也会自动跟新)
|
|
40
|
-
// + 内置默认前端目录(CLI 开发期改默认文件也即时生效)
|
|
41
|
-
const clients = new Set();
|
|
42
|
-
watchLive([dataDir, DEFAULT_WEB_DIR], clients);
|
|
43
|
-
const overrideDir = path.join(dataDir, WEB_OVERRIDE_DIR);
|
|
44
|
-
console.log(`frontend: ${fs.existsSync(overrideDir) ? `workspace override ${overrideDir} (missing files fall back to built-in)` : `built-in default (drop files into ${overrideDir}${path.sep} to customize)`}`);
|
|
45
42
|
const server = http.createServer((req, res) => {
|
|
46
|
-
|
|
47
|
-
// ws 每请求重建:命令写入(本端点的 /api/run,或另一终端的 practi new)
|
|
48
|
-
// 必须立即可见,不能拿启动时的快照过滤数据窗
|
|
49
|
-
handle(req, res, dataDir, openWorkspace(dataDir), clients);
|
|
50
|
-
}
|
|
51
|
-
catch (e) {
|
|
52
|
-
if (e instanceof PracticeError) {
|
|
53
|
-
send(res, 404, 'text/plain; charset=utf-8', `${e.code}: ${e.message}`);
|
|
54
|
-
}
|
|
55
|
-
else {
|
|
56
|
-
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
|
|
57
|
-
res.end(e instanceof Error ? e.message : String(e));
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
});
|
|
61
|
-
// 端口占用是常人操作(重复开 practi web),不该甩 Node 堆栈——给出人话 + 出路
|
|
62
|
-
server.on('error', (e) => {
|
|
63
|
-
if (e.code !== 'EADDRINUSE')
|
|
64
|
-
throw e;
|
|
65
|
-
console.error(`port ${opts.port} is already in use.`);
|
|
66
|
-
http.get({ host: '127.0.0.1', port: opts.port, path: '/healthz', timeout: 1000 }, r => {
|
|
67
|
-
const chunks = [];
|
|
68
|
-
r.on('data', c => void chunks.push(c));
|
|
69
|
-
r.on('end', () => {
|
|
70
|
-
if (Buffer.concat(chunks).toString('utf8') === 'ok') {
|
|
71
|
-
console.error('it looks like another practi web is already serving there.');
|
|
72
|
-
console.error(`open ${url} directly, or start on a different port: practi web --port <other>`);
|
|
73
|
-
}
|
|
74
|
-
else {
|
|
75
|
-
console.error('something else occupies it — try: practi web --port <other>');
|
|
76
|
-
}
|
|
77
|
-
});
|
|
78
|
-
}).on('error', () => {
|
|
79
|
-
console.error('something else occupies it — try: practi web --port <other>');
|
|
80
|
-
}).on('timeout', function () {
|
|
81
|
-
this.destroy();
|
|
82
|
-
console.error('something else occupies it — try: practi web --port <other>');
|
|
83
|
-
});
|
|
84
|
-
setTimeout(() => process.exit(1), 1500);
|
|
43
|
+
void handle(req, res, ctx);
|
|
85
44
|
});
|
|
86
45
|
server.listen(opts.port, '127.0.0.1', () => {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
46
|
+
if (ctx.kind === 'repo') {
|
|
47
|
+
console.log(`practi web — ${ctx.repo.chain.name}@${ctx.repo.chain.current} → ${url}`);
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
console.log(`practi web — practices home ${ctx.homeDir} → ${url}`);
|
|
51
|
+
}
|
|
52
|
+
console.log('Ctrl+C to stop');
|
|
90
53
|
if (opts.open)
|
|
91
54
|
openBrowser(url);
|
|
92
55
|
});
|
|
93
56
|
return 0;
|
|
94
57
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
send(res, 200, 'text/javascript; charset=utf-8', LR_SCRIPT);
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
if (pathname === '/api/practices') {
|
|
107
|
-
const practices = listRegistryPractices(dataDir).map(function (r) {
|
|
108
|
-
const head = r.chain.branches[r.chain.current] ?? null;
|
|
109
|
-
return {
|
|
110
|
-
name: r.chain.name,
|
|
111
|
-
owner: r.chain.owner,
|
|
112
|
-
branch: r.chain.current,
|
|
113
|
-
head: head,
|
|
114
|
-
commits: r.chain.commits.length,
|
|
115
|
-
unpushed: r.chain.commits.filter(function (c) { return !c.pushedAt; }).length,
|
|
116
|
-
};
|
|
117
|
-
});
|
|
118
|
-
send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ practices: practices }, null, 2));
|
|
119
|
-
return;
|
|
120
|
-
}
|
|
121
|
-
if (pathname === '/api/directs') {
|
|
122
|
-
send(res, 200, 'application/json; charset=utf-8', JSON.stringify(directsPayload(dataDir, ws, state), null, 2));
|
|
123
|
-
return;
|
|
124
|
-
}
|
|
125
|
-
if (pathname === '/api/notes') {
|
|
126
|
-
if (req.method === 'POST')
|
|
127
|
-
void handleNoteWrite(req, res, dataDir, ws);
|
|
128
|
-
else
|
|
129
|
-
notesRoute(req, res, dataDir, ws);
|
|
130
|
-
return;
|
|
131
|
-
}
|
|
132
|
-
if (pathname === '/api/run') {
|
|
133
|
-
void handleRun(req, res, dataDir);
|
|
134
|
-
return;
|
|
58
|
+
/** 打开系统默认浏览器(oauth 登录流程共用);失败静默——URL 已打印在终端 */
|
|
59
|
+
export function openBrowser(url) {
|
|
60
|
+
const opener = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open';
|
|
61
|
+
const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
|
|
62
|
+
try {
|
|
63
|
+
const child = spawn(opener, args, { stdio: 'ignore', detached: true });
|
|
64
|
+
child.on('error', () => console.log(`open this in your browser: ${url}`));
|
|
65
|
+
child.unref();
|
|
135
66
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
return;
|
|
139
|
-
send(res, 500, 'text/plain; charset=utf-8', 'built-in web frontend missing — reinstall the CLI');
|
|
140
|
-
return;
|
|
67
|
+
catch {
|
|
68
|
+
console.log(`open this in your browser: ${url}`);
|
|
141
69
|
}
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
send(res, 404, 'application/json; charset=utf-8', JSON.stringify({ error: 'no such practice' }));
|
|
70
|
+
}
|
|
71
|
+
async function handle(req, res, ctx) {
|
|
72
|
+
const pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname);
|
|
73
|
+
try {
|
|
74
|
+
if (ctx.kind === 'repo') {
|
|
75
|
+
await handleRepo(req, res, ctx.repo, pathname);
|
|
149
76
|
return;
|
|
150
77
|
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
parent_hash: c.parent,
|
|
155
|
-
message: c.message,
|
|
156
|
-
pushed: c.pushedAt !== undefined,
|
|
157
|
-
}));
|
|
158
|
-
if (practice[2] === '.json') {
|
|
159
|
-
send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ name, owner: repo.chain.owner, branch: repo.chain.current, revisions: rows }, null, 2));
|
|
78
|
+
// ── home 模式:/ 总览页、/api/practices 清单、/p/<name>/… 实例前缀路由 ──
|
|
79
|
+
if (pathname === '/' || pathname === '/index.html') {
|
|
80
|
+
servePage(res, 'home.html');
|
|
160
81
|
return;
|
|
161
82
|
}
|
|
162
|
-
|
|
163
|
-
.
|
|
164
|
-
const mark = r.root_hash === repo.chain.branches[repo.chain.current] ? ' ●' : '';
|
|
165
|
-
return ('<tr><td>v' + r.seq + '</td><td><a class="doc-name" href="/pop/' + encodeURIComponent(r.root_hash) + '">' +
|
|
166
|
-
r.root_hash.slice(7, 19) + '</a>' + mark + '</td><td>' +
|
|
167
|
-
String(r.message).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]) + '</td><td>' + (r.pushed ? 'synced' : 'local') + '</td></tr>');
|
|
168
|
-
})
|
|
169
|
-
.join('\n');
|
|
170
|
-
const owner = repo.chain.owner ? repo.chain.owner + '/' + name : name + ' (local only)';
|
|
171
|
-
send(res, 200, 'text/html; charset=utf-8', '<!doctype html><html lang="en"><head><meta charset="utf-8"><title>' + name + ' — Practi</title>' +
|
|
172
|
-
'<link rel="stylesheet" href="/style.css"></head><body><header><a class="brand-link" href="/"><span class="brand">practi</span></a></header>' +
|
|
173
|
-
'<main id="app"><h3 class="page-title">' + owner + ' @ ' + repo.chain.current + '</h3>' +
|
|
174
|
-
'<table class="doc-table"><thead><tr><th>Seq</th><th>Root</th><th>Message</th><th>Sync</th></tr></thead><tbody>' +
|
|
175
|
-
table +
|
|
176
|
-
'</tbody></table></main></body></html>');
|
|
177
|
-
return;
|
|
178
|
-
}
|
|
179
|
-
const pop = pathname.match(/^\/pop\/(.+)$/);
|
|
180
|
-
if (pop) {
|
|
181
|
-
const hash = decodeURIComponent(pop[1]).replace(/\.json$/, '');
|
|
182
|
-
const resolved = resolveNodeRef(ws, hash);
|
|
183
|
-
if (pathname.endsWith('.json')) {
|
|
184
|
-
const view = aggregateView(resolved, ws.nodes);
|
|
185
|
-
send(res, 200, 'application/json; charset=utf-8', JSON.stringify(view, null, 2));
|
|
83
|
+
if (pathname === '/api/practices') {
|
|
84
|
+
send(res, 200, 'application/json; charset=utf-8', JSON.stringify(listPractices(ctx.homeDir), null, 2));
|
|
186
85
|
return;
|
|
187
86
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
87
|
+
const m = pathname.match(/^\/p\/([^/]+)(\/.*)?$/);
|
|
88
|
+
if (m) {
|
|
89
|
+
const name = m[1];
|
|
90
|
+
const prefix = `/p/${name}`;
|
|
91
|
+
if (name === '.' || name === '..' || name.includes('\\')) {
|
|
92
|
+
send(res, 404, 'text/plain; charset=utf-8', 'not found');
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
const dir = path.join(ctx.homeDir, name);
|
|
96
|
+
const chain = isRepoDir(dir) ? loadChain(chainPathFor(dir)) : null;
|
|
97
|
+
if (!chain) {
|
|
98
|
+
send(res, 404, 'text/plain; charset=utf-8', 'practice not found');
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const repo = { dir, chain, chainPath: chainPathFor(dir), filePath: workingFileFor(dir, chain.name), poolDir: practiDirFor(dir) };
|
|
102
|
+
const rest = m[2] ?? '/';
|
|
103
|
+
if (rest === '/' || rest === '/index.html' || /^\/(api|pop|doc|blobs)\//.test(rest)) {
|
|
104
|
+
await handleRepo(req, res, repo, rest, prefix);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
send(res, 404, 'text/plain; charset=utf-8', 'not found');
|
|
198
108
|
return;
|
|
199
109
|
}
|
|
200
|
-
|
|
201
|
-
return;
|
|
202
|
-
}
|
|
203
|
-
const doc = pathname.match(/^\/doc\/(.+)$/);
|
|
204
|
-
if (doc) {
|
|
205
|
-
const hash = decodeURIComponent(doc[1]).replace(/\.json$/, '');
|
|
206
|
-
const node = ws.nodes.get(resolveNodeRef(ws, hash));
|
|
207
|
-
if (node) {
|
|
208
|
-
// 加法演进:树字段仍在顶层(老前端照常读),nodeIndex 是新增兄弟键(新前端才消费)。
|
|
209
|
-
// 前端文件热更可能跑在服务器 dist 前面、用户覆盖的 web/ 也可能落后 CLI 升级——
|
|
210
|
-
// 数据窗任何改动都必须新旧两端互容,不能用信封换结构
|
|
211
|
-
const tree = exportSubtree(node, ws.nodes);
|
|
212
|
-
send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ ...tree, nodeIndex: buildNodeIndex(tree) }, null, 2));
|
|
110
|
+
if (serveStatic(res, pathname.slice(1)))
|
|
213
111
|
return;
|
|
214
|
-
|
|
215
|
-
}
|
|
216
|
-
if (pathname === '/healthz') {
|
|
217
|
-
send(res, 200, 'text/plain', 'ok');
|
|
218
|
-
return;
|
|
112
|
+
send(res, 404, 'text/plain; charset=utf-8', 'not found');
|
|
219
113
|
}
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
return;
|
|
223
|
-
send(res, 404, 'text/plain; charset=utf-8', 'not found');
|
|
224
|
-
}
|
|
225
|
-
class ApiError extends Error {
|
|
226
|
-
status;
|
|
227
|
-
constructor(status, message) {
|
|
228
|
-
super(message);
|
|
229
|
-
this.status = status;
|
|
114
|
+
catch (e) {
|
|
115
|
+
send(res, 500, 'text/plain; charset=utf-8', e instanceof Error ? e.message : String(e));
|
|
230
116
|
}
|
|
231
117
|
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
throw new ApiError(400, 'string argument expected');
|
|
235
|
-
return v;
|
|
236
|
-
}
|
|
237
|
-
const RUNNABLE = {
|
|
238
|
-
new: {
|
|
239
|
-
run: (a, d) => {
|
|
240
|
-
const json = asStr(a.json);
|
|
241
|
-
if (!json || !json.trim())
|
|
242
|
-
throw new ApiError(400, 'new requires args.json (POP document text)');
|
|
243
|
-
return runNew({ dataDir: d, json, positional: [] });
|
|
244
|
-
},
|
|
245
|
-
},
|
|
246
|
-
};
|
|
247
|
-
/** 命令输出捕获:命令函数走 console.log/error,调用期间临时替换收集,finally 恢复。
|
|
248
|
-
* 进程级替换在并发下有竞态 → runQueue 互斥,同一时刻只跑一条命令(写操作本就不应并发) */
|
|
249
|
-
let runQueue = Promise.resolve();
|
|
250
|
-
function enqueueRun(fn) {
|
|
251
|
-
const next = runQueue.then(fn, fn);
|
|
252
|
-
runQueue = next.catch(() => { });
|
|
253
|
-
return next;
|
|
254
|
-
}
|
|
255
|
-
async function captureConsole(fn) {
|
|
256
|
-
const out = [];
|
|
257
|
-
const errBuf = [];
|
|
258
|
-
const origLog = console.log;
|
|
259
|
-
const origErr = console.error;
|
|
260
|
-
console.log = (...a) => void out.push(a.join(' '));
|
|
261
|
-
console.error = (...a) => void errBuf.push(a.join(' '));
|
|
118
|
+
/** 单实例路由(pathname 已剥前缀):单仓模式 prefix 为空串,home 模式传 /p/<name> 供页面注入 */
|
|
119
|
+
async function handleRepo(req, res, repo, pathname, prefix = '') {
|
|
262
120
|
try {
|
|
263
|
-
|
|
121
|
+
if (pathname === '/api/repo') {
|
|
122
|
+
const branch = new URL(req.url ?? '/', 'http://x').searchParams.get('branch') ?? repo.chain.current;
|
|
123
|
+
const head = repo.chain.branches[branch] ?? null;
|
|
124
|
+
const byRoot = new Map(repo.chain.commits.map((c) => [c.root, c]));
|
|
125
|
+
const commits = [];
|
|
126
|
+
const seen = new Set();
|
|
127
|
+
let cur = head;
|
|
128
|
+
while (cur !== null && !seen.has(cur)) {
|
|
129
|
+
const c = byRoot.get(cur);
|
|
130
|
+
if (!c)
|
|
131
|
+
break;
|
|
132
|
+
seen.add(cur);
|
|
133
|
+
commits.push({ seq: c.seq, root: c.root, message: c.message, pushedAt: c.pushedAt ?? null });
|
|
134
|
+
cur = c.parent;
|
|
135
|
+
}
|
|
136
|
+
send(res, 200, 'application/json; charset=utf-8', JSON.stringify({
|
|
137
|
+
name: repo.chain.name,
|
|
138
|
+
owner: repo.chain.owner,
|
|
139
|
+
current: repo.chain.current,
|
|
140
|
+
branches: Object.entries(repo.chain.branches).map(([name, r]) => ({
|
|
141
|
+
name,
|
|
142
|
+
head: r,
|
|
143
|
+
isDefault: name === 'main',
|
|
144
|
+
current: name === repo.chain.current,
|
|
145
|
+
})),
|
|
146
|
+
branch,
|
|
147
|
+
head,
|
|
148
|
+
commits,
|
|
149
|
+
}, null, 2));
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (pathname === '/api/notes') {
|
|
153
|
+
if (req.method === 'POST') {
|
|
154
|
+
await handleNoteWrite(req, res, repo.poolDir);
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
notesRoute(req, res, repo.poolDir);
|
|
158
|
+
}
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (pathname === '/' || pathname === '/index.html') {
|
|
162
|
+
servePage(res, 'chain.html', prefix);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
const pop = pathname.match(/^\/pop\/(.+)$/);
|
|
166
|
+
if (pop) {
|
|
167
|
+
const hash = pop[1].replace(/\.json$/, '');
|
|
168
|
+
const ws = openPool(repo);
|
|
169
|
+
const resolved = resolveNodeRef(ws, hash);
|
|
170
|
+
if (pathname.endsWith('.json')) {
|
|
171
|
+
const view = aggregateView(resolved, ws.nodes, { full: true });
|
|
172
|
+
send(res, 200, 'application/json; charset=utf-8', JSON.stringify(view, null, 2));
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
servePage(res, 'detail.html', prefix);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const doc = pathname.match(/^\/doc\/(.+)$/);
|
|
179
|
+
if (doc) {
|
|
180
|
+
const hash = doc[1].replace(/\.json$/, '');
|
|
181
|
+
const ws = openPool(repo);
|
|
182
|
+
const node = ws.nodes.get(resolveNodeRef(ws, hash));
|
|
183
|
+
if (!node) {
|
|
184
|
+
send(res, 404, 'application/json; charset=utf-8', JSON.stringify({ error: 'node not found' }));
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const document = exportSubtree(node, ws.nodes);
|
|
188
|
+
// 加法演进:树字段在顶层(老前端照常读),nodeIndex 是新增兄弟键(前端把
|
|
189
|
+
// inputs.from 反解成 #编号引用用——哈希不在树里,引用靠旁路登记)
|
|
190
|
+
send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ ...document, nodeIndex: buildNodeIndex(document) }, null, 2));
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const blob = pathname.match(/^\/blobs\/(sha256:[0-9a-f]{64})$/);
|
|
194
|
+
if (blob) {
|
|
195
|
+
const ws = openPool(repo);
|
|
196
|
+
const bytes = readBlob(ws.root, blob[1]);
|
|
197
|
+
if (bytes === null) {
|
|
198
|
+
send(res, 404, 'text/plain; charset=utf-8', 'E_BLOB_MISSING: blob not present in this practice');
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
sendBytes(res, mimeFor(bytes), bytes);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (serveStatic(res, pathname.slice(1)))
|
|
205
|
+
return;
|
|
206
|
+
send(res, 404, 'text/plain; charset=utf-8', 'not found');
|
|
264
207
|
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
console.error = origErr;
|
|
208
|
+
catch (e) {
|
|
209
|
+
send(res, 500, 'text/plain; charset=utf-8', e instanceof Error ? e.message : String(e));
|
|
268
210
|
}
|
|
269
211
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
const
|
|
274
|
-
const
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
return new URL(origin).host === host;
|
|
279
|
-
}
|
|
280
|
-
catch {
|
|
281
|
-
return false;
|
|
212
|
+
// ── 学习笔记(/api/notes,sidecar .practi/notes.json;GET 按哈希分组、?ref= 过滤;POST add/update/delete)──
|
|
213
|
+
function notesRoute(req, res, poolDir) {
|
|
214
|
+
const ref = new URL(req.url ?? '/', 'http://x').searchParams.get('ref') ?? undefined;
|
|
215
|
+
const byHash = {};
|
|
216
|
+
for (const n of loadNotes(poolDir).notes) {
|
|
217
|
+
if (ref !== undefined && n.hash !== ref)
|
|
218
|
+
continue;
|
|
219
|
+
(byHash[n.hash] ??= []).push(n);
|
|
282
220
|
}
|
|
221
|
+
send(res, 200, 'application/json; charset=utf-8', JSON.stringify(byHash, null, 2));
|
|
283
222
|
}
|
|
284
|
-
async function
|
|
223
|
+
async function handleNoteWrite(req, res, poolDir) {
|
|
285
224
|
const fail = (status, message) => send(res, status, 'application/json; charset=utf-8', JSON.stringify({ error: message }));
|
|
286
225
|
try {
|
|
287
226
|
if (req.method !== 'POST')
|
|
288
|
-
throw new
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
const body = await readBody(req,
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
227
|
+
throw new Error('POST only');
|
|
228
|
+
const origin = req.headers.origin;
|
|
229
|
+
const host = req.headers.host;
|
|
230
|
+
if (typeof origin !== 'string' || typeof host !== 'string' || new URL(origin).host !== host) {
|
|
231
|
+
throw new Error('same-origin POST required');
|
|
232
|
+
}
|
|
233
|
+
const body = JSON.parse(await readBody(req, 1024 * 1024));
|
|
234
|
+
// 口径与 CLI 对齐:文本非空(trim 后),update/delete 的未知 id/歧义前缀如实 400
|
|
235
|
+
const fail = (m) => { throw new Error(m); };
|
|
236
|
+
if (body.op === 'add' && typeof body.hash === 'string' && typeof body.text === 'string' && body.text.trim() !== '') {
|
|
237
|
+
insertNote(poolDir, body.hash, body.text);
|
|
238
|
+
}
|
|
239
|
+
else if (body.op === 'update' && typeof body.id === 'string' && typeof body.text === 'string' && body.text.trim() !== '') {
|
|
240
|
+
const m = updateNote(poolDir, body.id, body.text);
|
|
241
|
+
if (!m.ok)
|
|
242
|
+
fail(m.reason === 'ambiguous' ? `ambiguous note id: ${body.id}` : 'no such note');
|
|
243
|
+
}
|
|
244
|
+
else if (body.op === 'delete' && typeof body.id === 'string') {
|
|
245
|
+
const m = removeNote(poolDir, body.id);
|
|
246
|
+
if (!m.ok)
|
|
247
|
+
fail(m.reason === 'ambiguous' ? `ambiguous note id: ${body.id}` : 'no such note');
|
|
298
248
|
}
|
|
299
|
-
|
|
300
|
-
throw new
|
|
249
|
+
else {
|
|
250
|
+
throw new Error('op must be add{hash,text} / update{id,text} / delete{id} (text must be non-empty)');
|
|
301
251
|
}
|
|
302
|
-
|
|
303
|
-
if (!spec)
|
|
304
|
-
throw new ApiError(400, `unknown cmd — runnable: ${Object.keys(RUNNABLE).join(', ')}`);
|
|
305
|
-
const args = parsed.args ?? {};
|
|
306
|
-
const result = await enqueueRun(() => captureConsole(() => spec.run(args, dataDir)).catch(e => {
|
|
307
|
-
// 参数校验错误透传为 4xx;命令自身的异常对齐 CLI 顶层语义(打印 + 退出码 1),
|
|
308
|
-
// 命令失败是结果不是服务器错误,不该是 500
|
|
309
|
-
if (e instanceof ApiError)
|
|
310
|
-
throw e;
|
|
311
|
-
return { code: 1, out: '', err: e instanceof Error ? e.message : String(e) };
|
|
312
|
-
}));
|
|
313
|
-
send(res, 200, 'application/json; charset=utf-8', JSON.stringify(result));
|
|
252
|
+
send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ ok: true }));
|
|
314
253
|
}
|
|
315
254
|
catch (e) {
|
|
316
|
-
|
|
317
|
-
fail(e.status, e.message);
|
|
318
|
-
else
|
|
319
|
-
fail(500, e instanceof Error ? e.message : String(e));
|
|
255
|
+
fail(400, e instanceof Error ? e.message : String(e));
|
|
320
256
|
}
|
|
321
257
|
}
|
|
322
258
|
async function readBody(req, limit) {
|
|
@@ -326,7 +262,7 @@ async function readBody(req, limit) {
|
|
|
326
262
|
req.on('data', (c) => {
|
|
327
263
|
size += c.length;
|
|
328
264
|
if (size > limit) {
|
|
329
|
-
reject(new
|
|
265
|
+
reject(new Error('request body too large'));
|
|
330
266
|
req.destroy();
|
|
331
267
|
return;
|
|
332
268
|
}
|
|
@@ -337,8 +273,7 @@ async function readBody(req, limit) {
|
|
|
337
273
|
});
|
|
338
274
|
}
|
|
339
275
|
/** 节点指纹登记簿(哈希→树内 children 下标路径),/doc 数据窗附带:前端把 inputs.from
|
|
340
|
-
* 反解成
|
|
341
|
-
* 引用靠旁路登记。根(空路径)不成节、无编号,不登记(from 指向根按未命中回落哈希)。 */
|
|
276
|
+
* 反解成 #编号引用用。根(空路径)不成节、无编号,不登记。 */
|
|
342
277
|
function buildNodeIndex(tree) {
|
|
343
278
|
const index = {};
|
|
344
279
|
const visit = (n, p) => {
|
|
@@ -350,234 +285,77 @@ function buildNodeIndex(tree) {
|
|
|
350
285
|
visit(tree, []);
|
|
351
286
|
return index;
|
|
352
287
|
}
|
|
353
|
-
function
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
}
|
|
357
|
-
/** 静态文件:workspace 的 web/ 按文件覆盖,缺失文件回落内置默认。
|
|
358
|
-
* 拒绝 `..` 段做路径遍历防护;HTML 响应注入 live reload 脚本(对默认与自定义前端一视同仁) */
|
|
359
|
-
function serveStatic(res, rel, dataDir) {
|
|
360
|
-
const parts = rel.split('/').filter(Boolean);
|
|
361
|
-
if (parts.length === 0 || parts.includes('..'))
|
|
288
|
+
function serveStatic(res, rel) {
|
|
289
|
+
const file = path.join(DEFAULT_WEB_DIR, rel);
|
|
290
|
+
if (!file.startsWith(DEFAULT_WEB_DIR) || !fs.existsSync(file) || !fs.statSync(file).isFile())
|
|
362
291
|
return false;
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
if (!file)
|
|
366
|
-
return false;
|
|
367
|
-
const type = STATIC_TYPES[path.extname(file).toLowerCase()] ?? 'application/octet-stream';
|
|
368
|
-
const body = fs.readFileSync(file);
|
|
369
|
-
res.writeHead(200, { 'content-type': type, 'cache-control': 'no-cache' });
|
|
370
|
-
if (type.startsWith('text/html')) {
|
|
371
|
-
res.end(injectLiveReload(body.toString('utf8')));
|
|
372
|
-
}
|
|
373
|
-
else {
|
|
374
|
-
res.end(body);
|
|
375
|
-
}
|
|
292
|
+
const type = STATIC_TYPES[path.extname(file)] ?? 'application/octet-stream';
|
|
293
|
+
sendBytes(res, type, fs.readFileSync(file));
|
|
376
294
|
return true;
|
|
377
295
|
}
|
|
378
|
-
/**
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
.filter(h => ws.nodes.has(h))
|
|
384
|
-
.map(h => {
|
|
385
|
-
const v = aggregateView(h, ws.nodes);
|
|
386
|
-
const claimedAt = state.claims?.[h] ?? null;
|
|
387
|
-
return {
|
|
388
|
-
hash: v.hash,
|
|
389
|
-
name: v.name,
|
|
390
|
-
description: v.description,
|
|
391
|
-
type: v.type,
|
|
392
|
-
op: v.type === 'practice' ? v.op : null,
|
|
393
|
-
steps: v.steps.length,
|
|
394
|
-
// 全树节点数(含根,=详情页侧栏 countNodes 口径);steps 保留给既有消费者(加法演进)
|
|
395
|
-
nodes: subtreeHashes(ws, h).size,
|
|
396
|
-
outputs: v.outputs.length,
|
|
397
|
-
claimedAt,
|
|
398
|
-
addedAt: claimedAt ?? nodeFileTime(dataDir, h),
|
|
399
|
-
};
|
|
400
|
-
});
|
|
401
|
-
return { dataDir, docs };
|
|
402
|
-
}
|
|
403
|
-
/** POST /api/notes:note 的第二个写入门(官方前端侧栏编辑用;CLI practi note 仍是第一门)。
|
|
404
|
-
* 本地个人数据,无审核诉求,但 CSRF 闸与 /api/run 同规格(sameOrigin + application/json)。
|
|
405
|
-
* body={op:'add',hash,content} | {op:'edit',id,content} | {op:'delete',id}。 */
|
|
406
|
-
async function handleNoteWrite(req, res, dataDir, ws) {
|
|
407
|
-
const fail = (status, message) => send(res, status, 'application/json; charset=utf-8', JSON.stringify({ error: message }));
|
|
408
|
-
try {
|
|
409
|
-
if (req.method !== 'POST')
|
|
410
|
-
throw new ApiError(405, 'POST only');
|
|
411
|
-
if (!sameOrigin(req))
|
|
412
|
-
throw new ApiError(403, 'same-origin POST required (Origin header missing or foreign)');
|
|
413
|
-
const ctype = String(req.headers['content-type'] ?? '');
|
|
414
|
-
if (!ctype.startsWith('application/json'))
|
|
415
|
-
throw new ApiError(415, 'content-type must be application/json');
|
|
416
|
-
const body = await readBody(req, 256 * 1024);
|
|
417
|
-
let parsed;
|
|
418
|
-
try {
|
|
419
|
-
parsed = JSON.parse(body);
|
|
420
|
-
}
|
|
421
|
-
catch {
|
|
422
|
-
throw new ApiError(400, 'request body is not valid JSON');
|
|
423
|
-
}
|
|
424
|
-
const content = typeof parsed.content === 'string' ? parsed.content : '';
|
|
425
|
-
const okBody = (note) => send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ note }, null, 2));
|
|
426
|
-
switch (parsed.op) {
|
|
427
|
-
case 'add': {
|
|
428
|
-
if (!content.trim())
|
|
429
|
-
throw new ApiError(400, 'content required');
|
|
430
|
-
const ref = typeof parsed.hash === 'string' ? parsed.hash : '';
|
|
431
|
-
let hash;
|
|
432
|
-
try {
|
|
433
|
-
hash = resolveNodeRef(ws, ref);
|
|
434
|
-
}
|
|
435
|
-
catch (e) {
|
|
436
|
-
throw new ApiError(404, e instanceof PracticeError ? `${e.code}: ${e.message}` : String(e));
|
|
437
|
-
}
|
|
438
|
-
return void okBody(insertNote(dataDir, hash, content));
|
|
439
|
-
}
|
|
440
|
-
case 'edit': {
|
|
441
|
-
if (!content.trim())
|
|
442
|
-
throw new ApiError(400, 'content required');
|
|
443
|
-
const id = typeof parsed.id === 'string' ? parsed.id : '';
|
|
444
|
-
const m = updateNote(dataDir, id, content);
|
|
445
|
-
if (!m.ok)
|
|
446
|
-
throw mutationError(id, m);
|
|
447
|
-
return void okBody(m.note);
|
|
448
|
-
}
|
|
449
|
-
case 'delete': {
|
|
450
|
-
const id = typeof parsed.id === 'string' ? parsed.id : '';
|
|
451
|
-
const m = removeNote(dataDir, id);
|
|
452
|
-
if (!m.ok)
|
|
453
|
-
throw mutationError(id, m);
|
|
454
|
-
return void send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ deleted: true, id: m.note.id }, null, 2));
|
|
455
|
-
}
|
|
456
|
-
default:
|
|
457
|
-
throw new ApiError(400, 'op must be add | edit | delete');
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
catch (e) {
|
|
461
|
-
if (e instanceof ApiError)
|
|
462
|
-
fail(e.status, e.message);
|
|
463
|
-
else
|
|
464
|
-
fail(500, e instanceof Error ? e.message : String(e));
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
function mutationError(id, m) {
|
|
468
|
-
return m.reason === 'not_found'
|
|
469
|
-
? new ApiError(404, `note "${id}" not found`)
|
|
470
|
-
: new ApiError(400, `note id prefix "${id}" matches ${m.matches} notes`);
|
|
471
|
-
}
|
|
472
|
-
/** 笔记数据窗:GET /api/notes?ref=<hash> → 该节点子树内的本地笔记(存入顺序=时间正序)。
|
|
473
|
-
* 独立只读端点、纯加法(不碰既有数据窗);写入口在 CLI(practi note)。ref 缺失 400、
|
|
474
|
-
* 解析不到 404——错误对齐其它路由的纯文本口径。notes.json 在 dataDir 下,live reload
|
|
475
|
-
* 天然覆盖:另一终端 note add 后页面自动刷新出笔记 */
|
|
476
|
-
function notesRoute(req, res, dataDir, ws) {
|
|
477
|
-
const ref = new URL(req.url ?? '/', 'http://localhost').searchParams.get('ref');
|
|
478
|
-
if (!ref) {
|
|
479
|
-
send(res, 400, 'text/plain; charset=utf-8', 'E_ARGS: missing ?ref=<hash>');
|
|
296
|
+
/** 页面文件(html):prefix 非空时注入 window.POP_WEB_PREFIX,前端据此拼 API/链接 */
|
|
297
|
+
function servePage(res, file, prefix = '') {
|
|
298
|
+
const fp = path.join(DEFAULT_WEB_DIR, file);
|
|
299
|
+
if (!fp.startsWith(DEFAULT_WEB_DIR) || !fs.existsSync(fp) || !fs.statSync(fp).isFile()) {
|
|
300
|
+
send(res, 404, 'text/plain; charset=utf-8', 'not found');
|
|
480
301
|
return;
|
|
481
302
|
}
|
|
482
|
-
let
|
|
303
|
+
let html = fs.readFileSync(fp, 'utf8');
|
|
304
|
+
if (prefix)
|
|
305
|
+
html = html.replace(/<\/head>/i, `<script>window.POP_WEB_PREFIX=${JSON.stringify(prefix)};</script></head>`);
|
|
306
|
+
send(res, 200, 'text/html; charset=utf-8', html);
|
|
307
|
+
}
|
|
308
|
+
/** 家目录扫描(每请求现扫:另一终端 new/clone 后刷新即见)。子目录含 .practi/chain.json 即收录 */
|
|
309
|
+
function listPractices(homeDir) {
|
|
310
|
+
let names;
|
|
483
311
|
try {
|
|
484
|
-
|
|
312
|
+
names = fs.readdirSync(homeDir, { withFileTypes: true })
|
|
313
|
+
.filter((e) => e.isDirectory() && !e.name.startsWith('.'))
|
|
314
|
+
.map((e) => e.name);
|
|
485
315
|
}
|
|
486
|
-
catch
|
|
487
|
-
|
|
488
|
-
send(res, 404, 'text/plain; charset=utf-8', msg);
|
|
489
|
-
return;
|
|
316
|
+
catch {
|
|
317
|
+
return [];
|
|
490
318
|
}
|
|
491
|
-
const
|
|
492
|
-
const
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
res.writeHead(200, {
|
|
497
|
-
'content-type': 'text/event-stream',
|
|
498
|
-
'cache-control': 'no-cache',
|
|
499
|
-
connection: 'keep-alive',
|
|
500
|
-
});
|
|
501
|
-
res.write('retry: 1000\n\n');
|
|
502
|
-
clients.add(res);
|
|
503
|
-
req.on('close', () => clients.delete(res));
|
|
504
|
-
}
|
|
505
|
-
/** 监听 roots(递归;平台不支持时降级单层,再失败静默跳过——live reload 是锦上添花,不致命)。
|
|
506
|
-
* 事件去抖:一次保存或一条 practi 命令会喷一串文件事件,合并成一次广播。
|
|
507
|
-
* notes.json 例外:不触发整页 reload(写字段的页面自己会局部更新,整刷会白屏闪烁),
|
|
508
|
-
* 改发轻量 notes 事件——前端只重拉笔记数据重绘右栏,内容区/滚动位/草稿全程不动 */
|
|
509
|
-
function watchLive(roots, clients) {
|
|
510
|
-
let reloadTimer = null;
|
|
511
|
-
let notesTimer = null;
|
|
512
|
-
const broadcast = (event) => {
|
|
513
|
-
if (clients.size === 0)
|
|
514
|
-
return;
|
|
515
|
-
for (const res of clients)
|
|
516
|
-
res.write(`event: ${event}\ndata: 1\n\n`);
|
|
517
|
-
};
|
|
518
|
-
const onChange = (_event, filename) => {
|
|
519
|
-
const isNotes = filename !== null && path.basename(filename) === NOTES_FILE;
|
|
520
|
-
const unknown = filename === null; // 个别平台不给文件名:保守起见两种事件都发——宁多推一次不漏
|
|
521
|
-
if (!isNotes || unknown) {
|
|
522
|
-
if (reloadTimer === null) {
|
|
523
|
-
reloadTimer = setTimeout(() => { reloadTimer = null; broadcast('reload'); }, 150);
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
if (isNotes || unknown) {
|
|
527
|
-
if (notesTimer === null) {
|
|
528
|
-
notesTimer = setTimeout(() => { notesTimer = null; broadcast('notes'); }, 150);
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
};
|
|
532
|
-
for (const root of roots) {
|
|
533
|
-
if (!fs.existsSync(root))
|
|
319
|
+
const out = [];
|
|
320
|
+
for (const name of names) {
|
|
321
|
+
const chainPath = chainPathFor(path.join(homeDir, name));
|
|
322
|
+
const chain = loadChain(chainPath);
|
|
323
|
+
if (!chain)
|
|
534
324
|
continue;
|
|
325
|
+
let updated = null;
|
|
535
326
|
try {
|
|
536
|
-
fs.
|
|
537
|
-
}
|
|
538
|
-
catch {
|
|
539
|
-
try {
|
|
540
|
-
fs.watch(root, onChange);
|
|
541
|
-
}
|
|
542
|
-
catch {
|
|
543
|
-
// fs.watch 完全不可用:live reload 静默失效,其余功能不受影响
|
|
544
|
-
}
|
|
327
|
+
updated = fs.statSync(chainPath).mtime.toISOString();
|
|
545
328
|
}
|
|
329
|
+
catch { /* 无从考据就不显示 */ }
|
|
330
|
+
const tip = chain.commits[chain.commits.length - 1] ?? null;
|
|
331
|
+
out.push({
|
|
332
|
+
name,
|
|
333
|
+
current: chain.current,
|
|
334
|
+
commits: chain.commits.length,
|
|
335
|
+
head: tip ? { seq: tip.seq, root: tip.root, message: tip.message } : null,
|
|
336
|
+
updated,
|
|
337
|
+
});
|
|
546
338
|
}
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
for (const res of clients)
|
|
550
|
-
res.write(': ping\n\n');
|
|
551
|
-
}, 25000).unref();
|
|
339
|
+
out.sort((a, b) => (b.updated ?? '').localeCompare(a.updated ?? '') || a.name.localeCompare(b.name));
|
|
340
|
+
return out;
|
|
552
341
|
}
|
|
553
|
-
function
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
for (const a of n.attachments ?? []) {
|
|
563
|
-
if (a.hash === hash && a.mime)
|
|
564
|
-
return a.mime;
|
|
565
|
-
}
|
|
566
|
-
}
|
|
342
|
+
function mimeFor(bytes) {
|
|
343
|
+
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff)
|
|
344
|
+
return 'image/jpeg';
|
|
345
|
+
if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47)
|
|
346
|
+
return 'image/png';
|
|
347
|
+
if (bytes.length >= 6 && bytes.toString('ascii', 0, 6) === 'GIF89a')
|
|
348
|
+
return 'image/gif';
|
|
349
|
+
if (bytes.length >= 5 && bytes.toString('ascii', 0, 5) === '<?xml')
|
|
350
|
+
return 'image/svg+xml';
|
|
567
351
|
return 'application/octet-stream';
|
|
568
352
|
}
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
detached: true,
|
|
577
|
-
}).unref();
|
|
578
|
-
return;
|
|
579
|
-
}
|
|
580
|
-
const cmd = process.platform === 'darwin' ? 'open' : 'xdg-open';
|
|
581
|
-
spawn(cmd, [url], { stdio: 'ignore', detached: true }).unref();
|
|
353
|
+
function send(res, code, type, body) {
|
|
354
|
+
res.writeHead(code, { 'content-type': type });
|
|
355
|
+
res.end(body);
|
|
356
|
+
}
|
|
357
|
+
function sendBytes(res, type, body) {
|
|
358
|
+
res.writeHead(200, { 'content-type': type });
|
|
359
|
+
res.end(body);
|
|
582
360
|
}
|
|
583
361
|
//# sourceMappingURL=web.js.map
|