@li-canghai/dsh-paper 0.0.0-stage → 0.8.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/LICENSE +21 -0
- package/README.md +137 -2
- package/cordis.patch.yml +4 -0
- package/lib/annotate-tool.js +334 -0
- package/lib/arxiv-id.js +74 -0
- package/lib/asset-routes.js +210 -0
- package/lib/bibliography-formats.js +126 -0
- package/lib/bibliography-import.js +105 -0
- package/lib/bibliography-service.js +43 -0
- package/lib/bibliography.js +42 -0
- package/lib/block-authors.js +292 -0
- package/lib/block-cache.js +39 -0
- package/lib/blocks-markdown.js +157 -0
- package/lib/blocks-reconcile.js +218 -0
- package/lib/blocks.js +1344 -0
- package/lib/citation-metadata.js +260 -0
- package/lib/citation-styles.js +120 -0
- package/lib/client-parts/01-pure-helpers.js +2607 -0
- package/lib/client.js +9569 -0
- package/lib/code-source.js +68 -0
- package/lib/concurrency-gate.js +91 -0
- package/lib/context.js +233 -0
- package/lib/csl/SOURCES.md +10 -0
- package/lib/csl/gb-t-7714.csl +441 -0
- package/lib/csl/ieee.csl +520 -0
- package/lib/csl/locales-zh-CN.xml +438 -0
- package/lib/csl/nature.csl +190 -0
- package/lib/discussion.js +400 -0
- package/lib/documents.js +67 -0
- package/lib/export.js +848 -0
- package/lib/file-lock.js +177 -0
- package/lib/gloss.js +181 -0
- package/lib/glossary.js +279 -0
- package/lib/index.js +3862 -0
- package/lib/inline-html.js +53 -0
- package/lib/install-dependency.js +120 -0
- package/lib/item-ops.js +83 -0
- package/lib/job-facade.js +58 -0
- package/lib/json-store.js +54 -0
- package/lib/library-model.js +132 -0
- package/lib/library-service.js +180 -0
- package/lib/library-tool.js +982 -0
- package/lib/library.js +814 -0
- package/lib/markdown-assets.js +138 -0
- package/lib/markdown-literals.js +93 -0
- package/lib/metadata-enrichment.js +516 -0
- package/lib/metadata-fetch.js +146 -0
- package/lib/metadata-node.js +158 -0
- package/lib/metadata-proxy.ps1 +35 -0
- package/lib/mineru-config.js +95 -0
- package/lib/mineru-sdk-helper.py +123 -0
- package/lib/mineru-sdk.js +182 -0
- package/lib/mineru.js +268 -0
- package/lib/mirror-export.js +240 -0
- package/lib/outline.js +296 -0
- package/lib/page-image-helper.py +294 -0
- package/lib/page-image.js +454 -0
- package/lib/paper-metadata.js +242 -0
- package/lib/parse-export.js +631 -0
- package/lib/pdf-analysis-tool.js +750 -0
- package/lib/pdf-metadata-helper.py +75 -0
- package/lib/pdf-metadata.js +141 -0
- package/lib/pdf-page.js +183 -0
- package/lib/pdf-scan.js +134 -0
- package/lib/pdf-text.js +68 -0
- package/lib/picker.js +305 -0
- package/lib/portable.js +379 -0
- package/lib/purge.js +170 -0
- package/lib/read-tool.js +660 -0
- package/lib/reader-store.js +497 -0
- package/lib/reading-order.js +207 -0
- package/lib/rename-document.js +480 -0
- package/lib/rename.js +372 -0
- package/lib/renderer-status.js +161 -0
- package/lib/resolver.js +1152 -0
- package/lib/result-archive.js +157 -0
- package/lib/revisions.js +330 -0
- package/lib/search-database.js +62 -0
- package/lib/search-index.js +601 -0
- package/lib/search-scan.js +185 -0
- package/lib/search-source.js +23 -0
- package/lib/search-terms.js +539 -0
- package/lib/section-audit.js +209 -0
- package/lib/selection-message.js +332 -0
- package/lib/serial-tail.js +21 -0
- package/lib/slicing.js +425 -0
- package/lib/source-resolver.js +581 -0
- package/lib/stem-repair.js +189 -0
- package/lib/storage.js +562 -0
- package/lib/store-paths.js +253 -0
- package/lib/table-gfm.js +236 -0
- package/lib/tasks.js +270 -0
- package/lib/tex-align.js +509 -0
- package/lib/tex-blocks.js +653 -0
- package/lib/tex-fetch.js +455 -0
- package/lib/tex-figures.js +140 -0
- package/lib/tex-inline.js +166 -0
- package/lib/tex-merge.js +279 -0
- package/lib/tex-pipeline.js +242 -0
- package/lib/tex-prepare.js +746 -0
- package/lib/tex-tables.js +210 -0
- package/lib/text-similarity.js +85 -0
- package/lib/tool-contract.js +86 -0
- package/lib/tool-host.js +1058 -0
- package/lib/tool-identity.js +214 -0
- package/lib/translatable-text.js +48 -0
- package/lib/translate-prompts.js +709 -0
- package/lib/translate-queue.js +418 -0
- package/lib/translate-task.js +158 -0
- package/lib/translate.js +909 -0
- package/lib/update-check.js +438 -0
- package/lib/update-contracts.js +75 -0
- package/lib/usage.js +282 -0
- package/package.json +55 -4
package/lib/tex-fetch.js
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 获取层:把 arXiv 的 e-print(LaTeX 源码包)取到本地并解成内存里的文件表。
|
|
3
|
+
*
|
|
4
|
+
* 这一层只回答一个问题——这个 arXiv 编号的源码包能不能拿到、里面有哪些文件。
|
|
5
|
+
* 主文件判定、宏展开、切块都不归它管。
|
|
6
|
+
*
|
|
7
|
+
* 四条贯穿全文件的约束:
|
|
8
|
+
* 1. **不可用是常态,不是异常**:返回 `{state:'degraded', reason}` 而不是抛错,让上层
|
|
9
|
+
* 统一走「退回 MinerU」这条路。抛错误会让调用方以为解析失败。
|
|
10
|
+
* 2. **绝不信任远端**:tar 头必须过 checksum,条目名必须过路径规范化(拒绝绝对路径与
|
|
11
|
+
* \\.. 段),任何一项不合法就整包丢弃——这是唯一可能把文件写到目录外的入口。
|
|
12
|
+
* 3. **上限硬编码**:单文件 32MB、解压总量 256MB、条目 5000。GPT-3 的包是 173 个文件
|
|
13
|
+
* 281KB 正文,正常论文远低于此;超限说明这不是一篇论文的包。
|
|
14
|
+
* 4. **缓存按编号+版本键控**:同一篇重解析不重复下载,但版本变了必须换一份——
|
|
15
|
+
* 按不带版本的编号缓存会让 v1 的字节冒充 v2。
|
|
16
|
+
*/
|
|
17
|
+
import { createHash } from 'node:crypto'
|
|
18
|
+
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
19
|
+
import { join } from 'node:path'
|
|
20
|
+
import { gunzipSync } from 'node:zlib'
|
|
21
|
+
|
|
22
|
+
/** 降级原因码。字符串常量的唯一真源:日志、notice、旁挂 JSON 都从这里取。 */
|
|
23
|
+
export const DEGRADE_REASON = {
|
|
24
|
+
NETWORK: 'network',
|
|
25
|
+
NO_TEX: 'no-tex',
|
|
26
|
+
NO_MAIN: 'no-main',
|
|
27
|
+
PDF_ONLY: 'pdf-only',
|
|
28
|
+
MACROS: 'macros',
|
|
29
|
+
EMPTY: 'empty',
|
|
30
|
+
ALIGN: 'align',
|
|
31
|
+
MISMATCH: 'mismatch',
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 单文件上限 32MB:正常论文最大的 .tex 是几 MB,最大的图是十几 MB。 */
|
|
35
|
+
const MAX_FILE_BYTES = 32 * 1024 * 1024
|
|
36
|
+
/** 解压总量上限 256MB:防 gzip 炸弹。 */
|
|
37
|
+
const MAX_TOTAL_BYTES = 256 * 1024 * 1024
|
|
38
|
+
/** 条目数上限 5000:GPT-3 的包是 173 个文件。 */
|
|
39
|
+
const MAX_FILES = 5000
|
|
40
|
+
/** tar 数据块大小。 */
|
|
41
|
+
const TAR_BLOCK = 512
|
|
42
|
+
/** 下载缓存默认上限。 */
|
|
43
|
+
const DEFAULT_CACHE_BYTES = 500 * 1024 * 1024
|
|
44
|
+
/** 单次下载超时:e-print 一般 1-10s,30s 已经很宽松。 */
|
|
45
|
+
const DEFAULT_TIMEOUT_MS = 30_000
|
|
46
|
+
/**
|
|
47
|
+
* 下载尝试次数。
|
|
48
|
+
*
|
|
49
|
+
* 实测网络抖动是常态:一次性跑 60 篇里有 11 篇报了 "fetch failed"(连接被重置 / 瞬时不可达),
|
|
50
|
+
* 隔一会儿单独重试全部成功,源码包本身是好的。一次抖动就让整篇退回 MinerU 不合算 ——
|
|
51
|
+
* 重试的代价是几秒等待,收益是这篇论文的正文准确率。
|
|
52
|
+
*/
|
|
53
|
+
const FETCH_ATTEMPTS = 3
|
|
54
|
+
/** 退避基数与上限:第 1 次等 0.8s,第 2 次 1.6s,封顶 8s。 */
|
|
55
|
+
const RETRY_BASE_MS = 800
|
|
56
|
+
const RETRY_MAX_MS = 8_000
|
|
57
|
+
/** 抖动上限:多篇同时重试时不要踩同一个节拍(arXiv 的限速按时间窗算)。 */
|
|
58
|
+
const RETRY_JITTER_MS = 250
|
|
59
|
+
|
|
60
|
+
const TEX_SIGNATURE = /(?:^|[^\\])\\(?:documentclass|documentstyle|begin\s*\{document\}|input\s*\{|section\s*\*?\{)/
|
|
61
|
+
|
|
62
|
+
const ARXIV_ID = /^(\d{4}\.\d{4,5})(v\d+)?$/
|
|
63
|
+
const ARXIV_OLD_ID = /^([a-z][a-z-]*(?:\.[A-Z]{2})?\/\d{7})(v\d+)?$/
|
|
64
|
+
const ARXIV_ABS = /arxiv\.org\/(?:abs|pdf)\/(.+?)(?:\.pdf)?$/i
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 从裸编号、abs 链接或 pdf 链接里取出 `{id, version}`。
|
|
68
|
+
*
|
|
69
|
+
* 为什么接受链接:库里的条目存的是 `sourceUrl`(`https://arxiv.org/pdf/2401.04088v2`),
|
|
70
|
+
* 要让「重解析」复用同一条记录,就得能从这个地址反推回编号与版本。
|
|
71
|
+
* 取不出来返回 null(不是抛错):调用方据此走 SKIP。
|
|
72
|
+
*/
|
|
73
|
+
export function normalizeArxivId(value) {
|
|
74
|
+
const text = String(value ?? '').trim()
|
|
75
|
+
if (text === '') return null
|
|
76
|
+
const candidate = /^https?:/i.test(text) ? (ARXIV_ABS.exec(text)?.[1] ?? '') : text
|
|
77
|
+
if (candidate === '') return null
|
|
78
|
+
const modern = ARXIV_ID.exec(candidate)
|
|
79
|
+
if (modern) return { id: modern[1], version: modern[2] ?? '' }
|
|
80
|
+
const legacy = ARXIV_OLD_ID.exec(candidate)
|
|
81
|
+
if (legacy) return { id: legacy[1], version: legacy[2] ?? '' }
|
|
82
|
+
return null
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** e-print 地址。带版本时下的是那一版,不带版本时 arXiv 给最新版。 */
|
|
86
|
+
export function eprintUrl(id, version = '') {
|
|
87
|
+
return `https://arxiv.org/e-print/${id}${version}`
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 把条目名规范化成**相对包根的安全路径**;不安全时返回 null。
|
|
92
|
+
*
|
|
93
|
+
* 拒绝四类:绝对路径(`/x`、`C:/x`)、任何 `..` 段、空名、控制字符。
|
|
94
|
+
* 反斜杠先转正斜杠:tar 在 Windows 上打的包会用反斜杠,而 `..\\x` 不会命中 `../` 判定。
|
|
95
|
+
*/
|
|
96
|
+
export function sanitizeEntryName(name) {
|
|
97
|
+
const raw = String(name ?? '')
|
|
98
|
+
if (raw === '' || /[\u0000-\u001f\u007f]/.test(raw)) return null
|
|
99
|
+
const slash = raw.replace(/\\/g, '/')
|
|
100
|
+
if (slash.startsWith('/') || /^[a-zA-Z]:/.test(slash)) return null
|
|
101
|
+
const parts = []
|
|
102
|
+
for (const part of slash.split('/')) {
|
|
103
|
+
if (part === '' || part === '.') continue
|
|
104
|
+
if (part === '..') return null
|
|
105
|
+
parts.push(part)
|
|
106
|
+
}
|
|
107
|
+
return parts.length === 0 ? null : parts.join('/')
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 八进制字段;GNU base-256 形态(首字节 0x80)也认。非法返回 null。 */
|
|
111
|
+
function tarNumber(buffer, offset, length) {
|
|
112
|
+
const first = buffer[offset]
|
|
113
|
+
if (first === undefined) return null
|
|
114
|
+
if ((first & 0x80) !== 0) {
|
|
115
|
+
let value = first & 0x7f
|
|
116
|
+
for (let index = 1; index < length; index += 1) value = value * 256 + buffer[offset + index]
|
|
117
|
+
return Number.isFinite(value) ? value : null
|
|
118
|
+
}
|
|
119
|
+
const text = buffer.subarray(offset, offset + length).toString('latin1').replace(/\0/g, ' ').trim()
|
|
120
|
+
if (text === '') return 0
|
|
121
|
+
if (!/^[0-7]+$/.test(text)) return null
|
|
122
|
+
return Number.parseInt(text, 8)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 一个 512 字节头块是否合法:有 ustar 标识,且 checksum 对得上(signed / unsigned 两种算法)。 */
|
|
126
|
+
function isTarHeader(block) {
|
|
127
|
+
if (block.length < TAR_BLOCK) return false
|
|
128
|
+
const magic = block.subarray(257, 262).toString('latin1')
|
|
129
|
+
if (magic !== 'ustar') return false
|
|
130
|
+
const stored = tarNumber(block, 148, 8)
|
|
131
|
+
if (stored === null) return false
|
|
132
|
+
let unsigned = 0
|
|
133
|
+
let signed = 0
|
|
134
|
+
for (let index = 0; index < TAR_BLOCK; index += 1) {
|
|
135
|
+
const byte = index >= 148 && index < 156 ? 0x20 : block[index]
|
|
136
|
+
unsigned += byte
|
|
137
|
+
signed += byte > 127 ? byte - 256 : byte
|
|
138
|
+
}
|
|
139
|
+
return stored === unsigned || stored === signed
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 一个块是否全零(tar 的结束标记)。 */
|
|
143
|
+
function isZeroBlock(block) {
|
|
144
|
+
for (let index = 0; index < block.length; index += 1) if (block[index] !== 0) return false
|
|
145
|
+
return true
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** pax 扩展头的 `key=value` 记录(每条前置十进制长度)。只取 path。 */
|
|
149
|
+
function paxPath(text) {
|
|
150
|
+
let path = ''
|
|
151
|
+
let cursor = 0
|
|
152
|
+
while (cursor < text.length) {
|
|
153
|
+
const space = text.indexOf(' ', cursor)
|
|
154
|
+
if (space === -1) break
|
|
155
|
+
const length = Number.parseInt(text.slice(cursor, space), 10)
|
|
156
|
+
if (!Number.isInteger(length) || length <= 0) break
|
|
157
|
+
const record = text.slice(space + 1, cursor + length - 1)
|
|
158
|
+
const equals = record.indexOf('=')
|
|
159
|
+
if (equals > 0 && record.slice(0, equals) === 'path') path = record.slice(equals + 1)
|
|
160
|
+
cursor += length
|
|
161
|
+
}
|
|
162
|
+
return path
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 解析 tar,返回普通文件条目。
|
|
167
|
+
*
|
|
168
|
+
* 不抛错的地方:未知 typeflag、重复条目名(后到覆盖先到)、空名——都只是跳过。
|
|
169
|
+
* 抛错的地方只有一处:头块 checksum 不对。那不是「包里有怪东西」,而是**这不是 tar**,
|
|
170
|
+
* 继续往下解析只会把二进制垃圾当成文件名。
|
|
171
|
+
*/
|
|
172
|
+
export function readTar(buffer) {
|
|
173
|
+
const files = []
|
|
174
|
+
const seen = new Set()
|
|
175
|
+
let cursor = 0
|
|
176
|
+
let pendingLongName = ''
|
|
177
|
+
let totalBytes = 0
|
|
178
|
+
while (cursor + TAR_BLOCK <= buffer.length) {
|
|
179
|
+
const header = buffer.subarray(cursor, cursor + TAR_BLOCK)
|
|
180
|
+
if (isZeroBlock(header)) break
|
|
181
|
+
if (!isTarHeader(header)) throw new Error('tar 头校验失败')
|
|
182
|
+
const size = tarNumber(header, 124, 12)
|
|
183
|
+
if (size === null || size < 0) throw new Error('tar 条目长度非法')
|
|
184
|
+
const typeflag = String.fromCharCode(header[156] || 0x30)
|
|
185
|
+
const dataStart = cursor + TAR_BLOCK
|
|
186
|
+
const dataEnd = dataStart + size
|
|
187
|
+
if (dataEnd > buffer.length) throw new Error('tar 条目越界')
|
|
188
|
+
const data = buffer.subarray(dataStart, dataEnd)
|
|
189
|
+
cursor = dataStart + Math.ceil(size / TAR_BLOCK) * TAR_BLOCK
|
|
190
|
+
|
|
191
|
+
if (typeflag === 'x' || typeflag === 'g') {
|
|
192
|
+
// pax:下一条目用更长的路径(>100 字符,或含无法用 prefix 表达的多字节名)。
|
|
193
|
+
const override = paxPath(data.toString('utf8'))
|
|
194
|
+
if (override !== '') pendingLongName = override
|
|
195
|
+
continue
|
|
196
|
+
}
|
|
197
|
+
if (typeflag === 'L') {
|
|
198
|
+
// GNU 长名:后面紧跟的就是长路径本身。
|
|
199
|
+
pendingLongName = data.toString('utf8').replace(/\0+$/, '')
|
|
200
|
+
continue
|
|
201
|
+
}
|
|
202
|
+
if (typeflag !== '0' && typeflag !== '\0' && typeflag !== '7') continue
|
|
203
|
+
|
|
204
|
+
const prefix = header.subarray(345, 500).toString('latin1').replace(/\0+$/, '').trim()
|
|
205
|
+
const name = pendingLongName !== '' ? pendingLongName : (prefix === '' ? '' : prefix + '/') + header.subarray(0, 100).toString('latin1').replace(/\0+$/, '')
|
|
206
|
+
pendingLongName = ''
|
|
207
|
+
const safe = sanitizeEntryName(name)
|
|
208
|
+
if (safe === null) continue
|
|
209
|
+
if (data.length > MAX_FILE_BYTES) continue
|
|
210
|
+
totalBytes += data.length
|
|
211
|
+
if (totalBytes > MAX_TOTAL_BYTES || files.length >= MAX_FILES) throw new Error('源码包超出解包上限')
|
|
212
|
+
if (seen.has(safe)) continue
|
|
213
|
+
seen.add(safe)
|
|
214
|
+
files.push({ name: safe, bytes: Buffer.from(data) })
|
|
215
|
+
}
|
|
216
|
+
return files
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** gzip 魔数。 */
|
|
220
|
+
function isGzip(buffer) {
|
|
221
|
+
return buffer.length >= 2 && buffer[0] === 0x1f && buffer[1] === 0x8b
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** 看起来像 tar:首块是合法头。 */
|
|
225
|
+
function isTar(buffer) {
|
|
226
|
+
return buffer.length >= TAR_BLOCK && isTarHeader(buffer.subarray(0, TAR_BLOCK))
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* 解一个 e-print 响应体,返回文件表。
|
|
231
|
+
*
|
|
232
|
+
* 三种形态都实测见过:
|
|
233
|
+
* - `gzip(tar)`:现代论文的绝大多数(40/40 抽样);
|
|
234
|
+
* - 裸 `tar`:老论文,arXiv 只在客户端加压;
|
|
235
|
+
* - 裸单个 `.tex`:极老论文(1994 年前后),整个 e-print 就是一份源码。
|
|
236
|
+
*
|
|
237
|
+
* 三种都不是时返回空数组,让上层判 no-tex —— 这里不抛错,因为「包解不开」与「包里没源码」
|
|
238
|
+
* 对上层是同一个动作(退回 MinerU)。
|
|
239
|
+
*/
|
|
240
|
+
export function unpackEprint(bytes) {
|
|
241
|
+
const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes ?? [])
|
|
242
|
+
if (buffer.length === 0) return []
|
|
243
|
+
let body = buffer
|
|
244
|
+
if (isGzip(buffer)) {
|
|
245
|
+
try {
|
|
246
|
+
body = gunzipSync(buffer, { maxOutputLength: MAX_TOTAL_BYTES })
|
|
247
|
+
} catch {
|
|
248
|
+
return []
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (isTar(body)) {
|
|
252
|
+
try {
|
|
253
|
+
return readTar(body)
|
|
254
|
+
} catch {
|
|
255
|
+
return []
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
// 裸单文件:只接受「看起来是 TeX」的内容,避免把一段 HTML 错误页当源码。
|
|
259
|
+
const text = body.toString('utf8')
|
|
260
|
+
if (TEX_SIGNATURE.test(text.slice(0, 4096))) {
|
|
261
|
+
return [{ name: 'main.tex', bytes: Buffer.from(text, 'utf8') }]
|
|
262
|
+
}
|
|
263
|
+
return []
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** 缓存键:编号 + 版本。版本为空表示「最新版」,与带版本的键刻意不同(见文件头第 4 条)。 */
|
|
267
|
+
export function eprintCacheKey(id, version = '') {
|
|
268
|
+
return `${id}${version}`
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** 缓存文件路径。文件名取键的 sha256 前 40 位,避免老式编号里的斜杠变成目录。 */
|
|
272
|
+
export function eprintCachePath(cacheDir, id, version = '') {
|
|
273
|
+
return join(cacheDir, `${createHash('sha256').update(eprintCacheKey(id, version)).digest('hex').slice(0, 40)}.bin`)
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* 按总大小修剪缓存(LRU:最久未访问的先删)。
|
|
278
|
+
*
|
|
279
|
+
* 用 mtime 而不是 atime:Windows 上 atime 默认不更新(NtfsDisableLastAccessUpdate),
|
|
280
|
+
* 按它排序等于随机删。命中缓存时调用方负责 touch 一下 mtime。
|
|
281
|
+
*/
|
|
282
|
+
export async function pruneEprintCache(cacheDir, maxBytes = DEFAULT_CACHE_BYTES) {
|
|
283
|
+
let entries
|
|
284
|
+
try {
|
|
285
|
+
entries = await readdir(cacheDir, { withFileTypes: true })
|
|
286
|
+
} catch {
|
|
287
|
+
return { removed: 0, bytes: 0 }
|
|
288
|
+
}
|
|
289
|
+
const rows = []
|
|
290
|
+
let total = 0
|
|
291
|
+
for (const entry of entries) {
|
|
292
|
+
if (!entry.isFile() || !entry.name.endsWith('.bin')) continue
|
|
293
|
+
const path = join(cacheDir, entry.name)
|
|
294
|
+
try {
|
|
295
|
+
const info = await stat(path)
|
|
296
|
+
rows.push({ path, size: info.size, at: info.mtimeMs })
|
|
297
|
+
total += info.size
|
|
298
|
+
} catch {
|
|
299
|
+
// 并发删除:跳过即可。
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (total <= maxBytes) return { removed: 0, bytes: total }
|
|
303
|
+
rows.sort((left, right) => left.at - right.at)
|
|
304
|
+
let removed = 0
|
|
305
|
+
for (const row of rows) {
|
|
306
|
+
if (total <= maxBytes) break
|
|
307
|
+
try {
|
|
308
|
+
await rm(row.path, { force: true })
|
|
309
|
+
total -= row.size
|
|
310
|
+
removed += 1
|
|
311
|
+
} catch {
|
|
312
|
+
// 删不掉就留着,下一轮再试。
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return { removed, bytes: total }
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** 缓存文件是否可用:存在且非空。 */
|
|
319
|
+
async function cacheHit(path) {
|
|
320
|
+
try {
|
|
321
|
+
const info = await stat(path)
|
|
322
|
+
return info.isFile() && info.size > 0
|
|
323
|
+
} catch {
|
|
324
|
+
return false
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* 取一份 e-print 源码包。
|
|
330
|
+
*
|
|
331
|
+
* @param {{id: string, version?: string, fetchImpl?: Function, cacheDir?: string,
|
|
332
|
+
* timeoutMs?: number, maxCacheBytes?: number, logger?: object}} input
|
|
333
|
+
* @returns {Promise<{state: 'ready', files: Array<{name: string, bytes: Buffer}>, source: 'cache'|'network'}
|
|
334
|
+
* | {state: 'degraded', reason: string, detail: string}>}
|
|
335
|
+
*/
|
|
336
|
+
export async function fetchEprint({
|
|
337
|
+
id,
|
|
338
|
+
version = '',
|
|
339
|
+
fetchImpl = globalThis.fetch,
|
|
340
|
+
cacheDir = '',
|
|
341
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
342
|
+
maxCacheBytes = DEFAULT_CACHE_BYTES,
|
|
343
|
+
logger,
|
|
344
|
+
sleep = defaultSleep,
|
|
345
|
+
} = {}) {
|
|
346
|
+
const normalized = normalizeArxivId(id === undefined ? '' : `${id}${version}`) ?? normalizeArxivId(id)
|
|
347
|
+
if (normalized === null) return { state: 'degraded', reason: DEGRADE_REASON.NETWORK, detail: '不是合法的 arXiv 编号' }
|
|
348
|
+
const useVersion = version === '' ? normalized.version : version
|
|
349
|
+
const url = eprintUrl(normalized.id, useVersion)
|
|
350
|
+
const cachePath = cacheDir === '' ? '' : eprintCachePath(cacheDir, normalized.id, useVersion)
|
|
351
|
+
|
|
352
|
+
if (cachePath !== '') {
|
|
353
|
+
if (await cacheHit(cachePath)) {
|
|
354
|
+
try {
|
|
355
|
+
const bytes = await readFile(cachePath)
|
|
356
|
+
const files = unpackEprint(bytes)
|
|
357
|
+
// 缓存里的字节再解一次:解包是纯 CPU 且很便宜(透明 gzip 几毫秒),
|
|
358
|
+
// 而把解好的文件表另存一份就等于把缓存做成两套失效逻辑。
|
|
359
|
+
if (files.length > 0) {
|
|
360
|
+
await touch(cachePath)
|
|
361
|
+
return { state: 'ready', files, source: 'cache' }
|
|
362
|
+
}
|
|
363
|
+
// 缓存内容解不出文件:当作坏缓存删掉,往下走网络。
|
|
364
|
+
await rm(cachePath, { force: true })
|
|
365
|
+
} catch (error) {
|
|
366
|
+
logger?.warn?.(`dsh-paper tex: 读取源码缓存失败,重新下载:${String(error?.message ?? error).slice(0, 120)}`)
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
let lastError = ''
|
|
372
|
+
let delay = 0
|
|
373
|
+
for (let attempt = 0; attempt < FETCH_ATTEMPTS; attempt += 1) {
|
|
374
|
+
// 退避排在这一次之前:第 1 次立刻试,之后每次等上一轮算出来的时长。
|
|
375
|
+
if (attempt > 0 && delay > 0) await sleep(delay)
|
|
376
|
+
try {
|
|
377
|
+
const response = await fetchImpl(url, {
|
|
378
|
+
headers: { 'user-agent': 'dsh-paper (LaTeX source fetch)', accept: 'application/gzip, application/x-eprint, application/octet-stream' },
|
|
379
|
+
signal: typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(timeoutMs) : undefined,
|
|
380
|
+
})
|
|
381
|
+
if (response?.status === 404 || response?.status === 403) {
|
|
382
|
+
return { state: 'degraded', reason: DEGRADE_REASON.NETWORK, detail: `e-print 不可用:HTTP ${response.status}` }
|
|
383
|
+
}
|
|
384
|
+
// 429 与 5xx 是「这次不行、下次可能行」:先看 Retry-After,没有就按指数退避。
|
|
385
|
+
if (response?.status === 429 || (response?.status ?? 0) >= 500) {
|
|
386
|
+
lastError = 'HTTP ' + response.status
|
|
387
|
+
delay = retryAfterMs(response) ?? backoffMs(attempt)
|
|
388
|
+
continue
|
|
389
|
+
}
|
|
390
|
+
if (!response?.ok) throw new Error(`HTTP ${response?.status}`)
|
|
391
|
+
const bytes = Buffer.from(await response.arrayBuffer())
|
|
392
|
+
const files = unpackEprint(bytes)
|
|
393
|
+
if (files.length === 0) {
|
|
394
|
+
return { state: 'degraded', reason: DEGRADE_REASON.NO_TEX, detail: 'e-print 里没有可识别的源码文件' }
|
|
395
|
+
}
|
|
396
|
+
if (cachePath !== '') {
|
|
397
|
+
await mkdir(cacheDir, { recursive: true })
|
|
398
|
+
const temp = `${cachePath}.${process.pid}.tmp`
|
|
399
|
+
try {
|
|
400
|
+
await writeFile(temp, bytes, { flag: 'wx' })
|
|
401
|
+
await rename(temp, cachePath)
|
|
402
|
+
await pruneEprintCache(cacheDir, maxCacheBytes)
|
|
403
|
+
} catch (error) {
|
|
404
|
+
await rm(temp, { force: true })
|
|
405
|
+
logger?.warn?.(`dsh-paper tex: 写入源码缓存失败(不影响本次解析):${String(error?.message ?? error).slice(0, 120)}`)
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return { state: 'ready', files, source: 'network' }
|
|
409
|
+
} catch (error) {
|
|
410
|
+
lastError = String(error?.message ?? error)
|
|
411
|
+
// 超时与连接错误同属「下次可能行」;404/403 已在上方直接返回,不重试。
|
|
412
|
+
delay = backoffMs(attempt)
|
|
413
|
+
if (attempt + 1 < FETCH_ATTEMPTS) {
|
|
414
|
+
logger?.warn?.('dsh-paper tex: 下载源码失败(第 ' + (attempt + 1) + ' 次),' + delay + 'ms 后重试:' + lastError.slice(0, 120))
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
return { state: 'degraded', reason: DEGRADE_REASON.NETWORK, detail: `下载源码失败:${lastError.slice(0, 160)}` }
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** 默认等待器:抽成参数是为了让测试不真的睡。 */
|
|
422
|
+
function defaultSleep(ms) {
|
|
423
|
+
return new Promise(resolve => setTimeout(resolve, ms))
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** 退避时长:指数增长 + 抖动(多篇同时重试时不要踩同一个节拍)。 */
|
|
427
|
+
function backoffMs(attempt) {
|
|
428
|
+
const base = Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** attempt)
|
|
429
|
+
return base + Math.floor(Math.random() * RETRY_JITTER_MS)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** 429/503 可能带 Retry-After(秒数或 HTTP 日期);取得到就按它等,上限是退避封顶的两倍。 */
|
|
433
|
+
function retryAfterMs(response) {
|
|
434
|
+
const header = response?.headers?.get?.('retry-after')
|
|
435
|
+
if (typeof header !== 'string' || header.trim() === '') return null
|
|
436
|
+
const seconds = Number(header.trim())
|
|
437
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.min(RETRY_MAX_MS * 2, seconds * 1000)
|
|
438
|
+
const at = Date.parse(header)
|
|
439
|
+
if (!Number.isFinite(at)) return null
|
|
440
|
+
return Math.max(0, Math.min(RETRY_MAX_MS * 2, at - Date.now()))
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** 把 mtime 推到当前时刻,作为 LRU 的访问记号。失败无影响。 */
|
|
444
|
+
async function touch(path) {
|
|
445
|
+
const now = new Date()
|
|
446
|
+
try {
|
|
447
|
+
const { utimes } = await import('node:fs/promises')
|
|
448
|
+
await utimes(path, now, now)
|
|
449
|
+
} catch {
|
|
450
|
+
// 只影响缓存淘汰顺序。
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** 导出上限常量,供测试与文档引用(避免测试里抄死字面量)。 */
|
|
455
|
+
export const TEX_LIMITS = { MAX_FILE_BYTES, MAX_TOTAL_BYTES, MAX_FILES, DEFAULT_TIMEOUT_MS, DEFAULT_CACHE_BYTES }
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 图表资源层:把源码包里的图片变成阅读器能显示的位图。
|
|
3
|
+
*
|
|
4
|
+
* 三条实测约束:
|
|
5
|
+
* - 40 篇抽样里矢量图 252 个、位图 95 个 —— 绝大多数图片是 PDF/PS 矢量,浏览器不能直接显示,
|
|
6
|
+
* 必须转成 PNG;
|
|
7
|
+
* - 转换要外部命令(pdftocairo),所以命令执行**注入**:测试不依赖本机装没装 TeX Live,
|
|
8
|
+
* 生产路径由 pipeline 传真实执行器;
|
|
9
|
+
* - 转换失败不是错误,是「这张图拿不到」—— 返回 null,调用方就不产这一块,让 MinerU 那份留着。
|
|
10
|
+
*
|
|
11
|
+
* 这一层有 IO(写文件、跑命令),但没有隐藏状态。
|
|
12
|
+
*/
|
|
13
|
+
import { execFile } from 'node:child_process'
|
|
14
|
+
import { access, mkdir, rm, writeFile } from 'node:fs/promises'
|
|
15
|
+
import { join } from 'node:path'
|
|
16
|
+
import { promisify } from 'node:util'
|
|
17
|
+
|
|
18
|
+
import { readGroup, readOptional, skipSpaces } from './tex-prepare.js'
|
|
19
|
+
import { inlineText } from './tex-inline.js'
|
|
20
|
+
|
|
21
|
+
const BACKSLASH = '\\'
|
|
22
|
+
|
|
23
|
+
/** 位图后缀:浏览器直接能显示,复制即可。 */
|
|
24
|
+
const RASTER_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp'])
|
|
25
|
+
/** 矢量后缀:需要 pdftocairo 转位图。EPS/PS 需要 ghostscript,本机没有,按不可用处理。 */
|
|
26
|
+
const VECTOR_EXTENSIONS = new Set(['.pdf'])
|
|
27
|
+
|
|
28
|
+
/** 图片类型:raster / vector / null(不认识或本机转不了)。 */
|
|
29
|
+
export function imageKindOf(name) {
|
|
30
|
+
const lower = String(name ?? '').toLowerCase()
|
|
31
|
+
const dot = lower.lastIndexOf('.')
|
|
32
|
+
if (dot === -1) return null
|
|
33
|
+
const extension = lower.slice(dot)
|
|
34
|
+
if (RASTER_EXTENSIONS.has(extension)) return 'raster'
|
|
35
|
+
if (VECTOR_EXTENSIONS.has(extension)) return 'vector'
|
|
36
|
+
return null
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 取 figure 容器里的 caption(可能带短标题)。 */
|
|
40
|
+
function captionOf(text) {
|
|
41
|
+
const at = text.indexOf(BACKSLASH + 'caption')
|
|
42
|
+
if (at === -1) return ''
|
|
43
|
+
let cursor = skipSpaces(text, at + 'caption'.length + 1)
|
|
44
|
+
const short = readOptional(text, cursor)
|
|
45
|
+
if (short !== null) cursor = skipSpaces(text, short.end)
|
|
46
|
+
const group = readGroup(text, cursor)
|
|
47
|
+
return group === null ? '' : inlineText(group.content)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 从 figure 容器里取图片路径与 caption。
|
|
52
|
+
*
|
|
53
|
+
* 只认第一个 includegraphics:一张图里放多个子图的写法(subfigure / 手排两栏)在源码里
|
|
54
|
+
* 是两次独立的 includegraphics,取第一个至少保证「有图」;子图拼合是第 3 批之后的事。
|
|
55
|
+
* 没有 includegraphics 时返回 null(纯 TikZ 图属于这种情况,本机没有编译链,拿不到)。
|
|
56
|
+
*/
|
|
57
|
+
export function figureOf(body) {
|
|
58
|
+
const source = String(body ?? '')
|
|
59
|
+
const at = source.indexOf(BACKSLASH + 'includegraphics')
|
|
60
|
+
if (at === -1) return null
|
|
61
|
+
let cursor = skipSpaces(source, at + BACKSLASH.length + 'includegraphics'.length)
|
|
62
|
+
const options = readOptional(source, cursor)
|
|
63
|
+
if (options !== null) cursor = skipSpaces(source, options.end)
|
|
64
|
+
const group = readGroup(source, cursor)
|
|
65
|
+
if (group === null) return null
|
|
66
|
+
const path = group.content.trim()
|
|
67
|
+
if (path === '') return null
|
|
68
|
+
let width = ''
|
|
69
|
+
if (options !== null) {
|
|
70
|
+
const start = options.content.indexOf('width=')
|
|
71
|
+
if (start !== -1) {
|
|
72
|
+
let end = start + 'width='.length
|
|
73
|
+
while (end < options.content.length && options.content[end] !== ',' && options.content[end] !== ']') end += 1
|
|
74
|
+
width = options.content.slice(start + 'width='.length, end).trim()
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return { path, caption: captionOf(source), width }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const execFileAsync = promisify(execFile)
|
|
81
|
+
|
|
82
|
+
/** 默认执行器:跑 pdftocairo 转位图,失败只回错误码(不抛)。 */
|
|
83
|
+
async function defaultRunner(command, args) {
|
|
84
|
+
try {
|
|
85
|
+
await execFileAsync(command, args, { windowsHide: true })
|
|
86
|
+
return { code: 0 }
|
|
87
|
+
} catch (error) {
|
|
88
|
+
return { code: Number.isInteger(error?.code) ? error.code : 1 }
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** 文件存在与否,不抛错。 */
|
|
93
|
+
async function exists(path) {
|
|
94
|
+
try {
|
|
95
|
+
await access(path)
|
|
96
|
+
return true
|
|
97
|
+
} catch {
|
|
98
|
+
return false
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 把一张图落成可显示的文件。
|
|
104
|
+
*
|
|
105
|
+
* @param {{name: string, bytes: Buffer, targetDir: string, targetName: string,
|
|
106
|
+
* runner: (command: string, args: string[]) => Promise<{code?: number}>}} input
|
|
107
|
+
* @returns {Promise<{path: string, kind: 'raster'|'vector'} | null>}
|
|
108
|
+
*/
|
|
109
|
+
export async function materializeFigure({ name, bytes, targetDir, targetName, runner = defaultRunner } = {}) {
|
|
110
|
+
const kind = imageKindOf(name)
|
|
111
|
+
if (kind === null || !Buffer.isBuffer(bytes) || bytes.length === 0) return null
|
|
112
|
+
if (typeof targetDir !== 'string' || targetDir === '' || typeof targetName !== 'string' || targetName === '') return null
|
|
113
|
+
await mkdir(targetDir, { recursive: true })
|
|
114
|
+
const target = join(targetDir, targetName)
|
|
115
|
+
|
|
116
|
+
if (kind === 'raster') {
|
|
117
|
+
try {
|
|
118
|
+
await writeFile(target, bytes)
|
|
119
|
+
return { path: targetName, kind }
|
|
120
|
+
} catch {
|
|
121
|
+
return null
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// 矢量:先落一份临时 PDF,再让 pdftocairo 转 PNG(200dpi,与页图缓存同一档)。
|
|
126
|
+
const tempPdf = join(targetDir, targetName.replace(/\.pdf$/i, '') + '.src.pdf')
|
|
127
|
+
const stem = target.replace(/\.png$/i, '')
|
|
128
|
+
try {
|
|
129
|
+
await writeFile(tempPdf, bytes)
|
|
130
|
+
if (typeof runner !== 'function') return null
|
|
131
|
+
const result = await runner('pdftocairo', ['-png', '-r', '200', '-singlefile', tempPdf, stem])
|
|
132
|
+
if (result?.code !== 0 && result?.code !== undefined) return null
|
|
133
|
+
if (!await exists(stem + '.png')) return null
|
|
134
|
+
return { path: targetName, kind }
|
|
135
|
+
} catch {
|
|
136
|
+
return null
|
|
137
|
+
} finally {
|
|
138
|
+
await rm(tempPdf, { force: true })
|
|
139
|
+
}
|
|
140
|
+
}
|