@li-canghai/dsh-paper 0.0.0-stage → 0.8.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.
Files changed (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -2
  3. package/cordis.patch.yml +4 -0
  4. package/lib/annotate-tool.js +334 -0
  5. package/lib/arxiv-id.js +74 -0
  6. package/lib/asset-routes.js +210 -0
  7. package/lib/bibliography-formats.js +126 -0
  8. package/lib/bibliography-import.js +105 -0
  9. package/lib/bibliography-service.js +43 -0
  10. package/lib/bibliography.js +42 -0
  11. package/lib/block-authors.js +292 -0
  12. package/lib/block-cache.js +39 -0
  13. package/lib/blocks-markdown.js +157 -0
  14. package/lib/blocks-reconcile.js +218 -0
  15. package/lib/blocks.js +1344 -0
  16. package/lib/citation-metadata.js +260 -0
  17. package/lib/citation-styles.js +120 -0
  18. package/lib/client-parts/01-pure-helpers.js +2762 -0
  19. package/lib/client-parts/02-author-year.js +95 -0
  20. package/lib/client.js +10381 -0
  21. package/lib/code-source.js +68 -0
  22. package/lib/concurrency-gate.js +91 -0
  23. package/lib/context.js +233 -0
  24. package/lib/csl/SOURCES.md +10 -0
  25. package/lib/csl/gb-t-7714.csl +441 -0
  26. package/lib/csl/ieee.csl +520 -0
  27. package/lib/csl/locales-zh-CN.xml +438 -0
  28. package/lib/csl/nature.csl +190 -0
  29. package/lib/discussion.js +400 -0
  30. package/lib/documents.js +67 -0
  31. package/lib/export.js +848 -0
  32. package/lib/file-lock.js +177 -0
  33. package/lib/gloss.js +181 -0
  34. package/lib/glossary.js +279 -0
  35. package/lib/index.js +3862 -0
  36. package/lib/inline-html.js +53 -0
  37. package/lib/install-dependency.js +120 -0
  38. package/lib/item-ops.js +83 -0
  39. package/lib/job-facade.js +58 -0
  40. package/lib/json-store.js +54 -0
  41. package/lib/library-model.js +132 -0
  42. package/lib/library-service.js +180 -0
  43. package/lib/library-tool.js +982 -0
  44. package/lib/library.js +814 -0
  45. package/lib/markdown-assets.js +138 -0
  46. package/lib/markdown-literals.js +93 -0
  47. package/lib/metadata-enrichment.js +516 -0
  48. package/lib/metadata-fetch.js +146 -0
  49. package/lib/metadata-node.js +158 -0
  50. package/lib/metadata-proxy.ps1 +35 -0
  51. package/lib/mineru-config.js +95 -0
  52. package/lib/mineru-sdk-helper.py +123 -0
  53. package/lib/mineru-sdk.js +182 -0
  54. package/lib/mineru.js +268 -0
  55. package/lib/mirror-export.js +240 -0
  56. package/lib/outline.js +296 -0
  57. package/lib/page-image-helper.py +308 -0
  58. package/lib/page-image.js +454 -0
  59. package/lib/paper-metadata.js +242 -0
  60. package/lib/parse-export.js +631 -0
  61. package/lib/pdf-analysis-tool.js +750 -0
  62. package/lib/pdf-metadata-helper.py +75 -0
  63. package/lib/pdf-metadata.js +141 -0
  64. package/lib/pdf-page.js +261 -0
  65. package/lib/pdf-scan.js +134 -0
  66. package/lib/pdf-text.js +68 -0
  67. package/lib/picker.js +305 -0
  68. package/lib/portable.js +379 -0
  69. package/lib/purge.js +170 -0
  70. package/lib/read-tool.js +660 -0
  71. package/lib/reader-store.js +497 -0
  72. package/lib/reading-order.js +207 -0
  73. package/lib/rename-document.js +480 -0
  74. package/lib/rename.js +372 -0
  75. package/lib/renderer-status.js +161 -0
  76. package/lib/resolver.js +1152 -0
  77. package/lib/result-archive.js +157 -0
  78. package/lib/revisions.js +330 -0
  79. package/lib/search-database.js +62 -0
  80. package/lib/search-index.js +601 -0
  81. package/lib/search-scan.js +185 -0
  82. package/lib/search-source.js +23 -0
  83. package/lib/search-terms.js +539 -0
  84. package/lib/section-audit.js +209 -0
  85. package/lib/selection-message.js +332 -0
  86. package/lib/serial-tail.js +21 -0
  87. package/lib/slicing.js +425 -0
  88. package/lib/source-resolver.js +581 -0
  89. package/lib/stem-repair.js +189 -0
  90. package/lib/storage.js +562 -0
  91. package/lib/store-paths.js +253 -0
  92. package/lib/table-gfm.js +236 -0
  93. package/lib/tasks.js +270 -0
  94. package/lib/tex-align.js +509 -0
  95. package/lib/tex-blocks.js +653 -0
  96. package/lib/tex-fetch.js +455 -0
  97. package/lib/tex-figures.js +140 -0
  98. package/lib/tex-inline.js +166 -0
  99. package/lib/tex-merge.js +279 -0
  100. package/lib/tex-pipeline.js +242 -0
  101. package/lib/tex-prepare.js +746 -0
  102. package/lib/tex-tables.js +210 -0
  103. package/lib/text-similarity.js +85 -0
  104. package/lib/tool-contract.js +86 -0
  105. package/lib/tool-host.js +1058 -0
  106. package/lib/tool-identity.js +214 -0
  107. package/lib/translatable-text.js +48 -0
  108. package/lib/translate-prompts.js +709 -0
  109. package/lib/translate-queue.js +418 -0
  110. package/lib/translate-task.js +158 -0
  111. package/lib/translate.js +909 -0
  112. package/lib/update-check.js +438 -0
  113. package/lib/update-contracts.js +75 -0
  114. package/lib/usage.js +282 -0
  115. package/package.json +55 -4
@@ -0,0 +1,454 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { createHash } from 'node:crypto'
3
+ import { readFile, readdir, stat } from 'node:fs/promises'
4
+ import { basename, join } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { childEnvironment } from './mineru-sdk.js'
7
+ import { PAGE_IMAGE_PAGES_DIR } from './store-paths.js'
8
+
9
+ const HELPER_PATH = fileURLToPath(new URL('./page-image-helper.py', import.meta.url))
10
+ const RESULT_BEGIN = 'DSH-PAPER-PAGE-BEGIN'
11
+ const RESULT_END = 'DSH-PAPER-PAGE-END'
12
+ const MAX_STDOUT_BYTES = 1024 * 1024
13
+ const MAX_STDERR_BYTES = 64 * 1024
14
+ /** 默认启动器:与 mineru-sdk 同款白名单判定,只认 uvx。 */
15
+ const DEFAULT_COMMAND = 'uvx'
16
+ const UVX_COMMANDS = ['uvx', 'uvx.exe']
17
+ /** 包版本钉死:本机 uv 缓存里就是这两个版本,不跟随上游漂移;不加 --offline(首次运行要联网下载)。 */
18
+ const PYPDFIUM_SPEC = 'pypdfium2==5.13.0'
19
+ const PILLOW_SPEC = 'pillow==12.3.0'
20
+ const DEFAULT_WIDTH = 1200
21
+ const DEFAULT_QUALITY = 80
22
+ const DEFAULT_FORMAT = 'webp'
23
+ const DEFAULT_TIMEOUT_MS = 120000
24
+ /** 单次渲染的页数上限:省略 pages 时按它截断,多出来的进 skipped。 */
25
+ const MAX_PAGES = 50
26
+ /** 裁边画布落盘的文件名,与 helper 共用同一个字面量。 */
27
+ const CANVAS_FILE = 'canvas.json'
28
+ /** documentId 会被拼进缓存路径,必须挡掉 `..` 与分隔符。 */
29
+ const DOCUMENT_ID_PATTERN = /^[A-Za-z0-9._-]+$/
30
+ const UNAVAILABLE_GUIDE = '需要 uvx 在 PATH 上;首次运行需联网下载 pypdfium2 与 pillow。'
31
+
32
+ /** 渲染不可用(uvx 缺失、启动失败、退出码非 0、超时、helper 报错)的统一错误码。 */
33
+ export const PAGE_IMAGE_UNAVAILABLE = 'PAGE_IMAGE_UNAVAILABLE'
34
+
35
+ /**
36
+ * 判断一个错误是不是「页面图渲染不可用」。调用方据此降级 —— 本模块只负责把原因说清楚,
37
+ * 绝不吞掉错误。
38
+ *
39
+ * @param {unknown} error
40
+ * @returns {boolean}
41
+ */
42
+ export function isPageImageUnavailable(error) {
43
+ return Boolean(error) && error.code === PAGE_IMAGE_UNAVAILABLE
44
+ }
45
+
46
+ function unavailableError(detail) {
47
+ const error = new Error(`页面图渲染不可用:${detail}。${UNAVAILABLE_GUIDE}`)
48
+ error.code = PAGE_IMAGE_UNAVAILABLE
49
+ return error
50
+ }
51
+
52
+ function abortError() {
53
+ const error = new Error('页面图渲染已取消')
54
+ error.name = 'AbortError'
55
+ return error
56
+ }
57
+
58
+ /**
59
+ * 解析启动器。**非 uvx 一律拒绝** —— `--from <包>` 的语义只对 uvx 成立,换成别的启动器
60
+ * 只会得到一个看不懂的报错。这里只做名字判定,不碰 PATH:全部命中缓存时不会起子进程。
61
+ */
62
+ export function resolveCommand(command) {
63
+ const configured = typeof command === 'string' ? command.trim() : ''
64
+ const resolved = configured === '' ? DEFAULT_COMMAND : configured
65
+ if (!UVX_COMMANDS.includes(basename(resolved).toLowerCase())) {
66
+ throw unavailableError(`启动器 ${resolved} 不是 uvx`)
67
+ }
68
+ return resolved
69
+ }
70
+
71
+ function positiveInt(value, fallback, name) {
72
+ if (value === undefined || value === null || value === '') return fallback
73
+ const number = Number(value)
74
+ if (!Number.isSafeInteger(number) || number <= 0) throw new Error(`页面图渲染的 ${name} 必须是正整数`)
75
+ return number
76
+ }
77
+
78
+ function normalizeFormat(format) {
79
+ const resolved = typeof format === 'string' && format.trim() !== '' ? format.trim().toLowerCase() : DEFAULT_FORMAT
80
+ if (resolved !== DEFAULT_FORMAT) throw new Error(`页面图渲染暂不支持 ${resolved} 格式,只支持 webp`)
81
+ return resolved
82
+ }
83
+
84
+ function normalizeQuality(quality) {
85
+ if (quality === undefined || quality === null || quality === '') return DEFAULT_QUALITY
86
+ const number = Number(quality)
87
+ if (!Number.isFinite(number)) throw new Error('页面图渲染的 quality 必须是数字')
88
+ return Math.min(100, Math.max(1, Math.round(number)))
89
+ }
90
+
91
+ /**
92
+ * 归一化页码。返回三份:能交给 helper 的 requested(去重升序、已截断到上限)、
93
+ * 参数本身就不合法的 invalid、以及超出单次上限的 overflow。后两份直接进 skipped。
94
+ *
95
+ * page 字段保留原始输入值(可能是字符串),这样调用方能看出是哪一条被丢了。
96
+ */
97
+ function normalizePages(pages) {
98
+ if (pages === undefined || pages === null) return { requested: null, invalid: [], overflow: [] }
99
+ if (!Array.isArray(pages)) throw new Error('页面图渲染的 pages 必须是页码数组')
100
+ const invalid = []
101
+ const kept = []
102
+ const seen = new Set()
103
+ for (const value of pages) {
104
+ const number = typeof value === 'number' ? value : Number(value)
105
+ if (!Number.isSafeInteger(number) || number < 1) {
106
+ invalid.push({ page: value, reason: '页码必须是正整数' })
107
+ continue
108
+ }
109
+ if (seen.has(number)) continue
110
+ seen.add(number)
111
+ kept.push(number)
112
+ }
113
+ kept.sort((left, right) => left - right)
114
+ const overflow = kept.slice(MAX_PAGES).map(page => ({ page, reason: `超过单次渲染上限 ${MAX_PAGES} 页` }))
115
+ return { requested: kept.slice(0, MAX_PAGES), invalid, overflow }
116
+ }
117
+
118
+ /** 缓存键必须含内容标识:优先用调用方给的 documentId,否则算 PDF 文件的 sha256。 */
119
+ async function resolveDocumentKey(input, pdfPath) {
120
+ const documentId = typeof input.documentId === 'string' ? input.documentId.trim() : ''
121
+ if (documentId !== '') {
122
+ if (!DOCUMENT_ID_PATTERN.test(documentId)) {
123
+ throw new Error(`页面图渲染的 documentId 只允许 [A-Za-z0-9._-],收到:${documentId}`)
124
+ }
125
+ return documentId
126
+ }
127
+ try {
128
+ return createHash('sha256').update(await readFile(pdfPath)).digest('hex')
129
+ } catch (error) {
130
+ throw unavailableError(`读不到 PDF ${pdfPath}(${error.message})`)
131
+ }
132
+ }
133
+
134
+ /** 裁边档位的文件名后缀:不裁保持接入前的原样(旧缓存照常命中),裁边另起一套。 */
135
+ const CROP_SUFFIX = '-crop'
136
+
137
+ function cacheFileName(page, width, format, crop = false) {
138
+ return `${page}@${width}${crop ? CROP_SUFFIX : ''}.${format}`
139
+ }
140
+
141
+ /**
142
+ * 读 WEBP 头部拿像素尺寸。缓存命中时尺寸只能从文件本身读出来 —— 这正是「读不动的缓存文件
143
+ * 当未命中」的判据:头解析不出来就重渲。VP8X / VP8 (有损) / VP8L (无损) 三种容器都认。
144
+ */
145
+ function readWebpSize(buffer) {
146
+ if (buffer.length < 16) return null
147
+ if (buffer.toString('ascii', 0, 4) !== 'RIFF' || buffer.toString('ascii', 8, 12) !== 'WEBP') return null
148
+ let offset = 12
149
+ while (offset + 8 <= buffer.length) {
150
+ const fourcc = buffer.toString('ascii', offset, offset + 4)
151
+ const size = buffer.readUInt32LE(offset + 4)
152
+ const data = offset + 8
153
+ if (fourcc === 'VP8X' && data + 10 <= buffer.length) {
154
+ return {
155
+ width: buffer.readUIntLE(data + 4, 3) + 1,
156
+ height: buffer.readUIntLE(data + 7, 3) + 1,
157
+ }
158
+ }
159
+ if (fourcc === 'VP8 ' && data + 10 <= buffer.length) {
160
+ if (buffer[data + 3] !== 0x9d || buffer[data + 4] !== 0x01 || buffer[data + 5] !== 0x2a) return null
161
+ return {
162
+ width: buffer.readUInt16LE(data + 6) & 0x3fff,
163
+ height: buffer.readUInt16LE(data + 8) & 0x3fff,
164
+ }
165
+ }
166
+ if (fourcc === 'VP8L' && data + 5 <= buffer.length) {
167
+ if (buffer[data] !== 0x2f) return null
168
+ const bits = buffer.readUInt32LE(data + 1)
169
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 }
170
+ }
171
+ offset = data + size + (size % 2)
172
+ }
173
+ return null
174
+ }
175
+
176
+ /**
177
+ * 归一化 helper 回传的裁边画布:四个方向都是 0–1 的占比,且裁完还剩得下东西。
178
+ * 任何一项不成立就返回 null —— 调用方按「这一篇没裁」处理,不拿半套坐标去错位。
179
+ *
180
+ * @param {unknown} value helper 回来的 canvas 字段。
181
+ * @returns {{left: number, top: number, right: number, bottom: number}|null}
182
+ */
183
+ export function normalizeCanvas(value) {
184
+ if (!value || typeof value !== 'object') return null
185
+ const sides = ['left', 'top', 'right', 'bottom']
186
+ const canvas = {}
187
+ for (const side of sides) {
188
+ const number = Number(value[side])
189
+ if (!Number.isFinite(number) || number < 0 || number >= 1) return null
190
+ canvas[side] = number
191
+ }
192
+ if (canvas.left + canvas.right >= 1 || canvas.top + canvas.bottom >= 1) return null
193
+ return canvas
194
+ }
195
+
196
+ /** 缓存目录里的 canvas.json:命中缓存时 helper 不起子进程,画布只能从盘上读回来。 */
197
+ async function readCanvas(directory) {
198
+ try {
199
+ return normalizeCanvas(JSON.parse(await readFile(join(directory, CANVAS_FILE), 'utf8')))
200
+ } catch {
201
+ return null
202
+ }
203
+ }
204
+
205
+ /** 命中判据:文件在、大小 > 0、读得动、头解析得出尺寸。任何一步不成立都当未命中,不抛错。 */
206
+ async function readCacheEntry(path) {
207
+ try {
208
+ const info = await stat(path)
209
+ if (!info.isFile() || info.size <= 0) return null
210
+ const data = await readFile(path)
211
+ if (data.length === 0) return null
212
+ const size = readWebpSize(data)
213
+ if (size === null) return null
214
+ return { data, width: size.width, height: size.height }
215
+ } catch {
216
+ return null
217
+ }
218
+ }
219
+
220
+ /** 缓存目录里已有哪些页(省略 pages 时用;目录不存在就是空)。 */
221
+ async function listCachedPages(directory, width, format, crop = false) {
222
+ const suffix = `@${width}${crop ? CROP_SUFFIX : ''}.${format}`
223
+ let names
224
+ try {
225
+ names = await readdir(directory)
226
+ } catch {
227
+ return []
228
+ }
229
+ const pages = []
230
+ for (const name of names) {
231
+ if (!name.endsWith(suffix)) continue
232
+ const page = Number(name.slice(0, -suffix.length))
233
+ if (Number.isSafeInteger(page) && page > 0) pages.push(page)
234
+ }
235
+ return pages.sort((left, right) => left - right)
236
+ }
237
+
238
+ async function collectCachedImages(directory, pages, width, format, crop = false) {
239
+ const hit = new Set()
240
+ const images = []
241
+ for (const page of pages) {
242
+ const path = join(directory, cacheFileName(page, width, format, crop))
243
+ const entry = await readCacheEntry(path)
244
+ if (entry === null) continue
245
+ hit.add(page)
246
+ images.push({
247
+ page,
248
+ data: new Uint8Array(entry.data.buffer, entry.data.byteOffset, entry.data.byteLength),
249
+ width: entry.width,
250
+ height: entry.height,
251
+ bytes: entry.data.byteLength,
252
+ path,
253
+ })
254
+ }
255
+ return { images, hit }
256
+ }
257
+
258
+ /**
259
+ * 运行页面图桥接器。默认实现:与 mineru-sdk.js 的 runMineruSdkHelper 同款(spawn 选项、
260
+ * stdout/stderr 上限、超时、结果标记),便于单测用 options.runHelper 换掉。
261
+ */
262
+ export async function runPageImageHelper(launch, payload) {
263
+ return new Promise((resolve, reject) => {
264
+ const child = spawn(launch.command, launch.args, {
265
+ cwd: launch.cwd || undefined,
266
+ env: launch.env,
267
+ windowsHide: true,
268
+ stdio: ['pipe', 'pipe', 'pipe'],
269
+ })
270
+ let stdout = Buffer.alloc(0)
271
+ let stderr = Buffer.alloc(0)
272
+ let settled = false
273
+ const finish = callback => value => {
274
+ if (settled) return
275
+ settled = true
276
+ clearTimeout(timer)
277
+ launch.signal?.removeEventListener?.('abort', abort)
278
+ callback(value)
279
+ }
280
+ const fail = finish(reject)
281
+ const succeed = finish(resolve)
282
+ const append = (current, chunk, limit) => {
283
+ const next = Buffer.concat([current, Buffer.from(chunk)])
284
+ if (next.length > limit) throw new Error('页面图桥接器输出超过限制')
285
+ return next
286
+ }
287
+ const abort = () => {
288
+ child.kill()
289
+ fail(abortError())
290
+ }
291
+ const timer = setTimeout(() => {
292
+ child.kill()
293
+ fail(new Error(`页面图渲染超过 ${launch.timeoutMs} ms`))
294
+ }, launch.timeoutMs)
295
+ timer.unref?.()
296
+ launch.signal?.addEventListener?.('abort', abort, { once: true })
297
+ child.stdout.on('data', chunk => {
298
+ try { stdout = append(stdout, chunk, MAX_STDOUT_BYTES) } catch (error) { child.kill(); fail(error) }
299
+ })
300
+ child.stderr.on('data', chunk => {
301
+ try { stderr = append(stderr, chunk, MAX_STDERR_BYTES) } catch (error) { child.kill(); fail(error) }
302
+ })
303
+ child.on('error', fail)
304
+ child.on('close', code => {
305
+ if (settled) return
306
+ try {
307
+ if (code !== 0) {
308
+ const detail = stderr.toString('utf8').slice(-MAX_STDERR_BYTES).trim()
309
+ throw new Error(`页面图桥接器退出码 ${code}${detail ? `:${detail}` : ''}`)
310
+ }
311
+ succeed(resultPayload(stdout.toString('utf8')))
312
+ } catch (error) { fail(error) }
313
+ })
314
+ child.stdin.on('error', fail)
315
+ child.stdin.end(JSON.stringify(payload))
316
+ })
317
+ }
318
+
319
+ function resultPayload(stdout) {
320
+ const begin = stdout.lastIndexOf(RESULT_BEGIN)
321
+ const end = stdout.indexOf(RESULT_END, begin + RESULT_BEGIN.length)
322
+ if (begin < 0 || end < 0) throw new Error('页面图桥接器没有返回结果标记')
323
+ const parsed = JSON.parse(stdout.slice(begin + RESULT_BEGIN.length, end).trim())
324
+ if (!parsed || parsed.ok !== true || !parsed.result || typeof parsed.result !== 'object') {
325
+ throw new Error(typeof parsed?.error === 'string' ? parsed.error : '页面图桥接器返回无效结果')
326
+ }
327
+ return parsed.result
328
+ }
329
+
330
+ /** 把 helper 写在盘上的图片读回来;读不动只记 skipped,不炸整次调用。 */
331
+ async function readRenderedImage(entry, skipped) {
332
+ const page = Number(entry?.page)
333
+ const path = typeof entry?.path === 'string' ? entry.path : ''
334
+ if (path === '') {
335
+ skipped.push({ page, reason: '渲染结果没有返回路径' })
336
+ return null
337
+ }
338
+ try {
339
+ const data = await readFile(path)
340
+ if (data.length === 0) throw new Error('文件是 0 字节')
341
+ return {
342
+ page,
343
+ data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
344
+ width: Number(entry.width) || 0,
345
+ height: Number(entry.height) || 0,
346
+ bytes: data.byteLength,
347
+ path,
348
+ }
349
+ } catch (error) {
350
+ skipped.push({ page, reason: `渲染结果读不动(${error.message})` })
351
+ return null
352
+ }
353
+ }
354
+
355
+ /**
356
+ * 把 PDF 页渲染成图片字节,带磁盘缓存。
357
+ *
358
+ * **一次子进程渲染多页**:需要渲的页码一次性交给 helper,禁止每页起一个进程。图片字节
359
+ * 不走 stdout —— helper 直接写盘,stdout 只回传路径与元数据。
360
+ *
361
+ * 缓存落在 `<cacheDir>/pages/<内容标识>/<页码>@<宽度>.webp`,helper 用临时文件 + 原子替换
362
+ * 写入;页码越界或参数非法只进 `skipped`,不抛错。渲染本身不可用(uvx 缺失、超时、
363
+ * helper 报错)才抛带 `PAGE_IMAGE_UNAVAILABLE` 的错误,由调用方决定怎么降级。
364
+ *
365
+ * @param {{pdfPath?: string, pages?: number[], width?: number, quality?: number, format?: string, documentId?: string, timeoutMs?: number, signal?: AbortSignal, crop?: boolean}} input
366
+ * @param {{cacheDir?: string, runHelper?: Function, command?: string, parentEnv?: NodeJS.ProcessEnv}} options
367
+ */
368
+ export async function renderPageImages(input = {}, options = {}) {
369
+ const cacheDir = typeof options.cacheDir === 'string' ? options.cacheDir.trim() : ''
370
+ if (cacheDir === '') throw new Error('页面图渲染需要 options.cacheDir')
371
+ const pdfPath = typeof input.pdfPath === 'string' ? input.pdfPath.trim() : ''
372
+ if (pdfPath === '') throw new Error('页面图渲染需要 input.pdfPath')
373
+ const command = resolveCommand(options.command)
374
+ const width = positiveInt(input.width, DEFAULT_WIDTH, 'width')
375
+ const quality = normalizeQuality(input.quality)
376
+ const format = normalizeFormat(input.format)
377
+ const timeoutMs = positiveInt(input.timeoutMs, DEFAULT_TIMEOUT_MS, 'timeoutMs')
378
+ const signal = input.signal
379
+ if (signal?.aborted) throw abortError()
380
+ // 裁边开关进缓存键:同一篇裁与不裁是两套像素,共用文件名会让开关切换后命中旧图。
381
+ const crop = input.crop === true
382
+
383
+ const pages = normalizePages(input.pages)
384
+ const key = await resolveDocumentKey(input, pdfPath)
385
+ const directory = join(cacheDir, PAGE_IMAGE_PAGES_DIR, key)
386
+ const cacheName = page => cacheFileName(page, width, format, crop)
387
+ const cachedPages = pages.requested === null
388
+ ? await listCachedPages(directory, width, format, crop)
389
+ : pages.requested
390
+ const { images: cachedImages, hit } = await collectCachedImages(directory, cachedPages, width, format, crop)
391
+ const missing = pages.requested === null ? null : pages.requested.filter(page => !hit.has(page))
392
+
393
+ const skipped = [...pages.invalid, ...pages.overflow]
394
+ const renderedImages = []
395
+ let pageCount = null
396
+ let renderedCanvas = null
397
+
398
+ if (missing === null || missing.length > 0) {
399
+ const launch = {
400
+ command,
401
+ args: ['--from', PYPDFIUM_SPEC, '--with', PILLOW_SPEC, 'python', HELPER_PATH],
402
+ env: childEnvironment({}, options.parentEnv ?? process.env),
403
+ timeoutMs,
404
+ signal,
405
+ }
406
+ const payload = {
407
+ pdfPath,
408
+ outputDir: directory,
409
+ pages: missing,
410
+ limit: MAX_PAGES,
411
+ skipPages: [...hit],
412
+ width,
413
+ quality,
414
+ format,
415
+ cropPages: crop,
416
+ // 裁边档单独一个文件名:与整页那份共存,切换开关不必重渲另一档。
417
+ fileSuffix: crop ? CROP_SUFFIX : '',
418
+ }
419
+ let result
420
+ try {
421
+ result = await (options.runHelper ?? runPageImageHelper)(launch, payload)
422
+ } catch (error) {
423
+ if (error?.name === 'AbortError') throw error
424
+ throw unavailableError(error instanceof Error ? error.message : String(error))
425
+ }
426
+ pageCount = Number.isSafeInteger(result?.pageCount) ? result.pageCount : null
427
+ renderedCanvas = normalizeCanvas(result?.canvas)
428
+ for (const entry of Array.isArray(result?.images) ? result.images : []) {
429
+ const image = await readRenderedImage(entry, skipped)
430
+ if (image !== null) renderedImages.push(image)
431
+ }
432
+ for (const item of Array.isArray(result?.skipped) ? result.skipped : []) {
433
+ skipped.push({ page: item?.page, reason: String(item?.reason ?? '渲染被跳过') })
434
+ }
435
+ }
436
+
437
+ // 缓存里可能留着同一 documentId 下更早版本的页图;有页数信息时把它挡掉。
438
+ const stale = image => pageCount !== null && image.page > pageCount
439
+ const keptRendered = renderedImages.filter(image => {
440
+ if (!stale(image)) return true
441
+ skipped.push({ page: image.page, reason: `页码超出文档页数 ${pageCount}` })
442
+ return false
443
+ })
444
+ const keptCached = cachedImages.filter(image => {
445
+ if (!stale(image)) return true
446
+ skipped.push({ page: image.page, reason: `缓存页码超出文档页数 ${pageCount}` })
447
+ return false
448
+ })
449
+
450
+ const images = [...keptCached, ...keptRendered].sort((left, right) => left.page - right.page)
451
+ // 画布随结果一起回:调用方要靠它把词坐标平移到裁后的图上,读不到就是"没裁"。
452
+ const canvas = crop ? (renderedCanvas ?? await readCanvas(directory)) : null
453
+ return { images, rendered: keptRendered.length, cached: keptCached.length, skipped, canvas }
454
+ }