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/markdown.js CHANGED
@@ -1,309 +1,309 @@
1
- import { Readability } from '@mozilla/readability'
2
- import { dump as dumpYaml } from 'js-yaml'
3
- import { parseHTML } from 'linkedom'
4
- import { marked } from 'marked'
5
- import sanitizeHtml from 'sanitize-html'
6
- import TurndownService from 'turndown'
7
- import { gfm } from 'turndown-plugin-gfm'
8
-
9
- function escapeHtmlAttribute(value) {
10
- return String(value)
11
- .replaceAll('&', '&')
12
- .replaceAll('"', '"')
13
- .replaceAll('<', '&lt;')
14
- .replaceAll('>', '&gt;')
15
- }
16
-
17
- function withBaseHref(html, baseUrl) {
18
- const base = `<base href="${escapeHtmlAttribute(baseUrl)}">`
19
- if (/<head[^>]*>/i.test(html)) return html.replace(/<head([^>]*)>/i, `<head$1>${base}`)
20
- if (/<html[^>]*>/i.test(html)) return html.replace(/<html([^>]*)>/i, `<html$1><head>${base}</head>`)
21
- return `<!doctype html><html><head>${base}</head><body>${html}</body></html>`
22
- }
23
-
24
- function metaContent(document, selectors) {
25
- for (const selector of selectors) {
26
- const element = document.querySelector(selector)
27
- if (element === null) continue
28
- const value = element.getAttribute('content') ?? element.getAttribute('href') ?? element.textContent
29
- if (typeof value === 'string' && value.trim() !== '') return value.trim()
30
- }
31
- return ''
32
- }
33
-
34
- function absoluteUrl(value, baseUrl) {
35
- const raw = String(value ?? '').trim()
36
- if (raw === '') return ''
37
- if (raw.startsWith('#')) return raw
38
- try {
39
- return new URL(raw, baseUrl).toString()
40
- } catch {
41
- return ''
42
- }
43
- }
44
-
45
- function isSafeHref(value) {
46
- if (value.startsWith('#')) return true
47
- try {
48
- const parsed = new URL(value)
49
- return parsed.protocol === 'http:' || parsed.protocol === 'https:' || parsed.protocol === 'mailto:'
50
- } catch {
51
- return false
52
- }
53
- }
54
-
55
- function makeTurndown(baseUrl) {
56
- const turndown = new TurndownService({
57
- headingStyle: 'atx',
58
- codeBlockStyle: 'fenced',
59
- bulletListMarker: '-',
60
- emDelimiter: '*',
61
- })
62
- turndown.use(gfm)
63
- turndown.remove(['script', 'style', 'noscript', 'iframe', 'form', 'button', 'input', 'select', 'textarea', 'svg', 'canvas'])
64
-
65
- turndown.addRule('absoluteLinks', {
66
- filter: 'a',
67
- replacement(content, node) {
68
- const href = absoluteUrl(node.getAttribute?.('href'), baseUrl)
69
- const text = content.trim()
70
- if (href === '' || !isSafeHref(href)) return text
71
- if (text === '') return ''
72
- return `[${text}](${href})`
73
- },
74
- })
75
-
76
- turndown.addRule('absoluteImages', {
77
- filter: 'img',
78
- replacement(_content, node) {
79
- const src = absoluteUrl(node.getAttribute?.('src'), baseUrl)
80
- if (src === '' || !/^https?:/i.test(src)) return ''
81
- const alt = String(node.getAttribute?.('alt') ?? '').replace(/\s+/g, ' ').trim()
82
- const title = String(node.getAttribute?.('title') ?? '').trim()
83
- return `![${alt}](${src}${title === '' ? '' : ` "${title.replaceAll('"', '\\"')}"`})`
84
- },
85
- })
86
-
87
- return turndown
88
- }
89
-
90
- function countWords(text) {
91
- const cjk = (text.match(/[぀-ヿ㐀-䶿一-鿿가-힯]/g) || []).length
92
- const latin = (text.replace(/[぀-ヿ㐀-䶿一-鿿가-힯]/g, ' ').match(/[A-Za-z0-9_]+/g) || []).length
93
- return { wordCount: cjk + latin, charCount: text.length, cjk }
94
- }
95
-
96
- function detectLanguage(document, text, cjk) {
97
- const declared = String(document?.documentElement?.getAttribute?.('lang') ?? '').trim().toLowerCase()
98
- if (declared !== '') return declared.split('-')[0]
99
- return cjk > 0 && cjk >= text.length * 0.05 ? 'zh' : 'en'
100
- }
101
-
102
- function cleanMarkdown(markdown) {
103
- return markdown
104
- .replace(/\]\((?:javascript|data|vbscript|file):[^)\s]*\)/gi, '](#)')
105
- .replace(/[ \t]+\n/g, '\n')
106
- .replace(/\n{3,}/g, '\n\n')
107
- .trim()
108
- }
109
-
110
- function clampText(value, maxLength) {
111
- const text = String(value ?? '').replace(/\s+/g, ' ').trim()
112
- return text.length > maxLength ? text.slice(0, maxLength) : text
113
- }
114
-
115
- /**
116
- * Turn raw HTML into a clean article: metadata, a Turndown Markdown body, and
117
- * a safe rendered HTML fragment. Readability runs on a fresh document so meta
118
- * extraction and the fallback path cannot see a half-mutated DOM.
119
- */
120
- export function parseArticle(html, options = {}) {
121
- const url = options.url ?? 'https://example.invalid/'
122
- const maxMarkdownChars = options.maxMarkdownChars ?? 400_000
123
- const withBase = withBaseHref(String(html ?? ''), url)
124
-
125
- const metaDocument = parseHTML(withBase).document
126
- const metaTitle = metaContent(metaDocument, [
127
- 'meta[property="og:title"]',
128
- 'meta[name="twitter:title"]',
129
- 'meta[name="title"]',
130
- ]) || String(metaDocument.title ?? '').trim()
131
- const byline = metaContent(metaDocument, [
132
- 'meta[name="author"]',
133
- 'meta[property="article:author"]',
134
- 'meta[name="byl"]',
135
- ])
136
- const siteName = metaContent(metaDocument, [
137
- 'meta[property="og:site_name"]',
138
- 'meta[name="application-name"]',
139
- ]) || (() => {
140
- try { return new URL(url).hostname } catch { return '' }
141
- })()
142
- const published = metaContent(metaDocument, [
143
- 'meta[property="article:published_time"]',
144
- 'meta[name="date"]',
145
- 'meta[name="pubdate"]',
146
- 'meta[name="publishdate"]',
147
- 'meta[name="dc.date"]',
148
- ])
149
- const keywords = metaContent(metaDocument, [
150
- 'meta[name="keywords"]',
151
- 'meta[name="news_keywords"]',
152
- ])
153
- const canonicalRaw = absoluteUrl(
154
- metaContent(metaDocument, ['link[rel="canonical"]']),
155
- url,
156
- )
157
- // A hostile page can put megabytes in <link rel=canonical>. Keep the URL
158
- // usable as a base, but do not persist an unbounded value.
159
- const canonical = canonicalRaw.length <= 2_048 ? canonicalRaw : ''
160
-
161
- // Relative links and images should survive the archive. Prefer the page's
162
- // declared canonical URL over the URL we happened to fetch through, so a
163
- // mirror/local server does not bake its own origin into the saved copy.
164
- const articleBase = canonical !== '' ? canonical : url
165
- const articleDocument = parseHTML(withBaseHref(String(html ?? ''), articleBase)).document
166
- let article = null
167
- try {
168
- article = new Readability(articleDocument, {
169
- charThreshold: 80,
170
- keepClasses: false,
171
- disableJSONLD: true,
172
- }).parse()
173
- } catch {
174
- article = null
175
- }
176
-
177
- const body = articleDocument.body
178
- const fallbackText = String(body?.textContent ?? '').replace(/\s+/g, ' ').trim()
179
- const contentHtml = article?.content ?? body?.innerHTML ?? ''
180
- const textContent = String(article?.textContent ?? fallbackText).replace(/\s+/g, ' ').trim()
181
-
182
- if (contentHtml.trim() === '' || textContent.length < 40) {
183
- return {
184
- ok: false,
185
- reason: '没有提取到正文。页面可能是登录页、SPA 或反爬页;请用浏览器打开后复制正文,或换一个来源。',
186
- }
187
- }
188
-
189
- const title = clampText(article?.title ?? metaTitle ?? '', 300) || (() => {
190
- try { return new URL(url).hostname } catch { return '未命名文章' }
191
- })()
192
- const turndown = makeTurndown(articleBase)
193
- let markdown = cleanMarkdown(
194
- turndown.turndown(contentHtml)
195
- .replace(/^#\s+.*\n+/, ''),
196
- )
197
- let truncated = false
198
- if (markdown.length > maxMarkdownChars) {
199
- markdown = `${markdown.slice(0, maxMarkdownChars)}\n\n> 内容过长,已截断。`
200
- truncated = true
201
- }
202
-
203
- const excerptSource = String(article?.excerpt ?? textContent).replace(/\s+/g, ' ').trim()
204
- const excerpt = excerptSource.length > 240 ? `${excerptSource.slice(0, 240)}…` : excerptSource
205
- const counts = countWords(textContent)
206
- const images = (markdown.match(/!\[[^\]]*\]\([^)]*\)/g) || []).length
207
- const keywordList = clampText(keywords, 1_000)
208
- .split(',')
209
- .map(value => clampText(value, 40))
210
- .filter(Boolean)
211
- .slice(0, 10)
212
-
213
- return {
214
- ok: true,
215
- title,
216
- byline: clampText(article?.byline ?? byline, 200),
217
- siteName: clampText(article?.siteName ?? siteName, 200),
218
- published: clampText(published, 64),
219
- excerpt,
220
- markdown,
221
- textContent,
222
- canonicalUrl: canonical,
223
- keywords: keywordList,
224
- wordCount: counts.wordCount,
225
- charCount: counts.charCount,
226
- lang: detectLanguage(articleDocument, textContent, counts.cjk),
227
- images,
228
- truncated,
229
- }
230
- }
231
-
232
- const RENDER_ALLOWED_TAGS = [
233
- 'a', 'abbr', 'b', 'blockquote', 'br', 'caption', 'code', 'col', 'colgroup', 'dd', 'del',
234
- 'details', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5',
235
- 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 's', 'section',
236
- 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th',
237
- 'thead', 'tr', 'u', 'ul',
238
- ]
239
-
240
- export function renderMarkdown(markdown) {
241
- const raw = marked.parse(String(markdown ?? ''), { gfm: true, breaks: false, async: false })
242
- return sanitizeHtml(raw, {
243
- allowedTags: RENDER_ALLOWED_TAGS,
244
- allowedAttributes: {
245
- a: ['href', 'title', 'target', 'rel'],
246
- img: ['src', 'alt', 'title', 'loading'],
247
- code: ['class'],
248
- th: ['align'],
249
- td: ['align'],
250
- },
251
- allowedSchemes: ['http', 'https', 'mailto'],
252
- allowedSchemesByTag: { img: ['http', 'https'] },
253
- transformTags: {
254
- a: (tagName, attribs) => ({
255
- tagName,
256
- attribs: {
257
- ...attribs,
258
- target: '_blank',
259
- rel: 'noopener noreferrer',
260
- },
261
- }),
262
- img: (tagName, attribs) => ({
263
- tagName,
264
- attribs: { ...attribs, loading: 'lazy' },
265
- }),
266
- },
267
- })
268
- }
269
-
270
- export function exportMarkdown(meta, body, annotations = []) {
271
- const frontmatter = dumpYaml({
272
- title: meta.title,
273
- url: meta.url,
274
- site: meta.site,
275
- author: meta.author,
276
- published: meta.published,
277
- clipped: meta.clippedAt,
278
- tags: meta.tags,
279
- }, {
280
- lineWidth: 120,
281
- noRefs: true,
282
- quotingType: '"',
283
- }).trimEnd()
284
- const safeTitle = String(meta.title ?? '').replaceAll('\n', ' ').trim()
285
- const source = meta.author
286
- ? `> 来源:[${meta.site || meta.url}](${meta.url}) · ${meta.author}`
287
- : `> 来源:[${meta.site || meta.url}](${meta.url})`
288
-
289
- const usable = (Array.isArray(annotations) ? annotations : [])
290
- .filter(annotation => annotation !== null && typeof annotation === 'object' && annotation.status !== 'stale')
291
- const annotationBlock = usable.length === 0 ? '' : `\n## 批注\n\n${usable.map(annotation => {
292
- const quote = String(annotation.quote ?? '').replaceAll('\n', '\n> ')
293
- const note = String(annotation.note ?? '').trim()
294
- return `> ${quote}${note === '' ? '' : `\n\n**笔记:** ${note}`}`
295
- }).join('\n\n')}\n`
296
-
297
- return `---\n${frontmatter}\n---\n\n# ${safeTitle}\n\n${source}\n\n${String(body ?? '').trim()}\n${annotationBlock}`
298
- }
299
-
300
- /**
301
- * The plain text a reader sees in the rendered article. Highlight offsets are
302
- * stored against this projection, not against Markdown source, so UI selections
303
- * and server-side validation use the same coordinates.
304
- */
305
- export function renderedText(markdown) {
306
- const html = renderMarkdown(markdown)
307
- const document = parseHTML(`<!doctype html><html><body>${html}</body></html>`).document
308
- return String(document.body?.textContent ?? '')
309
- }
1
+ import { Readability } from '@mozilla/readability'
2
+ import { dump as dumpYaml } from 'js-yaml'
3
+ import { parseHTML } from 'linkedom'
4
+ import { marked } from 'marked'
5
+ import sanitizeHtml from 'sanitize-html'
6
+ import TurndownService from 'turndown'
7
+ import { gfm } from 'turndown-plugin-gfm'
8
+
9
+ function escapeHtmlAttribute(value) {
10
+ return String(value)
11
+ .replaceAll('&', '&amp;')
12
+ .replaceAll('"', '&quot;')
13
+ .replaceAll('<', '&lt;')
14
+ .replaceAll('>', '&gt;')
15
+ }
16
+
17
+ function withBaseHref(html, baseUrl) {
18
+ const base = `<base href="${escapeHtmlAttribute(baseUrl)}">`
19
+ if (/<head[^>]*>/i.test(html)) return html.replace(/<head([^>]*)>/i, `<head$1>${base}`)
20
+ if (/<html[^>]*>/i.test(html)) return html.replace(/<html([^>]*)>/i, `<html$1><head>${base}</head>`)
21
+ return `<!doctype html><html><head>${base}</head><body>${html}</body></html>`
22
+ }
23
+
24
+ function metaContent(document, selectors) {
25
+ for (const selector of selectors) {
26
+ const element = document.querySelector(selector)
27
+ if (element === null) continue
28
+ const value = element.getAttribute('content') ?? element.getAttribute('href') ?? element.textContent
29
+ if (typeof value === 'string' && value.trim() !== '') return value.trim()
30
+ }
31
+ return ''
32
+ }
33
+
34
+ function absoluteUrl(value, baseUrl) {
35
+ const raw = String(value ?? '').trim()
36
+ if (raw === '') return ''
37
+ if (raw.startsWith('#')) return raw
38
+ try {
39
+ return new URL(raw, baseUrl).toString()
40
+ } catch {
41
+ return ''
42
+ }
43
+ }
44
+
45
+ function isSafeHref(value) {
46
+ if (value.startsWith('#')) return true
47
+ try {
48
+ const parsed = new URL(value)
49
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' || parsed.protocol === 'mailto:'
50
+ } catch {
51
+ return false
52
+ }
53
+ }
54
+
55
+ function makeTurndown(baseUrl) {
56
+ const turndown = new TurndownService({
57
+ headingStyle: 'atx',
58
+ codeBlockStyle: 'fenced',
59
+ bulletListMarker: '-',
60
+ emDelimiter: '*',
61
+ })
62
+ turndown.use(gfm)
63
+ turndown.remove(['script', 'style', 'noscript', 'iframe', 'form', 'button', 'input', 'select', 'textarea', 'svg', 'canvas'])
64
+
65
+ turndown.addRule('absoluteLinks', {
66
+ filter: 'a',
67
+ replacement(content, node) {
68
+ const href = absoluteUrl(node.getAttribute?.('href'), baseUrl)
69
+ const text = content.trim()
70
+ if (href === '' || !isSafeHref(href)) return text
71
+ if (text === '') return ''
72
+ return `[${text}](${href})`
73
+ },
74
+ })
75
+
76
+ turndown.addRule('absoluteImages', {
77
+ filter: 'img',
78
+ replacement(_content, node) {
79
+ const src = absoluteUrl(node.getAttribute?.('src'), baseUrl)
80
+ if (src === '' || !/^https?:/i.test(src)) return ''
81
+ const alt = String(node.getAttribute?.('alt') ?? '').replace(/\s+/g, ' ').trim()
82
+ const title = String(node.getAttribute?.('title') ?? '').trim()
83
+ return `![${alt}](${src}${title === '' ? '' : ` "${title.replaceAll('"', '\\"')}"`})`
84
+ },
85
+ })
86
+
87
+ return turndown
88
+ }
89
+
90
+ function countWords(text) {
91
+ const cjk = (text.match(/[぀-ヿ㐀-䶿一-鿿가-힯]/g) || []).length
92
+ const latin = (text.replace(/[぀-ヿ㐀-䶿一-鿿가-힯]/g, ' ').match(/[A-Za-z0-9_]+/g) || []).length
93
+ return { wordCount: cjk + latin, charCount: text.length, cjk }
94
+ }
95
+
96
+ function detectLanguage(document, text, cjk) {
97
+ const declared = String(document?.documentElement?.getAttribute?.('lang') ?? '').trim().toLowerCase()
98
+ if (declared !== '') return declared.split('-')[0]
99
+ return cjk > 0 && cjk >= text.length * 0.05 ? 'zh' : 'en'
100
+ }
101
+
102
+ function cleanMarkdown(markdown) {
103
+ return markdown
104
+ .replace(/\]\((?:javascript|data|vbscript|file):[^)\s]*\)/gi, '](#)')
105
+ .replace(/[ \t]+\n/g, '\n')
106
+ .replace(/\n{3,}/g, '\n\n')
107
+ .trim()
108
+ }
109
+
110
+ function clampText(value, maxLength) {
111
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim()
112
+ return text.length > maxLength ? text.slice(0, maxLength) : text
113
+ }
114
+
115
+ /**
116
+ * Turn raw HTML into a clean article: metadata, a Turndown Markdown body, and
117
+ * a safe rendered HTML fragment. Readability runs on a fresh document so meta
118
+ * extraction and the fallback path cannot see a half-mutated DOM.
119
+ */
120
+ export function parseArticle(html, options = {}) {
121
+ const url = options.url ?? 'https://example.invalid/'
122
+ const maxMarkdownChars = options.maxMarkdownChars ?? 400_000
123
+ const withBase = withBaseHref(String(html ?? ''), url)
124
+
125
+ const metaDocument = parseHTML(withBase).document
126
+ const metaTitle = metaContent(metaDocument, [
127
+ 'meta[property="og:title"]',
128
+ 'meta[name="twitter:title"]',
129
+ 'meta[name="title"]',
130
+ ]) || String(metaDocument.title ?? '').trim()
131
+ const byline = metaContent(metaDocument, [
132
+ 'meta[name="author"]',
133
+ 'meta[property="article:author"]',
134
+ 'meta[name="byl"]',
135
+ ])
136
+ const siteName = metaContent(metaDocument, [
137
+ 'meta[property="og:site_name"]',
138
+ 'meta[name="application-name"]',
139
+ ]) || (() => {
140
+ try { return new URL(url).hostname } catch { return '' }
141
+ })()
142
+ const published = metaContent(metaDocument, [
143
+ 'meta[property="article:published_time"]',
144
+ 'meta[name="date"]',
145
+ 'meta[name="pubdate"]',
146
+ 'meta[name="publishdate"]',
147
+ 'meta[name="dc.date"]',
148
+ ])
149
+ const keywords = metaContent(metaDocument, [
150
+ 'meta[name="keywords"]',
151
+ 'meta[name="news_keywords"]',
152
+ ])
153
+ const canonicalRaw = absoluteUrl(
154
+ metaContent(metaDocument, ['link[rel="canonical"]']),
155
+ url,
156
+ )
157
+ // A hostile page can put megabytes in <link rel=canonical>. Keep the URL
158
+ // usable as a base, but do not persist an unbounded value.
159
+ const canonical = canonicalRaw.length <= 2_048 ? canonicalRaw : ''
160
+
161
+ // Relative links and images should survive the archive. Prefer the page's
162
+ // declared canonical URL over the URL we happened to fetch through, so a
163
+ // mirror/local server does not bake its own origin into the saved copy.
164
+ const articleBase = canonical !== '' ? canonical : url
165
+ const articleDocument = parseHTML(withBaseHref(String(html ?? ''), articleBase)).document
166
+ let article = null
167
+ try {
168
+ article = new Readability(articleDocument, {
169
+ charThreshold: 80,
170
+ keepClasses: false,
171
+ disableJSONLD: true,
172
+ }).parse()
173
+ } catch {
174
+ article = null
175
+ }
176
+
177
+ const body = articleDocument.body
178
+ const fallbackText = String(body?.textContent ?? '').replace(/\s+/g, ' ').trim()
179
+ const contentHtml = article?.content ?? body?.innerHTML ?? ''
180
+ const textContent = String(article?.textContent ?? fallbackText).replace(/\s+/g, ' ').trim()
181
+
182
+ if (contentHtml.trim() === '' || textContent.length < 40) {
183
+ return {
184
+ ok: false,
185
+ reason: '没有提取到正文。页面可能是登录页、SPA 或反爬页;请用浏览器打开后复制正文,或换一个来源。',
186
+ }
187
+ }
188
+
189
+ const title = clampText(article?.title ?? metaTitle ?? '', 300) || (() => {
190
+ try { return new URL(url).hostname } catch { return '未命名文章' }
191
+ })()
192
+ const turndown = makeTurndown(articleBase)
193
+ let markdown = cleanMarkdown(
194
+ turndown.turndown(contentHtml)
195
+ .replace(/^#\s+.*\n+/, ''),
196
+ )
197
+ let truncated = false
198
+ if (markdown.length > maxMarkdownChars) {
199
+ markdown = `${markdown.slice(0, maxMarkdownChars)}\n\n> 内容过长,已截断。`
200
+ truncated = true
201
+ }
202
+
203
+ const excerptSource = String(article?.excerpt ?? textContent).replace(/\s+/g, ' ').trim()
204
+ const excerpt = excerptSource.length > 240 ? `${excerptSource.slice(0, 240)}…` : excerptSource
205
+ const counts = countWords(textContent)
206
+ const images = (markdown.match(/!\[[^\]]*\]\([^)]*\)/g) || []).length
207
+ const keywordList = clampText(keywords, 1_000)
208
+ .split(',')
209
+ .map(value => clampText(value, 40))
210
+ .filter(Boolean)
211
+ .slice(0, 10)
212
+
213
+ return {
214
+ ok: true,
215
+ title,
216
+ byline: clampText(article?.byline ?? byline, 200),
217
+ siteName: clampText(article?.siteName ?? siteName, 200),
218
+ published: clampText(published, 64),
219
+ excerpt,
220
+ markdown,
221
+ textContent,
222
+ canonicalUrl: canonical,
223
+ keywords: keywordList,
224
+ wordCount: counts.wordCount,
225
+ charCount: counts.charCount,
226
+ lang: detectLanguage(articleDocument, textContent, counts.cjk),
227
+ images,
228
+ truncated,
229
+ }
230
+ }
231
+
232
+ const RENDER_ALLOWED_TAGS = [
233
+ 'a', 'abbr', 'b', 'blockquote', 'br', 'caption', 'code', 'col', 'colgroup', 'dd', 'del',
234
+ 'details', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5',
235
+ 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 's', 'section',
236
+ 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th',
237
+ 'thead', 'tr', 'u', 'ul',
238
+ ]
239
+
240
+ export function renderMarkdown(markdown) {
241
+ const raw = marked.parse(String(markdown ?? ''), { gfm: true, breaks: false, async: false })
242
+ return sanitizeHtml(raw, {
243
+ allowedTags: RENDER_ALLOWED_TAGS,
244
+ allowedAttributes: {
245
+ a: ['href', 'title', 'target', 'rel'],
246
+ img: ['src', 'alt', 'title', 'loading'],
247
+ code: ['class'],
248
+ th: ['align'],
249
+ td: ['align'],
250
+ },
251
+ allowedSchemes: ['http', 'https', 'mailto'],
252
+ allowedSchemesByTag: { img: ['http', 'https'] },
253
+ transformTags: {
254
+ a: (tagName, attribs) => ({
255
+ tagName,
256
+ attribs: {
257
+ ...attribs,
258
+ target: '_blank',
259
+ rel: 'noopener noreferrer',
260
+ },
261
+ }),
262
+ img: (tagName, attribs) => ({
263
+ tagName,
264
+ attribs: { ...attribs, loading: 'lazy' },
265
+ }),
266
+ },
267
+ })
268
+ }
269
+
270
+ export function exportMarkdown(meta, body, annotations = []) {
271
+ const frontmatter = dumpYaml({
272
+ title: meta.title,
273
+ url: meta.url,
274
+ site: meta.site,
275
+ author: meta.author,
276
+ published: meta.published,
277
+ clipped: meta.clippedAt,
278
+ tags: meta.tags,
279
+ }, {
280
+ lineWidth: 120,
281
+ noRefs: true,
282
+ quotingType: '"',
283
+ }).trimEnd()
284
+ const safeTitle = String(meta.title ?? '').replaceAll('\n', ' ').trim()
285
+ const source = meta.author
286
+ ? `> 来源:[${meta.site || meta.url}](${meta.url}) · ${meta.author}`
287
+ : `> 来源:[${meta.site || meta.url}](${meta.url})`
288
+
289
+ const usable = (Array.isArray(annotations) ? annotations : [])
290
+ .filter(annotation => annotation !== null && typeof annotation === 'object' && annotation.status !== 'stale')
291
+ const annotationBlock = usable.length === 0 ? '' : `\n## 批注\n\n${usable.map(annotation => {
292
+ const quote = String(annotation.quote ?? '').replaceAll('\n', '\n> ')
293
+ const note = String(annotation.note ?? '').trim()
294
+ return `> ${quote}${note === '' ? '' : `\n\n**笔记:** ${note}`}`
295
+ }).join('\n\n')}\n`
296
+
297
+ return `---\n${frontmatter}\n---\n\n# ${safeTitle}\n\n${source}\n\n${String(body ?? '').trim()}\n${annotationBlock}`
298
+ }
299
+
300
+ /**
301
+ * The plain text a reader sees in the rendered article. Highlight offsets are
302
+ * stored against this projection, not against Markdown source, so UI selections
303
+ * and server-side validation use the same coordinates.
304
+ */
305
+ export function renderedText(markdown) {
306
+ const html = renderMarkdown(markdown)
307
+ const document = parseHTML(`<!doctype html><html><body>${html}</body></html>`).document
308
+ return String(document.body?.textContent ?? '')
309
+ }