dsh-zdiary-kit 0.7.5 → 0.8.3

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.
@@ -0,0 +1,563 @@
1
+ /**
2
+ * read-only(宿主半边)—— 给人看的只读视图 / RSS / JSON 接口。
3
+ *
4
+ * 设计边界(和设置页的写 API 完全分开):
5
+ * · 只挂 4 条 GET 路由,全部在 /dsh-zdiary-kit 下,和 DSH 同端口,不自己 listen;
6
+ * · 方法门:GET / HEAD 以外一律 405,默认拒绝 —— 不是「没写 POST 就算只读」;
7
+ * · 副作用门:只调 hasNotebook / allNotes / searchNotes / readNote / graphEdges,
8
+ * **不调 ensureNotebook**(那会建库)、不跑 init / index / install;
9
+ * · 面门:不读 /api/settings 的 snapshot,不返回 zkPath / 配置文件路径 / absPath;
10
+ * · 地址门:只认回环(Host + 对端地址),DSH 绑到 0.0.0.0 时视图也不会跟着上网。
11
+ *
12
+ * 这里是「读」,写入仍然只走 agent 的 zk_* 工具与 CLI —— 锁、stamp、冲突处理都在那边。
13
+ */
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { isLoopback, json, ROUTE_BASE } from '../../lib/http.js';
17
+ import { config } from '../../config/store.js';
18
+ import { absPathOf, allNotes, graphEdges, hasNotebook, isUnderDir, localDate, readNote, searchNotes, ZkError } from '../../lib/zk.js';
19
+ import { isMetaPath } from '../../lib/meta.js';
20
+ import { buildMemoryPayload, formatFileShares } from '../../lib/memory.js';
21
+ import { esc, layout, renderMarkdown } from './html.js';
22
+ const BASE = ROUTE_BASE;
23
+ const VIEW = `${BASE}/view`;
24
+ const FEED = `${BASE}/feed.xml`;
25
+ const API_NOTES = `${BASE}/api/notes`;
26
+ const API_NOTE = `${BASE}/api/note`;
27
+ /** 一次索引最多载入多少篇(超出只在页脚说明,不静默装作全量) */
28
+ const INDEX_LIMIT = 2000;
29
+ /** 页面 / API 单篇正文上限:日记再长也不该把浏览器拖死 */
30
+ const MAX_CONTENT = 200_000;
31
+ /** 磁盘文件上限:超过就不读(readNote 会把整篇读进内存) */
32
+ const MAX_FILE = 2 * 1024 * 1024;
33
+ /**
34
+ * 只读视图只认 zk 索引得到的扩展名(md / markdown)。
35
+ * 别照抄 zk.ts 的 NOTE_EXT:那里带 org / txt 是为了剥双链的扩展名,
36
+ * 而 zk 默认不索引 org / txt —— 放进来只会得到「能直连、永远搜不到、还被 markdown 渲染坏」的页面。
37
+ */
38
+ const NOTE_EXT = /\.(?:md|markdown)$/i;
39
+ /** 站内链接:查询串路由(宿主的 register 只支持 exact,拼不出 /note/:id) */
40
+ function viewHref(params) {
41
+ return `${VIEW}?${new URLSearchParams(params).toString()}`;
42
+ }
43
+ function noteHref(rel) {
44
+ return viewHref({ p: 'note', path: rel });
45
+ }
46
+ function byModified(a, b) {
47
+ return String(b.modified || b.created).localeCompare(String(a.modified || a.created));
48
+ }
49
+ function messageOf(err) {
50
+ return err instanceof Error ? err.message : String(err);
51
+ }
52
+ /**
53
+ * 对外文案:只回插件自己写的校验文案;zk 进程 / 文件系统的原文写日志,不写进页面。
54
+ * zk 的 stderr 与 spawn 报错常带绝对路径(笔记本、zk 二进制),页面和 JSON 都不该带出去。
55
+ */
56
+ function publicMessage(err) {
57
+ if (err instanceof ZkError && err.code !== 'zk-failed')
58
+ return err.message;
59
+ try {
60
+ console.warn('[zdiary] 只读视图:' + messageOf(err));
61
+ }
62
+ catch { /* ignore */ }
63
+ return '读取失败(详细原因见 DSH 日志)';
64
+ }
65
+ /**
66
+ * 请求自己的 origin。DSH 的 TLS 由 webServer 直接终结(node:https),
67
+ * 所以 `socket.encrypted` 就是真实协议 —— 别把 RSS 的链接写死成 http。
68
+ */
69
+ function requestOrigin(req) {
70
+ const secure = req.socket?.encrypted === true;
71
+ return `${secure ? 'https' : 'http'}://${String(req.headers.host ?? '127.0.0.1')}`;
72
+ }
73
+ /**
74
+ * 解析请求 URL。Host 是客户端可控的:畸形值(例如 `127.0.0.1:80,evil`)会让 new URL 抛错,
75
+ * 在路由外抛出去只会落到兜底的 500 JSON —— 在这里统一收成 400。
76
+ */
77
+ function parseRequestUrl(req) {
78
+ try {
79
+ return new URL(String(req.url ?? '/'), `http://${String(req.headers.host ?? '127.0.0.1')}`);
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
85
+ /** 所有只读响应共用的安全头:无脚本、不可被框、无 referer、不缓存 */
86
+ function secure(res) {
87
+ res.setHeader('content-security-policy', "default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'");
88
+ res.setHeader('x-content-type-options', 'nosniff');
89
+ res.setHeader('x-frame-options', 'DENY');
90
+ res.setHeader('referrer-policy', 'no-referrer');
91
+ res.setHeader('cross-origin-resource-policy', 'same-origin');
92
+ res.setHeader('cache-control', 'no-store');
93
+ }
94
+ function sendHtml(res, status, body) {
95
+ res.statusCode = status;
96
+ res.setHeader('content-type', 'text/html; charset=utf-8');
97
+ res.end(body);
98
+ }
99
+ function sendText(res, status, body, type = 'text/plain; charset=utf-8') {
100
+ res.statusCode = status;
101
+ res.setHeader('content-type', type);
102
+ res.end(body);
103
+ }
104
+ /**
105
+ * 公共门:先上安全头,再判地址 / 方法。
106
+ * 所有路由共用它 —— 只读保证只有这一处,不靠「每个 handler 都记得写」。
107
+ * 地址判定用 lib/http 的 isLoopback(Host + 对端都要回环),不在这里另写一份。
108
+ */
109
+ function guard(req, res, mode) {
110
+ secure(res);
111
+ if (!isLoopback(req)) {
112
+ const msg = '只读视图只在回环地址(127.0.0.1 / localhost)上开放';
113
+ if (mode === 'json')
114
+ json(res, 403, { ok: false, error: msg });
115
+ else if (mode === 'xml')
116
+ sendText(res, 403, msg);
117
+ else
118
+ sendHtml(res, 403, layout({ title: '禁止访问', notebook: '只读视图', body: `<h1>禁止访问</h1><p class="error">${esc(msg)}</p>` }));
119
+ return false;
120
+ }
121
+ const method = String(req.method ?? 'GET').toUpperCase();
122
+ if (method !== 'GET' && method !== 'HEAD') {
123
+ res.setHeader('allow', 'GET, HEAD');
124
+ const msg = '只读视图不支持写请求(只接受 GET / HEAD)';
125
+ if (mode === 'json')
126
+ json(res, 405, { ok: false, error: msg });
127
+ else if (mode === 'xml')
128
+ sendText(res, 405, msg);
129
+ else
130
+ sendHtml(res, 405, layout({ title: '只读', notebook: '只读视图', body: `<h1>只读</h1><p class="error">${esc(msg)}</p>` }));
131
+ return false;
132
+ }
133
+ return true;
134
+ }
135
+ /** 只判断「有没有初始化过」,绝不顺手建库 */
136
+ function state() {
137
+ const cfg = config();
138
+ if (!hasNotebook(cfg)) {
139
+ return { cfg, ready: false, reason: '笔记本还没初始化(缺 .zk/config.toml):到设置页点「初始化 / 补建」,或让 agent 先写一篇。' };
140
+ }
141
+ return { cfg, ready: true, reason: '' };
142
+ }
143
+ function shell(cfg, title, body, note) {
144
+ return layout({ title, notebook: cfg.active || 'zdiary', body, note });
145
+ }
146
+ function noticePage(res, cfg, title, message, status = 200) {
147
+ sendHtml(res, status, shell(cfg, title, `<h1>${esc(title)}</h1><p class="notice">${esc(message)}</p><p><a href="${VIEW}">返回首页</a></p>`));
148
+ }
149
+ function errorPage(res, cfg, status, title, message) {
150
+ sendHtml(res, status, shell(cfg, title, `<h1>${esc(title)}</h1><p class="error">${esc(message)}</p><p><a href="${VIEW}">返回首页</a></p>`));
151
+ }
152
+ function tagCounts(notes) {
153
+ const counts = new Map();
154
+ for (const note of notes)
155
+ for (const tag of note.tags)
156
+ counts.set(tag, (counts.get(tag) ?? 0) + 1);
157
+ return [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
158
+ }
159
+ function tagLinks(tags) {
160
+ return tags.map((tag) => `<a href="${esc(viewHref({ p: 'tag', tag }))}">#${esc(tag)}</a>`).join(' ');
161
+ }
162
+ function noteTable(notes) {
163
+ if (!notes.length)
164
+ return '<p class="meta">没有笔记。</p>';
165
+ const rows = notes.map((note) => {
166
+ const date = localDate(note.modified || note.created) || '—';
167
+ return `<tr><td class="meta">${esc(date)}</td><td><a href="${esc(noteHref(note.path))}">${esc(note.title || note.path)}</a></td><td class="meta">${tagLinks(note.tags)}</td></tr>`;
168
+ }).join('');
169
+ return `<table><tr><th>日期</th><th>标题</th><th>标签</th></tr>${rows}</table>`;
170
+ }
171
+ function searchForm(value = '') {
172
+ return `<form class="search" method="get" action="${VIEW}"><input type="search" name="q" value="${esc(value)}" placeholder="搜索标题、正文…" aria-label="搜索"><button type="submit">搜索</button></form>`;
173
+ }
174
+ async function loadAll(cfg) {
175
+ return allNotes(cfg, { limit: INDEX_LIMIT });
176
+ }
177
+ /** 搜索 / 标签走 zk;`q` 与 `tag` 同时给就是两个条件一起收(zk 按 AND 处理,不静默忽略其中一个) */
178
+ async function pickNotes(cfg, opts) {
179
+ if (opts.q || opts.tag) {
180
+ return searchNotes(cfg, { query: opts.q, tags: opts.tag ? [opts.tag] : [], limit: opts.limit, sort: 'modified-desc' });
181
+ }
182
+ return (await loadAll(cfg)).sort(byModified).slice(0, opts.limit);
183
+ }
184
+ // ── 页面 ──────────────────────────────────────────────────────────────
185
+ async function handleHome(res, cfg) {
186
+ const all = await loadAll(cfg);
187
+ const recent = [...all].sort(byModified).slice(0, 30);
188
+ const journal = all.filter((note) => isUnderDir(note.path, cfg.dailyDir) || note.type === 'daily').sort(byModified).slice(0, 10);
189
+ const tags = tagCounts(all);
190
+ const body = [
191
+ `<h1>${esc(cfg.active || 'zdiary')}</h1>`,
192
+ searchForm(),
193
+ `<p class="meta">${all.length} 篇笔记 · ${tags.length} 个标签 · 只读</p>`,
194
+ '<h2>最近更新</h2>',
195
+ noteTable(recent),
196
+ '<h2>日记</h2>',
197
+ noteTable(journal),
198
+ '<h2>标签</h2>',
199
+ tags.length
200
+ ? `<p class="tags">${tags.slice(0, 80).map(([tag, count]) => `<a href="${esc(viewHref({ p: 'tag', tag }))}">#${esc(tag)}</a><span class="count">${count}</span>`).join(' · ')}</p>`
201
+ : '<p class="meta">还没有标签。</p>',
202
+ ].join('\n');
203
+ const note = all.length >= INDEX_LIMIT ? `只载入了最近 ${INDEX_LIMIT} 篇;更早的请用搜索。` : undefined;
204
+ sendHtml(res, 200, shell(cfg, '首页', body, note));
205
+ }
206
+ async function handleSearch(res, cfg, q) {
207
+ const notes = await searchNotes(cfg, { query: q, limit: 100, sort: 'modified-desc' });
208
+ const body = [
209
+ `<p class="crumb"><a href="${VIEW}">首页</a> / 搜索</p>`,
210
+ `<h1>搜索:${esc(q)}</h1>`,
211
+ searchForm(q),
212
+ `<p class="meta">${notes.length} 条结果(最多 100 条)</p>`,
213
+ noteTable(notes),
214
+ ].join('\n');
215
+ sendHtml(res, 200, shell(cfg, `搜索 ${q}`, body));
216
+ }
217
+ /** 记忆页固定的四份文件:只从这个常量取名字,不接受路径参数(meta 仍然不能按路径打开) */
218
+ const MEMORY_PAGE_FILES = ['AGENTS.md', 'USER.md', 'MEMORY.md', 'DREAMS.md'];
219
+ /**
220
+ * 记忆页(P1-5):人的周审需要一个入口 —— 当前记忆、预算、哪些被截断,都在这一页。
221
+ * 不走 `loadNote`:根目录 meta 被 `loadAll` 排除、也被 `loadNote` 明确拒绝;
222
+ * 这里按常量直接读盘,再复用渲染层的转义与双链白名单。
223
+ */
224
+ async function handleMemory(res, cfg) {
225
+ let all = [];
226
+ try {
227
+ all = await loadAll(cfg);
228
+ }
229
+ catch { /* 索引挂了也能读记忆,双链退化成纯文字 */ }
230
+ const linkFor = linkResolver(all);
231
+ const payload = buildMemoryPayload(cfg);
232
+ const shares = formatFileShares(payload.files, payload.tocWords);
233
+ const usage = `记忆 ${payload.words}/${payload.budget} 词(${shares || '三份都空'})` +
234
+ (payload.truncatedWords > 0 ? ` · 已截断 ${payload.truncatedWords} 词` : '');
235
+ const sections = MEMORY_PAGE_FILES.map((name) => {
236
+ let body = '';
237
+ try {
238
+ body = fs.readFileSync(path.join(cfg.notebook, name), 'utf8');
239
+ }
240
+ catch {
241
+ body = '';
242
+ }
243
+ return [
244
+ `<h2>${esc(name)}</h2>`,
245
+ body.trim()
246
+ ? `<article>${renderMarkdown(body, { linkFor, skipFirstH1: true })}</article>`
247
+ : '<p class="meta">还没写。</p>',
248
+ ].join('\n');
249
+ });
250
+ const body = [
251
+ `<p class="crumb"><a href="${VIEW}">首页</a> / 记忆</p>`,
252
+ '<h1>记忆</h1>',
253
+ `<p class="meta">${esc(usage)}</p>`,
254
+ '<p class="meta">这四份文件由人和 agent 直接编辑,不进检索;这里只读。</p>',
255
+ ...sections,
256
+ ].join('\n');
257
+ sendHtml(res, 200, shell(cfg, '记忆', body));
258
+ }
259
+ async function handleTags(res, cfg) {
260
+ const notes = await loadAll(cfg);
261
+ const tags = tagCounts(notes);
262
+ const body = [
263
+ `<p class="crumb"><a href="${VIEW}">首页</a> / 标签</p>`,
264
+ '<h1>标签</h1>',
265
+ `<p class="meta">${tags.length} 个标签 · ${notes.length} 篇笔记</p>`,
266
+ tags.length
267
+ ? `<p class="tags">${tags.map(([tag, count]) => `<a href="${esc(viewHref({ p: 'tag', tag }))}">#${esc(tag)}</a><span class="count">${count}</span>`).join(' · ')}</p>`
268
+ : '<p class="meta">还没有标签。</p>',
269
+ ].join('\n');
270
+ sendHtml(res, 200, shell(cfg, '标签', body));
271
+ }
272
+ async function handleTag(res, cfg, tag) {
273
+ if (!tag) {
274
+ noticePage(res, cfg, '标签', '没给标签名:从首页或标签页点一个进来。', 400);
275
+ return;
276
+ }
277
+ const notes = await searchNotes(cfg, { tags: [tag], limit: 200, sort: 'modified-desc' });
278
+ const body = [
279
+ `<p class="crumb"><a href="${VIEW}">首页</a> / <a href="${esc(viewHref({ p: 'tags' }))}">标签</a></p>`,
280
+ `<h1>#${esc(tag)}</h1>`,
281
+ `<p class="meta">${notes.length} 篇(最多 200 篇)</p>`,
282
+ noteTable(notes),
283
+ ].join('\n');
284
+ sendHtml(res, 200, shell(cfg, `#${tag}`, body));
285
+ }
286
+ /** 读一篇:路径必须在笔记本内、不是 .zk / 根 meta、扩展名与大小都过关 */
287
+ async function loadNote(cfg, input) {
288
+ const abs = absPathOf(cfg, input);
289
+ const rel = path.relative(cfg.notebook, abs).split(path.sep).join('/');
290
+ if (isMetaPath(rel))
291
+ throw new ZkError(`根目录的 meta 文件(${rel})不在只读视图里显示`, undefined, 'meta');
292
+ if (!NOTE_EXT.test(abs))
293
+ throw new ZkError('只读视图只显示 .md / .markdown', undefined, 'unsupported');
294
+ const stat = fs.statSync(abs, { throwIfNoEntry: false });
295
+ if (!stat || !stat.isFile())
296
+ throw new ZkError(`笔记不存在:${input}`, undefined, 'not-found');
297
+ if (stat.size > MAX_FILE) {
298
+ throw new ZkError(`文件太大(${Math.round(stat.size / 1024)} KiB),只读视图不加载超过 2 MiB 的文件`, undefined, 'too-large');
299
+ }
300
+ return { doc: await readNote(cfg, rel), rel };
301
+ }
302
+ /** 把 [[目标]] 解析成站内链接:路径 → 去扩展名路径 → 标题 → 文件名 */
303
+ function linkResolver(notes) {
304
+ const byPath = new Map();
305
+ const byTitle = new Map();
306
+ const byBase = new Map();
307
+ for (const note of notes) {
308
+ if (!byPath.has(note.path))
309
+ byPath.set(note.path, note);
310
+ const noExt = note.path.replace(NOTE_EXT, '');
311
+ if (!byPath.has(noExt))
312
+ byPath.set(noExt, note);
313
+ if (note.title && !byTitle.has(note.title))
314
+ byTitle.set(note.title, note);
315
+ const base = path.basename(noExt);
316
+ if (!byBase.has(base))
317
+ byBase.set(base, note);
318
+ }
319
+ return (input) => {
320
+ const target = input.trim().replace(/^<|>$/g, '').replace(/^\.\//, '').replace(/^\/+/, '').split('#')[0] ?? '';
321
+ if (!target)
322
+ return null;
323
+ const hit = byPath.get(target) ?? byTitle.get(target) ?? byBase.get(target);
324
+ return hit ? noteHref(hit.path) : null;
325
+ };
326
+ }
327
+ async function handleNote(res, cfg, rel) {
328
+ if (!rel) {
329
+ noticePage(res, cfg, '笔记', '没给路径:从首页或搜索结果点一篇进来。', 400);
330
+ return;
331
+ }
332
+ let loaded;
333
+ try {
334
+ loaded = await loadNote(cfg, rel);
335
+ }
336
+ catch (err) {
337
+ const missing = err instanceof ZkError && err.code === 'not-found';
338
+ errorPage(res, cfg, missing ? 404 : 400, missing ? '没有这篇笔记' : '打不开这篇笔记', publicMessage(err));
339
+ return;
340
+ }
341
+ let all = [];
342
+ try {
343
+ all = await loadAll(cfg);
344
+ }
345
+ catch { /* 索引挂了也能显示正文,双链退化成纯文字 */ }
346
+ const linkFor = linkResolver(all);
347
+ let backlinks = [];
348
+ try {
349
+ const relPath = loaded.rel;
350
+ const byPath = new Map(all.map((note) => [note.path, note]));
351
+ const seen = new Set();
352
+ for (const edge of (await graphEdges(cfg)).edges) {
353
+ if (edge.targetPath !== relPath || edge.sourcePath === relPath)
354
+ continue;
355
+ if (seen.has(edge.sourcePath))
356
+ continue;
357
+ seen.add(edge.sourcePath);
358
+ const hit = byPath.get(edge.sourcePath);
359
+ backlinks.push(hit ?? {
360
+ title: path.basename(edge.sourcePath).replace(NOTE_EXT, ''),
361
+ path: edge.sourcePath,
362
+ absPath: '',
363
+ link: '',
364
+ tags: [],
365
+ created: '',
366
+ modified: '',
367
+ lead: '',
368
+ words: 0,
369
+ metadata: {},
370
+ status: '',
371
+ type: '',
372
+ authority: '',
373
+ });
374
+ }
375
+ backlinks = backlinks.sort((a, b) => a.title.localeCompare(b.title));
376
+ }
377
+ catch { /* 图读不出来就不显示反链 */ }
378
+ const content = loaded.doc.content.length > MAX_CONTENT
379
+ ? loaded.doc.content.slice(0, MAX_CONTENT)
380
+ : loaded.doc.content;
381
+ const truncated = content.length < loaded.doc.content.length;
382
+ const body = [
383
+ `<p class="crumb"><a href="${VIEW}">首页</a> / ${esc(loaded.doc.type || '笔记')}</p>`,
384
+ `<h1>${esc(loaded.doc.title || loaded.rel)}</h1>`,
385
+ `<p class="meta">${esc(localDate(loaded.doc.created) || '—')} · ${loaded.doc.words} 词${loaded.doc.tags.length ? ' · ' + tagLinks(loaded.doc.tags) : ''}</p>`,
386
+ truncated ? `<p class="notice">正文超过 ${MAX_CONTENT} 字符,这里只显示前 ${MAX_CONTENT} 字符。</p>` : '',
387
+ `<article>${renderMarkdown(content, { linkFor, skipFirstH1: true })}</article>`,
388
+ '<h2>反链</h2>',
389
+ backlinks.length
390
+ ? `<ul>${backlinks.slice(0, 100).map((note) => `<li><a href="${esc(noteHref(note.path))}">${esc(note.title || note.path)}</a></li>`).join('')}</ul>`
391
+ : '<p class="meta">没有其它笔记链到这里。</p>',
392
+ ].join('\n');
393
+ sendHtml(res, 200, shell(cfg, loaded.doc.title || loaded.rel, body));
394
+ }
395
+ async function handleView(req, res) {
396
+ if (!guard(req, res, 'html'))
397
+ return;
398
+ const url = parseRequestUrl(req);
399
+ if (!url) {
400
+ sendHtml(res, 400, layout({ title: '请求不合法', notebook: '只读视图', body: '<h1>请求不合法</h1><p class="error">Host 头不是合法地址。</p>' }));
401
+ return;
402
+ }
403
+ const st = state();
404
+ const p = url.searchParams.get('p') ?? '';
405
+ const q = (url.searchParams.get('q') ?? '').trim();
406
+ const tag = (url.searchParams.get('tag') ?? '').trim();
407
+ if (!st.ready) {
408
+ noticePage(res, st.cfg, '只读视图', st.reason);
409
+ return;
410
+ }
411
+ try {
412
+ if (p === 'note')
413
+ return await handleNote(res, st.cfg, (url.searchParams.get('path') ?? '').trim());
414
+ if (p === 'memory')
415
+ return await handleMemory(res, st.cfg);
416
+ if (p === 'tags')
417
+ return await handleTags(res, st.cfg);
418
+ if (p === 'tag')
419
+ return await handleTag(res, st.cfg, tag);
420
+ if (q)
421
+ return await handleSearch(res, st.cfg, q);
422
+ return await handleHome(res, st.cfg);
423
+ }
424
+ catch (err) {
425
+ errorPage(res, st.cfg, err instanceof ZkError ? 503 : 500, '读不出来', publicMessage(err));
426
+ }
427
+ }
428
+ // ── JSON / RSS ────────────────────────────────────────────────────────
429
+ function publicNote(note) {
430
+ return {
431
+ title: note.title,
432
+ path: note.path,
433
+ tags: note.tags,
434
+ created: localDate(note.created),
435
+ modified: localDate(note.modified),
436
+ type: note.type,
437
+ status: note.status,
438
+ lead: note.lead,
439
+ words: note.words,
440
+ };
441
+ }
442
+ function limitOf(url) {
443
+ const raw = Number.parseInt(url.searchParams.get('limit') ?? '', 10);
444
+ if (!Number.isFinite(raw))
445
+ return 50;
446
+ return Math.min(200, Math.max(1, raw));
447
+ }
448
+ async function handleApiNotes(req, res) {
449
+ if (!guard(req, res, 'json'))
450
+ return;
451
+ const url = parseRequestUrl(req);
452
+ if (!url) {
453
+ json(res, 400, { ok: false, error: 'Host 头不是合法地址' });
454
+ return;
455
+ }
456
+ const st = state();
457
+ if (!st.ready) {
458
+ json(res, 503, { ok: false, error: st.reason });
459
+ return;
460
+ }
461
+ const q = (url.searchParams.get('q') ?? '').trim();
462
+ const tag = (url.searchParams.get('tag') ?? '').trim();
463
+ try {
464
+ const notes = await pickNotes(st.cfg, { q, tag, limit: limitOf(url) });
465
+ json(res, 200, { ok: true, count: notes.length, notes: notes.map(publicNote) });
466
+ }
467
+ catch (err) {
468
+ json(res, 503, { ok: false, error: publicMessage(err) });
469
+ }
470
+ }
471
+ async function handleApiNote(req, res) {
472
+ if (!guard(req, res, 'json'))
473
+ return;
474
+ const url = parseRequestUrl(req);
475
+ if (!url) {
476
+ json(res, 400, { ok: false, error: 'Host 头不是合法地址' });
477
+ return;
478
+ }
479
+ const st = state();
480
+ if (!st.ready) {
481
+ json(res, 503, { ok: false, error: st.reason });
482
+ return;
483
+ }
484
+ const rel = (url.searchParams.get('path') ?? '').trim();
485
+ if (!rel) {
486
+ json(res, 400, { ok: false, error: '缺少 path 参数(相对笔记本的笔记路径)' });
487
+ return;
488
+ }
489
+ try {
490
+ const { doc, rel: normalized } = await loadNote(st.cfg, rel);
491
+ const content = doc.content.length > MAX_CONTENT ? doc.content.slice(0, MAX_CONTENT) : doc.content;
492
+ json(res, 200, {
493
+ ok: true,
494
+ note: {
495
+ ...publicNote(doc),
496
+ path: normalized,
497
+ content,
498
+ chars: doc.content.length,
499
+ truncated: content.length < doc.content.length,
500
+ },
501
+ });
502
+ }
503
+ catch (err) {
504
+ const missing = err instanceof ZkError && err.code === 'not-found';
505
+ json(res, missing ? 404 : 400, { ok: false, error: publicMessage(err) });
506
+ }
507
+ }
508
+ function rssDate(iso) {
509
+ const date = new Date(iso);
510
+ return Number.isNaN(date.getTime()) ? '' : date.toUTCString();
511
+ }
512
+ /**
513
+ * RSS:只在真读到索引时才给 200。
514
+ * 没初始化 / zk 挂了就回 503 + 原因 —— 一个 200 的空频道会被阅读器当成功缓存住,
515
+ * 用户看到的是「今天没有新笔记」,而不是「插件坏了」。
516
+ */
517
+ async function handleFeed(req, res) {
518
+ if (!guard(req, res, 'xml'))
519
+ return;
520
+ const st = state();
521
+ if (!st.ready) {
522
+ sendText(res, 503, st.reason);
523
+ return;
524
+ }
525
+ let notes;
526
+ try {
527
+ notes = (await loadAll(st.cfg)).sort(byModified).slice(0, 30);
528
+ }
529
+ catch (err) {
530
+ sendText(res, 503, publicMessage(err));
531
+ return;
532
+ }
533
+ const origin = requestOrigin(req);
534
+ const items = notes.map((note) => [
535
+ '<item>',
536
+ `<title>${esc(note.title || note.path)}</title>`,
537
+ `<link>${esc(origin + noteHref(note.path))}</link>`,
538
+ `<guid isPermaLink="false">${esc(note.path)}</guid>`,
539
+ `<pubDate>${esc(rssDate(note.modified || note.created))}</pubDate>`,
540
+ `<description>${esc(note.lead)}</description>`,
541
+ '</item>',
542
+ ].join('')).join('');
543
+ const xml = [
544
+ '<?xml version="1.0" encoding="utf-8"?>',
545
+ '<rss version="2.0"><channel>',
546
+ `<title>${esc((st.cfg.active || 'zdiary') + ' · 只读笔记')}</title>`,
547
+ `<link>${esc(origin + VIEW)}</link>`,
548
+ '<description>只读笔记流(最近 30 篇)</description>',
549
+ '<language>zh-CN</language>',
550
+ items,
551
+ '</channel></rss>',
552
+ ].join('');
553
+ sendText(res, 200, xml, 'application/rss+xml; charset=utf-8');
554
+ }
555
+ // ── 挂载 ──────────────────────────────────────────────────────────────
556
+ export function registerReadOnly({ route }) {
557
+ // handler 自己 guard / 解析 URL:畸形 Host 在 guard 里或 parseRequestUrl 里就被收住,
558
+ // 不会在路由外抛错落到兜底的 500 JSON
559
+ route(VIEW, handleView);
560
+ route(FEED, handleFeed);
561
+ route(API_NOTES, handleApiNotes);
562
+ route(API_NOTE, handleApiNote);
563
+ }