dsh-reading-inbox 0.2.1 → 0.4.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,1000 @@
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
+ normalizeQuote,
10
+ resolveAnnotations,
11
+ } from './annotations.js'
12
+ import { fetchHtml } from './fetch.js'
13
+ import { countWords, exportMarkdown, htmlToMarkdown, parseArticle, renderMarkdown, renderedText } from './markdown.js'
14
+ import { makeSnippet, parseQuery, queryTerms } from './search.js'
15
+
16
+ const INDEX_VERSION = 1
17
+ const STATUSES = new Set(['unread', 'reading', 'read', 'archived'])
18
+ const MAX_TAGS = 20
19
+ const MAX_TAG_LENGTH = 40
20
+ const MAX_ANNOTATIONS = 500
21
+
22
+ function nowIso() {
23
+ return new Date().toISOString()
24
+ }
25
+
26
+ function digest(value, length = 12) {
27
+ return createHash('sha256').update(String(value)).digest('hex').slice(0, length)
28
+ }
29
+
30
+ function safeClipId(value) {
31
+ return typeof value === 'string'
32
+ && /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/.test(value)
33
+ && !value.includes('..')
34
+ ? value
35
+ : null
36
+ }
37
+
38
+ function slugify(value) {
39
+ const ascii = String(value ?? '')
40
+ .normalize('NFKD')
41
+ .replace(/[̀-ͯ]/g, '')
42
+ .toLowerCase()
43
+ .replace(/[^a-z0-9]+/g, '-')
44
+ .replace(/^-+|-+$/g, '')
45
+ .slice(0, 60)
46
+ return ascii === '' ? 'clip' : ascii
47
+ }
48
+
49
+ export function normalizeTags(tags = []) {
50
+ const seen = new Set()
51
+ const result = []
52
+ for (const raw of Array.isArray(tags) ? tags : [tags]) {
53
+ const value = String(raw ?? '')
54
+ .replace(/^#/, '')
55
+ .replace(/[\r\n,,]/g, ' ')
56
+ .replace(/\s+/g, ' ')
57
+ .trim()
58
+ if (value === '' || value.length > MAX_TAG_LENGTH) continue
59
+ const key = value.toLowerCase()
60
+ if (seen.has(key)) continue
61
+ seen.add(key)
62
+ result.push(value)
63
+ if (result.length >= MAX_TAGS) break
64
+ }
65
+ return result
66
+ }
67
+
68
+ export function normalizeUrl(rawUrl) {
69
+ let url
70
+ try {
71
+ url = new URL(String(rawUrl ?? '').trim())
72
+ } catch {
73
+ throw new Error('URL 格式不正确,需要以 http:// 或 https:// 开头')
74
+ }
75
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
76
+ throw new Error(`不支持的协议:${url.protocol};只允许 http/https`)
77
+ }
78
+ url.hash = ''
79
+ for (const key of [...url.searchParams.keys()]) {
80
+ if (/^(utm_|fbclid$|gclid$|spm$)/i.test(key)) url.searchParams.delete(key)
81
+ }
82
+ return url.toString()
83
+ }
84
+
85
+ function tokenize(text) {
86
+ const normalized = String(text ?? '').toLowerCase()
87
+ const chunks = normalized.match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[a-z0-9_]+/gu) || []
88
+ const tokens = []
89
+ for (const chunk of chunks) {
90
+ if (/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(chunk)) {
91
+ for (let index = 0; index < chunk.length; index += 1) {
92
+ tokens.push(chunk[index])
93
+ if (index + 1 < chunk.length) tokens.push(chunk.slice(index, index + 2))
94
+ }
95
+ } else {
96
+ tokens.push(chunk)
97
+ }
98
+ }
99
+ return tokens
100
+ }
101
+
102
+ function createSearchIndex() {
103
+ return new MiniSearch({
104
+ fields: ['title', 'excerpt', 'body', 'tags', 'site'],
105
+ storeFields: ['id'],
106
+ idField: 'id',
107
+ tokenize,
108
+ searchOptions: {
109
+ boost: { title: 3, tags: 2, site: 1.5 },
110
+ prefix: true,
111
+ fuzzy: 0.2,
112
+ combineWith: 'AND',
113
+ },
114
+ })
115
+ }
116
+
117
+ function toSearchDoc(meta, body) {
118
+ return {
119
+ id: meta.id,
120
+ title: meta.title,
121
+ excerpt: meta.excerpt,
122
+ body: String(body ?? '').slice(0, 40_000),
123
+ tags: (meta.tags ?? []).join(' '),
124
+ site: meta.site,
125
+ }
126
+ }
127
+
128
+ function publicMeta(meta) {
129
+ return {
130
+ id: meta.id,
131
+ title: meta.title,
132
+ url: meta.url,
133
+ site: meta.site,
134
+ author: meta.author,
135
+ published: meta.published,
136
+ clippedAt: meta.clippedAt,
137
+ tags: meta.tags,
138
+ status: meta.status,
139
+ excerpt: meta.excerpt,
140
+ wordCount: meta.wordCount,
141
+ charCount: meta.charCount,
142
+ lang: meta.lang,
143
+ images: meta.images,
144
+ truncated: meta.truncated === true,
145
+ annotationCount: Number.isInteger(meta.annotationCount) ? meta.annotationCount : 0,
146
+ }
147
+ }
148
+
149
+ async function writeJsonAtomic(path, value) {
150
+ const temporary = `${path}.tmp`
151
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
152
+ await rename(temporary, path)
153
+ }
154
+
155
+ export class ReadingInbox {
156
+ constructor(config, options = {}) {
157
+ this.config = config
158
+ // Leave this undefined unless a caller explicitly injects a fetch. fetch.js
159
+ // uses its own validating dispatcher (or ProxyAgent) when no override is
160
+ // present; defaulting to globalThis.fetch here used to bypass both.
161
+ this.fetchImpl = options.fetchImpl
162
+ this.dir = config.dir
163
+ this.clipsDir = join(this.dir, 'clips')
164
+ this.indexPath = join(this.dir, 'index.json')
165
+ this.viewsPath = join(this.dir, 'views.json')
166
+ this.warnings = []
167
+ this._ready = null
168
+ this._clips = []
169
+ this._byId = new Map()
170
+ this._byUrl = new Map()
171
+ this._search = null
172
+ this._writeChain = Promise.resolve()
173
+ this._mutationChain = Promise.resolve()
174
+ this._inflight = new Map()
175
+ this._textCache = new Map()
176
+ }
177
+
178
+ ready() {
179
+ this._ready ??= this.init()
180
+ return this._ready
181
+ }
182
+
183
+ async init() {
184
+ await mkdir(this.clipsDir, { recursive: true })
185
+ try {
186
+ const raw = await readFile(this.indexPath, 'utf8')
187
+ const parsed = JSON.parse(raw)
188
+ const clips = Array.isArray(parsed?.clips) ? parsed.clips : []
189
+ const byId = new Map()
190
+ for (const item of clips) {
191
+ if (item !== null && typeof item === 'object' && typeof item.id === 'string' && !byId.has(item.id)) {
192
+ byId.set(item.id, item)
193
+ }
194
+ }
195
+ this._clips = [...byId.values()]
196
+ } catch (error) {
197
+ if (error?.code !== 'ENOENT') {
198
+ const backup = `${this.indexPath}.corrupt-${Date.now()}`
199
+ await rename(this.indexPath, backup).catch(() => {})
200
+ this.warnings.push(`索引读取失败,已备份到 ${backup}:${error instanceof Error ? error.message : String(error)}`)
201
+ }
202
+ this._clips = []
203
+ }
204
+ this._byId = new Map(this._clips.map(item => [item.id, item]))
205
+ this._byUrl = new Map()
206
+ for (const item of this._clips) {
207
+ if (typeof item.url === 'string') this._byUrl.set(item.url, item)
208
+ if (typeof item.canonicalUrl === 'string') this._byUrl.set(item.canonicalUrl, item)
209
+ }
210
+ this._search = createSearchIndex()
211
+ for (const item of this._clips) {
212
+ const body = await this.readBody(item.id).catch(() => '')
213
+ try {
214
+ this._search.add(toSearchDoc(item, body))
215
+ } catch (error) {
216
+ this.warnings.push(
217
+ `索引条目 ${item.id} 重复或损坏,已跳过:${error instanceof Error ? error.message : String(error)}`,
218
+ )
219
+ }
220
+ }
221
+ return this
222
+ }
223
+
224
+ async readBody(id) {
225
+ const meta = this._byId.get(id)
226
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
227
+ return readFile(join(this.dir, meta.articlePath), 'utf8')
228
+ }
229
+
230
+ annotationPath(meta) {
231
+ return join(this.clipsDir, meta.id, 'annotations.json')
232
+ }
233
+
234
+ textForClip(meta, markdown) {
235
+ const key = `${meta.id}:${meta.contentHash ?? ''}`
236
+ const cached = this._textCache.get(key)
237
+ if (cached !== undefined) return cached
238
+ const text = renderedText(markdown)
239
+ if (this._textCache.size > 30) this._textCache.clear()
240
+ this._textCache.set(key, text)
241
+ return text
242
+ }
243
+
244
+ async readAnnotations(meta) {
245
+ try {
246
+ const raw = await readFile(this.annotationPath(meta), 'utf8')
247
+ const parsed = JSON.parse(raw)
248
+ if (Array.isArray(parsed)) return parsed
249
+ return Array.isArray(parsed?.annotations) ? parsed.annotations : []
250
+ } catch (error) {
251
+ if (error?.code !== 'ENOENT') {
252
+ this.warnings.push(
253
+ `批注读取失败(${meta.id}):${error instanceof Error ? error.message : String(error)}`,
254
+ )
255
+ }
256
+ return []
257
+ }
258
+ }
259
+
260
+ async writeAnnotations(meta, annotations) {
261
+ await writeJsonAtomic(this.annotationPath(meta), {
262
+ version: 1,
263
+ contentVersion: meta.contentHash ?? '',
264
+ annotations,
265
+ })
266
+ }
267
+
268
+ async listAnnotations(id, body = null) {
269
+ await this.ready()
270
+ const meta = this._byId.get(String(id))
271
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
272
+ const markdown = body ?? await this.readBody(meta.id)
273
+ const text = this.textForClip(meta, markdown)
274
+ const annotations = await this.readAnnotations(meta)
275
+ return resolveAnnotations(text, annotations)
276
+ }
277
+
278
+ async addAnnotation(id, input = {}) {
279
+ await this.ready()
280
+ return this._withMutation(async () => {
281
+ const meta = this._byId.get(String(id))
282
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
283
+ const body = await this.readBody(meta.id)
284
+ const text = this.textForClip(meta, body)
285
+ const anchor = buildAnnotationAnchor(text, {
286
+ quote: input.quote,
287
+ prefix: input.prefix,
288
+ suffix: input.suffix,
289
+ startOffset: Number.isInteger(input.startOffset) ? input.startOffset : undefined,
290
+ endOffset: Number.isInteger(input.endOffset) ? input.endOffset : undefined,
291
+ })
292
+ const existing = await this.readAnnotations(meta)
293
+ if (existing.length >= MAX_ANNOTATIONS) {
294
+ throw new Error(`单篇批注数量已达上限(${MAX_ANNOTATIONS})`)
295
+ }
296
+ const now = nowIso()
297
+ const used = new Set(existing.map(annotation => annotation.id))
298
+ let annotationId = `hl-${digest(`${anchor.quote}\n${anchor.startOffset}\n${now}`, 12)}`
299
+ let counter = 2
300
+ while (used.has(annotationId)) {
301
+ annotationId = `hl-${digest(`${anchor.quote}\n${anchor.startOffset}\n${now}\n${counter}`, 12)}`
302
+ counter += 1
303
+ }
304
+ const annotation = {
305
+ id: annotationId,
306
+ ...anchor,
307
+ color: normalizeColor(input.color),
308
+ note: normalizeNote(input.note),
309
+ contentVersion: meta.contentHash ?? '',
310
+ createdAt: now,
311
+ updatedAt: now,
312
+ }
313
+ const next = [...existing, annotation]
314
+ await this.writeAnnotations(meta, next)
315
+ meta.annotationCount = next.length
316
+ await this.persist()
317
+ return resolveAnnotations(text, [annotation])[0]
318
+ })
319
+ }
320
+
321
+ async updateAnnotation(id, annotationId, patch = {}) {
322
+ await this.ready()
323
+ return this._withMutation(async () => {
324
+ const meta = this._byId.get(String(id))
325
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
326
+ const body = await this.readBody(meta.id)
327
+ const text = this.textForClip(meta, body)
328
+ const existing = await this.readAnnotations(meta)
329
+ const index = existing.findIndex(annotation => annotation.id === String(annotationId))
330
+ if (index === -1) throw new Error(`找不到批注:${annotationId}`)
331
+ const updated = {
332
+ ...existing[index],
333
+ note: patch.note === undefined ? existing[index].note : normalizeNote(patch.note),
334
+ color: patch.color === undefined ? existing[index].color : normalizeColor(patch.color),
335
+ updatedAt: nowIso(),
336
+ }
337
+ const next = [...existing]
338
+ next[index] = updated
339
+ await this.writeAnnotations(meta, next)
340
+ meta.annotationCount = next.length
341
+ await this.persist()
342
+ return resolveAnnotations(text, [updated])[0]
343
+ })
344
+ }
345
+
346
+ async deleteAnnotation(id, annotationId) {
347
+ await this.ready()
348
+ return this._withMutation(async () => {
349
+ const meta = this._byId.get(String(id))
350
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
351
+ const existing = await this.readAnnotations(meta)
352
+ const next = existing.filter(annotation => annotation.id !== String(annotationId))
353
+ if (next.length === existing.length) throw new Error(`找不到批注:${annotationId}`)
354
+ await this.writeAnnotations(meta, next)
355
+ meta.annotationCount = next.length
356
+ await this.persist()
357
+ return { count: next.length }
358
+ })
359
+ }
360
+
361
+ async readViews() {
362
+ try {
363
+ const raw = await readFile(this.viewsPath, 'utf8')
364
+ const parsed = JSON.parse(raw)
365
+ return Array.isArray(parsed?.views) ? parsed.views : []
366
+ } catch (error) {
367
+ if (error?.code !== 'ENOENT') {
368
+ this.warnings.push(`视图读取失败:${error instanceof Error ? error.message : String(error)}`)
369
+ }
370
+ return []
371
+ }
372
+ }
373
+
374
+ async listViews() {
375
+ await this.ready()
376
+ return this.readViews()
377
+ }
378
+
379
+ async saveView(name, query) {
380
+ await this.ready()
381
+ return this._withMutation(async () => {
382
+ const label = String(name ?? '').trim().slice(0, 60)
383
+ const q = String(query ?? '').trim().slice(0, 500)
384
+ if (label === '') throw new Error('视图名称不能为空')
385
+ if (q === '') throw new Error('视图查询不能为空')
386
+ const views = await this.readViews()
387
+ const now = nowIso()
388
+ const existing = views.find(view => view.query === q)
389
+ if (existing !== undefined) {
390
+ existing.name = label
391
+ existing.updatedAt = now
392
+ await writeJsonAtomic(this.viewsPath, { version: 1, views })
393
+ return existing
394
+ }
395
+ const used = new Set(views.map(view => view.id))
396
+ let viewId = `view-${digest(`${q}\n${now}`, 10)}`
397
+ let counter = 2
398
+ while (used.has(viewId)) {
399
+ viewId = `view-${digest(`${q}\n${now}\n${counter}`, 10)}`
400
+ counter += 1
401
+ }
402
+ const view = { id: viewId, name: label, query: q, createdAt: now, updatedAt: now }
403
+ views.push(view)
404
+ await writeJsonAtomic(this.viewsPath, { version: 1, views })
405
+ return view
406
+ })
407
+ }
408
+
409
+ async deleteView(id) {
410
+ await this.ready()
411
+ return this._withMutation(async () => {
412
+ const views = await this.readViews()
413
+ const next = views.filter(view => view.id !== String(id))
414
+ if (next.length === views.length) throw new Error(`找不到视图:${id}`)
415
+ await writeJsonAtomic(this.viewsPath, { version: 1, views: next })
416
+ return { count: next.length }
417
+ })
418
+ }
419
+
420
+ async clip(rawUrl, options = {}) {
421
+ await this.ready()
422
+ const url = normalizeUrl(rawUrl)
423
+ const pending = this._inflight.get(url)
424
+ if (pending !== undefined) return pending
425
+ let task
426
+ task = this._clipOnce(url, options).finally(() => {
427
+ if (this._inflight.get(url) === task) this._inflight.delete(url)
428
+ })
429
+ this._inflight.set(url, task)
430
+ return task
431
+ }
432
+
433
+ _withMutation(fn) {
434
+ const run = this._mutationChain.then(() => fn(), () => fn())
435
+ this._mutationChain = run.then(() => undefined, () => undefined)
436
+ return run
437
+ }
438
+
439
+ async saveText(input = {}) {
440
+ await this.ready()
441
+ const rawMarkdown = String(input.markdown ?? '').trim()
442
+ const rawHtml = String(input.html ?? '').trim()
443
+ const rawText = String(input.text ?? '').trim()
444
+ if (rawMarkdown === '' && rawHtml === '' && rawText === '') {
445
+ throw new Error('需要 text、markdown 或 html')
446
+ }
447
+ const url = typeof input.url === 'string' && input.url.trim() !== ''
448
+ ? normalizeUrl(input.url)
449
+ : ''
450
+ const existing = url === '' ? undefined : this._byUrl.get(url)
451
+ if (existing !== undefined) {
452
+ const body = await this.readBody(existing.id).catch(() => '')
453
+ return { ...publicMeta(existing), duplicate: true, preview: body.slice(0, 500) }
454
+ }
455
+
456
+ return this._withMutation(async () => {
457
+ const current = url === '' ? undefined : this._byUrl.get(url)
458
+ if (current !== undefined) {
459
+ const body = await this.readBody(current.id).catch(() => '')
460
+ return { ...publicMeta(current), duplicate: true, preview: body.slice(0, 500) }
461
+ }
462
+
463
+ let markdown = rawMarkdown || (rawHtml !== '' ? htmlToMarkdown(rawHtml, url) : rawText)
464
+ markdown = markdown.trim()
465
+ if (markdown === '') throw new Error('内容为空')
466
+ let truncated = false
467
+ if (markdown.length > this.config.maxMarkdownChars) {
468
+ markdown = `${markdown.slice(0, this.config.maxMarkdownChars)}\n\n> 内容过长,已截断。`
469
+ truncated = true
470
+ }
471
+
472
+ const plain = renderedText(markdown)
473
+ const counts = countWords(plain)
474
+ const firstLine = plain.split(/\r?\n/).map(line => line.trim()).find(line => line !== '')
475
+ const titleSource = String(input.title ?? '').trim()
476
+ || firstLine
477
+ || (url === '' ? '未命名笔记' : (() => { try { return new URL(url).hostname } catch { return '未命名笔记' } })())
478
+ const title = titleSource.replace(/\s+/g, ' ').slice(0, 300)
479
+ const id = this.uniqueId(title, url || `text:${digest(markdown, 12)}`)
480
+ const explicitTags = normalizeTags([
481
+ ...(Array.isArray(input.tags) ? input.tags : []),
482
+ ...(this.config.defaultTags ?? []),
483
+ ])
484
+ const tags = explicitTags.length > 0
485
+ ? explicitTags
486
+ : normalizeTags((plain.match(/#[^\s#]+/g) ?? []).slice(0, 3).map(tag => tag.slice(1)))
487
+ const site = url === ''
488
+ ? '手动保存'
489
+ : (() => { try { return new URL(url).hostname } catch { return '手动保存' } })()
490
+ const meta = {
491
+ id,
492
+ url,
493
+ canonicalUrl: url,
494
+ title,
495
+ site,
496
+ author: '',
497
+ published: '',
498
+ clippedAt: nowIso(),
499
+ tags,
500
+ status: 'unread',
501
+ excerpt: plain.replace(/\s+/g, ' ').trim().slice(0, 240),
502
+ wordCount: counts.wordCount,
503
+ charCount: counts.charCount,
504
+ lang: counts.cjk > 0 ? 'zh' : 'en',
505
+ images: (markdown.match(/!\[[^\]]*\]\([^)]*\)/g) ?? []).length,
506
+ truncated,
507
+ annotationCount: 0,
508
+ contentHash: digest(markdown, 16),
509
+ manual: true,
510
+ articlePath: `clips/${id}/article.md`,
511
+ htmlPath: `clips/${id}/original.html`,
512
+ metaPath: `clips/${id}/meta.json`,
513
+ }
514
+
515
+ const clipDir = join(this.clipsDir, id)
516
+ await mkdir(clipDir, { recursive: true })
517
+ await writeFile(join(this.dir, meta.articlePath), `${markdown}\n`, 'utf8')
518
+ await writeFile(join(this.dir, meta.htmlPath), rawHtml || renderMarkdown(markdown), 'utf8')
519
+ await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
520
+
521
+ this._clips.push(meta)
522
+ this._byId.set(meta.id, meta)
523
+ if (url !== '') this._byUrl.set(url, meta)
524
+ this._search.add(toSearchDoc(meta, markdown))
525
+ await this.persist()
526
+
527
+ return { ...publicMeta(meta), duplicate: false, preview: markdown.slice(0, 1_500) }
528
+ })
529
+ }
530
+
531
+ async _clipOnce(url, options = {}) {
532
+ const existing = this._byUrl.get(url)
533
+ if (existing !== undefined && options.force !== true) {
534
+ const body = await this.readBody(existing.id).catch(() => '')
535
+ return { ...publicMeta(existing), duplicate: true, preview: body.slice(0, 500) }
536
+ }
537
+
538
+ const fetched = await fetchHtml(url, this.config, {
539
+ fetchImpl: this.fetchImpl,
540
+ signal: options.signal,
541
+ })
542
+ const parsed = parseArticle(fetched.html, {
543
+ url: fetched.finalUrl,
544
+ maxMarkdownChars: this.config.maxMarkdownChars,
545
+ })
546
+ if (parsed.ok !== true) throw new Error(parsed.reason)
547
+
548
+ const canonicalUrl = parsed.canonicalUrl || fetched.finalUrl
549
+
550
+ return this._withMutation(async () => {
551
+ // Re-check after the network await: another request may have committed
552
+ // the same URL, or a different URL resolving to the same canonical URL,
553
+ // while this one was fetching. This is the serialization point that
554
+ // prevents duplicate ids and a corrupted index.
555
+ const current =
556
+ this._byUrl.get(url) ??
557
+ this._byUrl.get(fetched.finalUrl) ??
558
+ this._byUrl.get(canonicalUrl)
559
+ if (current !== undefined && options.force !== true) {
560
+ const body = await this.readBody(current.id).catch(() => '')
561
+ return { ...publicMeta(current), duplicate: true, preview: body.slice(0, 500) }
562
+ }
563
+ if (current !== undefined && options.force === true) {
564
+ return this.refreshClip(current, parsed, fetched, options)
565
+ }
566
+
567
+ const id = this.uniqueId(parsed.title, canonicalUrl)
568
+ const explicitTags = normalizeTags([
569
+ ...(Array.isArray(options.tags) ? options.tags : []),
570
+ ...(this.config.defaultTags ?? []),
571
+ ])
572
+ // Page keywords are often SEO noise. Use them only when the user gave no
573
+ // tags at all, so a careful reader's own taxonomy always wins.
574
+ const tags = explicitTags.length > 0
575
+ ? explicitTags
576
+ : normalizeTags((parsed.keywords ?? []).slice(0, 3))
577
+ const meta = {
578
+ id,
579
+ url: fetched.finalUrl,
580
+ canonicalUrl,
581
+ title: parsed.title,
582
+ site: parsed.siteName,
583
+ author: parsed.byline,
584
+ published: parsed.published,
585
+ clippedAt: nowIso(),
586
+ tags,
587
+ status: 'unread',
588
+ excerpt: parsed.excerpt,
589
+ wordCount: parsed.wordCount,
590
+ charCount: parsed.charCount,
591
+ lang: parsed.lang,
592
+ images: parsed.images,
593
+ truncated: parsed.truncated === true,
594
+ annotationCount: 0,
595
+ contentHash: digest(parsed.markdown, 16),
596
+ articlePath: `clips/${id}/article.md`,
597
+ htmlPath: `clips/${id}/original.html`,
598
+ metaPath: `clips/${id}/meta.json`,
599
+ }
600
+
601
+ const clipDir = join(this.clipsDir, id)
602
+ await mkdir(clipDir, { recursive: true })
603
+ await writeFile(join(this.dir, meta.articlePath), `${parsed.markdown.trim()}\n`, 'utf8')
604
+ await writeFile(join(this.dir, meta.htmlPath), fetched.html, 'utf8')
605
+ await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
606
+
607
+ this._clips.push(meta)
608
+ this._byId.set(meta.id, meta)
609
+ this._byUrl.set(meta.url, meta)
610
+ this._byUrl.set(meta.canonicalUrl, meta)
611
+ this._search.add(toSearchDoc(meta, parsed.markdown))
612
+ await this.persist()
613
+
614
+ return {
615
+ ...publicMeta(meta),
616
+ duplicate: false,
617
+ preview: parsed.markdown.slice(0, 1_500),
618
+ }
619
+ })
620
+ }
621
+
622
+ async refreshClip(meta, parsed, fetched, options = {}) {
623
+ const canonicalUrl = parsed.canonicalUrl || fetched.finalUrl
624
+ meta.url = fetched.finalUrl
625
+ meta.canonicalUrl = canonicalUrl
626
+ meta.title = parsed.title
627
+ meta.site = parsed.siteName
628
+ meta.author = parsed.byline
629
+ meta.published = parsed.published
630
+ meta.excerpt = parsed.excerpt
631
+ meta.wordCount = parsed.wordCount
632
+ meta.charCount = parsed.charCount
633
+ meta.lang = parsed.lang
634
+ meta.images = parsed.images
635
+ meta.truncated = parsed.truncated === true
636
+ meta.annotationCount = (await this.readAnnotations(meta)).length
637
+ meta.updatedAt = nowIso()
638
+ meta.contentHash = digest(parsed.markdown, 16)
639
+ if (Array.isArray(options.tags) && options.tags.length > 0) {
640
+ meta.tags = normalizeTags(options.tags)
641
+ }
642
+
643
+ await writeFile(join(this.dir, meta.articlePath), `${parsed.markdown.trim()}\n`, 'utf8')
644
+ await writeFile(join(this.dir, meta.htmlPath), fetched.html, 'utf8')
645
+ await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
646
+
647
+ this._byUrl.set(meta.url, meta)
648
+ this._byUrl.set(meta.canonicalUrl, meta)
649
+ try {
650
+ this._search.discard(meta.id)
651
+ } catch {
652
+ // The id may be absent after a manual index edit; adding it back is enough.
653
+ }
654
+ this._search.add(toSearchDoc(meta, parsed.markdown))
655
+ await this.persist()
656
+
657
+ return {
658
+ ...publicMeta(meta),
659
+ duplicate: false,
660
+ preview: parsed.markdown.slice(0, 1_500),
661
+ }
662
+ }
663
+
664
+ uniqueId(title, url) {
665
+ const base = `${slugify(title)}-${digest(url, 8)}`
666
+ let id = base
667
+ let counter = 2
668
+ while (this._byId.has(id)) {
669
+ id = `${base}-${counter}`
670
+ counter += 1
671
+ }
672
+ return id
673
+ }
674
+
675
+ async search(query) {
676
+ await this.ready()
677
+ const parsed = parseQuery(query)
678
+ if (parsed.text === '') return null
679
+ try {
680
+ return this._search.search(parsed.text).map(result => ({
681
+ id: result.id,
682
+ score: result.score,
683
+ terms: result.terms ?? [],
684
+ }))
685
+ } catch {
686
+ return []
687
+ }
688
+ }
689
+
690
+ async list(options = {}) {
691
+ await this.ready()
692
+ const parsed = parseQuery(options.q)
693
+ const terms = queryTerms(parsed)
694
+ const status = options.status ?? 'all'
695
+ const tag = String(options.tag ?? '').trim().toLowerCase()
696
+ const tags = [tag, ...parsed.tags].filter(value => value !== '')
697
+ const limit = Math.max(1, Math.min(200, Number(options.limit) || 50))
698
+ const offset = Math.max(0, Number(options.offset) || 0)
699
+
700
+ let source
701
+ if (parsed.text !== '') {
702
+ let ranked = []
703
+ try {
704
+ ranked = this._search.search(parsed.text)
705
+ } catch {
706
+ ranked = []
707
+ }
708
+ const scoreById = new Map(ranked.map(item => [item.id, item.score]))
709
+ source = this._clips
710
+ .filter(item => scoreById.has(item.id))
711
+ .sort((a, b) => (scoreById.get(b.id) ?? 0) - (scoreById.get(a.id) ?? 0))
712
+ } else {
713
+ source = [...this._clips].sort((a, b) => String(b.clippedAt).localeCompare(String(a.clippedAt)))
714
+ }
715
+
716
+ const filtered = source.filter(item => {
717
+ if (status !== 'all' && item.status !== status) return false
718
+ if (parsed.statuses.length > 0 && !parsed.statuses.includes(item.status)) return false
719
+ const itemTags = (item.tags ?? []).map(value => String(value).toLowerCase())
720
+ if (tags.some(value => !itemTags.includes(value))) return false
721
+ if (parsed.sites.length > 0) {
722
+ const site = String(item.site ?? '').toLowerCase()
723
+ let host = ''
724
+ try { host = new URL(item.url).hostname.toLowerCase() } catch { /* no host */ }
725
+ if (!parsed.sites.some(value => site.includes(value) || host.includes(value))) return false
726
+ }
727
+ const day = String(item.clippedAt ?? '').slice(0, 10)
728
+ if (parsed.after !== '' && day < parsed.after) return false
729
+ if (parsed.before !== '' && day > parsed.before) return false
730
+ if (parsed.hasHighlight && !(Number.isInteger(item.annotationCount) && item.annotationCount > 0)) return false
731
+ return true
732
+ })
733
+
734
+ const items = filtered.slice(offset, offset + limit).map(publicMeta)
735
+ if (terms.length > 0) {
736
+ for (const item of items) {
737
+ const body = await this.readBody(item.id).catch(() => '')
738
+ const snippet = makeSnippet(`${item.title}\n${renderedText(body)}`, terms)
739
+ if (snippet !== '') item.snippet = snippet
740
+ }
741
+ }
742
+
743
+ return {
744
+ total: filtered.length,
745
+ offset,
746
+ limit,
747
+ items,
748
+ }
749
+ }
750
+
751
+ async get(id) {
752
+ await this.ready()
753
+ const meta = this._byId.get(String(id))
754
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
755
+ const body = await this.readBody(meta.id)
756
+ const annotations = await this.listAnnotations(meta.id, body)
757
+ return {
758
+ ...publicMeta(meta),
759
+ annotationCount: annotations.length,
760
+ content: body,
761
+ html: renderMarkdown(body),
762
+ annotations,
763
+ }
764
+ }
765
+
766
+ async read(id, options = {}) {
767
+ await this.ready()
768
+ const meta = this._byId.get(String(id))
769
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
770
+ const body = await this.readBody(meta.id)
771
+ const offset = Math.max(0, Number(options.offset) || 0)
772
+ const limit = Math.max(1, Math.min(40_000, Number(options.limit) || 12_000))
773
+ const content = body.slice(offset, offset + limit)
774
+ const nextOffset = offset + content.length
775
+ return {
776
+ ...publicMeta(meta),
777
+ content,
778
+ offset,
779
+ totalChars: body.length,
780
+ nextOffset,
781
+ hasMore: nextOffset < body.length,
782
+ }
783
+ }
784
+
785
+ async update(id, patch = {}) {
786
+ await this.ready()
787
+ const meta = this._byId.get(String(id))
788
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
789
+ if (patch.status !== undefined) {
790
+ if (!STATUSES.has(patch.status)) {
791
+ throw new Error(`无效状态:${patch.status};可选 unread/reading/read/archived`)
792
+ }
793
+ meta.status = patch.status
794
+ }
795
+ if (patch.tags !== undefined) meta.tags = normalizeTags(patch.tags)
796
+ await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
797
+ const body = await this.readBody(meta.id).catch(() => '')
798
+ try {
799
+ this._search.discard(meta.id)
800
+ } catch {
801
+ // MiniSearch throws when the id is absent; a missing doc needs no discard.
802
+ }
803
+ this._search.add(toSearchDoc(meta, body))
804
+ await this.persist()
805
+ return publicMeta(meta)
806
+ }
807
+
808
+ async stats() {
809
+ await this.ready()
810
+ const counts = { all: this._clips.length, unread: 0, reading: 0, read: 0, archived: 0 }
811
+ const tags = new Map()
812
+ for (const item of this._clips) {
813
+ if (counts[item.status] !== undefined) counts[item.status] += 1
814
+ for (const tag of item.tags ?? []) tags.set(tag, (tags.get(tag) ?? 0) + 1)
815
+ }
816
+ return {
817
+ ...counts,
818
+ tags: [...tags.entries()]
819
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
820
+ .slice(0, 40)
821
+ .map(([name, count]) => ({ name, count })),
822
+ warnings: this.warnings,
823
+ }
824
+ }
825
+
826
+ async export(id) {
827
+ await this.ready()
828
+ const meta = this._byId.get(String(id))
829
+ if (meta === undefined) throw new Error(`找不到文章:${id}`)
830
+ const body = await this.readBody(meta.id)
831
+ const annotations = await this.listAnnotations(meta.id, body)
832
+ return { meta: publicMeta(meta), markdown: exportMarkdown(meta, body, annotations) }
833
+ }
834
+
835
+ async exportBundle(options = {}) {
836
+ await this.ready()
837
+ const clips = []
838
+ for (const meta of this._clips) {
839
+ const article = await this.readBody(meta.id).catch(() => '')
840
+ if (article === '') continue
841
+ const annotations = await this.readAnnotations(meta)
842
+ const item = { meta: publicMeta(meta), article, annotations }
843
+ if (options.includeOriginal === true) {
844
+ item.originalHtml = await readFile(join(this.dir, meta.htmlPath), 'utf8').catch(() => '')
845
+ }
846
+ clips.push(item)
847
+ }
848
+ return { version: 1, exportedAt: nowIso(), clips, views: await this.readViews() }
849
+ }
850
+
851
+ async exportAllMarkdown() {
852
+ await this.ready()
853
+ const parts = []
854
+ for (const meta of this._clips) {
855
+ const body = await this.readBody(meta.id).catch(() => '')
856
+ if (body === '') continue
857
+ const annotations = await this.listAnnotations(meta.id, body)
858
+ parts.push(exportMarkdown(meta, body, annotations))
859
+ }
860
+ return parts.join('\n\n---\n\n')
861
+ }
862
+
863
+ async importBundle(bundle) {
864
+ await this.ready()
865
+ if (bundle === null || typeof bundle !== 'object' || !Array.isArray(bundle.clips)) {
866
+ throw new Error('导入文件需要包含 clips 数组')
867
+ }
868
+ return this._withMutation(async () => {
869
+ let imported = 0
870
+ let skipped = 0
871
+ const errors = []
872
+ for (let index = 0; index < bundle.clips.length; index += 1) {
873
+ const raw = bundle.clips[index]
874
+ try {
875
+ if (raw === null || typeof raw !== 'object' || typeof raw.article !== 'string' || raw.article.trim() === '') {
876
+ skipped += 1
877
+ continue
878
+ }
879
+ const article = raw.article.trim()
880
+ if (article.length > 5_000_000) throw new Error('单篇正文超过 5 MB')
881
+ const metaIn = raw.meta !== null && typeof raw.meta === 'object' ? raw.meta : {}
882
+ let url = ''
883
+ if (typeof metaIn.url === 'string' && metaIn.url.trim() !== '') {
884
+ try { url = normalizeUrl(metaIn.url) } catch { url = '' }
885
+ }
886
+ if (url !== '' && this._byUrl.has(url)) {
887
+ skipped += 1
888
+ continue
889
+ }
890
+ const plain = renderedText(article)
891
+ const firstLine = plain.split(/\r?\n/).map(line => line.trim()).find(line => line !== '')
892
+ const title = (String(metaIn.title ?? '').trim() || firstLine || '导入文章')
893
+ .replace(/\s+/g, ' ')
894
+ .slice(0, 300)
895
+ const candidate = safeClipId(metaIn.id)
896
+ if (candidate !== null && this._byId.has(candidate)) {
897
+ skipped += 1
898
+ continue
899
+ }
900
+ const id = candidate === null
901
+ ? this.uniqueId(title, url || `import:${digest(article, 12)}`)
902
+ : candidate
903
+ const counts = countWords(plain)
904
+ const annotations = (Array.isArray(raw.annotations) ? raw.annotations : [])
905
+ .filter(annotation => annotation !== null && typeof annotation === 'object' && typeof annotation.id === 'string')
906
+ .map(annotation => ({
907
+ ...annotation,
908
+ quote: normalizeQuote(annotation.quote),
909
+ note: normalizeNote(annotation.note),
910
+ color: normalizeColor(annotation.color),
911
+ status: annotation.status === 'stale' ? 'stale' : 'active',
912
+ }))
913
+ const meta = {
914
+ id,
915
+ url,
916
+ canonicalUrl: typeof metaIn.canonicalUrl === 'string' ? metaIn.canonicalUrl : url,
917
+ title,
918
+ site: String(metaIn.site ?? (url === '' ? '导入' : '')).slice(0, 200),
919
+ author: String(metaIn.author ?? '').slice(0, 200),
920
+ published: String(metaIn.published ?? '').slice(0, 64),
921
+ clippedAt: typeof metaIn.clippedAt === 'string' && !Number.isNaN(Date.parse(metaIn.clippedAt))
922
+ ? metaIn.clippedAt
923
+ : nowIso(),
924
+ tags: normalizeTags(metaIn.tags),
925
+ status: STATUSES.has(metaIn.status) ? metaIn.status : 'unread',
926
+ excerpt: String(metaIn.excerpt ?? plain.replace(/\s+/g, ' ').trim().slice(0, 240)).slice(0, 240),
927
+ wordCount: counts.wordCount,
928
+ charCount: counts.charCount,
929
+ lang: counts.cjk > 0 ? 'zh' : 'en',
930
+ images: (article.match(/!\[[^\]]*\]\([^)]*\)/g) ?? []).length,
931
+ truncated: metaIn.truncated === true,
932
+ annotationCount: annotations.length,
933
+ contentHash: digest(article, 16),
934
+ manual: metaIn.manual === true,
935
+ articlePath: `clips/${id}/article.md`,
936
+ htmlPath: `clips/${id}/original.html`,
937
+ metaPath: `clips/${id}/meta.json`,
938
+ }
939
+ const originalHtml = typeof raw.originalHtml === 'string' && raw.originalHtml !== ''
940
+ ? raw.originalHtml
941
+ : renderMarkdown(article)
942
+ const clipDir = join(this.clipsDir, id)
943
+ await mkdir(clipDir, { recursive: true })
944
+ await writeFile(join(this.dir, meta.articlePath), `${article}\n`, 'utf8')
945
+ await writeFile(join(this.dir, meta.htmlPath), originalHtml, 'utf8')
946
+ await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
947
+ if (annotations.length > 0) {
948
+ await writeJsonAtomic(this.annotationPath(meta), {
949
+ version: 1,
950
+ contentVersion: meta.contentHash,
951
+ annotations,
952
+ })
953
+ }
954
+ this._clips.push(meta)
955
+ this._byId.set(meta.id, meta)
956
+ if (url !== '') this._byUrl.set(url, meta)
957
+ if (meta.canonicalUrl !== '') this._byUrl.set(meta.canonicalUrl, meta)
958
+ this._search.add(toSearchDoc(meta, article))
959
+ imported += 1
960
+ } catch (error) {
961
+ errors.push({ index, message: error instanceof Error ? error.message : String(error) })
962
+ }
963
+ }
964
+
965
+ let viewsImported = 0
966
+ if (Array.isArray(bundle.views) && bundle.views.length > 0) {
967
+ const views = await this.readViews()
968
+ const existing = new Set(views.map(view => view.query))
969
+ for (const raw of bundle.views) {
970
+ if (raw === null || typeof raw !== 'object') continue
971
+ const name = String(raw.name ?? '').trim().slice(0, 60)
972
+ const query = String(raw.query ?? '').trim().slice(0, 500)
973
+ if (name === '' || query === '' || existing.has(query)) continue
974
+ const now = nowIso()
975
+ views.push({
976
+ id: `view-${digest(`${query}\n${now}`, 10)}`,
977
+ name,
978
+ query,
979
+ createdAt: now,
980
+ updatedAt: now,
981
+ })
982
+ existing.add(query)
983
+ viewsImported += 1
984
+ }
985
+ if (viewsImported > 0) await writeJsonAtomic(this.viewsPath, { version: 1, views })
986
+ }
987
+
988
+ if (imported > 0) await this.persist()
989
+ return { imported, skipped, viewsImported, errors }
990
+ })
991
+ }
992
+
993
+ async persist() {
994
+ const snapshot = { version: INDEX_VERSION, clips: this._clips }
995
+ this._writeChain = this._writeChain
996
+ .catch(() => {})
997
+ .then(() => writeJsonAtomic(this.indexPath, snapshot))
998
+ await this._writeChain
999
+ }
1000
+ }