dsh-reading-inbox 0.2.0 → 0.3.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/store.js CHANGED
@@ -1,647 +1,741 @@
1
- import { createHash } from 'node:crypto'
2
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
3
- import { join } from 'node:path'
4
- import MiniSearch from 'minisearch'
5
- import {
6
- buildAnnotationAnchor,
7
- normalizeColor,
8
- normalizeNote,
9
- resolveAnnotations,
10
- } from './annotations.js'
11
- import { fetchHtml } from './fetch.js'
12
- import { exportMarkdown, parseArticle, renderMarkdown, renderedText } from './markdown.js'
13
-
14
- const INDEX_VERSION = 1
15
- const STATUSES = new Set(['unread', 'reading', 'read', 'archived'])
16
- const MAX_TAGS = 20
17
- const MAX_TAG_LENGTH = 40
18
- const MAX_ANNOTATIONS = 500
19
-
20
- function nowIso() {
21
- return new Date().toISOString()
22
- }
23
-
24
- function digest(value, length = 12) {
25
- return createHash('sha256').update(String(value)).digest('hex').slice(0, length)
26
- }
27
-
28
- function slugify(value) {
29
- const ascii = String(value ?? '')
30
- .normalize('NFKD')
31
- .replace(/[̀-ͯ]/g, '')
32
- .toLowerCase()
33
- .replace(/[^a-z0-9]+/g, '-')
34
- .replace(/^-+|-+$/g, '')
35
- .slice(0, 60)
36
- return ascii === '' ? 'clip' : ascii
37
- }
38
-
39
- export function normalizeTags(tags = []) {
40
- const seen = new Set()
41
- const result = []
42
- for (const raw of Array.isArray(tags) ? tags : [tags]) {
43
- const value = String(raw ?? '')
44
- .replace(/^#/, '')
45
- .replace(/[\r\n,,]/g, ' ')
46
- .replace(/\s+/g, ' ')
47
- .trim()
48
- if (value === '' || value.length > MAX_TAG_LENGTH) continue
49
- const key = value.toLowerCase()
50
- if (seen.has(key)) continue
51
- seen.add(key)
52
- result.push(value)
53
- if (result.length >= MAX_TAGS) break
54
- }
55
- return result
56
- }
57
-
58
- export function normalizeUrl(rawUrl) {
59
- let url
60
- try {
61
- url = new URL(String(rawUrl ?? '').trim())
62
- } catch {
63
- throw new Error('URL 格式不正确,需要以 http:// 或 https:// 开头')
64
- }
65
- if (url.protocol !== 'http:' && url.protocol !== 'https:') {
66
- throw new Error(`不支持的协议:${url.protocol};只允许 http/https`)
67
- }
68
- url.hash = ''
69
- for (const key of [...url.searchParams.keys()]) {
70
- if (/^(utm_|fbclid$|gclid$|spm$)/i.test(key)) url.searchParams.delete(key)
71
- }
72
- return url.toString()
73
- }
74
-
75
- function tokenize(text) {
76
- const normalized = String(text ?? '').toLowerCase()
77
- const chunks = normalized.match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[a-z0-9_]+/gu) || []
78
- const tokens = []
79
- for (const chunk of chunks) {
80
- if (/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(chunk)) {
81
- for (let index = 0; index < chunk.length; index += 1) {
82
- tokens.push(chunk[index])
83
- if (index + 1 < chunk.length) tokens.push(chunk.slice(index, index + 2))
84
- }
85
- } else {
86
- tokens.push(chunk)
87
- }
88
- }
89
- return tokens
90
- }
91
-
92
- function createSearchIndex() {
93
- return new MiniSearch({
94
- fields: ['title', 'excerpt', 'body', 'tags', 'site'],
95
- storeFields: ['id'],
96
- idField: 'id',
97
- tokenize,
98
- searchOptions: {
99
- boost: { title: 3, tags: 2, site: 1.5 },
100
- prefix: true,
101
- fuzzy: 0.2,
102
- combineWith: 'AND',
103
- },
104
- })
105
- }
106
-
107
- function toSearchDoc(meta, body) {
108
- return {
109
- id: meta.id,
110
- title: meta.title,
111
- excerpt: meta.excerpt,
112
- body: String(body ?? '').slice(0, 40_000),
113
- tags: (meta.tags ?? []).join(' '),
114
- site: meta.site,
115
- }
116
- }
117
-
118
- function publicMeta(meta) {
119
- return {
120
- id: meta.id,
121
- title: meta.title,
122
- url: meta.url,
123
- site: meta.site,
124
- author: meta.author,
125
- published: meta.published,
126
- clippedAt: meta.clippedAt,
127
- tags: meta.tags,
128
- status: meta.status,
129
- excerpt: meta.excerpt,
130
- wordCount: meta.wordCount,
131
- charCount: meta.charCount,
132
- lang: meta.lang,
133
- images: meta.images,
134
- truncated: meta.truncated === true,
135
- annotationCount: Number.isInteger(meta.annotationCount) ? meta.annotationCount : 0,
136
- }
137
- }
138
-
139
- async function writeJsonAtomic(path, value) {
140
- const temporary = `${path}.tmp`
141
- await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
142
- await rename(temporary, path)
143
- }
144
-
145
- export class ReadingInbox {
146
- constructor(config, options = {}) {
147
- this.config = config
148
- // Leave this undefined unless a caller explicitly injects a fetch. fetch.js
149
- // uses its own validating dispatcher (or ProxyAgent) when no override is
150
- // present; defaulting to globalThis.fetch here used to bypass both.
151
- this.fetchImpl = options.fetchImpl
152
- this.dir = config.dir
153
- this.clipsDir = join(this.dir, 'clips')
154
- this.indexPath = join(this.dir, 'index.json')
155
- this.warnings = []
156
- this._ready = null
157
- this._clips = []
158
- this._byId = new Map()
159
- this._byUrl = new Map()
160
- this._search = null
161
- this._writeChain = Promise.resolve()
162
- this._mutationChain = Promise.resolve()
163
- this._inflight = new Map()
164
- this._textCache = new Map()
165
- }
166
-
167
- ready() {
168
- this._ready ??= this.init()
169
- return this._ready
170
- }
171
-
172
- async init() {
173
- await mkdir(this.clipsDir, { recursive: true })
174
- try {
175
- const raw = await readFile(this.indexPath, 'utf8')
176
- const parsed = JSON.parse(raw)
177
- const clips = Array.isArray(parsed?.clips) ? parsed.clips : []
178
- const byId = new Map()
179
- for (const item of clips) {
180
- if (item !== null && typeof item === 'object' && typeof item.id === 'string' && !byId.has(item.id)) {
181
- byId.set(item.id, item)
182
- }
183
- }
184
- this._clips = [...byId.values()]
185
- } catch (error) {
186
- if (error?.code !== 'ENOENT') {
187
- const backup = `${this.indexPath}.corrupt-${Date.now()}`
188
- await rename(this.indexPath, backup).catch(() => {})
189
- this.warnings.push(`索引读取失败,已备份到 ${backup}:${error instanceof Error ? error.message : String(error)}`)
190
- }
191
- this._clips = []
192
- }
193
- this._byId = new Map(this._clips.map(item => [item.id, item]))
194
- this._byUrl = new Map()
195
- for (const item of this._clips) {
196
- if (typeof item.url === 'string') this._byUrl.set(item.url, item)
197
- if (typeof item.canonicalUrl === 'string') this._byUrl.set(item.canonicalUrl, item)
198
- }
199
- this._search = createSearchIndex()
200
- for (const item of this._clips) {
201
- const body = await this.readBody(item.id).catch(() => '')
202
- try {
203
- this._search.add(toSearchDoc(item, body))
204
- } catch (error) {
205
- this.warnings.push(
206
- `索引条目 ${item.id} 重复或损坏,已跳过:${error instanceof Error ? error.message : String(error)}`,
207
- )
208
- }
209
- }
210
- return this
211
- }
212
-
213
- async readBody(id) {
214
- const meta = this._byId.get(id)
215
- if (meta === undefined) throw new Error(`找不到文章:${id}`)
216
- return readFile(join(this.dir, meta.articlePath), 'utf8')
217
- }
218
-
219
- annotationPath(meta) {
220
- return join(this.clipsDir, meta.id, 'annotations.json')
221
- }
222
-
223
- textForClip(meta, markdown) {
224
- const key = `${meta.id}:${meta.contentHash ?? ''}`
225
- const cached = this._textCache.get(key)
226
- if (cached !== undefined) return cached
227
- const text = renderedText(markdown)
228
- if (this._textCache.size > 30) this._textCache.clear()
229
- this._textCache.set(key, text)
230
- return text
231
- }
232
-
233
- async readAnnotations(meta) {
234
- try {
235
- const raw = await readFile(this.annotationPath(meta), 'utf8')
236
- const parsed = JSON.parse(raw)
237
- if (Array.isArray(parsed)) return parsed
238
- return Array.isArray(parsed?.annotations) ? parsed.annotations : []
239
- } catch (error) {
240
- if (error?.code !== 'ENOENT') {
241
- this.warnings.push(
242
- `批注读取失败(${meta.id}):${error instanceof Error ? error.message : String(error)}`,
243
- )
244
- }
245
- return []
246
- }
247
- }
248
-
249
- async writeAnnotations(meta, annotations) {
250
- await writeJsonAtomic(this.annotationPath(meta), {
251
- version: 1,
252
- contentVersion: meta.contentHash ?? '',
253
- annotations,
254
- })
255
- }
256
-
257
- async listAnnotations(id, body = null) {
258
- await this.ready()
259
- const meta = this._byId.get(String(id))
260
- if (meta === undefined) throw new Error(`找不到文章:${id}`)
261
- const markdown = body ?? await this.readBody(meta.id)
262
- const text = this.textForClip(meta, markdown)
263
- const annotations = await this.readAnnotations(meta)
264
- return resolveAnnotations(text, annotations)
265
- }
266
-
267
- async addAnnotation(id, input = {}) {
268
- await this.ready()
269
- return this._withMutation(async () => {
270
- const meta = this._byId.get(String(id))
271
- if (meta === undefined) throw new Error(`找不到文章:${id}`)
272
- const body = await this.readBody(meta.id)
273
- const text = this.textForClip(meta, body)
274
- const anchor = buildAnnotationAnchor(text, {
275
- quote: input.quote,
276
- prefix: input.prefix,
277
- suffix: input.suffix,
278
- startOffset: Number.isInteger(input.startOffset) ? input.startOffset : undefined,
279
- endOffset: Number.isInteger(input.endOffset) ? input.endOffset : undefined,
280
- })
281
- const existing = await this.readAnnotations(meta)
282
- if (existing.length >= MAX_ANNOTATIONS) {
283
- throw new Error(`单篇批注数量已达上限(${MAX_ANNOTATIONS})`)
284
- }
285
- const now = nowIso()
286
- const used = new Set(existing.map(annotation => annotation.id))
287
- let annotationId = `hl-${digest(`${anchor.quote}\n${anchor.startOffset}\n${now}`, 12)}`
288
- let counter = 2
289
- while (used.has(annotationId)) {
290
- annotationId = `hl-${digest(`${anchor.quote}\n${anchor.startOffset}\n${now}\n${counter}`, 12)}`
291
- counter += 1
292
- }
293
- const annotation = {
294
- id: annotationId,
295
- ...anchor,
296
- color: normalizeColor(input.color),
297
- note: normalizeNote(input.note),
298
- contentVersion: meta.contentHash ?? '',
299
- createdAt: now,
300
- updatedAt: now,
301
- }
302
- const next = [...existing, annotation]
303
- await this.writeAnnotations(meta, next)
304
- meta.annotationCount = next.length
305
- await this.persist()
306
- return resolveAnnotations(text, [annotation])[0]
307
- })
308
- }
309
-
310
- async updateAnnotation(id, annotationId, patch = {}) {
311
- await this.ready()
312
- return this._withMutation(async () => {
313
- const meta = this._byId.get(String(id))
314
- if (meta === undefined) throw new Error(`找不到文章:${id}`)
315
- const body = await this.readBody(meta.id)
316
- const text = this.textForClip(meta, body)
317
- const existing = await this.readAnnotations(meta)
318
- const index = existing.findIndex(annotation => annotation.id === String(annotationId))
319
- if (index === -1) throw new Error(`找不到批注:${annotationId}`)
320
- const updated = {
321
- ...existing[index],
322
- note: patch.note === undefined ? existing[index].note : normalizeNote(patch.note),
323
- color: patch.color === undefined ? existing[index].color : normalizeColor(patch.color),
324
- updatedAt: nowIso(),
325
- }
326
- const next = [...existing]
327
- next[index] = updated
328
- await this.writeAnnotations(meta, next)
329
- meta.annotationCount = next.length
330
- await this.persist()
331
- return resolveAnnotations(text, [updated])[0]
332
- })
333
- }
334
-
335
- async deleteAnnotation(id, annotationId) {
336
- await this.ready()
337
- return this._withMutation(async () => {
338
- const meta = this._byId.get(String(id))
339
- if (meta === undefined) throw new Error(`找不到文章:${id}`)
340
- const existing = await this.readAnnotations(meta)
341
- const next = existing.filter(annotation => annotation.id !== String(annotationId))
342
- if (next.length === existing.length) throw new Error(`找不到批注:${annotationId}`)
343
- await this.writeAnnotations(meta, next)
344
- meta.annotationCount = next.length
345
- await this.persist()
346
- return { count: next.length }
347
- })
348
- }
349
-
350
- async clip(rawUrl, options = {}) {
351
- await this.ready()
352
- const url = normalizeUrl(rawUrl)
353
- const pending = this._inflight.get(url)
354
- if (pending !== undefined) return pending
355
- let task
356
- task = this._clipOnce(url, options).finally(() => {
357
- if (this._inflight.get(url) === task) this._inflight.delete(url)
358
- })
359
- this._inflight.set(url, task)
360
- return task
361
- }
362
-
363
- _withMutation(fn) {
364
- const run = this._mutationChain.then(() => fn(), () => fn())
365
- this._mutationChain = run.then(() => undefined, () => undefined)
366
- return run
367
- }
368
-
369
- async _clipOnce(url, options = {}) {
370
- const existing = this._byUrl.get(url)
371
- if (existing !== undefined && options.force !== true) {
372
- const body = await this.readBody(existing.id).catch(() => '')
373
- return { ...publicMeta(existing), duplicate: true, preview: body.slice(0, 500) }
374
- }
375
-
376
- const fetched = await fetchHtml(url, this.config, {
377
- fetchImpl: this.fetchImpl,
378
- signal: options.signal,
379
- })
380
- const parsed = parseArticle(fetched.html, {
381
- url: fetched.finalUrl,
382
- maxMarkdownChars: this.config.maxMarkdownChars,
383
- })
384
- if (parsed.ok !== true) throw new Error(parsed.reason)
385
-
386
- const canonicalUrl = parsed.canonicalUrl || fetched.finalUrl
387
-
388
- return this._withMutation(async () => {
389
- // Re-check after the network await: another request may have committed
390
- // the same URL, or a different URL resolving to the same canonical URL,
391
- // while this one was fetching. This is the serialization point that
392
- // prevents duplicate ids and a corrupted index.
393
- const current =
394
- this._byUrl.get(url) ??
395
- this._byUrl.get(fetched.finalUrl) ??
396
- this._byUrl.get(canonicalUrl)
397
- if (current !== undefined && options.force !== true) {
398
- const body = await this.readBody(current.id).catch(() => '')
399
- return { ...publicMeta(current), duplicate: true, preview: body.slice(0, 500) }
400
- }
401
- if (current !== undefined && options.force === true) {
402
- return this.refreshClip(current, parsed, fetched, options)
403
- }
404
-
405
- const id = this.uniqueId(parsed.title, canonicalUrl)
406
- const explicitTags = normalizeTags([
407
- ...(Array.isArray(options.tags) ? options.tags : []),
408
- ...(this.config.defaultTags ?? []),
409
- ])
410
- // Page keywords are often SEO noise. Use them only when the user gave no
411
- // tags at all, so a careful reader's own taxonomy always wins.
412
- const tags = explicitTags.length > 0
413
- ? explicitTags
414
- : normalizeTags((parsed.keywords ?? []).slice(0, 3))
415
- const meta = {
416
- id,
417
- url: fetched.finalUrl,
418
- canonicalUrl,
419
- title: parsed.title,
420
- site: parsed.siteName,
421
- author: parsed.byline,
422
- published: parsed.published,
423
- clippedAt: nowIso(),
424
- tags,
425
- status: 'unread',
426
- excerpt: parsed.excerpt,
427
- wordCount: parsed.wordCount,
428
- charCount: parsed.charCount,
429
- lang: parsed.lang,
430
- images: parsed.images,
431
- truncated: parsed.truncated === true,
432
- annotationCount: 0,
433
- contentHash: digest(parsed.markdown, 16),
434
- articlePath: `clips/${id}/article.md`,
435
- htmlPath: `clips/${id}/original.html`,
436
- metaPath: `clips/${id}/meta.json`,
437
- }
438
-
439
- const clipDir = join(this.clipsDir, id)
440
- await mkdir(clipDir, { recursive: true })
441
- await writeFile(join(this.dir, meta.articlePath), `${parsed.markdown.trim()}\n`, 'utf8')
442
- await writeFile(join(this.dir, meta.htmlPath), fetched.html, 'utf8')
443
- await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
444
-
445
- this._clips.push(meta)
446
- this._byId.set(meta.id, meta)
447
- this._byUrl.set(meta.url, meta)
448
- this._byUrl.set(meta.canonicalUrl, meta)
449
- this._search.add(toSearchDoc(meta, parsed.markdown))
450
- await this.persist()
451
-
452
- return {
453
- ...publicMeta(meta),
454
- duplicate: false,
455
- preview: parsed.markdown.slice(0, 1_500),
456
- }
457
- })
458
- }
459
-
460
- async refreshClip(meta, parsed, fetched, options = {}) {
461
- const canonicalUrl = parsed.canonicalUrl || fetched.finalUrl
462
- meta.url = fetched.finalUrl
463
- meta.canonicalUrl = canonicalUrl
464
- meta.title = parsed.title
465
- meta.site = parsed.siteName
466
- meta.author = parsed.byline
467
- meta.published = parsed.published
468
- meta.excerpt = parsed.excerpt
469
- meta.wordCount = parsed.wordCount
470
- meta.charCount = parsed.charCount
471
- meta.lang = parsed.lang
472
- meta.images = parsed.images
473
- meta.truncated = parsed.truncated === true
474
- meta.annotationCount = (await this.readAnnotations(meta)).length
475
- meta.updatedAt = nowIso()
476
- meta.contentHash = digest(parsed.markdown, 16)
477
- if (Array.isArray(options.tags) && options.tags.length > 0) {
478
- meta.tags = normalizeTags(options.tags)
479
- }
480
-
481
- await writeFile(join(this.dir, meta.articlePath), `${parsed.markdown.trim()}\n`, 'utf8')
482
- await writeFile(join(this.dir, meta.htmlPath), fetched.html, 'utf8')
483
- await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
484
-
485
- this._byUrl.set(meta.url, meta)
486
- this._byUrl.set(meta.canonicalUrl, meta)
487
- try {
488
- this._search.discard(meta.id)
489
- } catch {
490
- // The id may be absent after a manual index edit; adding it back is enough.
491
- }
492
- this._search.add(toSearchDoc(meta, parsed.markdown))
493
- await this.persist()
494
-
495
- return {
496
- ...publicMeta(meta),
497
- duplicate: false,
498
- preview: parsed.markdown.slice(0, 1_500),
499
- }
500
- }
501
-
502
- uniqueId(title, url) {
503
- const base = `${slugify(title)}-${digest(url, 8)}`
504
- let id = base
505
- let counter = 2
506
- while (this._byId.has(id)) {
507
- id = `${base}-${counter}`
508
- counter += 1
509
- }
510
- return id
511
- }
512
-
513
- async search(query) {
514
- await this.ready()
515
- const q = String(query ?? '').trim()
516
- if (q === '') return null
517
- try {
518
- return this._search.search(q).map(result => ({ id: result.id, score: result.score }))
519
- } catch {
520
- return []
521
- }
522
- }
523
-
524
- async list(options = {}) {
525
- await this.ready()
526
- const status = options.status ?? 'all'
527
- const tag = String(options.tag ?? '').trim().toLowerCase()
528
- const limit = Math.max(1, Math.min(200, Number(options.limit) || 50))
529
- const offset = Math.max(0, Number(options.offset) || 0)
530
-
531
- let source
532
- const ranked = await this.search(options.q)
533
- if (ranked !== null) {
534
- const scoreById = new Map(ranked.map(item => [item.id, item.score]))
535
- source = this._clips
536
- .filter(item => scoreById.has(item.id))
537
- .sort((a, b) => (scoreById.get(b.id) ?? 0) - (scoreById.get(a.id) ?? 0))
538
- } else {
539
- source = [...this._clips].sort((a, b) => String(b.clippedAt).localeCompare(String(a.clippedAt)))
540
- }
541
-
542
- const filtered = source.filter(item => {
543
- if (status !== 'all' && item.status !== status) return false
544
- if (tag !== '' && !(item.tags ?? []).some(value => String(value).toLowerCase() === tag)) return false
545
- return true
546
- })
547
-
548
- return {
549
- total: filtered.length,
550
- offset,
551
- limit,
552
- items: filtered.slice(offset, offset + limit).map(publicMeta),
553
- }
554
- }
555
-
556
- async get(id) {
557
- await this.ready()
558
- const meta = this._byId.get(String(id))
559
- if (meta === undefined) throw new Error(`找不到文章:${id}`)
560
- const body = await this.readBody(meta.id)
561
- const annotations = await this.listAnnotations(meta.id, body)
562
- return {
563
- ...publicMeta(meta),
564
- annotationCount: annotations.length,
565
- content: body,
566
- html: renderMarkdown(body),
567
- annotations,
568
- }
569
- }
570
-
571
- async read(id, options = {}) {
572
- await this.ready()
573
- const meta = this._byId.get(String(id))
574
- if (meta === undefined) throw new Error(`找不到文章:${id}`)
575
- const body = await this.readBody(meta.id)
576
- const offset = Math.max(0, Number(options.offset) || 0)
577
- const limit = Math.max(1, Math.min(40_000, Number(options.limit) || 12_000))
578
- const content = body.slice(offset, offset + limit)
579
- const nextOffset = offset + content.length
580
- return {
581
- ...publicMeta(meta),
582
- content,
583
- offset,
584
- totalChars: body.length,
585
- nextOffset,
586
- hasMore: nextOffset < body.length,
587
- }
588
- }
589
-
590
- async update(id, patch = {}) {
591
- await this.ready()
592
- const meta = this._byId.get(String(id))
593
- if (meta === undefined) throw new Error(`找不到文章:${id}`)
594
- if (patch.status !== undefined) {
595
- if (!STATUSES.has(patch.status)) {
596
- throw new Error(`无效状态:${patch.status};可选 unread/reading/read/archived`)
597
- }
598
- meta.status = patch.status
599
- }
600
- if (patch.tags !== undefined) meta.tags = normalizeTags(patch.tags)
601
- await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
602
- const body = await this.readBody(meta.id).catch(() => '')
603
- try {
604
- this._search.discard(meta.id)
605
- } catch {
606
- // MiniSearch throws when the id is absent; a missing doc needs no discard.
607
- }
608
- this._search.add(toSearchDoc(meta, body))
609
- await this.persist()
610
- return publicMeta(meta)
611
- }
612
-
613
- async stats() {
614
- await this.ready()
615
- const counts = { all: this._clips.length, unread: 0, reading: 0, read: 0, archived: 0 }
616
- const tags = new Map()
617
- for (const item of this._clips) {
618
- if (counts[item.status] !== undefined) counts[item.status] += 1
619
- for (const tag of item.tags ?? []) tags.set(tag, (tags.get(tag) ?? 0) + 1)
620
- }
621
- return {
622
- ...counts,
623
- tags: [...tags.entries()]
624
- .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
625
- .slice(0, 40)
626
- .map(([name, count]) => ({ name, count })),
627
- warnings: this.warnings,
628
- }
629
- }
630
-
631
- async export(id) {
632
- await this.ready()
633
- const meta = this._byId.get(String(id))
634
- if (meta === undefined) throw new Error(`找不到文章:${id}`)
635
- const body = await this.readBody(meta.id)
636
- const annotations = await this.listAnnotations(meta.id, body)
637
- return { meta: publicMeta(meta), markdown: exportMarkdown(meta, body, annotations) }
638
- }
639
-
640
- async persist() {
641
- const snapshot = { version: INDEX_VERSION, clips: this._clips }
642
- this._writeChain = this._writeChain
643
- .catch(() => {})
644
- .then(() => writeJsonAtomic(this.indexPath, snapshot))
645
- await this._writeChain
646
- }
647
- }
1
+ import { createHash } from 'node:crypto'
2
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import MiniSearch from 'minisearch'
5
+ import {
6
+ buildAnnotationAnchor,
7
+ normalizeColor,
8
+ normalizeNote,
9
+ resolveAnnotations,
10
+ } from './annotations.js'
11
+ import { fetchHtml } from './fetch.js'
12
+ import { exportMarkdown, parseArticle, renderMarkdown, renderedText } from './markdown.js'
13
+ import { makeSnippet, parseQuery, queryTerms } from './search.js'
14
+
15
+ const INDEX_VERSION = 1
16
+ const STATUSES = new Set(['unread', 'reading', 'read', 'archived'])
17
+ const MAX_TAGS = 20
18
+ const MAX_TAG_LENGTH = 40
19
+ const MAX_ANNOTATIONS = 500
20
+
21
+ function nowIso() {
22
+ return new Date().toISOString()
23
+ }
24
+
25
+ function digest(value, length = 12) {
26
+ return createHash('sha256').update(String(value)).digest('hex').slice(0, length)
27
+ }
28
+
29
+ function slugify(value) {
30
+ const ascii = String(value ?? '')
31
+ .normalize('NFKD')
32
+ .replace(/[̀-ͯ]/g, '')
33
+ .toLowerCase()
34
+ .replace(/[^a-z0-9]+/g, '-')
35
+ .replace(/^-+|-+$/g, '')
36
+ .slice(0, 60)
37
+ return ascii === '' ? 'clip' : ascii
38
+ }
39
+
40
+ export function normalizeTags(tags = []) {
41
+ const seen = new Set()
42
+ const result = []
43
+ for (const raw of Array.isArray(tags) ? tags : [tags]) {
44
+ const value = String(raw ?? '')
45
+ .replace(/^#/, '')
46
+ .replace(/[\r\n,,]/g, ' ')
47
+ .replace(/\s+/g, ' ')
48
+ .trim()
49
+ if (value === '' || value.length > MAX_TAG_LENGTH) continue
50
+ const key = value.toLowerCase()
51
+ if (seen.has(key)) continue
52
+ seen.add(key)
53
+ result.push(value)
54
+ if (result.length >= MAX_TAGS) break
55
+ }
56
+ return result
57
+ }
58
+
59
+ export function normalizeUrl(rawUrl) {
60
+ let url
61
+ try {
62
+ url = new URL(String(rawUrl ?? '').trim())
63
+ } catch {
64
+ throw new Error('URL 格式不正确,需要以 http:// 或 https:// 开头')
65
+ }
66
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
67
+ throw new Error(`不支持的协议:${url.protocol};只允许 http/https`)
68
+ }
69
+ url.hash = ''
70
+ for (const key of [...url.searchParams.keys()]) {
71
+ if (/^(utm_|fbclid$|gclid$|spm$)/i.test(key)) url.searchParams.delete(key)
72
+ }
73
+ return url.toString()
74
+ }
75
+
76
+ function tokenize(text) {
77
+ const normalized = String(text ?? '').toLowerCase()
78
+ const chunks = normalized.match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[a-z0-9_]+/gu) || []
79
+ const tokens = []
80
+ for (const chunk of chunks) {
81
+ if (/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(chunk)) {
82
+ for (let index = 0; index < chunk.length; index += 1) {
83
+ tokens.push(chunk[index])
84
+ if (index + 1 < chunk.length) tokens.push(chunk.slice(index, index + 2))
85
+ }
86
+ } else {
87
+ tokens.push(chunk)
88
+ }
89
+ }
90
+ return tokens
91
+ }
92
+
93
+ function createSearchIndex() {
94
+ return new MiniSearch({
95
+ fields: ['title', 'excerpt', 'body', 'tags', 'site'],
96
+ storeFields: ['id'],
97
+ idField: 'id',
98
+ tokenize,
99
+ searchOptions: {
100
+ boost: { title: 3, tags: 2, site: 1.5 },
101
+ prefix: true,
102
+ fuzzy: 0.2,
103
+ combineWith: 'AND',
104
+ },
105
+ })
106
+ }
107
+
108
+ function toSearchDoc(meta, body) {
109
+ return {
110
+ id: meta.id,
111
+ title: meta.title,
112
+ excerpt: meta.excerpt,
113
+ body: String(body ?? '').slice(0, 40_000),
114
+ tags: (meta.tags ?? []).join(' '),
115
+ site: meta.site,
116
+ }
117
+ }
118
+
119
+ function publicMeta(meta) {
120
+ return {
121
+ id: meta.id,
122
+ title: meta.title,
123
+ url: meta.url,
124
+ site: meta.site,
125
+ author: meta.author,
126
+ published: meta.published,
127
+ clippedAt: meta.clippedAt,
128
+ tags: meta.tags,
129
+ status: meta.status,
130
+ excerpt: meta.excerpt,
131
+ wordCount: meta.wordCount,
132
+ charCount: meta.charCount,
133
+ lang: meta.lang,
134
+ images: meta.images,
135
+ truncated: meta.truncated === true,
136
+ annotationCount: Number.isInteger(meta.annotationCount) ? meta.annotationCount : 0,
137
+ }
138
+ }
139
+
140
+ async function writeJsonAtomic(path, value) {
141
+ const temporary = `${path}.tmp`
142
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
143
+ await rename(temporary, path)
144
+ }
145
+
146
+ export class ReadingInbox {
147
+ constructor(config, options = {}) {
148
+ this.config = config
149
+ // Leave this undefined unless a caller explicitly injects a fetch. fetch.js
150
+ // uses its own validating dispatcher (or ProxyAgent) when no override is
151
+ // present; defaulting to globalThis.fetch here used to bypass both.
152
+ this.fetchImpl = options.fetchImpl
153
+ this.dir = config.dir
154
+ this.clipsDir = join(this.dir, 'clips')
155
+ this.indexPath = join(this.dir, 'index.json')
156
+ this.viewsPath = join(this.dir, 'views.json')
157
+ this.warnings = []
158
+ this._ready = null
159
+ this._clips = []
160
+ this._byId = new Map()
161
+ this._byUrl = new Map()
162
+ this._search = null
163
+ this._writeChain = Promise.resolve()
164
+ this._mutationChain = Promise.resolve()
165
+ this._inflight = new Map()
166
+ this._textCache = new Map()
167
+ }
168
+
169
+ ready() {
170
+ this._ready ??= this.init()
171
+ return this._ready
172
+ }
173
+
174
+ async init() {
175
+ await mkdir(this.clipsDir, { recursive: true })
176
+ try {
177
+ const raw = await readFile(this.indexPath, 'utf8')
178
+ const parsed = JSON.parse(raw)
179
+ const clips = Array.isArray(parsed?.clips) ? parsed.clips : []
180
+ const byId = new Map()
181
+ for (const item of clips) {
182
+ if (item !== null && typeof item === 'object' && typeof item.id === 'string' && !byId.has(item.id)) {
183
+ byId.set(item.id, item)
184
+ }
185
+ }
186
+ this._clips = [...byId.values()]
187
+ } catch (error) {
188
+ if (error?.code !== 'ENOENT') {
189
+ const backup = `${this.indexPath}.corrupt-${Date.now()}`
190
+ await rename(this.indexPath, backup).catch(() => {})
191
+ this.warnings.push(`索引读取失败,已备份到 ${backup}:${error instanceof Error ? error.message : String(error)}`)
192
+ }
193
+ this._clips = []
194
+ }
195
+ this._byId = new Map(this._clips.map(item => [item.id, item]))
196
+ this._byUrl = new Map()
197
+ for (const item of this._clips) {
198
+ if (typeof item.url === 'string') this._byUrl.set(item.url, item)
199
+ if (typeof item.canonicalUrl === 'string') this._byUrl.set(item.canonicalUrl, item)
200
+ }
201
+ this._search = createSearchIndex()
202
+ for (const item of this._clips) {
203
+ const body = await this.readBody(item.id).catch(() => '')
204
+ try {
205
+ this._search.add(toSearchDoc(item, body))
206
+ } catch (error) {
207
+ this.warnings.push(
208
+ `索引条目 ${item.id} 重复或损坏,已跳过:${error instanceof Error ? error.message : String(error)}`,
209
+ )
210
+ }
211
+ }
212
+ return this
213
+ }
214
+
215
+ async readBody(id) {
216
+ const meta = this._byId.get(id)
217
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
218
+ return readFile(join(this.dir, meta.articlePath), 'utf8')
219
+ }
220
+
221
+ annotationPath(meta) {
222
+ return join(this.clipsDir, meta.id, 'annotations.json')
223
+ }
224
+
225
+ textForClip(meta, markdown) {
226
+ const key = `${meta.id}:${meta.contentHash ?? ''}`
227
+ const cached = this._textCache.get(key)
228
+ if (cached !== undefined) return cached
229
+ const text = renderedText(markdown)
230
+ if (this._textCache.size > 30) this._textCache.clear()
231
+ this._textCache.set(key, text)
232
+ return text
233
+ }
234
+
235
+ async readAnnotations(meta) {
236
+ try {
237
+ const raw = await readFile(this.annotationPath(meta), 'utf8')
238
+ const parsed = JSON.parse(raw)
239
+ if (Array.isArray(parsed)) return parsed
240
+ return Array.isArray(parsed?.annotations) ? parsed.annotations : []
241
+ } catch (error) {
242
+ if (error?.code !== 'ENOENT') {
243
+ this.warnings.push(
244
+ `批注读取失败(${meta.id}):${error instanceof Error ? error.message : String(error)}`,
245
+ )
246
+ }
247
+ return []
248
+ }
249
+ }
250
+
251
+ async writeAnnotations(meta, annotations) {
252
+ await writeJsonAtomic(this.annotationPath(meta), {
253
+ version: 1,
254
+ contentVersion: meta.contentHash ?? '',
255
+ annotations,
256
+ })
257
+ }
258
+
259
+ async listAnnotations(id, body = null) {
260
+ await this.ready()
261
+ const meta = this._byId.get(String(id))
262
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
263
+ const markdown = body ?? await this.readBody(meta.id)
264
+ const text = this.textForClip(meta, markdown)
265
+ const annotations = await this.readAnnotations(meta)
266
+ return resolveAnnotations(text, annotations)
267
+ }
268
+
269
+ async addAnnotation(id, input = {}) {
270
+ await this.ready()
271
+ return this._withMutation(async () => {
272
+ const meta = this._byId.get(String(id))
273
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
274
+ const body = await this.readBody(meta.id)
275
+ const text = this.textForClip(meta, body)
276
+ const anchor = buildAnnotationAnchor(text, {
277
+ quote: input.quote,
278
+ prefix: input.prefix,
279
+ suffix: input.suffix,
280
+ startOffset: Number.isInteger(input.startOffset) ? input.startOffset : undefined,
281
+ endOffset: Number.isInteger(input.endOffset) ? input.endOffset : undefined,
282
+ })
283
+ const existing = await this.readAnnotations(meta)
284
+ if (existing.length >= MAX_ANNOTATIONS) {
285
+ throw new Error(`单篇批注数量已达上限(${MAX_ANNOTATIONS})`)
286
+ }
287
+ const now = nowIso()
288
+ const used = new Set(existing.map(annotation => annotation.id))
289
+ let annotationId = `hl-${digest(`${anchor.quote}\n${anchor.startOffset}\n${now}`, 12)}`
290
+ let counter = 2
291
+ while (used.has(annotationId)) {
292
+ annotationId = `hl-${digest(`${anchor.quote}\n${anchor.startOffset}\n${now}\n${counter}`, 12)}`
293
+ counter += 1
294
+ }
295
+ const annotation = {
296
+ id: annotationId,
297
+ ...anchor,
298
+ color: normalizeColor(input.color),
299
+ note: normalizeNote(input.note),
300
+ contentVersion: meta.contentHash ?? '',
301
+ createdAt: now,
302
+ updatedAt: now,
303
+ }
304
+ const next = [...existing, annotation]
305
+ await this.writeAnnotations(meta, next)
306
+ meta.annotationCount = next.length
307
+ await this.persist()
308
+ return resolveAnnotations(text, [annotation])[0]
309
+ })
310
+ }
311
+
312
+ async updateAnnotation(id, annotationId, patch = {}) {
313
+ await this.ready()
314
+ return this._withMutation(async () => {
315
+ const meta = this._byId.get(String(id))
316
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
317
+ const body = await this.readBody(meta.id)
318
+ const text = this.textForClip(meta, body)
319
+ const existing = await this.readAnnotations(meta)
320
+ const index = existing.findIndex(annotation => annotation.id === String(annotationId))
321
+ if (index === -1) throw new Error(`找不到批注:${annotationId}`)
322
+ const updated = {
323
+ ...existing[index],
324
+ note: patch.note === undefined ? existing[index].note : normalizeNote(patch.note),
325
+ color: patch.color === undefined ? existing[index].color : normalizeColor(patch.color),
326
+ updatedAt: nowIso(),
327
+ }
328
+ const next = [...existing]
329
+ next[index] = updated
330
+ await this.writeAnnotations(meta, next)
331
+ meta.annotationCount = next.length
332
+ await this.persist()
333
+ return resolveAnnotations(text, [updated])[0]
334
+ })
335
+ }
336
+
337
+ async deleteAnnotation(id, annotationId) {
338
+ await this.ready()
339
+ return this._withMutation(async () => {
340
+ const meta = this._byId.get(String(id))
341
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
342
+ const existing = await this.readAnnotations(meta)
343
+ const next = existing.filter(annotation => annotation.id !== String(annotationId))
344
+ if (next.length === existing.length) throw new Error(`找不到批注:${annotationId}`)
345
+ await this.writeAnnotations(meta, next)
346
+ meta.annotationCount = next.length
347
+ await this.persist()
348
+ return { count: next.length }
349
+ })
350
+ }
351
+
352
+ async readViews() {
353
+ try {
354
+ const raw = await readFile(this.viewsPath, 'utf8')
355
+ const parsed = JSON.parse(raw)
356
+ return Array.isArray(parsed?.views) ? parsed.views : []
357
+ } catch (error) {
358
+ if (error?.code !== 'ENOENT') {
359
+ this.warnings.push(`视图读取失败:${error instanceof Error ? error.message : String(error)}`)
360
+ }
361
+ return []
362
+ }
363
+ }
364
+
365
+ async listViews() {
366
+ await this.ready()
367
+ return this.readViews()
368
+ }
369
+
370
+ async saveView(name, query) {
371
+ await this.ready()
372
+ return this._withMutation(async () => {
373
+ const label = String(name ?? '').trim().slice(0, 60)
374
+ const q = String(query ?? '').trim().slice(0, 500)
375
+ if (label === '') throw new Error('视图名称不能为空')
376
+ if (q === '') throw new Error('视图查询不能为空')
377
+ const views = await this.readViews()
378
+ const now = nowIso()
379
+ const existing = views.find(view => view.query === q)
380
+ if (existing !== undefined) {
381
+ existing.name = label
382
+ existing.updatedAt = now
383
+ await writeJsonAtomic(this.viewsPath, { version: 1, views })
384
+ return existing
385
+ }
386
+ const used = new Set(views.map(view => view.id))
387
+ let viewId = `view-${digest(`${q}\n${now}`, 10)}`
388
+ let counter = 2
389
+ while (used.has(viewId)) {
390
+ viewId = `view-${digest(`${q}\n${now}\n${counter}`, 10)}`
391
+ counter += 1
392
+ }
393
+ const view = { id: viewId, name: label, query: q, createdAt: now, updatedAt: now }
394
+ views.push(view)
395
+ await writeJsonAtomic(this.viewsPath, { version: 1, views })
396
+ return view
397
+ })
398
+ }
399
+
400
+ async deleteView(id) {
401
+ await this.ready()
402
+ return this._withMutation(async () => {
403
+ const views = await this.readViews()
404
+ const next = views.filter(view => view.id !== String(id))
405
+ if (next.length === views.length) throw new Error(`找不到视图:${id}`)
406
+ await writeJsonAtomic(this.viewsPath, { version: 1, views: next })
407
+ return { count: next.length }
408
+ })
409
+ }
410
+
411
+ async clip(rawUrl, options = {}) {
412
+ await this.ready()
413
+ const url = normalizeUrl(rawUrl)
414
+ const pending = this._inflight.get(url)
415
+ if (pending !== undefined) return pending
416
+ let task
417
+ task = this._clipOnce(url, options).finally(() => {
418
+ if (this._inflight.get(url) === task) this._inflight.delete(url)
419
+ })
420
+ this._inflight.set(url, task)
421
+ return task
422
+ }
423
+
424
+ _withMutation(fn) {
425
+ const run = this._mutationChain.then(() => fn(), () => fn())
426
+ this._mutationChain = run.then(() => undefined, () => undefined)
427
+ return run
428
+ }
429
+
430
+ async _clipOnce(url, options = {}) {
431
+ const existing = this._byUrl.get(url)
432
+ if (existing !== undefined && options.force !== true) {
433
+ const body = await this.readBody(existing.id).catch(() => '')
434
+ return { ...publicMeta(existing), duplicate: true, preview: body.slice(0, 500) }
435
+ }
436
+
437
+ const fetched = await fetchHtml(url, this.config, {
438
+ fetchImpl: this.fetchImpl,
439
+ signal: options.signal,
440
+ })
441
+ const parsed = parseArticle(fetched.html, {
442
+ url: fetched.finalUrl,
443
+ maxMarkdownChars: this.config.maxMarkdownChars,
444
+ })
445
+ if (parsed.ok !== true) throw new Error(parsed.reason)
446
+
447
+ const canonicalUrl = parsed.canonicalUrl || fetched.finalUrl
448
+
449
+ return this._withMutation(async () => {
450
+ // Re-check after the network await: another request may have committed
451
+ // the same URL, or a different URL resolving to the same canonical URL,
452
+ // while this one was fetching. This is the serialization point that
453
+ // prevents duplicate ids and a corrupted index.
454
+ const current =
455
+ this._byUrl.get(url) ??
456
+ this._byUrl.get(fetched.finalUrl) ??
457
+ this._byUrl.get(canonicalUrl)
458
+ if (current !== undefined && options.force !== true) {
459
+ const body = await this.readBody(current.id).catch(() => '')
460
+ return { ...publicMeta(current), duplicate: true, preview: body.slice(0, 500) }
461
+ }
462
+ if (current !== undefined && options.force === true) {
463
+ return this.refreshClip(current, parsed, fetched, options)
464
+ }
465
+
466
+ const id = this.uniqueId(parsed.title, canonicalUrl)
467
+ const explicitTags = normalizeTags([
468
+ ...(Array.isArray(options.tags) ? options.tags : []),
469
+ ...(this.config.defaultTags ?? []),
470
+ ])
471
+ // Page keywords are often SEO noise. Use them only when the user gave no
472
+ // tags at all, so a careful reader's own taxonomy always wins.
473
+ const tags = explicitTags.length > 0
474
+ ? explicitTags
475
+ : normalizeTags((parsed.keywords ?? []).slice(0, 3))
476
+ const meta = {
477
+ id,
478
+ url: fetched.finalUrl,
479
+ canonicalUrl,
480
+ title: parsed.title,
481
+ site: parsed.siteName,
482
+ author: parsed.byline,
483
+ published: parsed.published,
484
+ clippedAt: nowIso(),
485
+ tags,
486
+ status: 'unread',
487
+ excerpt: parsed.excerpt,
488
+ wordCount: parsed.wordCount,
489
+ charCount: parsed.charCount,
490
+ lang: parsed.lang,
491
+ images: parsed.images,
492
+ truncated: parsed.truncated === true,
493
+ annotationCount: 0,
494
+ contentHash: digest(parsed.markdown, 16),
495
+ articlePath: `clips/${id}/article.md`,
496
+ htmlPath: `clips/${id}/original.html`,
497
+ metaPath: `clips/${id}/meta.json`,
498
+ }
499
+
500
+ const clipDir = join(this.clipsDir, id)
501
+ await mkdir(clipDir, { recursive: true })
502
+ await writeFile(join(this.dir, meta.articlePath), `${parsed.markdown.trim()}\n`, 'utf8')
503
+ await writeFile(join(this.dir, meta.htmlPath), fetched.html, 'utf8')
504
+ await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
505
+
506
+ this._clips.push(meta)
507
+ this._byId.set(meta.id, meta)
508
+ this._byUrl.set(meta.url, meta)
509
+ this._byUrl.set(meta.canonicalUrl, meta)
510
+ this._search.add(toSearchDoc(meta, parsed.markdown))
511
+ await this.persist()
512
+
513
+ return {
514
+ ...publicMeta(meta),
515
+ duplicate: false,
516
+ preview: parsed.markdown.slice(0, 1_500),
517
+ }
518
+ })
519
+ }
520
+
521
+ async refreshClip(meta, parsed, fetched, options = {}) {
522
+ const canonicalUrl = parsed.canonicalUrl || fetched.finalUrl
523
+ meta.url = fetched.finalUrl
524
+ meta.canonicalUrl = canonicalUrl
525
+ meta.title = parsed.title
526
+ meta.site = parsed.siteName
527
+ meta.author = parsed.byline
528
+ meta.published = parsed.published
529
+ meta.excerpt = parsed.excerpt
530
+ meta.wordCount = parsed.wordCount
531
+ meta.charCount = parsed.charCount
532
+ meta.lang = parsed.lang
533
+ meta.images = parsed.images
534
+ meta.truncated = parsed.truncated === true
535
+ meta.annotationCount = (await this.readAnnotations(meta)).length
536
+ meta.updatedAt = nowIso()
537
+ meta.contentHash = digest(parsed.markdown, 16)
538
+ if (Array.isArray(options.tags) && options.tags.length > 0) {
539
+ meta.tags = normalizeTags(options.tags)
540
+ }
541
+
542
+ await writeFile(join(this.dir, meta.articlePath), `${parsed.markdown.trim()}\n`, 'utf8')
543
+ await writeFile(join(this.dir, meta.htmlPath), fetched.html, 'utf8')
544
+ await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
545
+
546
+ this._byUrl.set(meta.url, meta)
547
+ this._byUrl.set(meta.canonicalUrl, meta)
548
+ try {
549
+ this._search.discard(meta.id)
550
+ } catch {
551
+ // The id may be absent after a manual index edit; adding it back is enough.
552
+ }
553
+ this._search.add(toSearchDoc(meta, parsed.markdown))
554
+ await this.persist()
555
+
556
+ return {
557
+ ...publicMeta(meta),
558
+ duplicate: false,
559
+ preview: parsed.markdown.slice(0, 1_500),
560
+ }
561
+ }
562
+
563
+ uniqueId(title, url) {
564
+ const base = `${slugify(title)}-${digest(url, 8)}`
565
+ let id = base
566
+ let counter = 2
567
+ while (this._byId.has(id)) {
568
+ id = `${base}-${counter}`
569
+ counter += 1
570
+ }
571
+ return id
572
+ }
573
+
574
+ async search(query) {
575
+ await this.ready()
576
+ const parsed = parseQuery(query)
577
+ if (parsed.text === '') return null
578
+ try {
579
+ return this._search.search(parsed.text).map(result => ({
580
+ id: result.id,
581
+ score: result.score,
582
+ terms: result.terms ?? [],
583
+ }))
584
+ } catch {
585
+ return []
586
+ }
587
+ }
588
+
589
+ async list(options = {}) {
590
+ await this.ready()
591
+ const parsed = parseQuery(options.q)
592
+ const terms = queryTerms(parsed)
593
+ const status = options.status ?? 'all'
594
+ const tag = String(options.tag ?? '').trim().toLowerCase()
595
+ const tags = [tag, ...parsed.tags].filter(value => value !== '')
596
+ const limit = Math.max(1, Math.min(200, Number(options.limit) || 50))
597
+ const offset = Math.max(0, Number(options.offset) || 0)
598
+
599
+ let source
600
+ if (parsed.text !== '') {
601
+ let ranked = []
602
+ try {
603
+ ranked = this._search.search(parsed.text)
604
+ } catch {
605
+ ranked = []
606
+ }
607
+ const scoreById = new Map(ranked.map(item => [item.id, item.score]))
608
+ source = this._clips
609
+ .filter(item => scoreById.has(item.id))
610
+ .sort((a, b) => (scoreById.get(b.id) ?? 0) - (scoreById.get(a.id) ?? 0))
611
+ } else {
612
+ source = [...this._clips].sort((a, b) => String(b.clippedAt).localeCompare(String(a.clippedAt)))
613
+ }
614
+
615
+ const filtered = source.filter(item => {
616
+ if (status !== 'all' && item.status !== status) return false
617
+ if (parsed.statuses.length > 0 && !parsed.statuses.includes(item.status)) return false
618
+ const itemTags = (item.tags ?? []).map(value => String(value).toLowerCase())
619
+ if (tags.some(value => !itemTags.includes(value))) return false
620
+ if (parsed.sites.length > 0) {
621
+ const site = String(item.site ?? '').toLowerCase()
622
+ let host = ''
623
+ try { host = new URL(item.url).hostname.toLowerCase() } catch { /* no host */ }
624
+ if (!parsed.sites.some(value => site.includes(value) || host.includes(value))) return false
625
+ }
626
+ const day = String(item.clippedAt ?? '').slice(0, 10)
627
+ if (parsed.after !== '' && day < parsed.after) return false
628
+ if (parsed.before !== '' && day > parsed.before) return false
629
+ if (parsed.hasHighlight && !(Number.isInteger(item.annotationCount) && item.annotationCount > 0)) return false
630
+ return true
631
+ })
632
+
633
+ const items = filtered.slice(offset, offset + limit).map(publicMeta)
634
+ if (terms.length > 0) {
635
+ for (const item of items) {
636
+ const body = await this.readBody(item.id).catch(() => '')
637
+ const snippet = makeSnippet(`${item.title}\n${renderedText(body)}`, terms)
638
+ if (snippet !== '') item.snippet = snippet
639
+ }
640
+ }
641
+
642
+ return {
643
+ total: filtered.length,
644
+ offset,
645
+ limit,
646
+ items,
647
+ }
648
+ }
649
+
650
+ async get(id) {
651
+ await this.ready()
652
+ const meta = this._byId.get(String(id))
653
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
654
+ const body = await this.readBody(meta.id)
655
+ const annotations = await this.listAnnotations(meta.id, body)
656
+ return {
657
+ ...publicMeta(meta),
658
+ annotationCount: annotations.length,
659
+ content: body,
660
+ html: renderMarkdown(body),
661
+ annotations,
662
+ }
663
+ }
664
+
665
+ async read(id, options = {}) {
666
+ await this.ready()
667
+ const meta = this._byId.get(String(id))
668
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
669
+ const body = await this.readBody(meta.id)
670
+ const offset = Math.max(0, Number(options.offset) || 0)
671
+ const limit = Math.max(1, Math.min(40_000, Number(options.limit) || 12_000))
672
+ const content = body.slice(offset, offset + limit)
673
+ const nextOffset = offset + content.length
674
+ return {
675
+ ...publicMeta(meta),
676
+ content,
677
+ offset,
678
+ totalChars: body.length,
679
+ nextOffset,
680
+ hasMore: nextOffset < body.length,
681
+ }
682
+ }
683
+
684
+ async update(id, patch = {}) {
685
+ await this.ready()
686
+ const meta = this._byId.get(String(id))
687
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
688
+ if (patch.status !== undefined) {
689
+ if (!STATUSES.has(patch.status)) {
690
+ throw new Error(`无效状态:${patch.status};可选 unread/reading/read/archived`)
691
+ }
692
+ meta.status = patch.status
693
+ }
694
+ if (patch.tags !== undefined) meta.tags = normalizeTags(patch.tags)
695
+ await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
696
+ const body = await this.readBody(meta.id).catch(() => '')
697
+ try {
698
+ this._search.discard(meta.id)
699
+ } catch {
700
+ // MiniSearch throws when the id is absent; a missing doc needs no discard.
701
+ }
702
+ this._search.add(toSearchDoc(meta, body))
703
+ await this.persist()
704
+ return publicMeta(meta)
705
+ }
706
+
707
+ async stats() {
708
+ await this.ready()
709
+ const counts = { all: this._clips.length, unread: 0, reading: 0, read: 0, archived: 0 }
710
+ const tags = new Map()
711
+ for (const item of this._clips) {
712
+ if (counts[item.status] !== undefined) counts[item.status] += 1
713
+ for (const tag of item.tags ?? []) tags.set(tag, (tags.get(tag) ?? 0) + 1)
714
+ }
715
+ return {
716
+ ...counts,
717
+ tags: [...tags.entries()]
718
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
719
+ .slice(0, 40)
720
+ .map(([name, count]) => ({ name, count })),
721
+ warnings: this.warnings,
722
+ }
723
+ }
724
+
725
+ async export(id) {
726
+ await this.ready()
727
+ const meta = this._byId.get(String(id))
728
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
729
+ const body = await this.readBody(meta.id)
730
+ const annotations = await this.listAnnotations(meta.id, body)
731
+ return { meta: publicMeta(meta), markdown: exportMarkdown(meta, body, annotations) }
732
+ }
733
+
734
+ async persist() {
735
+ const snapshot = { version: INDEX_VERSION, clips: this._clips }
736
+ this._writeChain = this._writeChain
737
+ .catch(() => {})
738
+ .then(() => writeJsonAtomic(this.indexPath, snapshot))
739
+ await this._writeChain
740
+ }
741
+ }