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.
@@ -0,0 +1,74 @@
1
+ import { clampText, readJson, sha256, writeJsonAtomic } from './util.js'
2
+
3
+ const SCHEMA_VERSION = 1
4
+
5
+ function cleanTerm(value, maxLength = 80) {
6
+ return clampText(value, maxLength)
7
+ }
8
+
9
+ export class Glossary {
10
+ constructor({ file, limit = 500 }) {
11
+ this.file = file
12
+ this.limit = limit
13
+ this.terms = []
14
+ this.loaded = false
15
+ }
16
+
17
+ async ready() {
18
+ if (this.loaded) return
19
+ const data = await readJson(this.file, { schemaVersion: SCHEMA_VERSION, terms: [] })
20
+ this.terms = Array.isArray(data?.terms)
21
+ ? data.terms
22
+ .filter(term => term !== null && typeof term === 'object')
23
+ .map(term => ({
24
+ source: cleanTerm(term.source),
25
+ target: cleanTerm(term.target),
26
+ note: cleanTerm(term.note, 160),
27
+ }))
28
+ .filter(term => term.source !== '' && term.target !== '')
29
+ .slice(0, this.limit)
30
+ : []
31
+ this.loaded = true
32
+ }
33
+
34
+ list() {
35
+ return this.terms.map(term => ({ ...term }))
36
+ }
37
+
38
+ add(source, target, note = '') {
39
+ const cleanSource = cleanTerm(source)
40
+ const cleanTarget = cleanTerm(target)
41
+ if (cleanSource === '') throw new Error('术语 source 不能为空')
42
+ if (cleanTarget === '') throw new Error('术语 target 不能为空')
43
+ if (this.terms.length >= this.limit) throw new Error(`术语表最多 ${this.limit} 条`)
44
+ const existing = this.terms.find(term => term.source.toLowerCase() === cleanSource.toLowerCase())
45
+ if (existing !== undefined) {
46
+ existing.target = cleanTarget
47
+ existing.note = cleanTerm(note, 160)
48
+ } else {
49
+ this.terms.push({ source: cleanSource, target: cleanTarget, note: cleanTerm(note, 160) })
50
+ }
51
+ this.terms.sort((a, b) => a.source.localeCompare(b.source))
52
+ return this.list()
53
+ }
54
+
55
+ remove(source) {
56
+ const cleanSource = cleanTerm(source)
57
+ if (cleanSource === '') throw new Error('术语 source 不能为空')
58
+ const before = this.terms.length
59
+ this.terms = this.terms.filter(term => term.source.toLowerCase() !== cleanSource.toLowerCase())
60
+ if (this.terms.length === before) throw new Error(`术语表里没有:${cleanSource}`)
61
+ return this.list()
62
+ }
63
+
64
+ hash() {
65
+ return sha256(this.terms
66
+ .map(term => `${term.source}\u0000${term.target}`)
67
+ .sort()
68
+ .join('\n'))
69
+ }
70
+
71
+ async flush() {
72
+ await writeJsonAtomic(this.file, { schemaVersion: SCHEMA_VERSION, terms: this.terms })
73
+ }
74
+ }
package/src/prompt.js ADDED
@@ -0,0 +1,125 @@
1
+ import { targetLanguageName } from './config.js'
2
+ import { sha256 } from './util.js'
3
+
4
+ const MAX_GLOSSARY_TERMS = 40
5
+
6
+ export function glossaryHash(terms = []) {
7
+ return sha256(terms
8
+ .map(term => `${term.source}\u0000${term.target}`)
9
+ .sort()
10
+ .join('\n'))
11
+ }
12
+
13
+ export function selectGlossary(terms, text) {
14
+ const haystack = String(text ?? '').toLowerCase()
15
+ return terms
16
+ .filter(term => term.source !== '' && haystack.includes(term.source.toLowerCase()))
17
+ .slice(0, MAX_GLOSSARY_TERMS)
18
+ }
19
+
20
+ export function chunkBlocks(blocks, options = {}) {
21
+ const maxBlocks = options.maxBlocks ?? 6
22
+ const maxChars = options.maxChars ?? 3_500
23
+ const batches = []
24
+ let current = []
25
+ let chars = 0
26
+
27
+ for (const block of blocks) {
28
+ const length = String(block.text ?? block.original ?? '').length
29
+ if (current.length > 0 && (current.length >= maxBlocks || chars + length > maxChars)) {
30
+ batches.push(current)
31
+ current = []
32
+ chars = 0
33
+ }
34
+ current.push(block)
35
+ chars += length
36
+ }
37
+ if (current.length > 0) batches.push(current)
38
+ return batches
39
+ }
40
+
41
+ export function buildBatchPrompt({ blocks, targetLang, glossary = [], context = {} }) {
42
+ const language = targetLanguageName(targetLang)
43
+ const glossaryText = glossary.length === 0
44
+ ? ''
45
+ : glossary.map(term => `${term.source} => ${term.target}`).join('\n')
46
+ let system = [
47
+ `You are a precise translator. Translate every block into ${language}.`,
48
+ 'Preserve Markdown structure exactly: headings, list markers, blockquotes, table pipes, fenced code blocks, inline code, links, URLs, LaTeX and placeholder tokens such as ⟦0⟧.',
49
+ 'Never translate code, URLs, LaTeX or placeholder tokens. Never merge or split blocks.',
50
+ 'Translate only the prose. Do not add explanations, notes or commentary.',
51
+ 'Return only JSON: {"translations":["...", "..."]} with exactly one string per input block, in the same order.',
52
+ ].join(' ')
53
+ if (glossaryText !== '') {
54
+ system += ` Terminology (source => target), use the target consistently:\n${glossaryText}`
55
+ }
56
+
57
+ const payload = {
58
+ targetLanguage: language,
59
+ title: context.title ?? '',
60
+ contextBefore: context.before ?? '',
61
+ contextAfter: context.after ?? '',
62
+ glossary,
63
+ blocks: blocks.map(block => String(block.text ?? block.original ?? '')),
64
+ }
65
+ return { system, user: JSON.stringify(payload) }
66
+ }
67
+
68
+ function extractJson(raw) {
69
+ const cleaned = String(raw ?? '').trim()
70
+ .replace(/^```(?:json)?\s*/i, '')
71
+ .replace(/\s*```$/, '')
72
+ .trim()
73
+ try {
74
+ return JSON.parse(cleaned)
75
+ } catch {
76
+ const arrayStart = cleaned.indexOf('[')
77
+ const arrayEnd = cleaned.lastIndexOf(']')
78
+ if (arrayStart !== -1 && arrayEnd > arrayStart) {
79
+ try { return JSON.parse(cleaned.slice(arrayStart, arrayEnd + 1)) } catch { /* fall through */ }
80
+ }
81
+ const objectStart = cleaned.indexOf('{')
82
+ const objectEnd = cleaned.lastIndexOf('}')
83
+ if (objectStart !== -1 && objectEnd > objectStart) {
84
+ try { return JSON.parse(cleaned.slice(objectStart, objectEnd + 1)) } catch { /* fall through */ }
85
+ }
86
+ return null
87
+ }
88
+ }
89
+
90
+ function toStringArray(value) {
91
+ if (!Array.isArray(value)) return null
92
+ return value.map(item => {
93
+ if (typeof item === 'string') return item
94
+ if (item !== null && typeof item === 'object') {
95
+ if (typeof item.translation === 'string') return item.translation
96
+ if (typeof item.text === 'string') return item.text
97
+ }
98
+ return null
99
+ })
100
+ }
101
+
102
+ /**
103
+ * Accept a JSON array, {"translations":[...]}, or {"blocks":[...]}; tolerate
104
+ * fenced output and surrounding prose. Missing entries are returned as null so
105
+ * the caller can retry only those blocks.
106
+ */
107
+ export function parseBatchResponse(raw, expectedCount) {
108
+ const parsed = extractJson(raw)
109
+ let values = null
110
+ if (Array.isArray(parsed)) values = toStringArray(parsed)
111
+ else if (parsed !== null && typeof parsed === 'object') {
112
+ values = toStringArray(parsed.translations) ?? toStringArray(parsed.blocks)
113
+ }
114
+ if (values === null) {
115
+ if (expectedCount === 1) {
116
+ const plain = String(raw ?? '').trim().replace(/^```[a-z]*\s*/i, '').replace(/\s*```$/, '')
117
+ if (plain !== '') return [plain]
118
+ }
119
+ throw new Error('模型返回不是可解析的译文 JSON')
120
+ }
121
+ const result = values.slice(0, expectedCount)
122
+ while (result.length < expectedCount) result.push(null)
123
+ if (result.every(value => value === null)) throw new Error('模型没有返回任何译文')
124
+ return result
125
+ }
package/src/protect.js ADDED
@@ -0,0 +1,71 @@
1
+ const TOKEN_START = '⟦'
2
+ const TOKEN_END = '⟧'
3
+ const TOKEN_PATTERN = /⟦(\d+)⟧/g
4
+
5
+ function tokenFor(index) {
6
+ return `${TOKEN_START}${index}${TOKEN_END}`
7
+ }
8
+
9
+ /**
10
+ * Protect inline code, LaTeX, link targets, raw URLs and HTML tags before a
11
+ * block is sent to the model. The model is told to keep the tokens verbatim;
12
+ * restoreInline puts the original fragments back. If the model drops a token,
13
+ * the caller can retry that block instead of silently deleting a link or a
14
+ * code fragment.
15
+ */
16
+ export function protectInline(text) {
17
+ const values = []
18
+ let output = String(text ?? '')
19
+
20
+ function protect(regex, replacement) {
21
+ output = output.replace(regex, (...args) => {
22
+ const index = values.length
23
+ values.push(replacement(...args))
24
+ return tokenFor(index)
25
+ })
26
+ }
27
+
28
+ // Inline code and fenced fragments that survived block segmentation.
29
+ protect(/`[^`\n]*`/g, match => match)
30
+ // Display and inline LaTeX.
31
+ protect(/\$\$[\s\S]*?\$\$/g, match => match)
32
+ protect(/\$[^$\n]+\$/g, match => match)
33
+ // Keep link targets verbatim while allowing the link text to be translated.
34
+ protect(/\]\((https?:\/\/[^)\s]+|mailto:[^)\s]+)(\s+"[^"]*")?\)/g, (match, url, title = '') => `](${url}${title})`)
35
+ // Bare URLs.
36
+ protect(/https?:\/\/[^\s<>")\]]+/g, match => match)
37
+ // Inline HTML.
38
+ protect(/<[^>\n]+>/g, match => match)
39
+
40
+ return {
41
+ text: output,
42
+ values,
43
+ restore(translated) {
44
+ const seen = new Set()
45
+ const invalid = []
46
+ const restored = String(translated ?? '').replace(TOKEN_PATTERN, (_match, rawIndex) => {
47
+ const index = Number(rawIndex)
48
+ seen.add(index)
49
+ if (!Number.isInteger(index) || values[index] === undefined) {
50
+ invalid.push(rawIndex)
51
+ return ''
52
+ }
53
+ return values[index]
54
+ })
55
+ const dropped = values
56
+ .map((_value, index) => index)
57
+ .filter(index => !seen.has(index))
58
+ .map(String)
59
+ return { text: restored, missing: [...dropped, ...invalid] }
60
+ },
61
+ }
62
+ }
63
+
64
+ export function missingTokens(translated) {
65
+ const missing = []
66
+ String(translated ?? '').replace(TOKEN_PATTERN, (_match, rawIndex) => {
67
+ missing.push(rawIndex)
68
+ return ''
69
+ })
70
+ return missing
71
+ }
package/src/routes.js ADDED
@@ -0,0 +1,317 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+ import { TARGET_LANGUAGES } from './config.js'
4
+ import { renderMarkdown } from './extract.js'
5
+
6
+ export const PREFIX = '/dsh-bilingual-reader'
7
+ const API_PREFIX = `${PREFIX}/api`
8
+
9
+ const STATIC_FILES = new Map([
10
+ ['/', ['index.html', 'text/html; charset=utf-8']],
11
+ ['/index.html', ['index.html', 'text/html; charset=utf-8']],
12
+ ['/app.js', ['app.js', 'text/javascript; charset=utf-8']],
13
+ ['/style.css', ['style.css', 'text/css; charset=utf-8']],
14
+ ['/favicon.svg', ['favicon.svg', 'image/svg+xml']],
15
+ ])
16
+
17
+ const CSP = [
18
+ "default-src 'self'",
19
+ "img-src 'self' https: data:",
20
+ "style-src 'self' 'unsafe-inline'",
21
+ "script-src 'self'",
22
+ "connect-src 'self'",
23
+ "frame-ancestors 'self'",
24
+ "base-uri 'none'",
25
+ "form-action 'self'",
26
+ ].join('; ')
27
+
28
+ function isLoopbackRequest(req) {
29
+ const address = req.socket?.remoteAddress
30
+ if (address !== '127.0.0.1' && address !== '::1' && address !== '::ffff:127.0.0.1') return false
31
+ const host = req.headers?.host
32
+ if (typeof host !== 'string') return false
33
+ let parsedHost
34
+ try {
35
+ parsedHost = new URL(`http://${host}`)
36
+ } catch {
37
+ return false
38
+ }
39
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(parsedHost.hostname)) return false
40
+ if (req.headers['sec-fetch-site'] === 'cross-site') return false
41
+ const origin = req.headers.origin
42
+ if (origin === undefined) return true
43
+ try {
44
+ return new URL(origin).host === parsedHost.host
45
+ } catch {
46
+ return false
47
+ }
48
+ }
49
+
50
+ function commonHeaders(contentType) {
51
+ return {
52
+ 'content-type': contentType,
53
+ 'cache-control': 'no-store',
54
+ 'referrer-policy': 'no-referrer',
55
+ 'x-content-type-options': 'nosniff',
56
+ 'content-security-policy': CSP,
57
+ }
58
+ }
59
+
60
+ function writeJson(res, status, body) {
61
+ res.writeHead(status, commonHeaders('application/json; charset=utf-8'))
62
+ res.end(JSON.stringify(body))
63
+ }
64
+
65
+ function writeError(res, status, message) {
66
+ writeJson(res, status, { ok: false, error: message })
67
+ }
68
+
69
+ async function readJsonBody(req, maxBytes = 1024 * 1024) {
70
+ const chunks = []
71
+ let size = 0
72
+ for await (const chunk of req) {
73
+ size += chunk.length
74
+ if (size > maxBytes) throw new Error('请求体过大')
75
+ chunks.push(chunk)
76
+ }
77
+ if (chunks.length === 0) return {}
78
+ try {
79
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'))
80
+ return parsed !== null && typeof parsed === 'object' ? parsed : {}
81
+ } catch {
82
+ throw new Error('请求体不是合法 JSON')
83
+ }
84
+ }
85
+
86
+ function decodeSegment(value) {
87
+ try {
88
+ return decodeURIComponent(value)
89
+ } catch {
90
+ return value
91
+ }
92
+ }
93
+
94
+ function summarizeDoc(doc) {
95
+ return {
96
+ id: doc.id,
97
+ title: doc.title,
98
+ url: doc.url,
99
+ siteName: doc.meta?.siteName ?? '',
100
+ targetLang: doc.targetLang,
101
+ status: doc.status,
102
+ error: doc.error,
103
+ progress: doc.progress ?? 0,
104
+ createdAt: doc.createdAt,
105
+ updatedAt: doc.updatedAt,
106
+ truncated: doc.truncated === true,
107
+ stats: doc.stats,
108
+ }
109
+ }
110
+
111
+ function decorateBlocks(blocks) {
112
+ return blocks.map(block => ({
113
+ ...block,
114
+ originalHtml: renderMarkdown(block.original),
115
+ translationHtml: block.translation ? renderMarkdown(block.translation) : '',
116
+ }))
117
+ }
118
+
119
+ function decorateDoc(doc) {
120
+ return { ...summarizeDoc(doc), meta: doc.meta, blocks: decorateBlocks(doc.blocks) }
121
+ }
122
+
123
+ async function serveStatic(res, webDir, rest) {
124
+ const file = STATIC_FILES.get(rest)
125
+ if (file === undefined) {
126
+ writeError(res, 404, 'not found')
127
+ return
128
+ }
129
+ const [name, contentType] = file
130
+ try {
131
+ const body = await readFile(join(webDir, name))
132
+ res.writeHead(200, commonHeaders(contentType))
133
+ res.end(body)
134
+ } catch (error) {
135
+ writeError(res, 500, `读取界面文件失败:${error instanceof Error ? error.message : String(error)}`)
136
+ }
137
+ }
138
+
139
+ async function handleApi(req, res, url, store) {
140
+ await store.ready()
141
+ const rest = url.pathname.slice(API_PREFIX.length)
142
+ const segments = rest.split('/').filter(Boolean)
143
+ const method = req.method ?? 'GET'
144
+
145
+ if (segments.length === 0) {
146
+ writeError(res, 404, 'not found')
147
+ return
148
+ }
149
+
150
+ if (segments[0] === 'health' && segments.length === 1) {
151
+ if (method !== 'GET') return writeError(res, 405, 'method not allowed')
152
+ const stats = store.stats()
153
+ return writeJson(res, 200, {
154
+ ok: true,
155
+ name: 'dsh-bilingual-reader',
156
+ dir: store.dir,
157
+ ai: store.aiEnabled,
158
+ targetLang: store.config.targetLang,
159
+ languages: TARGET_LANGUAGES,
160
+ cache: stats.cache,
161
+ glossary: stats.glossary,
162
+ })
163
+ }
164
+
165
+ if (segments[0] === 'stats' && segments.length === 1) {
166
+ if (method !== 'GET') return writeError(res, 405, 'method not allowed')
167
+ return writeJson(res, 200, { ok: true, ...store.stats() })
168
+ }
169
+
170
+ if (segments[0] === 'read' && segments.length === 1) {
171
+ if (method !== 'POST') return writeError(res, 405, 'method not allowed')
172
+ const body = await readJsonBody(req)
173
+ if (typeof body.url !== 'string' || body.url.trim() === '') {
174
+ return writeError(res, 400, '缺少 url')
175
+ }
176
+ try {
177
+ const doc = await store.createDocFromUrl(body.url.trim(), { targetLang: body.targetLang })
178
+ await store.startJob(doc)
179
+ return writeJson(res, 200, { ok: true, doc: summarizeDoc(doc) })
180
+ } catch (error) {
181
+ return writeError(res, 400, error instanceof Error ? error.message : String(error))
182
+ }
183
+ }
184
+
185
+ if (segments[0] === 'translate' && segments.length === 1) {
186
+ if (method !== 'POST') return writeError(res, 405, 'method not allowed')
187
+ const body = await readJsonBody(req)
188
+ if (typeof body.text !== 'string' || body.text.trim() === '') {
189
+ return writeError(res, 400, '缺少 text')
190
+ }
191
+ try {
192
+ const doc = await store.translateText(body.text, { targetLang: body.targetLang })
193
+ return writeJson(res, 200, {
194
+ ok: true,
195
+ doc: {
196
+ title: '即时翻译',
197
+ targetLang: doc.targetLang,
198
+ status: doc.status,
199
+ error: doc.error,
200
+ progress: doc.progress,
201
+ stats: doc.stats,
202
+ blocks: decorateBlocks(doc.blocks),
203
+ },
204
+ })
205
+ } catch (error) {
206
+ return writeError(res, 400, error instanceof Error ? error.message : String(error))
207
+ }
208
+ }
209
+
210
+ if (segments[0] === 'docs') {
211
+ if (segments.length === 1 && method === 'GET') {
212
+ const limit = Number(url.searchParams.get('limit') ?? 30)
213
+ return writeJson(res, 200, {
214
+ ok: true,
215
+ docs: await store.listDocs({ limit: Number.isFinite(limit) ? limit : 30 }),
216
+ })
217
+ }
218
+ if (segments.length === 2) {
219
+ const id = decodeSegment(segments[1])
220
+ if (method === 'GET') {
221
+ const doc = await store.getDoc(id)
222
+ if (doc === null) return writeError(res, 404, '找不到文档')
223
+ return writeJson(res, 200, { ok: true, doc: decorateDoc(doc) })
224
+ }
225
+ if (method === 'DELETE') {
226
+ try {
227
+ await store.deleteDoc(id)
228
+ return writeJson(res, 200, { ok: true })
229
+ } catch (error) {
230
+ return writeError(res, 400, error instanceof Error ? error.message : String(error))
231
+ }
232
+ }
233
+ return writeError(res, 405, 'method not allowed')
234
+ }
235
+ if (segments.length === 3 && method === 'POST' && segments[2] === 'retry') {
236
+ const id = decodeSegment(segments[1])
237
+ try {
238
+ const doc = await store.retryDoc(id)
239
+ return writeJson(res, 200, { ok: true, doc: summarizeDoc(doc) })
240
+ } catch (error) {
241
+ return writeError(res, 400, error instanceof Error ? error.message : String(error))
242
+ }
243
+ }
244
+ if (segments.length === 3 && method === 'GET' && segments[2] === 'export') {
245
+ const id = decodeSegment(segments[1])
246
+ try {
247
+ const markdown = await store.exportMarkdown(id)
248
+ res.writeHead(200, {
249
+ ...commonHeaders('text/markdown; charset=utf-8'),
250
+ 'content-disposition': `attachment; filename="${id}.bilingual.md"`,
251
+ })
252
+ res.end(markdown)
253
+ } catch (error) {
254
+ writeError(res, 404, error instanceof Error ? error.message : String(error))
255
+ }
256
+ return
257
+ }
258
+ }
259
+
260
+ if (segments[0] === 'glossary' && segments.length === 1) {
261
+ if (method === 'GET') {
262
+ return writeJson(res, 200, { ok: true, terms: store.glossary.list() })
263
+ }
264
+ if (method === 'POST') {
265
+ const body = await readJsonBody(req)
266
+ try {
267
+ if (body.action === 'add') {
268
+ store.glossary.add(body.source, body.target, body.note)
269
+ } else if (body.action === 'remove') {
270
+ store.glossary.remove(body.source)
271
+ } else {
272
+ return writeError(res, 400, 'action 只支持 add / remove')
273
+ }
274
+ await store.glossary.flush()
275
+ return writeJson(res, 200, { ok: true, terms: store.glossary.list() })
276
+ } catch (error) {
277
+ return writeError(res, 400, error instanceof Error ? error.message : String(error))
278
+ }
279
+ }
280
+ return writeError(res, 405, 'method not allowed')
281
+ }
282
+
283
+ writeError(res, 404, 'not found')
284
+ }
285
+
286
+ export function createRoutes({ store, webDir }) {
287
+ return [{
288
+ kind: 'prefix',
289
+ path: PREFIX,
290
+ handler: async (req, res) => {
291
+ if (!isLoopbackRequest(req)) {
292
+ writeError(res, 403, 'forbidden: loopback-only')
293
+ return
294
+ }
295
+ const url = new URL(req.url ?? '/', 'http://localhost')
296
+
297
+ if (url.pathname === API_PREFIX || url.pathname.startsWith(`${API_PREFIX}/`)) {
298
+ try {
299
+ await handleApi(req, res, url, store)
300
+ } catch (error) {
301
+ const message = error instanceof Error ? error.message : String(error)
302
+ writeError(res, 500, message)
303
+ }
304
+ return
305
+ }
306
+
307
+ if (url.pathname === PREFIX) {
308
+ res.writeHead(302, { location: `${PREFIX}/${url.search}` })
309
+ res.end()
310
+ return
311
+ }
312
+
313
+ const rest = url.pathname.slice(PREFIX.length) || '/'
314
+ await serveStatic(res, webDir, rest)
315
+ },
316
+ }]
317
+ }