dsh-reading-inbox 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +17 -9
- package/README.md +17 -9
- package/VERIFY.md +14 -0
- package/index.js +3 -2
- package/package.json +1 -1
- package/src/config.js +3 -0
- package/src/fetch.js +67 -5
- package/src/markdown.js +8 -1
- package/src/routes.js +67 -0
- package/src/store.js +420 -12
- package/src/tools.js +53 -0
- package/web/app.js +118 -4
- package/web/index.html +20 -0
- package/web/style.css +66 -0
package/src/store.js
CHANGED
|
@@ -6,10 +6,11 @@ import {
|
|
|
6
6
|
buildAnnotationAnchor,
|
|
7
7
|
normalizeColor,
|
|
8
8
|
normalizeNote,
|
|
9
|
+
normalizeQuote,
|
|
9
10
|
resolveAnnotations,
|
|
10
11
|
} from './annotations.js'
|
|
11
|
-
import { fetchHtml } from './fetch.js'
|
|
12
|
-
import { exportMarkdown, parseArticle, renderMarkdown, renderedText } from './markdown.js'
|
|
12
|
+
import { fetchBinary, fetchHtml } from './fetch.js'
|
|
13
|
+
import { countWords, exportMarkdown, htmlToMarkdown, parseArticle, renderMarkdown, renderedText } from './markdown.js'
|
|
13
14
|
import { makeSnippet, parseQuery, queryTerms } from './search.js'
|
|
14
15
|
|
|
15
16
|
const INDEX_VERSION = 1
|
|
@@ -17,6 +18,20 @@ const STATUSES = new Set(['unread', 'reading', 'read', 'archived'])
|
|
|
17
18
|
const MAX_TAGS = 20
|
|
18
19
|
const MAX_TAG_LENGTH = 40
|
|
19
20
|
const MAX_ANNOTATIONS = 500
|
|
21
|
+
const ASSET_EXTENSIONS = {
|
|
22
|
+
'image/png': 'png',
|
|
23
|
+
'image/jpeg': 'jpg',
|
|
24
|
+
'image/gif': 'gif',
|
|
25
|
+
'image/webp': 'webp',
|
|
26
|
+
'image/svg+xml': 'svg',
|
|
27
|
+
'image/avif': 'avif',
|
|
28
|
+
'image/bmp': 'bmp',
|
|
29
|
+
'image/x-icon': 'ico',
|
|
30
|
+
'image/vnd.microsoft.icon': 'ico',
|
|
31
|
+
'image/tiff': 'tiff',
|
|
32
|
+
}
|
|
33
|
+
const ASSET_TYPES = new Map(Object.entries(ASSET_EXTENSIONS).map(([type, ext]) => [ext, type]))
|
|
34
|
+
const ASSET_FILE_RE = /^[a-f0-9]{64}\.(png|jpg|gif|webp|svg|avif|bmp|ico|tiff|bin)$/
|
|
20
35
|
|
|
21
36
|
function nowIso() {
|
|
22
37
|
return new Date().toISOString()
|
|
@@ -26,6 +41,14 @@ function digest(value, length = 12) {
|
|
|
26
41
|
return createHash('sha256').update(String(value)).digest('hex').slice(0, length)
|
|
27
42
|
}
|
|
28
43
|
|
|
44
|
+
function safeClipId(value) {
|
|
45
|
+
return typeof value === 'string'
|
|
46
|
+
&& /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/.test(value)
|
|
47
|
+
&& !value.includes('..')
|
|
48
|
+
? value
|
|
49
|
+
: null
|
|
50
|
+
}
|
|
51
|
+
|
|
29
52
|
function slugify(value) {
|
|
30
53
|
const ascii = String(value ?? '')
|
|
31
54
|
.normalize('NFKD')
|
|
@@ -232,6 +255,85 @@ export class ReadingInbox {
|
|
|
232
255
|
return text
|
|
233
256
|
}
|
|
234
257
|
|
|
258
|
+
async localizeAssets(id, markdown, options = {}) {
|
|
259
|
+
const urls = []
|
|
260
|
+
const matcher = /!\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g
|
|
261
|
+
let match
|
|
262
|
+
while ((match = matcher.exec(markdown)) !== null) {
|
|
263
|
+
const url = match[1]
|
|
264
|
+
if (/^https?:\/\//i.test(url) && !urls.includes(url)) urls.push(url)
|
|
265
|
+
}
|
|
266
|
+
const warnings = []
|
|
267
|
+
if (urls.length === 0) return { markdown, assets: [], warnings }
|
|
268
|
+
const limited = urls.slice(0, this.config.assetMaxCount)
|
|
269
|
+
if (urls.length > limited.length) {
|
|
270
|
+
warnings.push({ url: '', message: `图片数量超过 ${limited.length},其余保留远程地址` })
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const assetsDir = join(this.clipsDir, id, 'assets')
|
|
274
|
+
await mkdir(assetsDir, { recursive: true })
|
|
275
|
+
const byHash = new Map()
|
|
276
|
+
const results = new Array(limited.length)
|
|
277
|
+
let cursor = 0
|
|
278
|
+
|
|
279
|
+
const fetchOne = async url => {
|
|
280
|
+
try {
|
|
281
|
+
const fetched = await fetchBinary(url, this.config, { signal: options.signal })
|
|
282
|
+
const sha256 = createHash('sha256').update(fetched.buffer).digest('hex')
|
|
283
|
+
const type = fetched.contentType.split(';')[0].trim().toLowerCase()
|
|
284
|
+
const extension = ASSET_EXTENSIONS[type] ?? 'bin'
|
|
285
|
+
const file = `${sha256}.${extension}`
|
|
286
|
+
if (!byHash.has(sha256)) {
|
|
287
|
+
await writeFile(join(assetsDir, file), fetched.buffer)
|
|
288
|
+
byHash.set(sha256, file)
|
|
289
|
+
}
|
|
290
|
+
return {
|
|
291
|
+
url,
|
|
292
|
+
path: `assets/${file}`,
|
|
293
|
+
bytes: fetched.bytes,
|
|
294
|
+
contentType: fetched.contentType,
|
|
295
|
+
sha256,
|
|
296
|
+
}
|
|
297
|
+
} catch (error) {
|
|
298
|
+
warnings.push({
|
|
299
|
+
url,
|
|
300
|
+
message: error instanceof Error ? error.message : String(error),
|
|
301
|
+
})
|
|
302
|
+
return null
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const workers = Array.from({ length: Math.min(4, limited.length) }, async () => {
|
|
307
|
+
for (;;) {
|
|
308
|
+
const index = cursor
|
|
309
|
+
cursor += 1
|
|
310
|
+
if (index >= limited.length) break
|
|
311
|
+
results[index] = await fetchOne(limited[index])
|
|
312
|
+
}
|
|
313
|
+
})
|
|
314
|
+
await Promise.all(workers)
|
|
315
|
+
const assets = results.filter(Boolean)
|
|
316
|
+
let localized = markdown
|
|
317
|
+
for (const asset of assets) {
|
|
318
|
+
localized = localized.split(asset.url).join(asset.path)
|
|
319
|
+
}
|
|
320
|
+
return { markdown: localized, assets, warnings }
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async readAsset(id, file) {
|
|
324
|
+
await this.ready()
|
|
325
|
+
const meta = this._byId.get(String(id))
|
|
326
|
+
if (meta === undefined) throw new Error(`找不到文章:${id}`)
|
|
327
|
+
if (!ASSET_FILE_RE.test(String(file))) throw new Error('找不到资源')
|
|
328
|
+
const asset = (meta.assets ?? []).find(item => item.path === `assets/${file}`)
|
|
329
|
+
if (asset === undefined) throw new Error('找不到资源')
|
|
330
|
+
const buffer = await readFile(join(this.clipsDir, meta.id, 'assets', file))
|
|
331
|
+
return {
|
|
332
|
+
buffer,
|
|
333
|
+
contentType: asset.contentType || ASSET_TYPES.get(file.split('.').pop()) || 'application/octet-stream',
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
235
337
|
async readAnnotations(meta) {
|
|
236
338
|
try {
|
|
237
339
|
const raw = await readFile(this.annotationPath(meta), 'utf8')
|
|
@@ -427,6 +529,105 @@ export class ReadingInbox {
|
|
|
427
529
|
return run
|
|
428
530
|
}
|
|
429
531
|
|
|
532
|
+
async saveText(input = {}) {
|
|
533
|
+
await this.ready()
|
|
534
|
+
const rawMarkdown = String(input.markdown ?? '').trim()
|
|
535
|
+
const rawHtml = String(input.html ?? '').trim()
|
|
536
|
+
const rawText = String(input.text ?? '').trim()
|
|
537
|
+
if (rawMarkdown === '' && rawHtml === '' && rawText === '') {
|
|
538
|
+
throw new Error('需要 text、markdown 或 html')
|
|
539
|
+
}
|
|
540
|
+
const url = typeof input.url === 'string' && input.url.trim() !== ''
|
|
541
|
+
? normalizeUrl(input.url)
|
|
542
|
+
: ''
|
|
543
|
+
const existing = url === '' ? undefined : this._byUrl.get(url)
|
|
544
|
+
if (existing !== undefined) {
|
|
545
|
+
const body = await this.readBody(existing.id).catch(() => '')
|
|
546
|
+
return { ...publicMeta(existing), duplicate: true, preview: body.slice(0, 500) }
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
return this._withMutation(async () => {
|
|
550
|
+
const current = url === '' ? undefined : this._byUrl.get(url)
|
|
551
|
+
if (current !== undefined) {
|
|
552
|
+
const body = await this.readBody(current.id).catch(() => '')
|
|
553
|
+
return { ...publicMeta(current), duplicate: true, preview: body.slice(0, 500) }
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
let markdown = rawMarkdown || (rawHtml !== '' ? htmlToMarkdown(rawHtml, url) : rawText)
|
|
557
|
+
markdown = markdown.trim()
|
|
558
|
+
if (markdown === '') throw new Error('内容为空')
|
|
559
|
+
let truncated = false
|
|
560
|
+
if (markdown.length > this.config.maxMarkdownChars) {
|
|
561
|
+
markdown = `${markdown.slice(0, this.config.maxMarkdownChars)}\n\n> 内容过长,已截断。`
|
|
562
|
+
truncated = true
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const plain = renderedText(markdown)
|
|
566
|
+
const counts = countWords(plain)
|
|
567
|
+
const firstLine = plain.split(/\r?\n/).map(line => line.trim()).find(line => line !== '')
|
|
568
|
+
const titleSource = String(input.title ?? '').trim()
|
|
569
|
+
|| firstLine
|
|
570
|
+
|| (url === '' ? '未命名笔记' : (() => { try { return new URL(url).hostname } catch { return '未命名笔记' } })())
|
|
571
|
+
const title = titleSource.replace(/\s+/g, ' ').slice(0, 300)
|
|
572
|
+
const id = this.uniqueId(title, url || `text:${digest(markdown, 12)}`)
|
|
573
|
+
const explicitTags = normalizeTags([
|
|
574
|
+
...(Array.isArray(input.tags) ? input.tags : []),
|
|
575
|
+
...(this.config.defaultTags ?? []),
|
|
576
|
+
])
|
|
577
|
+
const tags = explicitTags.length > 0
|
|
578
|
+
? explicitTags
|
|
579
|
+
: normalizeTags((plain.match(/#[^\s#]+/g) ?? []).slice(0, 3).map(tag => tag.slice(1)))
|
|
580
|
+
const site = url === ''
|
|
581
|
+
? '手动保存'
|
|
582
|
+
: (() => { try { return new URL(url).hostname } catch { return '手动保存' } })()
|
|
583
|
+
const meta = {
|
|
584
|
+
id,
|
|
585
|
+
url,
|
|
586
|
+
canonicalUrl: url,
|
|
587
|
+
title,
|
|
588
|
+
site,
|
|
589
|
+
author: '',
|
|
590
|
+
published: '',
|
|
591
|
+
clippedAt: nowIso(),
|
|
592
|
+
tags,
|
|
593
|
+
status: 'unread',
|
|
594
|
+
excerpt: plain.replace(/\s+/g, ' ').trim().slice(0, 240),
|
|
595
|
+
wordCount: counts.wordCount,
|
|
596
|
+
charCount: counts.charCount,
|
|
597
|
+
lang: counts.cjk > 0 ? 'zh' : 'en',
|
|
598
|
+
images: (markdown.match(/!\[[^\]]*\]\([^)]*\)/g) ?? []).length,
|
|
599
|
+
truncated,
|
|
600
|
+
annotationCount: 0,
|
|
601
|
+
assets: [],
|
|
602
|
+
provenance: {
|
|
603
|
+
source: 'manual',
|
|
604
|
+
requestedUrl: url,
|
|
605
|
+
fetchedAt: nowIso(),
|
|
606
|
+
extractor: 'manual',
|
|
607
|
+
},
|
|
608
|
+
contentHash: digest(markdown, 16),
|
|
609
|
+
manual: true,
|
|
610
|
+
articlePath: `clips/${id}/article.md`,
|
|
611
|
+
htmlPath: `clips/${id}/original.html`,
|
|
612
|
+
metaPath: `clips/${id}/meta.json`,
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
const clipDir = join(this.clipsDir, id)
|
|
616
|
+
await mkdir(clipDir, { recursive: true })
|
|
617
|
+
await writeFile(join(this.dir, meta.articlePath), `${markdown}\n`, 'utf8')
|
|
618
|
+
await writeFile(join(this.dir, meta.htmlPath), rawHtml || renderMarkdown(markdown), 'utf8')
|
|
619
|
+
await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
|
|
620
|
+
|
|
621
|
+
this._clips.push(meta)
|
|
622
|
+
this._byId.set(meta.id, meta)
|
|
623
|
+
if (url !== '') this._byUrl.set(url, meta)
|
|
624
|
+
this._search.add(toSearchDoc(meta, markdown))
|
|
625
|
+
await this.persist()
|
|
626
|
+
|
|
627
|
+
return { ...publicMeta(meta), duplicate: false, preview: markdown.slice(0, 1_500) }
|
|
628
|
+
})
|
|
629
|
+
}
|
|
630
|
+
|
|
430
631
|
async _clipOnce(url, options = {}) {
|
|
431
632
|
const existing = this._byUrl.get(url)
|
|
432
633
|
if (existing !== undefined && options.force !== true) {
|
|
@@ -473,6 +674,18 @@ export class ReadingInbox {
|
|
|
473
674
|
const tags = explicitTags.length > 0
|
|
474
675
|
? explicitTags
|
|
475
676
|
: normalizeTags((parsed.keywords ?? []).slice(0, 3))
|
|
677
|
+
const useAssets = options.assets === 'local'
|
|
678
|
+
|| (options.assets === undefined && this.config.assets === 'local')
|
|
679
|
+
let markdown = parsed.markdown
|
|
680
|
+
let assets = []
|
|
681
|
+
let assetWarnings = []
|
|
682
|
+
if (useAssets) {
|
|
683
|
+
const localized = await this.localizeAssets(id, markdown, { signal: options.signal })
|
|
684
|
+
markdown = localized.markdown
|
|
685
|
+
assets = localized.assets
|
|
686
|
+
assetWarnings = localized.warnings
|
|
687
|
+
}
|
|
688
|
+
const now = nowIso()
|
|
476
689
|
const meta = {
|
|
477
690
|
id,
|
|
478
691
|
url: fetched.finalUrl,
|
|
@@ -481,7 +694,7 @@ export class ReadingInbox {
|
|
|
481
694
|
site: parsed.siteName,
|
|
482
695
|
author: parsed.byline,
|
|
483
696
|
published: parsed.published,
|
|
484
|
-
clippedAt:
|
|
697
|
+
clippedAt: now,
|
|
485
698
|
tags,
|
|
486
699
|
status: 'unread',
|
|
487
700
|
excerpt: parsed.excerpt,
|
|
@@ -491,7 +704,19 @@ export class ReadingInbox {
|
|
|
491
704
|
images: parsed.images,
|
|
492
705
|
truncated: parsed.truncated === true,
|
|
493
706
|
annotationCount: 0,
|
|
494
|
-
|
|
707
|
+
assets,
|
|
708
|
+
provenance: {
|
|
709
|
+
requestedUrl: url,
|
|
710
|
+
finalUrl: fetched.finalUrl,
|
|
711
|
+
status: fetched.status,
|
|
712
|
+
contentType: fetched.contentType,
|
|
713
|
+
charset: fetched.charset,
|
|
714
|
+
bytes: fetched.bytes,
|
|
715
|
+
fetchedAt: now,
|
|
716
|
+
extractor: 'readability+turndown',
|
|
717
|
+
warnings: assetWarnings,
|
|
718
|
+
},
|
|
719
|
+
contentHash: digest(markdown, 16),
|
|
495
720
|
articlePath: `clips/${id}/article.md`,
|
|
496
721
|
htmlPath: `clips/${id}/original.html`,
|
|
497
722
|
metaPath: `clips/${id}/meta.json`,
|
|
@@ -499,7 +724,7 @@ export class ReadingInbox {
|
|
|
499
724
|
|
|
500
725
|
const clipDir = join(this.clipsDir, id)
|
|
501
726
|
await mkdir(clipDir, { recursive: true })
|
|
502
|
-
await writeFile(join(this.dir, meta.articlePath), `${
|
|
727
|
+
await writeFile(join(this.dir, meta.articlePath), `${markdown.trim()}\n`, 'utf8')
|
|
503
728
|
await writeFile(join(this.dir, meta.htmlPath), fetched.html, 'utf8')
|
|
504
729
|
await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
|
|
505
730
|
|
|
@@ -507,19 +732,32 @@ export class ReadingInbox {
|
|
|
507
732
|
this._byId.set(meta.id, meta)
|
|
508
733
|
this._byUrl.set(meta.url, meta)
|
|
509
734
|
this._byUrl.set(meta.canonicalUrl, meta)
|
|
510
|
-
this._search.add(toSearchDoc(meta,
|
|
735
|
+
this._search.add(toSearchDoc(meta, markdown))
|
|
511
736
|
await this.persist()
|
|
512
737
|
|
|
513
738
|
return {
|
|
514
739
|
...publicMeta(meta),
|
|
515
740
|
duplicate: false,
|
|
516
|
-
preview:
|
|
741
|
+
preview: markdown.slice(0, 1_500),
|
|
517
742
|
}
|
|
518
743
|
})
|
|
519
744
|
}
|
|
520
745
|
|
|
521
746
|
async refreshClip(meta, parsed, fetched, options = {}) {
|
|
747
|
+
const requestedUrl = meta.url
|
|
522
748
|
const canonicalUrl = parsed.canonicalUrl || fetched.finalUrl
|
|
749
|
+
const useAssets = options.assets === 'local'
|
|
750
|
+
|| (options.assets === undefined && this.config.assets === 'local')
|
|
751
|
+
let markdown = parsed.markdown
|
|
752
|
+
let assets = []
|
|
753
|
+
let assetWarnings = []
|
|
754
|
+
if (useAssets) {
|
|
755
|
+
const localized = await this.localizeAssets(meta.id, markdown, { signal: options.signal })
|
|
756
|
+
markdown = localized.markdown
|
|
757
|
+
assets = localized.assets
|
|
758
|
+
assetWarnings = localized.warnings
|
|
759
|
+
}
|
|
760
|
+
const now = nowIso()
|
|
523
761
|
meta.url = fetched.finalUrl
|
|
524
762
|
meta.canonicalUrl = canonicalUrl
|
|
525
763
|
meta.title = parsed.title
|
|
@@ -533,13 +771,25 @@ export class ReadingInbox {
|
|
|
533
771
|
meta.images = parsed.images
|
|
534
772
|
meta.truncated = parsed.truncated === true
|
|
535
773
|
meta.annotationCount = (await this.readAnnotations(meta)).length
|
|
536
|
-
meta.updatedAt =
|
|
537
|
-
meta.
|
|
774
|
+
meta.updatedAt = now
|
|
775
|
+
meta.assets = assets
|
|
776
|
+
meta.provenance = {
|
|
777
|
+
requestedUrl,
|
|
778
|
+
finalUrl: fetched.finalUrl,
|
|
779
|
+
status: fetched.status,
|
|
780
|
+
contentType: fetched.contentType,
|
|
781
|
+
charset: fetched.charset,
|
|
782
|
+
bytes: fetched.bytes,
|
|
783
|
+
fetchedAt: now,
|
|
784
|
+
extractor: 'readability+turndown',
|
|
785
|
+
warnings: assetWarnings,
|
|
786
|
+
}
|
|
787
|
+
meta.contentHash = digest(markdown, 16)
|
|
538
788
|
if (Array.isArray(options.tags) && options.tags.length > 0) {
|
|
539
789
|
meta.tags = normalizeTags(options.tags)
|
|
540
790
|
}
|
|
541
791
|
|
|
542
|
-
await writeFile(join(this.dir, meta.articlePath), `${
|
|
792
|
+
await writeFile(join(this.dir, meta.articlePath), `${markdown.trim()}\n`, 'utf8')
|
|
543
793
|
await writeFile(join(this.dir, meta.htmlPath), fetched.html, 'utf8')
|
|
544
794
|
await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
|
|
545
795
|
|
|
@@ -550,13 +800,13 @@ export class ReadingInbox {
|
|
|
550
800
|
} catch {
|
|
551
801
|
// The id may be absent after a manual index edit; adding it back is enough.
|
|
552
802
|
}
|
|
553
|
-
this._search.add(toSearchDoc(meta,
|
|
803
|
+
this._search.add(toSearchDoc(meta, markdown))
|
|
554
804
|
await this.persist()
|
|
555
805
|
|
|
556
806
|
return {
|
|
557
807
|
...publicMeta(meta),
|
|
558
808
|
duplicate: false,
|
|
559
|
-
preview:
|
|
809
|
+
preview: markdown.slice(0, 1_500),
|
|
560
810
|
}
|
|
561
811
|
}
|
|
562
812
|
|
|
@@ -731,6 +981,164 @@ export class ReadingInbox {
|
|
|
731
981
|
return { meta: publicMeta(meta), markdown: exportMarkdown(meta, body, annotations) }
|
|
732
982
|
}
|
|
733
983
|
|
|
984
|
+
async exportBundle(options = {}) {
|
|
985
|
+
await this.ready()
|
|
986
|
+
const clips = []
|
|
987
|
+
for (const meta of this._clips) {
|
|
988
|
+
const article = await this.readBody(meta.id).catch(() => '')
|
|
989
|
+
if (article === '') continue
|
|
990
|
+
const annotations = await this.readAnnotations(meta)
|
|
991
|
+
const item = { meta: publicMeta(meta), article, annotations }
|
|
992
|
+
if (options.includeOriginal === true) {
|
|
993
|
+
item.originalHtml = await readFile(join(this.dir, meta.htmlPath), 'utf8').catch(() => '')
|
|
994
|
+
}
|
|
995
|
+
clips.push(item)
|
|
996
|
+
}
|
|
997
|
+
return { version: 1, exportedAt: nowIso(), clips, views: await this.readViews() }
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
async exportAllMarkdown() {
|
|
1001
|
+
await this.ready()
|
|
1002
|
+
const parts = []
|
|
1003
|
+
for (const meta of this._clips) {
|
|
1004
|
+
const body = await this.readBody(meta.id).catch(() => '')
|
|
1005
|
+
if (body === '') continue
|
|
1006
|
+
const annotations = await this.listAnnotations(meta.id, body)
|
|
1007
|
+
parts.push(exportMarkdown(meta, body, annotations))
|
|
1008
|
+
}
|
|
1009
|
+
return parts.join('\n\n---\n\n')
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
async importBundle(bundle) {
|
|
1013
|
+
await this.ready()
|
|
1014
|
+
if (bundle === null || typeof bundle !== 'object' || !Array.isArray(bundle.clips)) {
|
|
1015
|
+
throw new Error('导入文件需要包含 clips 数组')
|
|
1016
|
+
}
|
|
1017
|
+
return this._withMutation(async () => {
|
|
1018
|
+
let imported = 0
|
|
1019
|
+
let skipped = 0
|
|
1020
|
+
const errors = []
|
|
1021
|
+
for (let index = 0; index < bundle.clips.length; index += 1) {
|
|
1022
|
+
const raw = bundle.clips[index]
|
|
1023
|
+
try {
|
|
1024
|
+
if (raw === null || typeof raw !== 'object' || typeof raw.article !== 'string' || raw.article.trim() === '') {
|
|
1025
|
+
skipped += 1
|
|
1026
|
+
continue
|
|
1027
|
+
}
|
|
1028
|
+
const article = raw.article.trim()
|
|
1029
|
+
if (article.length > 5_000_000) throw new Error('单篇正文超过 5 MB')
|
|
1030
|
+
const metaIn = raw.meta !== null && typeof raw.meta === 'object' ? raw.meta : {}
|
|
1031
|
+
let url = ''
|
|
1032
|
+
if (typeof metaIn.url === 'string' && metaIn.url.trim() !== '') {
|
|
1033
|
+
try { url = normalizeUrl(metaIn.url) } catch { url = '' }
|
|
1034
|
+
}
|
|
1035
|
+
if (url !== '' && this._byUrl.has(url)) {
|
|
1036
|
+
skipped += 1
|
|
1037
|
+
continue
|
|
1038
|
+
}
|
|
1039
|
+
const plain = renderedText(article)
|
|
1040
|
+
const firstLine = plain.split(/\r?\n/).map(line => line.trim()).find(line => line !== '')
|
|
1041
|
+
const title = (String(metaIn.title ?? '').trim() || firstLine || '导入文章')
|
|
1042
|
+
.replace(/\s+/g, ' ')
|
|
1043
|
+
.slice(0, 300)
|
|
1044
|
+
const candidate = safeClipId(metaIn.id)
|
|
1045
|
+
if (candidate !== null && this._byId.has(candidate)) {
|
|
1046
|
+
skipped += 1
|
|
1047
|
+
continue
|
|
1048
|
+
}
|
|
1049
|
+
const id = candidate === null
|
|
1050
|
+
? this.uniqueId(title, url || `import:${digest(article, 12)}`)
|
|
1051
|
+
: candidate
|
|
1052
|
+
const counts = countWords(plain)
|
|
1053
|
+
const annotations = (Array.isArray(raw.annotations) ? raw.annotations : [])
|
|
1054
|
+
.filter(annotation => annotation !== null && typeof annotation === 'object' && typeof annotation.id === 'string')
|
|
1055
|
+
.map(annotation => ({
|
|
1056
|
+
...annotation,
|
|
1057
|
+
quote: normalizeQuote(annotation.quote),
|
|
1058
|
+
note: normalizeNote(annotation.note),
|
|
1059
|
+
color: normalizeColor(annotation.color),
|
|
1060
|
+
status: annotation.status === 'stale' ? 'stale' : 'active',
|
|
1061
|
+
}))
|
|
1062
|
+
const meta = {
|
|
1063
|
+
id,
|
|
1064
|
+
url,
|
|
1065
|
+
canonicalUrl: typeof metaIn.canonicalUrl === 'string' ? metaIn.canonicalUrl : url,
|
|
1066
|
+
title,
|
|
1067
|
+
site: String(metaIn.site ?? (url === '' ? '导入' : '')).slice(0, 200),
|
|
1068
|
+
author: String(metaIn.author ?? '').slice(0, 200),
|
|
1069
|
+
published: String(metaIn.published ?? '').slice(0, 64),
|
|
1070
|
+
clippedAt: typeof metaIn.clippedAt === 'string' && !Number.isNaN(Date.parse(metaIn.clippedAt))
|
|
1071
|
+
? metaIn.clippedAt
|
|
1072
|
+
: nowIso(),
|
|
1073
|
+
tags: normalizeTags(metaIn.tags),
|
|
1074
|
+
status: STATUSES.has(metaIn.status) ? metaIn.status : 'unread',
|
|
1075
|
+
excerpt: String(metaIn.excerpt ?? plain.replace(/\s+/g, ' ').trim().slice(0, 240)).slice(0, 240),
|
|
1076
|
+
wordCount: counts.wordCount,
|
|
1077
|
+
charCount: counts.charCount,
|
|
1078
|
+
lang: counts.cjk > 0 ? 'zh' : 'en',
|
|
1079
|
+
images: (article.match(/!\[[^\]]*\]\([^)]*\)/g) ?? []).length,
|
|
1080
|
+
truncated: metaIn.truncated === true,
|
|
1081
|
+
annotationCount: annotations.length,
|
|
1082
|
+
contentHash: digest(article, 16),
|
|
1083
|
+
manual: metaIn.manual === true,
|
|
1084
|
+
articlePath: `clips/${id}/article.md`,
|
|
1085
|
+
htmlPath: `clips/${id}/original.html`,
|
|
1086
|
+
metaPath: `clips/${id}/meta.json`,
|
|
1087
|
+
}
|
|
1088
|
+
const originalHtml = typeof raw.originalHtml === 'string' && raw.originalHtml !== ''
|
|
1089
|
+
? raw.originalHtml
|
|
1090
|
+
: renderMarkdown(article)
|
|
1091
|
+
const clipDir = join(this.clipsDir, id)
|
|
1092
|
+
await mkdir(clipDir, { recursive: true })
|
|
1093
|
+
await writeFile(join(this.dir, meta.articlePath), `${article}\n`, 'utf8')
|
|
1094
|
+
await writeFile(join(this.dir, meta.htmlPath), originalHtml, 'utf8')
|
|
1095
|
+
await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
|
|
1096
|
+
if (annotations.length > 0) {
|
|
1097
|
+
await writeJsonAtomic(this.annotationPath(meta), {
|
|
1098
|
+
version: 1,
|
|
1099
|
+
contentVersion: meta.contentHash,
|
|
1100
|
+
annotations,
|
|
1101
|
+
})
|
|
1102
|
+
}
|
|
1103
|
+
this._clips.push(meta)
|
|
1104
|
+
this._byId.set(meta.id, meta)
|
|
1105
|
+
if (url !== '') this._byUrl.set(url, meta)
|
|
1106
|
+
if (meta.canonicalUrl !== '') this._byUrl.set(meta.canonicalUrl, meta)
|
|
1107
|
+
this._search.add(toSearchDoc(meta, article))
|
|
1108
|
+
imported += 1
|
|
1109
|
+
} catch (error) {
|
|
1110
|
+
errors.push({ index, message: error instanceof Error ? error.message : String(error) })
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
let viewsImported = 0
|
|
1115
|
+
if (Array.isArray(bundle.views) && bundle.views.length > 0) {
|
|
1116
|
+
const views = await this.readViews()
|
|
1117
|
+
const existing = new Set(views.map(view => view.query))
|
|
1118
|
+
for (const raw of bundle.views) {
|
|
1119
|
+
if (raw === null || typeof raw !== 'object') continue
|
|
1120
|
+
const name = String(raw.name ?? '').trim().slice(0, 60)
|
|
1121
|
+
const query = String(raw.query ?? '').trim().slice(0, 500)
|
|
1122
|
+
if (name === '' || query === '' || existing.has(query)) continue
|
|
1123
|
+
const now = nowIso()
|
|
1124
|
+
views.push({
|
|
1125
|
+
id: `view-${digest(`${query}\n${now}`, 10)}`,
|
|
1126
|
+
name,
|
|
1127
|
+
query,
|
|
1128
|
+
createdAt: now,
|
|
1129
|
+
updatedAt: now,
|
|
1130
|
+
})
|
|
1131
|
+
existing.add(query)
|
|
1132
|
+
viewsImported += 1
|
|
1133
|
+
}
|
|
1134
|
+
if (viewsImported > 0) await writeJsonAtomic(this.viewsPath, { version: 1, views })
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
if (imported > 0) await this.persist()
|
|
1138
|
+
return { imported, skipped, viewsImported, errors }
|
|
1139
|
+
})
|
|
1140
|
+
}
|
|
1141
|
+
|
|
734
1142
|
async persist() {
|
|
735
1143
|
const snapshot = { version: INDEX_VERSION, clips: this._clips }
|
|
736
1144
|
this._writeChain = this._writeChain
|
package/src/tools.js
CHANGED
|
@@ -133,6 +133,11 @@ export function registerTools(ctx, { inbox }) {
|
|
|
133
133
|
type: 'boolean',
|
|
134
134
|
description: 'Re-clip and refresh an existing URL instead of returning the existing clip.',
|
|
135
135
|
},
|
|
136
|
+
assets: {
|
|
137
|
+
type: 'string',
|
|
138
|
+
enum: ['remote', 'local'],
|
|
139
|
+
description: 'Image policy for this clip: local downloads images into the clip assets directory; remote keeps original URLs.',
|
|
140
|
+
},
|
|
136
141
|
},
|
|
137
142
|
required: ['url'],
|
|
138
143
|
},
|
|
@@ -159,11 +164,59 @@ export function registerTools(ctx, { inbox }) {
|
|
|
159
164
|
return inbox.clip(args.url, {
|
|
160
165
|
tags: Array.isArray(args.tags) ? args.tags : [],
|
|
161
166
|
force: args.force === true,
|
|
167
|
+
assets: args.assets,
|
|
162
168
|
signal: exec.signal,
|
|
163
169
|
})
|
|
164
170
|
},
|
|
165
171
|
})
|
|
166
172
|
|
|
173
|
+
ctx.tools.register({
|
|
174
|
+
name: 'reading_save_text',
|
|
175
|
+
description:
|
|
176
|
+
'Save pasted text, Markdown, or HTML as a local reading-inbox clip when there is no fetchable URL. ' +
|
|
177
|
+
'Use this for login-walled pages, paywalled snippets, selections, or notes the user wants to keep. ' +
|
|
178
|
+
'Provide at least one of text, markdown, or html; title, url and tags are optional.',
|
|
179
|
+
parameters: {
|
|
180
|
+
type: 'object',
|
|
181
|
+
additionalProperties: false,
|
|
182
|
+
properties: {
|
|
183
|
+
title: { type: 'string', description: 'Optional title; first non-empty line is used otherwise.' },
|
|
184
|
+
text: { type: 'string', description: 'Plain text content.' },
|
|
185
|
+
markdown: { type: 'string', description: 'Markdown content; takes precedence over text.' },
|
|
186
|
+
html: { type: 'string', description: 'HTML content; converted to Markdown and archived as original.html.' },
|
|
187
|
+
url: { type: 'string', description: 'Optional source URL for attribution and duplicate detection.' },
|
|
188
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
189
|
+
},
|
|
190
|
+
required: [],
|
|
191
|
+
},
|
|
192
|
+
output: {
|
|
193
|
+
schema: {
|
|
194
|
+
type: 'object',
|
|
195
|
+
additionalProperties: false,
|
|
196
|
+
properties: clipProperties,
|
|
197
|
+
required: clipRequired,
|
|
198
|
+
},
|
|
199
|
+
render: (_args, value) => {
|
|
200
|
+
const lines = renderMeta(value, [])
|
|
201
|
+
if (value.duplicate) lines.push('note: this URL is already in the inbox; returning the existing clip.')
|
|
202
|
+
lines.push('', 'preview:', value.preview)
|
|
203
|
+
return text(lines.join('\n'))
|
|
204
|
+
},
|
|
205
|
+
},
|
|
206
|
+
timeoutMs: 15_000,
|
|
207
|
+
isConcurrencySafe: () => false,
|
|
208
|
+
async execute(args) {
|
|
209
|
+
return inbox.saveText({
|
|
210
|
+
title: args?.title,
|
|
211
|
+
text: args?.text,
|
|
212
|
+
markdown: args?.markdown,
|
|
213
|
+
html: args?.html,
|
|
214
|
+
url: args?.url,
|
|
215
|
+
tags: Array.isArray(args?.tags) ? args.tags : [],
|
|
216
|
+
})
|
|
217
|
+
},
|
|
218
|
+
})
|
|
219
|
+
|
|
167
220
|
ctx.tools.register({
|
|
168
221
|
name: 'reading_search',
|
|
169
222
|
description:
|