dsh-bilingual-reader 0.0.0-stage → 0.1.1

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/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
+ }
@@ -0,0 +1,169 @@
1
+ import dns from 'node:dns/promises'
2
+ import net from 'node:net'
3
+
4
+ const BLOCKED_HOST_SUFFIXES = [
5
+ '.localhost',
6
+ '.local',
7
+ '.internal',
8
+ '.home.arpa',
9
+ '.lan',
10
+ ]
11
+
12
+ const BLOCKED_HOSTS = new Set([
13
+ 'localhost',
14
+ 'metadata.google.internal',
15
+ 'metadata',
16
+ ])
17
+
18
+ function ipv4Parts(ip) {
19
+ const parts = ip.split('.').map(Number)
20
+ return parts.length === 4 && parts.every(part => Number.isInteger(part) && part >= 0 && part <= 255)
21
+ ? parts
22
+ : null
23
+ }
24
+
25
+ function isPrivateIpv4(ip, options = {}) {
26
+ const parts = ipv4Parts(ip)
27
+ if (parts === null) return false
28
+ const [a, b] = parts
29
+ if (a === 0 || a === 10 || a === 127) return true
30
+ if (a === 100 && b >= 64 && b <= 127) return true
31
+ if (a === 169 && b === 254) return true
32
+ if (a === 172 && b >= 16 && b <= 31) return true
33
+ if (a === 192 && b === 0) return true
34
+ if (a === 192 && b === 168) return true
35
+ // 198.18.0.0/15 is RFC 2544 benchmarking space, but Clash/Mihomo TUN mode
36
+ // hands out fake IPs from this range for every domain. Blocking it by
37
+ // default would break fetching for a large share of Chinese DSH users.
38
+ // Set DSH_BILINGUAL_BLOCK_FAKE_IP=1 to reject it and keep the strict SSRF
39
+ // guarantee (at the cost of breaking fake-IP TUN mode).
40
+ if (a === 198 && (b === 18 || b === 19)) return options.blockFakeIp === true
41
+ if (a >= 224) return true
42
+ return false
43
+ }
44
+
45
+ function ipv6Hextets(rawIp) {
46
+ const text = rawIp.toLowerCase().split('%')[0]
47
+ if (net.isIP(text) !== 6) return null
48
+ const halves = text.split('::')
49
+ if (halves.length > 2) return null
50
+
51
+ function parsePart(part) {
52
+ if (part === '') return []
53
+ const pieces = []
54
+ for (const piece of part.split(':')) {
55
+ if (piece.includes('.')) {
56
+ const v4 = ipv4Parts(piece)
57
+ if (v4 === null) return null
58
+ pieces.push((v4[0] << 8) | v4[1], (v4[2] << 8) | v4[3])
59
+ } else {
60
+ if (!/^[0-9a-f]{1,4}$/.test(piece)) return null
61
+ pieces.push(Number.parseInt(piece, 16))
62
+ }
63
+ }
64
+ return pieces
65
+ }
66
+
67
+ const head = parsePart(halves[0])
68
+ if (head === null) return null
69
+ if (halves.length === 1) return head.length === 8 ? head : null
70
+ const tail = parsePart(halves[1])
71
+ if (tail === null) return null
72
+ const missing = 8 - head.length - tail.length
73
+ if (missing < 0) return null
74
+ return [...head, ...Array(missing).fill(0), ...tail]
75
+ }
76
+
77
+ function embeddedIpv4(high, low) {
78
+ return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`
79
+ }
80
+
81
+ function isPrivateIpv6(rawIp, options = {}) {
82
+ const h = ipv6Hextets(rawIp)
83
+ if (h === null) return false
84
+ const zeroPrefix = count => h.slice(0, count).every(value => value === 0)
85
+
86
+ if (zeroPrefix(7)) return h[7] === 0 || h[7] === 1
87
+ // IPv4-mapped ::ffff:0:0/96. WHATWG URL canonicalizes every mapped form
88
+ // (::ffff:127.0.0.1, 0:0:0:0:0:ffff:7f00:1) to ::ffff:7f00:1.
89
+ if (zeroPrefix(5) && h[5] === 0xffff) {
90
+ return isPrivateIpv4(embeddedIpv4(h[6], h[7]), options)
91
+ }
92
+ // IPv4-compatible ::/96 (deprecated, but still routable on some stacks).
93
+ if (zeroPrefix(6)) return isPrivateIpv4(embeddedIpv4(h[6], h[7]), options)
94
+ // NAT64 64:ff9b::/96.
95
+ if (h[0] === 0x64 && h[1] === 0xff9b && h.slice(2, 6).every(value => value === 0)) {
96
+ return isPrivateIpv4(embeddedIpv4(h[6], h[7]), options)
97
+ }
98
+ // 6to4 2002::/16 embeds the IPv4 address in the next two hextets.
99
+ if (h[0] === 0x2002) return isPrivateIpv4(embeddedIpv4(h[1], h[2]), options)
100
+ // Unique local fc00::/7, link-local fe80::/10, deprecated site-local fec0::/10.
101
+ if ((h[0] & 0xfe00) === 0xfc00) return true
102
+ if ((h[0] & 0xffc0) === 0xfe80) return true
103
+ if ((h[0] & 0xffc0) === 0xfec0) return true
104
+ // Multicast ff00::/8.
105
+ if ((h[0] & 0xff00) === 0xff00) return true
106
+ // Documentation 2001:db8::/32.
107
+ if (h[0] === 0x2001 && h[1] === 0x0db8) return true
108
+ return false
109
+ }
110
+
111
+ export function isPrivateIp(ip, options = {}) {
112
+ const version = net.isIP(ip)
113
+ if (version === 4) return isPrivateIpv4(ip, options)
114
+ if (version === 6) return isPrivateIpv6(ip, options)
115
+ return false
116
+ }
117
+
118
+ function bareHostname(hostname) {
119
+ return hostname.toLowerCase().replace(/^\[/, '').replace(/\]$/, '').replace(/\.$/, '')
120
+ }
121
+
122
+ /**
123
+ * Resolve and reject hosts that point at loopback, private networks,
124
+ * link-local, CGNAT, multicast, or cloud metadata endpoints. The URL can come
125
+ * from a model, so it must be treated as hostile.
126
+ */
127
+ export async function assertPublicUrl(rawUrl, config = {}) {
128
+ let url
129
+ try {
130
+ url = new URL(rawUrl)
131
+ } catch {
132
+ throw new Error('URL 格式不正确,需要以 http:// 或 https:// 开头')
133
+ }
134
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
135
+ throw new Error(`不支持的协议:${url.protocol};只允许 http/https`)
136
+ }
137
+ const host = bareHostname(url.hostname)
138
+ if (host === '') throw new Error('URL 缺少主机名')
139
+ if (config.allowPrivate === true) return url
140
+
141
+ if (BLOCKED_HOSTS.has(host)) throw new Error(`拒绝访问本机/内网地址:${host}`)
142
+ for (const suffix of BLOCKED_HOST_SUFFIXES) {
143
+ if (host.endsWith(suffix)) throw new Error(`拒绝访问本机/内网地址:${host}`)
144
+ }
145
+
146
+ const ipOptions = { blockFakeIp: config.blockFakeIp === true }
147
+ if (net.isIP(host) !== 0) {
148
+ if (isPrivateIp(host, ipOptions)) throw new Error(`拒绝访问本机/内网地址:${host}`)
149
+ return url
150
+ }
151
+
152
+ let addresses
153
+ try {
154
+ addresses = await dns.lookup(host, { all: true, verbatim: true })
155
+ } catch {
156
+ throw new Error(`无法解析域名:${host}`)
157
+ }
158
+ if (addresses.length === 0) throw new Error(`域名没有可用地址:${host}`)
159
+ for (const { address } of addresses) {
160
+ if (isPrivateIp(address, ipOptions)) {
161
+ throw new Error(`域名 ${host} 解析到内网地址 ${address},已拒绝`)
162
+ }
163
+ }
164
+ return url
165
+ }
166
+
167
+ export async function assertResponseUrl(responseUrl, config) {
168
+ return assertPublicUrl(responseUrl, config)
169
+ }
package/src/segment.js ADDED
@@ -0,0 +1,116 @@
1
+ const TRANSLATABLE_TYPES = new Set(['heading', 'paragraph', 'list', 'table', 'blockquote'])
2
+
3
+ function detectType(raw) {
4
+ const lines = raw.split('\n')
5
+ const first = lines[0].trim()
6
+ if (/^(```|~~~)/.test(first)) return 'code'
7
+ if (lines.length > 1 && lines.filter(line => /^\s*\|.*\|\s*$/.test(line)).length >= 2) return 'table'
8
+ if (/^#{1,6}\s+/.test(first)) return 'heading'
9
+ if (/^\s*>/.test(first)) return 'blockquote'
10
+ if (/^\s*([-*+]|\d+\.)\s+/.test(first)) return 'list'
11
+ if (/^(\*\s*){3,}$|^(-\s*){3,}$|^(_\s*){3,}$/.test(first)) return 'hr'
12
+ if (/^!\[[^\]]*\]\([^)]*\)\s*$/.test(first)) return 'image'
13
+ return 'paragraph'
14
+ }
15
+
16
+ /**
17
+ * True when a block has enough prose to be worth a model request. Code,
18
+ * horizontal rules, image-only blocks and pure markdown scaffolding are
19
+ * skipped. Inline code, URLs and HTML tags are stripped before counting.
20
+ */
21
+ export function isTranslatable(raw, type = detectType(raw)) {
22
+ if (!TRANSLATABLE_TYPES.has(type)) return false
23
+ const stripped = String(raw ?? '')
24
+ .replace(/```[\s\S]*?```/g, ' ')
25
+ .replace(/`[^`\n]*`/g, ' ')
26
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
27
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
28
+ .replace(/<[^>\n]+>/g, ' ')
29
+ .replace(/https?:\/\/\S+/g, ' ')
30
+ .replace(/[#>*_~|=-]/g, ' ')
31
+ const cjk = (stripped.match(/[぀-ヿ㐀-䶿一-鿿가-힯]/g) || []).length
32
+ const latin = (stripped.match(/[A-Za-z]/g) || []).length
33
+ return cjk + latin >= 2
34
+ }
35
+
36
+ export function makeBlock(raw) {
37
+ const original = String(raw ?? '').trim()
38
+ if (original === '') return null
39
+ const type = detectType(original)
40
+ return {
41
+ type,
42
+ original,
43
+ translatable: isTranslatable(original, type),
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Split Markdown into block-level units. Fenced code stays atomic and is never
49
+ * translated; headings, paragraphs, list blocks, blockquotes and tables are
50
+ * kept together so the model sees the same structure the reader does.
51
+ */
52
+ export function segmentMarkdown(markdown, options = {}) {
53
+ const maxBlocks = options.maxBlocks ?? 400
54
+ const lines = String(markdown ?? '').replace(/\r\n/g, '\n').split('\n')
55
+ const blocks = []
56
+ let buffer = []
57
+ let fence = null
58
+
59
+ function flush() {
60
+ if (buffer.length === 0) return
61
+ const block = makeBlock(buffer.join('\n'))
62
+ buffer = []
63
+ if (block !== null) blocks.push(block)
64
+ }
65
+
66
+ for (const line of lines) {
67
+ const fenceMatch = /^\s*(```+|~~~+)/.exec(line)
68
+ if (fence !== null) {
69
+ buffer.push(line)
70
+ if (line.trim().startsWith(fence)) {
71
+ flush()
72
+ fence = null
73
+ }
74
+ continue
75
+ }
76
+ if (fenceMatch !== null) {
77
+ flush()
78
+ fence = fenceMatch[1]
79
+ buffer.push(line)
80
+ continue
81
+ }
82
+ if (line.trim() === '') {
83
+ flush()
84
+ continue
85
+ }
86
+ buffer.push(line)
87
+ }
88
+ flush()
89
+
90
+ if (blocks.length > maxBlocks) {
91
+ return { blocks: blocks.slice(0, maxBlocks), truncated: true }
92
+ }
93
+ return { blocks, truncated: false }
94
+ }
95
+
96
+ export function bilingualMarkdown(blocks) {
97
+ const parts = []
98
+ for (const block of blocks) {
99
+ if (block.translatable && typeof block.translation === 'string' && block.translation.trim() !== '') {
100
+ parts.push(block.original, block.translation)
101
+ } else {
102
+ parts.push(block.original)
103
+ }
104
+ }
105
+ return parts.join('\n\n').trim()
106
+ }
107
+
108
+ export function translationMarkdown(blocks) {
109
+ const parts = blocks.map(block => {
110
+ if (block.translatable && typeof block.translation === 'string' && block.translation.trim() !== '') {
111
+ return block.translation
112
+ }
113
+ return block.original
114
+ })
115
+ return parts.join('\n\n').trim()
116
+ }