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