dsh-bilingual-reader 0.0.0-stage → 0.1.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/cache.js ADDED
@@ -0,0 +1,76 @@
1
+ import { readJson, sha256, writeJsonAtomic } from './util.js'
2
+
3
+ const SCHEMA_VERSION = 1
4
+
5
+ export class TranslationCache {
6
+ constructor({ file, limit = 20_000 }) {
7
+ this.file = file
8
+ this.limit = limit
9
+ this.entries = new Map()
10
+ this.hits = 0
11
+ this.misses = 0
12
+ this.loaded = false
13
+ }
14
+
15
+ async ready() {
16
+ if (this.loaded) return
17
+ const data = await readJson(this.file, { schemaVersion: SCHEMA_VERSION, entries: {} })
18
+ const entries = data !== null && typeof data === 'object' && data.entries !== null && typeof data.entries === 'object'
19
+ ? data.entries
20
+ : {}
21
+ for (const [key, entry] of Object.entries(entries)) {
22
+ if (entry === null || typeof entry !== 'object' || typeof entry.translation !== 'string') continue
23
+ this.entries.set(key, {
24
+ translation: entry.translation,
25
+ createdAt: typeof entry.createdAt === 'string' ? entry.createdAt : new Date(0).toISOString(),
26
+ })
27
+ }
28
+ this.loaded = true
29
+ }
30
+
31
+ key(text, targetLang, glossaryHash) {
32
+ return sha256(`${targetLang}\u0000${glossaryHash}\u0000${text}`)
33
+ }
34
+
35
+ get(key) {
36
+ const entry = this.entries.get(key)
37
+ if (entry === undefined) {
38
+ this.misses += 1
39
+ return null
40
+ }
41
+ this.hits += 1
42
+ return entry.translation
43
+ }
44
+
45
+ set(key, translation) {
46
+ this.entries.set(key, { translation: String(translation), createdAt: new Date().toISOString() })
47
+ this.prune()
48
+ }
49
+
50
+ prune() {
51
+ if (this.entries.size <= this.limit) return
52
+ const sorted = [...this.entries.entries()].sort((a, b) => {
53
+ const left = Date.parse(a[1].createdAt) || 0
54
+ const right = Date.parse(b[1].createdAt) || 0
55
+ return left - right
56
+ })
57
+ const removeCount = Math.max(1, Math.ceil(this.entries.size * 0.1))
58
+ for (const [key] of sorted.slice(0, removeCount)) this.entries.delete(key)
59
+ }
60
+
61
+ stats() {
62
+ const total = this.hits + this.misses
63
+ return {
64
+ size: this.entries.size,
65
+ hits: this.hits,
66
+ misses: this.misses,
67
+ hitRate: total === 0 ? 0 : this.hits / total,
68
+ }
69
+ }
70
+
71
+ async flush() {
72
+ const entries = {}
73
+ for (const [key, entry] of this.entries) entries[key] = entry
74
+ await writeJsonAtomic(this.file, { schemaVersion: SCHEMA_VERSION, entries })
75
+ }
76
+ }
package/src/client.js ADDED
@@ -0,0 +1,59 @@
1
+ import { createElement as h } from 'react'
2
+
3
+ export const name = 'dsh-bilingual-reader-client'
4
+ export const inject = ['slots']
5
+
6
+ const ID = 'dsh-bilingual-reader'
7
+ const LABEL = '双语阅读'
8
+
9
+ function TranslateIcon(owner = {}) {
10
+ const size = owner.size ?? 16
11
+ return h('svg', {
12
+ width: size,
13
+ height: size,
14
+ viewBox: '0 0 24 24',
15
+ fill: 'none',
16
+ stroke: 'currentColor',
17
+ strokeWidth: 2,
18
+ strokeLinecap: 'round',
19
+ strokeLinejoin: 'round',
20
+ 'aria-hidden': 'true',
21
+ },
22
+ h('path', { d: 'M4 5h8M8 3v2c0 4-1.5 7-4 9' }),
23
+ h('path', { d: 'M5 11c2 2.5 4.5 4 7 5' }),
24
+ h('path', { d: 'M14 20l4-10 4 10' }),
25
+ h('path', { d: 'M15.5 16h5' }))
26
+ }
27
+
28
+ /**
29
+ * The sidebar row and the main panel. The panel is an iframe to the plugin's
30
+ * own same-origin route so the reader UI can live as plain HTML/CSS/JS without
31
+ * coupling to the host's React internals.
32
+ */
33
+ export function apply(ctx) {
34
+ const slots = ctx.slots
35
+
36
+ slots.inject('sidebar.panellist', () => slots.register({
37
+ name: 'sidebar.panellist',
38
+ id: ID,
39
+ order: 3,
40
+ label: () => LABEL,
41
+ }, TranslateIcon))
42
+
43
+ slots.inject('main', () => slots.register({
44
+ name: 'main',
45
+ id: ID,
46
+ key: ID,
47
+ order: 3,
48
+ }, () => h('iframe', {
49
+ src: '/dsh-bilingual-reader/',
50
+ title: LABEL,
51
+ style: {
52
+ display: 'block',
53
+ width: '100%',
54
+ height: '100%',
55
+ border: '0',
56
+ background: 'transparent',
57
+ },
58
+ })))
59
+ }
package/src/config.js ADDED
@@ -0,0 +1,73 @@
1
+ import { homedir } from 'node:os'
2
+ import { join, resolve } from 'node:path'
3
+
4
+ export const DEFAULT_DIR = join(homedir(), '.dsh-bilingual-reader')
5
+
6
+ export const TARGET_LANGUAGES = [
7
+ { code: 'zh-CN', label: '简体中文' },
8
+ { code: 'zh-TW', label: '繁體中文' },
9
+ { code: 'en', label: 'English' },
10
+ { code: 'ja', label: '日本語' },
11
+ { code: 'ko', label: '한국어' },
12
+ ]
13
+
14
+ const LANGUAGE_NAMES = {
15
+ 'zh-CN': 'Simplified Chinese',
16
+ 'zh-TW': 'Traditional Chinese',
17
+ en: 'English',
18
+ ja: 'Japanese',
19
+ ko: 'Korean',
20
+ }
21
+
22
+ function positiveInt(value, fallback) {
23
+ if (value === undefined || value === null || value === '') return fallback
24
+ const parsed = Number(value)
25
+ return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback
26
+ }
27
+
28
+ function expandHome(value) {
29
+ if (value === '~') return homedir()
30
+ if (value.startsWith('~/') || value.startsWith('~\\')) return join(homedir(), value.slice(2))
31
+ return value
32
+ }
33
+
34
+ export function normalizeTargetLang(value, fallback = 'zh-CN') {
35
+ const code = typeof value === 'string' ? value.trim() : ''
36
+ if (code === '') return fallback
37
+ const match = TARGET_LANGUAGES.find(item => item.code.toLowerCase() === code.toLowerCase())
38
+ return match === undefined ? fallback : match.code
39
+ }
40
+
41
+ export function targetLanguageName(code) {
42
+ return LANGUAGE_NAMES[code] ?? LANGUAGE_NAMES['zh-CN']
43
+ }
44
+
45
+ export function loadConfig(env = process.env) {
46
+ const dir = resolve(expandHome(env.DSH_BILINGUAL_READER_DIR || DEFAULT_DIR))
47
+ return {
48
+ dir,
49
+ targetLang: normalizeTargetLang(env.DSH_BILINGUAL_TARGET_LANG, 'zh-CN'),
50
+ timeoutMs: positiveInt(env.DSH_BILINGUAL_TIMEOUT_MS, 20_000),
51
+ maxBytes: positiveInt(env.DSH_BILINGUAL_MAX_BYTES, 5 * 1024 * 1024),
52
+ maxMarkdownChars: positiveInt(env.DSH_BILINGUAL_MAX_MARKDOWN_CHARS, 400_000),
53
+ maxRedirects: positiveInt(env.DSH_BILINGUAL_MAX_REDIRECTS, 5),
54
+ maxBlocks: positiveInt(env.DSH_BILINGUAL_MAX_BLOCKS, 400),
55
+ batchBlocks: positiveInt(env.DSH_BILINGUAL_BATCH_BLOCKS, 6),
56
+ batchChars: positiveInt(env.DSH_BILINGUAL_BATCH_CHARS, 3_500),
57
+ maxTranslateChars: positiveInt(env.DSH_BILINGUAL_MAX_TRANSLATE_CHARS, 20_000),
58
+ cacheLimit: positiveInt(env.DSH_BILINGUAL_CACHE_LIMIT, 20_000),
59
+ glossaryLimit: positiveInt(env.DSH_BILINGUAL_GLOSSARY_LIMIT, 500),
60
+ allowPrivate: env.DSH_BILINGUAL_ALLOW_PRIVATE === '1' || env.DSH_BILINGUAL_ALLOW_PRIVATE === 'true',
61
+ blockFakeIp: env.DSH_BILINGUAL_BLOCK_FAKE_IP === '1' || env.DSH_BILINGUAL_BLOCK_FAKE_IP === 'true',
62
+ userAgent:
63
+ env.DSH_BILINGUAL_USER_AGENT ||
64
+ 'dsh-bilingual-reader/0.1 (+https://github.com/Bit0620/dsh-bilingual-reader)',
65
+ proxy:
66
+ env.DSH_BILINGUAL_PROXY ||
67
+ env.HTTPS_PROXY ||
68
+ env.https_proxy ||
69
+ env.HTTP_PROXY ||
70
+ env.http_proxy ||
71
+ '',
72
+ }
73
+ }
package/src/extract.js ADDED
@@ -0,0 +1,259 @@
1
+ import { Readability } from '@mozilla/readability'
2
+ import { parseHTML } from 'linkedom'
3
+ import { marked } from 'marked'
4
+ import sanitizeHtml from 'sanitize-html'
5
+ import TurndownService from 'turndown'
6
+ import { gfm } from 'turndown-plugin-gfm'
7
+
8
+ function escapeHtmlAttribute(value) {
9
+ return String(value)
10
+ .replaceAll('&', '&amp;')
11
+ .replaceAll('"', '&quot;')
12
+ .replaceAll('<', '&lt;')
13
+ .replaceAll('>', '&gt;')
14
+ }
15
+
16
+ function withBaseHref(html, baseUrl) {
17
+ const base = `<base href="${escapeHtmlAttribute(baseUrl)}">`
18
+ if (/<head[^>]*>/i.test(html)) return html.replace(/<head([^>]*)>/i, `<head$1>${base}`)
19
+ if (/<html[^>]*>/i.test(html)) return html.replace(/<html([^>]*)>/i, `<html$1><head>${base}</head>`)
20
+ return `<!doctype html><html><head>${base}</head><body>${html}</body></html>`
21
+ }
22
+
23
+ function metaContent(document, selectors) {
24
+ for (const selector of selectors) {
25
+ const element = document.querySelector(selector)
26
+ if (element === null) continue
27
+ const value = element.getAttribute('content') ?? element.getAttribute('href') ?? element.textContent
28
+ if (typeof value === 'string' && value.trim() !== '') return value.trim()
29
+ }
30
+ return ''
31
+ }
32
+
33
+ function absoluteUrl(value, baseUrl) {
34
+ const raw = String(value ?? '').trim()
35
+ if (raw === '') return ''
36
+ if (raw.startsWith('#')) return raw
37
+ try {
38
+ return new URL(raw, baseUrl).toString()
39
+ } catch {
40
+ return ''
41
+ }
42
+ }
43
+
44
+ function isSafeHref(value) {
45
+ if (value.startsWith('#')) return true
46
+ try {
47
+ const parsed = new URL(value)
48
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' || parsed.protocol === 'mailto:'
49
+ } catch {
50
+ return false
51
+ }
52
+ }
53
+
54
+ function makeTurndown(baseUrl) {
55
+ const turndown = new TurndownService({
56
+ headingStyle: 'atx',
57
+ codeBlockStyle: 'fenced',
58
+ bulletListMarker: '-',
59
+ emDelimiter: '*',
60
+ })
61
+ turndown.use(gfm)
62
+ turndown.remove(['script', 'style', 'noscript', 'iframe', 'form', 'button', 'input', 'select', 'textarea', 'svg', 'canvas'])
63
+
64
+ turndown.addRule('absoluteLinks', {
65
+ filter: 'a',
66
+ replacement(content, node) {
67
+ const href = absoluteUrl(node.getAttribute?.('href'), baseUrl)
68
+ const text = content.trim()
69
+ if (href === '' || !isSafeHref(href)) return text
70
+ if (text === '') return ''
71
+ return `[${text}](${href})`
72
+ },
73
+ })
74
+
75
+ turndown.addRule('absoluteImages', {
76
+ filter: 'img',
77
+ replacement(_content, node) {
78
+ const src = absoluteUrl(node.getAttribute?.('src'), baseUrl)
79
+ if (src === '' || !/^https?:/i.test(src)) return ''
80
+ const alt = String(node.getAttribute?.('alt') ?? '').replace(/\s+/g, ' ').trim()
81
+ const title = String(node.getAttribute?.('title') ?? '').trim()
82
+ return `![${alt}](${src}${title === '' ? '' : ` "${title.replaceAll('"', '\\"')}"`})`
83
+ },
84
+ })
85
+
86
+ return turndown
87
+ }
88
+
89
+ export function countWords(text) {
90
+ const cjk = (text.match(/[぀-ヿ㐀-䶿一-鿿가-힯]/g) || []).length
91
+ const latin = (text.replace(/[぀-ヿ㐀-䶿一-鿿가-힯]/g, ' ').match(/[A-Za-z0-9_]+/g) || []).length
92
+ return { wordCount: cjk + latin, charCount: text.length, cjk }
93
+ }
94
+
95
+ function detectLanguage(document, text, cjk) {
96
+ const declared = String(document?.documentElement?.getAttribute?.('lang') ?? '').trim().toLowerCase()
97
+ if (declared !== '') return declared.split('-')[0]
98
+ return cjk > 0 && cjk >= text.length * 0.05 ? 'zh' : 'en'
99
+ }
100
+
101
+ function cleanMarkdown(markdown) {
102
+ return markdown
103
+ .replace(/\]\((?:javascript|data|vbscript|file):[^)\s]*\)/gi, '](#)')
104
+ .replace(/[ \t]+\n/g, '\n')
105
+ .replace(/\n{3,}/g, '\n\n')
106
+ .trim()
107
+ }
108
+
109
+ function clampText(value, maxLength) {
110
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim()
111
+ return text.length > maxLength ? text.slice(0, maxLength) : text
112
+ }
113
+
114
+ /**
115
+ * Turn raw HTML into a clean article: metadata, a Turndown Markdown body and
116
+ * the final URL. Readability runs on a fresh document so meta extraction and
117
+ * the fallback path cannot see a half-mutated DOM.
118
+ */
119
+ export function parseArticle(html, options = {}) {
120
+ const url = options.url ?? 'https://example.invalid/'
121
+ const maxMarkdownChars = options.maxMarkdownChars ?? 400_000
122
+ const withBase = withBaseHref(String(html ?? ''), url)
123
+
124
+ const metaDocument = parseHTML(withBase).document
125
+ const metaTitle = metaContent(metaDocument, [
126
+ 'meta[property="og:title"]',
127
+ 'meta[name="twitter:title"]',
128
+ 'meta[name="title"]',
129
+ ]) || String(metaDocument.title ?? '').trim()
130
+ const byline = metaContent(metaDocument, [
131
+ 'meta[name="author"]',
132
+ 'meta[property="article:author"]',
133
+ 'meta[name="byl"]',
134
+ ])
135
+ const siteName = metaContent(metaDocument, [
136
+ 'meta[property="og:site_name"]',
137
+ 'meta[name="application-name"]',
138
+ ]) || (() => {
139
+ try { return new URL(url).hostname } catch { return '' }
140
+ })()
141
+ const published = metaContent(metaDocument, [
142
+ 'meta[property="article:published_time"]',
143
+ 'meta[name="date"]',
144
+ 'meta[name="pubdate"]',
145
+ 'meta[name="publishdate"]',
146
+ 'meta[name="dc.date"]',
147
+ ])
148
+ const keywords = metaContent(metaDocument, [
149
+ 'meta[name="keywords"]',
150
+ 'meta[name="news_keywords"]',
151
+ ])
152
+ const canonicalRaw = absoluteUrl(
153
+ metaContent(metaDocument, ['link[rel="canonical"]']),
154
+ url,
155
+ )
156
+ const canonical = canonicalRaw.length <= 2_048 ? canonicalRaw : ''
157
+
158
+ const articleBase = canonical !== '' ? canonical : url
159
+ const articleDocument = parseHTML(withBaseHref(String(html ?? ''), articleBase)).document
160
+ let article = null
161
+ try {
162
+ article = new Readability(articleDocument, {
163
+ charThreshold: 80,
164
+ keepClasses: false,
165
+ disableJSONLD: true,
166
+ }).parse()
167
+ } catch {
168
+ article = null
169
+ }
170
+
171
+ const body = articleDocument.body
172
+ const fallbackText = String(body?.textContent ?? '').replace(/\s+/g, ' ').trim()
173
+ const contentHtml = article?.content ?? body?.innerHTML ?? ''
174
+ const textContent = String(article?.textContent ?? fallbackText).replace(/\s+/g, ' ').trim()
175
+
176
+ if (contentHtml.trim() === '' || textContent.length < 40) {
177
+ return {
178
+ ok: false,
179
+ reason: '没有提取到正文。页面可能是登录页、SPA 或反爬页;请用浏览器打开后复制正文,或换一个来源。',
180
+ }
181
+ }
182
+
183
+ const title = clampText(article?.title ?? metaTitle ?? '', 300) || (() => {
184
+ try { return new URL(url).hostname } catch { return '未命名文章' }
185
+ })()
186
+ const turndown = makeTurndown(articleBase)
187
+ let markdown = cleanMarkdown(
188
+ turndown.turndown(contentHtml)
189
+ .replace(/^#\s+.*\n+/, ''),
190
+ )
191
+ let truncated = false
192
+ if (markdown.length > maxMarkdownChars) {
193
+ markdown = `${markdown.slice(0, maxMarkdownChars)}\n\n> 内容过长,已截断。`
194
+ truncated = true
195
+ }
196
+
197
+ const excerptSource = String(article?.excerpt ?? textContent).replace(/\s+/g, ' ').trim()
198
+ const excerpt = excerptSource.length > 240 ? `${excerptSource.slice(0, 240)}…` : excerptSource
199
+ const counts = countWords(textContent)
200
+
201
+ return {
202
+ ok: true,
203
+ title,
204
+ byline: clampText(article?.byline ?? byline, 200),
205
+ siteName: clampText(article?.siteName ?? siteName, 200),
206
+ published: clampText(published, 64),
207
+ excerpt,
208
+ markdown,
209
+ textContent,
210
+ canonicalUrl: canonical,
211
+ keywords: clampText(keywords, 1_000)
212
+ .split(',')
213
+ .map(value => clampText(value, 40))
214
+ .filter(Boolean)
215
+ .slice(0, 10),
216
+ wordCount: counts.wordCount,
217
+ charCount: counts.charCount,
218
+ lang: detectLanguage(articleDocument, textContent, counts.cjk),
219
+ truncated,
220
+ }
221
+ }
222
+
223
+ const RENDER_ALLOWED_TAGS = [
224
+ 'a', 'abbr', 'b', 'blockquote', 'br', 'caption', 'code', 'col', 'colgroup', 'dd', 'del',
225
+ 'details', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5',
226
+ 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 's', 'section',
227
+ 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th',
228
+ 'thead', 'tr', 'u', 'ul',
229
+ ]
230
+
231
+ export function renderMarkdown(markdown) {
232
+ const raw = marked.parse(String(markdown ?? ''), { gfm: true, breaks: false, async: false })
233
+ return sanitizeHtml(raw, {
234
+ allowedTags: RENDER_ALLOWED_TAGS,
235
+ allowedAttributes: {
236
+ a: ['href', 'title', 'target', 'rel'],
237
+ img: ['src', 'alt', 'title', 'loading'],
238
+ code: ['class'],
239
+ th: ['align'],
240
+ td: ['align'],
241
+ },
242
+ allowedSchemes: ['http', 'https', 'mailto'],
243
+ allowedSchemesByTag: { img: ['http', 'https'] },
244
+ transformTags: {
245
+ a: (tagName, attribs) => ({
246
+ tagName,
247
+ attribs: {
248
+ ...attribs,
249
+ target: '_blank',
250
+ rel: 'noopener noreferrer',
251
+ },
252
+ }),
253
+ img: (tagName, attribs) => ({
254
+ tagName,
255
+ attribs: { ...attribs, loading: 'lazy' },
256
+ }),
257
+ },
258
+ })
259
+ }
package/src/fetch.js ADDED
@@ -0,0 +1,183 @@
1
+ import dns from 'node:dns'
2
+ import iconv from 'iconv-lite'
3
+ import { Agent, ProxyAgent, fetch as undiciFetch } from 'undici'
4
+ import { assertPublicUrl, isPrivateIp } from './security.js'
5
+
6
+ const proxyAgents = new Map()
7
+ const validatingAgents = new Map()
8
+
9
+ function proxyDispatcher(proxyUrl) {
10
+ if (!proxyUrl) return undefined
11
+ let agent = proxyAgents.get(proxyUrl)
12
+ if (agent === undefined) {
13
+ agent = new ProxyAgent(proxyUrl)
14
+ proxyAgents.set(proxyUrl, agent)
15
+ }
16
+ return agent
17
+ }
18
+
19
+ function validatingAgent(blockFakeIp) {
20
+ const key = blockFakeIp ? 'block-fake-ip' : 'allow-fake-ip'
21
+ let agent = validatingAgents.get(key)
22
+ if (agent !== undefined) return agent
23
+ agent = new Agent({
24
+ connect: {
25
+ // assertPublicUrl checks the hostname once, but the socket resolves it
26
+ // again. This lookup is the enforcement point that closes the DNS
27
+ // rebinding window.
28
+ lookup(hostname, options, callback) {
29
+ dns.lookup(hostname, { all: true, verbatim: true }, (error, addresses) => {
30
+ if (error) {
31
+ callback(error)
32
+ return
33
+ }
34
+ const allowed = addresses.filter(({ address }) => !isPrivateIp(address, { blockFakeIp }))
35
+ if (allowed.length === 0) {
36
+ callback(new Error(`拒绝连接:${hostname} 解析到内网地址`))
37
+ return
38
+ }
39
+ if (options?.all === true) callback(null, allowed)
40
+ else callback(null, allowed[0].address, allowed[0].family)
41
+ })
42
+ },
43
+ },
44
+ })
45
+ validatingAgents.set(key, agent)
46
+ return agent
47
+ }
48
+
49
+ function dispatcherFor(config, hasInjectedFetch) {
50
+ if (hasInjectedFetch) return undefined
51
+ if (config.allowPrivate === true) return undefined
52
+ if (config.proxy) return proxyDispatcher(config.proxy)
53
+ return validatingAgent(config.blockFakeIp === true)
54
+ }
55
+
56
+ const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308])
57
+ const HTML_TYPES = ['text/html', 'application/xhtml+xml']
58
+
59
+ function signalWithTimeout(signal, timeoutMs) {
60
+ const timeout = AbortSignal.timeout(timeoutMs)
61
+ if (signal === undefined || signal === null) return timeout
62
+ return AbortSignal.any([signal, timeout])
63
+ }
64
+
65
+ function charsetFromContentType(contentType) {
66
+ const match = /charset\s*=\s*["']?([^;"'\s]+)/i.exec(contentType || '')
67
+ return match ? match[1].toLowerCase() : undefined
68
+ }
69
+
70
+ function charsetFromHtml(buffer) {
71
+ const head = buffer.subarray(0, 4096).toString('latin1')
72
+ const meta = /<meta[^>]+charset\s*=\s*["']?([^"'\s/>]+)/i.exec(head)
73
+ if (meta !== null) return meta[1].toLowerCase()
74
+ const httpEquiv = /<meta[^>]+http-equiv\s*=\s*["']?content-type["']?[^>]+content\s*=\s*["'][^"']*charset=([^"'\s;]+)/i.exec(head)
75
+ return httpEquiv !== null ? httpEquiv[1].toLowerCase() : undefined
76
+ }
77
+
78
+ function decodeBody(buffer, contentType) {
79
+ const charset = charsetFromContentType(contentType) || charsetFromHtml(buffer) || 'utf-8'
80
+ try {
81
+ return { text: iconv.decode(buffer, charset), charset }
82
+ } catch {
83
+ return { text: buffer.toString('utf8'), charset: 'utf-8' }
84
+ }
85
+ }
86
+
87
+ async function readCapped(response, maxBytes) {
88
+ if (response.body === null) return Buffer.alloc(0)
89
+ const reader = response.body.getReader()
90
+ const chunks = []
91
+ let total = 0
92
+ try {
93
+ for (;;) {
94
+ const { done, value } = await reader.read()
95
+ if (done) break
96
+ total += value.byteLength
97
+ if (total > maxBytes) {
98
+ await reader.cancel().catch(() => {})
99
+ throw new Error(`页面超过大小上限(${Math.floor(maxBytes / 1024)} KB)`)
100
+ }
101
+ chunks.push(Buffer.from(value))
102
+ }
103
+ } finally {
104
+ reader.releaseLock?.()
105
+ }
106
+ return Buffer.concat(chunks, total)
107
+ }
108
+
109
+ function escapeHtml(text) {
110
+ return String(text)
111
+ .replaceAll('&', '&amp;')
112
+ .replaceAll('<', '&lt;')
113
+ .replaceAll('>', '&gt;')
114
+ .replaceAll('"', '&quot;')
115
+ }
116
+
117
+ /**
118
+ * Fetch an article with a manual redirect loop, per-hop SSRF validation, a
119
+ * byte cap, and charset detection (GBK/Big5 pages are common on the Chinese
120
+ * web). Returns HTML plus the final URL after redirects.
121
+ */
122
+ export async function fetchHtml(rawUrl, config, options = {}) {
123
+ const dispatcher = dispatcherFor(config, options.fetchImpl !== undefined)
124
+ const fetchImpl = options.fetchImpl ?? undiciFetch
125
+ const signal = signalWithTimeout(options.signal, config.timeoutMs)
126
+ let current = rawUrl
127
+
128
+ for (let hop = 0; hop <= config.maxRedirects; hop += 1) {
129
+ const url = await assertPublicUrl(current, config)
130
+ const response = await fetchImpl(url, {
131
+ redirect: 'manual',
132
+ signal,
133
+ ...(dispatcher === undefined ? {} : { dispatcher }),
134
+ headers: {
135
+ 'user-agent': config.userAgent,
136
+ accept: 'text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.1',
137
+ 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
138
+ },
139
+ })
140
+
141
+ if (REDIRECT_STATUS.has(response.status)) {
142
+ const location = response.headers.get('location')
143
+ if (location === null) throw new Error(`HTTP ${response.status} 重定向缺少 Location`)
144
+ current = new URL(location, url).toString()
145
+ if (hop === config.maxRedirects) throw new Error('重定向次数过多')
146
+ continue
147
+ }
148
+
149
+ if (!response.ok) {
150
+ throw new Error(`抓取失败:HTTP ${response.status} ${response.statusText}`.trim())
151
+ }
152
+
153
+ const contentType = (response.headers.get('content-type') || '').toLowerCase()
154
+ const buffer = await readCapped(response, config.maxBytes)
155
+ const finalUrl = response.url || url.toString()
156
+
157
+ if (HTML_TYPES.some(type => contentType.includes(type)) || contentType === '') {
158
+ const decoded = decodeBody(buffer, contentType)
159
+ return {
160
+ html: decoded.text,
161
+ finalUrl,
162
+ contentType,
163
+ charset: decoded.charset,
164
+ status: response.status,
165
+ bytes: buffer.length,
166
+ }
167
+ }
168
+ if (contentType.includes('text/plain')) {
169
+ const decoded = decodeBody(buffer, contentType)
170
+ return {
171
+ html: `<!doctype html><html><head><meta charset="utf-8"></head><body><pre>${escapeHtml(decoded.text)}</pre></body></html>`,
172
+ finalUrl,
173
+ contentType,
174
+ charset: decoded.charset,
175
+ status: response.status,
176
+ bytes: buffer.length,
177
+ }
178
+ }
179
+ throw new Error(`不支持的内容类型:${contentType.split(';')[0]};目前只支持 HTML/纯文本`)
180
+ }
181
+
182
+ throw new Error('重定向次数过多')
183
+ }