@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,182 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { basename } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ const HELPER_PATH = fileURLToPath(new URL('./mineru-sdk-helper.py', import.meta.url))
6
+ const RESULT_BEGIN = 'DSH-PAPER-MINERU-BEGIN'
7
+ const RESULT_END = 'DSH-PAPER-MINERU-END'
8
+ const MAX_STDOUT_BYTES = 1024 * 1024
9
+ const MAX_STDERR_BYTES = 64 * 1024
10
+ /**
11
+ * 启动器:与官方 `@deepseek-ai/dsh-mcp-client` 的 mineru 行同款。Windows 上 uvx 不在 PATH
12
+ * 时由插件 config 的 `mineruCommand` 覆盖(见 index.js 的接线),不再读环境变量。
13
+ */
14
+ const DEFAULT_COMMAND = 'uvx'
15
+ // Pin the SDK itself: the MCP formatter omits structured results and leaves its SDK unpinned.
16
+ const DEFAULT_PACKAGE_SPEC = 'mineru-open-sdk==0.2.5'
17
+ const UVX_COMMANDS = ['uvx', 'uvx.exe']
18
+ const INHERITED_ENV = [
19
+ 'PATH', 'PATHEXT', 'SYSTEMROOT', 'WINDIR', 'COMSPEC', 'TEMP', 'TMP', 'HOME',
20
+ 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'ProgramFiles', 'ProgramFiles(x86)',
21
+ 'CommonProgramFiles', 'OS', 'NUMBER_OF_PROCESSORS', 'PROCESSOR_ARCHITECTURE',
22
+ 'LANG', 'LC_ALL', 'LC_CTYPE', 'NO_COLOR', 'FORCE_COLOR', 'CI',
23
+ ]
24
+
25
+ /**
26
+ * The environment a controlled child process gets.
27
+ *
28
+ * Only the names in {@link INHERITED_ENV} are copied from the parent, so a harness
29
+ * credential (`MINERU_API_TOKEN` and friends) never reaches a child that renders output a
30
+ * dialog or a spill file could echo back. `serverEnv` names are added on top of that.
31
+ *
32
+ * @param serverEnv - values this child needs beyond the inherited set.
33
+ * @param parentEnv - the environment to read the inherited names from.
34
+ * @returns the child environment.
35
+ */
36
+ export function childEnvironment(serverEnv, parentEnv) {
37
+ const env = {}
38
+ for (const name of INHERITED_ENV) {
39
+ if (typeof parentEnv[name] === 'string') env[name] = parentEnv[name]
40
+ }
41
+ // 🔴 **Python 子进程的 stdio 必须钉 UTF-8,否则换台电脑就崩**:Python 在 Windows 上按
42
+ // **系统 ANSI 代码页**编解码管道(中文简体机 cp936/GBK、繁体 cp950),而 Node 侧写进去、
43
+ // 读回来的都是 UTF-8 字节。实测(模拟 ACP=936):带中文的 pdfPath 直接
44
+ // `UnicodeDecodeError: 'gbk' codec can't decode byte` —— 整页图与整篇解析全失败,
45
+ // 而本机 ACP=65001(UTF-8)时一条都复现不出来,所以必须有这行而不能靠「本机能跑」。
46
+ // PYTHONIOENCODING 优先于 PYTHONUTF8,两个都给是为了盖住「用户在系统里设了别的值」。
47
+ // 三个 helper 内部还会再 reconfigure 一次(双保险,且不依赖环境变量传递)。
48
+ env.PYTHONIOENCODING = 'utf-8'
49
+ env.PYTHONUTF8 = '1'
50
+ return { ...env, ...serverEnv }
51
+ }
52
+
53
+ function safeErrorText(value, secret) {
54
+ const text = String(value ?? '').slice(-MAX_STDERR_BYTES)
55
+ return secret ? text.replaceAll(secret, '[REDACTED]') : text
56
+ }
57
+
58
+ function resultPayload(stdout) {
59
+ const begin = stdout.lastIndexOf(RESULT_BEGIN)
60
+ const end = stdout.indexOf(RESULT_END, begin + RESULT_BEGIN.length)
61
+ if (begin < 0 || end < 0) throw new Error('MinerU SDK 桥接器没有返回结果标记')
62
+ const json = stdout.slice(begin + RESULT_BEGIN.length, end).trim()
63
+ const parsed = JSON.parse(json)
64
+ if (!parsed || parsed.ok !== true || !parsed.result || typeof parsed.result !== 'object') {
65
+ throw new Error(typeof parsed?.error === 'string' ? parsed.error : 'MinerU SDK 桥接器返回无效结果')
66
+ }
67
+ return parsed.result
68
+ }
69
+
70
+ /**
71
+ * 把一枚「插件已录入的 MinerU Key」解析成 SDK 桥接的启动配置。
72
+ *
73
+ * **纯函数**:令牌由调用方解出后经 `options.secret` 传进来(生产路径是 resolver 读
74
+ * `<runtimeRoot>/mineru.json`),这里既不读文件也不拼 `$DSH_HOME` 路径 —— 否则单测要造一个
75
+ * 假 home 才能测一个字符串解析。启动器默认 `uvx`,可由 `options.command` 覆盖(来自插件
76
+ * config 的 `mineruCommand`);**非 uvx 启动器一律拒绝**,因为 `--from <包>` 的语义只对 uvx
77
+ * 成立,换成别的启动器只会得到一个看不懂的报错。
78
+ *
79
+ * @param {{secret?: string, command?: string}} [options]
80
+ * @returns {{command: string, packageSpec: string, secret: string}|null} null 表示桥接不可用。
81
+ */
82
+ export function mineruSdkConfig(options = {}) {
83
+ const secret = typeof options.secret === 'string' ? options.secret.trim() : ''
84
+ if (secret === '') return null
85
+ const configuredCommand = typeof options.command === 'string' ? options.command.trim() : ''
86
+ const command = configuredCommand === '' ? DEFAULT_COMMAND : configuredCommand
87
+ if (!UVX_COMMANDS.includes(basename(command).toLowerCase())) return null
88
+ return { command, packageSpec: DEFAULT_PACKAGE_SPEC, secret }
89
+ }
90
+
91
+ export async function runMineruSdkHelper(launch, payload) {
92
+ return new Promise((resolve, reject) => {
93
+ const child = spawn(launch.command, launch.args, {
94
+ cwd: launch.cwd || undefined,
95
+ env: launch.env,
96
+ windowsHide: true,
97
+ stdio: ['pipe', 'pipe', 'pipe'],
98
+ })
99
+ let stdout = Buffer.alloc(0)
100
+ let stderr = Buffer.alloc(0)
101
+ let settled = false
102
+ const finish = callback => value => {
103
+ if (settled) return
104
+ settled = true
105
+ clearTimeout(timer)
106
+ launch.signal?.removeEventListener?.('abort', abort)
107
+ callback(value)
108
+ }
109
+ const fail = finish(reject)
110
+ const succeed = finish(resolve)
111
+ const append = (current, chunk, limit) => {
112
+ const next = Buffer.concat([current, Buffer.from(chunk)])
113
+ if (next.length > limit) throw new Error('MinerU SDK 桥接器输出超过限制')
114
+ return next
115
+ }
116
+ const abort = () => {
117
+ child.kill()
118
+ fail(new Error('MinerU SDK 调用已取消'))
119
+ }
120
+ const timer = setTimeout(() => {
121
+ child.kill()
122
+ fail(new Error(`MinerU SDK 调用超过 ${launch.timeoutMs} ms`))
123
+ }, launch.timeoutMs)
124
+ timer.unref?.()
125
+ launch.signal?.addEventListener?.('abort', abort, { once: true })
126
+ child.stdout.on('data', chunk => {
127
+ try { stdout = append(stdout, chunk, MAX_STDOUT_BYTES) } catch (error) { child.kill(); fail(error) }
128
+ })
129
+ child.stderr.on('data', chunk => {
130
+ try { stderr = append(stderr, chunk, MAX_STDERR_BYTES) } catch (error) { child.kill(); fail(error) }
131
+ })
132
+ child.on('error', fail)
133
+ child.on('close', code => {
134
+ if (settled) return
135
+ try {
136
+ if (code !== 0) {
137
+ // The helper's diagnostic is in its bounded JSON envelope, including on failure.
138
+ if (stdout.includes(RESULT_BEGIN)) resultPayload(stdout.toString('utf8'))
139
+ const detail = safeErrorText(stderr.toString('utf8'), launch.secret).trim()
140
+ throw new Error(`MinerU SDK 桥接器退出码 ${code}${detail ? `:${detail}` : ''}`)
141
+ }
142
+ succeed(resultPayload(stdout.toString('utf8')))
143
+ } catch (error) { fail(new Error(safeErrorText(error?.message ?? error, launch.secret))) }
144
+ })
145
+ child.stdin.on('error', fail)
146
+ child.stdin.end(JSON.stringify(payload))
147
+ })
148
+ }
149
+
150
+ /**
151
+ * 用配置好的 SDK 桥接解析一篇 PDF;桥接不可用时返回 `null`(调用方据此报「未配置」)。
152
+ *
153
+ * `options.config` 是调用方**已经解出**的配置,优先用它;没给才由 `options.secret` /
154
+ * `options.command` 现算一份(单测可以直接喂值)。令牌**只经子进程环境**传给 helper,绝不
155
+ * 进命令行 —— `args` 里只有包名与 helper 路径,而进程列表对同机其他用户可见。
156
+ */
157
+ export async function parseWithConfiguredMineruSdk(input, options = {}) {
158
+ const config = options.config !== undefined ? options.config : mineruSdkConfig(options)
159
+ if (config === null) return null
160
+ // 🔴 **不加 `--offline`**:它是「换台电脑就解析不了」的第二号原因。
161
+ // 本机装了那个包,加不加都是 122–127 ms(实测三轮,差值在噪声内,**没有任何收益**);
162
+ // 而在一台 uv 缓存是空的机器上,它直接让解析**必然失败**(实测冷缓存):
163
+ // × No solution found when resolving tool dependencies:
164
+ // Because mineru-open-mcp was not found in the cache …
165
+ // 首次运行本来就要联网下载 —— 这正是 page-image.js 那条链一直不加它的理由。
166
+ const launch = {
167
+ command: config.command,
168
+ args: ['--from', config.packageSpec, 'python', HELPER_PATH],
169
+ env: childEnvironment({ MINERU_API_TOKEN: config.secret }, options.parentEnv ?? process.env),
170
+ timeoutMs: input.timeoutMs,
171
+ signal: input.signal,
172
+ packageSpec: config.packageSpec,
173
+ secret: config.secret,
174
+ }
175
+ const payload = {
176
+ pdfPath: input.pdfPath, outputDir: input.outputDir, model: input.model,
177
+ timeoutMs: input.timeoutMs,
178
+ language: input.language ?? 'ch', ocr: input.ocr ?? false,
179
+ formula: true, table: true,
180
+ }
181
+ return (options.runHelper ?? runMineruSdkHelper)(launch, payload)
182
+ }
package/lib/mineru.js ADDED
@@ -0,0 +1,268 @@
1
+ import { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises'
2
+ import { isAbsolute, join, relative, resolve } from 'node:path'
3
+ import { copyMarkdownImages, missingMarkdownImagePaths, restoreMarkdownImagesFromZip } from './markdown-assets.js'
4
+ import { MAX_RESULT_ARCHIVE_BYTES, requestedFilesFromZip, zipEntryNames } from './result-archive.js'
5
+
6
+ function textBlocks(result) {
7
+ return Array.isArray(result?.content)
8
+ ? result.content.filter(block => block?.type === 'text' && typeof block.text === 'string').map(block => block.text)
9
+ : []
10
+ }
11
+
12
+ function collectCandidates(value, paths, markdown, archives, errors, contentLists, filenames) {
13
+ if (typeof value === 'string') return
14
+ if (Array.isArray(value)) return value.forEach(item => collectCandidates(item, paths, markdown, archives, errors, contentLists, filenames))
15
+ if (!value || typeof value !== 'object') return
16
+ for (const [key, item] of Object.entries(value)) {
17
+ if (typeof item === 'string' && ['extract_path', 'markdown_path', 'output_path'].includes(key)) paths.push(item)
18
+ if (typeof item === 'string' && ['content', 'markdown'].includes(key) && item.trim() !== '') markdown.push(item)
19
+ if (typeof item === 'string' && key === 'zip_url' && item.trim() !== '') archives.push(item)
20
+ if (typeof item === 'string' && key === 'error' && item.trim() !== '') errors.push(item)
21
+ // 块列表路径由本地 SDK 桥接器回传(helper 把它落盘后只交回路径);MCP 路径不产出该键。
22
+ if (typeof item === 'string' && key === 'content_list_path' && item.trim() !== '') contentLists.push(item)
23
+ if (typeof item === 'string' && key === 'filename' && item.trim() !== '') filenames.push(item)
24
+ collectCandidates(item, paths, markdown, archives, errors, contentLists, filenames)
25
+ }
26
+ }
27
+
28
+ /**
29
+ * 读取块列表文件的原始 JSON,失败一律当"没有块列表"。
30
+ *
31
+ * 上游产物可能有三种坏法:文件不存在(旧产物/降级)、不是合法 JSON(写到一半被中断)、
32
+ * 顶层不是数组(上游改结构)。三种都属于该论文没有块列表,不该让整次解析失败。
33
+ *
34
+ * @returns 数组,或 undefined 表示本次没有可用的块列表。
35
+ */
36
+ async function readContentList(path) {
37
+ try {
38
+ const parsed = JSON.parse(await readFile(path, 'utf8'))
39
+ return Array.isArray(parsed) ? parsed : undefined
40
+ } catch { return undefined }
41
+ }
42
+
43
+ /**
44
+ * ZIP 里块列表条目的候选名:MinerU 用 "<主名>_content_list.json",也存在裸名。
45
+ *
46
+ * 主名必须来自结果内部上报的 filename(外层 MCP 响应对象上没有这个字段);
47
+ * 一个都没有时只剩裸名兜底。
48
+ */
49
+ function contentListEntryNames(filenames) {
50
+ const names = []
51
+ for (const filename of filenames) {
52
+ const stem = filename.replace(/\.[^.]*$/, '')
53
+ if (stem !== '') names.push(`${stem}_content_list.json`)
54
+ }
55
+ names.push('content_list.json')
56
+ return [...new Set(names)]
57
+ }
58
+
59
+ /**
60
+ * 下载 MinerU 结果 ZIP 并取出其中的块列表。
61
+ *
62
+ * 本地 SDK 桥接器已经把块列表落盘了,正常情况下用不上这条路;它是给"helper 落盘失败、
63
+ * 但 ZIP 仍可下载"留的补取通道。取不到(条目名不同、ZIP 不可用)就返回 undefined 降级。
64
+ */
65
+ async function restoreArchiveContentList(filenames, archives, loadArchive, logger) {
66
+ const names = contentListEntryNames(filenames)
67
+ for (const archiveUrl of archives) {
68
+ try {
69
+ const archive = await loadArchive(archiveUrl)
70
+ // 🔴 云端把块列表命名为 `<任务UUID>_content_list.json`(D134 实测:vlm 与 pipeline 都这样),
71
+ // 主名既不是文件名也不是裸的 content_list —— 只按文件名猜**永远**取不到。所以先列出 ZIP 里的
72
+ // 全部条目,把所有 `*_content_list.json` 一起纳入候选;文件名猜测仍排在最前(自托管/旧版命名)。
73
+ const inZip = zipEntryNames(archive).filter(name => name.endsWith('_content_list.json'))
74
+ const candidates = [...names, ...inZip.filter(name => !names.includes(name))]
75
+ const files = requestedFilesFromZip(archive, candidates)
76
+ for (const name of candidates) {
77
+ const bytes = files.get(name)
78
+ if (bytes === undefined) continue
79
+ const parsed = JSON.parse(Buffer.from(bytes).toString('utf8'))
80
+ if (Array.isArray(parsed)) return parsed
81
+ }
82
+ } catch (error) {
83
+ logger?.warn(`dsh-paper: 无法从 MinerU 结果 ZIP 读取块列表:${String(error?.message ?? error).slice(0, 500)}`)
84
+ }
85
+ }
86
+ return undefined
87
+ }
88
+
89
+ async function markdownFiles(root) {
90
+ const found = []
91
+ async function visit(path) {
92
+ for (const entry of await readdir(path, { withFileTypes: true }).catch(() => [])) {
93
+ const child = join(path, entry.name)
94
+ if (entry.isDirectory()) await visit(child)
95
+ else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) found.push(child)
96
+ }
97
+ }
98
+ await visit(root)
99
+ return found
100
+ }
101
+
102
+ async function responseBuffer(response) {
103
+ if (!response.ok) throw new Error(`下载失败:HTTP ${response.status}`)
104
+ const declaredLength = Number(response.headers.get('content-length'))
105
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_RESULT_ARCHIVE_BYTES) throw new Error('结果 ZIP 超过 256 MiB 限制')
106
+ if (!response.body) throw new Error('下载响应没有正文')
107
+ const chunks = []
108
+ let length = 0
109
+ const reader = response.body.getReader()
110
+ while (true) {
111
+ const { done, value } = await reader.read()
112
+ if (done) break
113
+ length += value.byteLength
114
+ if (length > MAX_RESULT_ARCHIVE_BYTES) {
115
+ await reader.cancel().catch(() => {})
116
+ throw new Error('结果 ZIP 超过 256 MiB 限制')
117
+ }
118
+ chunks.push(Buffer.from(value))
119
+ }
120
+ return Buffer.concat(chunks, length)
121
+ }
122
+
123
+ async function downloadArchive(value, fetchImpl) {
124
+ if (typeof fetchImpl !== 'function') throw new Error('当前 Node 环境不支持下载 MinerU 结果 ZIP')
125
+ let url = new URL(value)
126
+ for (let redirects = 0; redirects <= 3; redirects += 1) {
127
+ if (url.protocol !== 'https:') throw new Error(`只允许 HTTPS 结果地址:${url.protocol}`)
128
+ const response = await fetchImpl(url, { redirect: 'manual', signal: AbortSignal.timeout(120_000) })
129
+ if (response.status < 300 || response.status >= 400) return responseBuffer(response)
130
+ const location = response.headers.get('location')
131
+ if (!location) throw new Error(`MinerU 结果 ZIP 重定向缺少地址:HTTP ${response.status}`)
132
+ url = new URL(location, url)
133
+ }
134
+ throw new Error('MinerU 结果 ZIP 重定向次数过多')
135
+ }
136
+
137
+ async function restoreArchiveImages(markdown, markdownPath, archives, loadArchive, logger) {
138
+ if (archives.length === 0 || (await missingMarkdownImagePaths(markdown, markdownPath)).length === 0) return
139
+ for (const archiveUrl of archives) {
140
+ try {
141
+ const archive = await loadArchive(archiveUrl)
142
+ const restored = await restoreMarkdownImagesFromZip(markdown, markdownPath, archive)
143
+ if (restored.restoredImages.length > 0) logger?.info(`dsh-paper: 从 MinerU 结果 ZIP 恢复 ${restored.restoredImages.length} 张图片`)
144
+ if (restored.missingImages.length === 0) return
145
+ } catch (error) {
146
+ logger?.warn(`dsh-paper: 无法恢复 MinerU 结果 ZIP 中的图片:${String(error?.message ?? error).slice(0, 500)}`)
147
+ }
148
+ }
149
+ }
150
+
151
+ /**
152
+ * 把一次 MinerU 调用物化成磁盘上的 Markdown,顺带取出块列表。
153
+ *
154
+ * 返回值仍是 Markdown 路径(既有契约不变);块列表经 `onContentList` 回调交出去,
155
+ * 这样两个产物来自同一次解析,调用方不必再下一次结果 ZIP。回调只在**确实拿到**块列表时
156
+ * 触发,并且只在正文成功物化后触发。兼容输入缺结构时允许只有 Markdown;
157
+ * `requireContentList` 要求非空块列表,SDK 原始 ZIP 还必须包含唯一正文、块列表及引用图片。
158
+ *
159
+ * @returns 物化后的 Markdown 绝对路径。
160
+ */
161
+ export async function materializeMineruResult(result, outputDir, { logger, fetch: fetchImpl = globalThis.fetch, onContentList, requireContentList = false } = {}) {
162
+ if (result?.isError === true) throw new Error(textBlocks(result).join('\n') || 'MinerU 解析失败')
163
+ await mkdir(outputDir, { recursive: true })
164
+ const paths = []
165
+ const markdown = []
166
+ const archives = []
167
+ const errors = []
168
+ const contentLists = []
169
+ const filenames = []
170
+ collectCandidates(result, paths, markdown, archives, errors, contentLists, filenames)
171
+ for (const text of textBlocks(result)) {
172
+ try { collectCandidates(JSON.parse(text), paths, markdown, archives, errors, contentLists, filenames) } catch {
173
+ if (/^#{1,6}\s|\n#{1,6}\s/m.test(text)) markdown.push(text)
174
+ }
175
+ }
176
+ const root = resolve(outputDir)
177
+ const archiveCache = new Map()
178
+ const localArchive = typeof result?.archive_path === 'string' ? resolve(result.archive_path) : undefined
179
+ if (localArchive) {
180
+ const child = relative(root, localArchive)
181
+ if (child === '' || child === '..' || child.startsWith('..') || isAbsolute(child)) throw new Error('MinerU 结果 ZIP 必须在本次输出目录内')
182
+ archives.unshift(localArchive)
183
+ }
184
+ const loadArchive = key => {
185
+ if (!archiveCache.has(key)) archiveCache.set(key, (async () => {
186
+ if (key !== localArchive) return downloadArchive(key, fetchImpl)
187
+ const info = await stat(key)
188
+ if (!info.isFile() || info.size > MAX_RESULT_ARCHIVE_BYTES) throw new Error('MinerU 结果 ZIP 无效或超过 256 MiB 限制')
189
+ return readFile(key)
190
+ })())
191
+ return archiveCache.get(key)
192
+ }
193
+ let contentList
194
+ if (localArchive) {
195
+ // Select one document from the original ZIP instead of the SDK's last .md/.json entry.
196
+ const archive = await loadArchive(localArchive)
197
+ const entries = zipEntryNames(archive)
198
+ const structures = entries.filter(name => /(?:^|\/)(?:[^/]+_)?content_list\.json$/.test(name))
199
+ const full = entries.filter(name => /(?:^|\/)full\.md$/i.test(name))
200
+ const texts = full.length > 0 ? full : entries.filter(name => /\.md$/i.test(name))
201
+ if (structures.length !== 1 || texts.length !== 1) throw new Error('MinerU 结果 ZIP 缺少唯一的正文和块列表,拒绝混用不同结果')
202
+ const files = requestedFilesFromZip(archive, [structures[0], texts[0]])
203
+ const decode = bytes => new TextDecoder('utf-8', { fatal: true }).decode(bytes)
204
+ contentList = JSON.parse(decode(files.get(structures[0])))
205
+ if (!Array.isArray(contentList) || contentList.length === 0) throw new Error('MinerU 结果 ZIP 的块列表为空或格式无效')
206
+ const source = decode(files.get(texts[0]))
207
+ if (source.trim() === '') throw new Error('MinerU 返回的 Markdown 为空')
208
+ const path = join(root, 'full.md')
209
+ await writeFile(path, source, 'utf8')
210
+ paths.unshift(path)
211
+ }
212
+ const completed = path => {
213
+ if (contentList !== undefined) onContentList?.(contentList)
214
+ return path
215
+ }
216
+ const localize = async path => {
217
+ const resolvedPath = resolve(path)
218
+ const localPath = relative(root, resolvedPath)
219
+ const destination = join(root, 'full.md')
220
+ const content = await readFile(resolvedPath, 'utf8')
221
+ if (content.trim() === '') throw new Error('MinerU 返回的 Markdown 为空')
222
+ const local = localPath === '' || (!localPath.startsWith('..') && !isAbsolute(localPath))
223
+ await restoreArchiveImages(content, local ? resolvedPath : destination, archives, loadArchive, logger)
224
+ if (localArchive && (await missingMarkdownImagePaths(content, local ? resolvedPath : destination)).length > 0) {
225
+ throw new Error('MinerU 结果 ZIP 中的正文图片缺失或损坏,无法完整保存本次解析')
226
+ }
227
+ if (local) return resolvedPath
228
+ const materialized = await copyMarkdownImages(content, resolvedPath, destination)
229
+ if (materialized.missingImages.length > 0) {
230
+ logger?.warn(`dsh-paper: MinerU 外部结果引用的 ${materialized.missingImages.length} 张本地图片缺失,已从物化副本剔除引用`)
231
+ }
232
+ await writeFile(destination, materialized.markdown, 'utf8')
233
+ return destination
234
+ }
235
+ // 块列表先于 Markdown 定位解析:helper 已经把它落到 outputDir,读文件远比下载结果 ZIP 便宜。
236
+ for (const candidate of contentList === undefined ? contentLists : []) {
237
+ const path = isAbsolute(candidate) ? resolve(candidate) : resolve(outputDir, candidate)
238
+ contentList = await readContentList(path)
239
+ if (contentList !== undefined) break
240
+ }
241
+ if (contentList === undefined) contentList = await restoreArchiveContentList(filenames, archives, loadArchive, logger)
242
+ if (requireContentList && (!Array.isArray(contentList) || contentList.length === 0)) {
243
+ throw new Error('本次解析缺少新的块列表,不能替换原有结构化结果')
244
+ }
245
+ for (const candidate of paths) {
246
+ const path = isAbsolute(candidate) ? resolve(candidate) : resolve(outputDir, candidate)
247
+ try {
248
+ const info = await stat(path)
249
+ if (info.isFile() && path.toLowerCase().endsWith('.md')) return completed(await localize(path))
250
+ if (info.isDirectory()) {
251
+ const files = await markdownFiles(path)
252
+ if (files.length === 1) return completed(await localize(files[0]))
253
+ if (files.length > 1) throw new Error('MinerU 返回多个 Markdown,无法确定本次正文')
254
+ }
255
+ } catch (error) { if (error?.code !== 'ENOENT') throw error }
256
+ }
257
+ const generated = await markdownFiles(outputDir)
258
+ if (generated.length === 1) return completed(await localize(generated[0]))
259
+ if (generated.length > 1) throw new Error('MinerU 返回多个 Markdown,无法确定本次正文')
260
+ if (markdown.length > 0) {
261
+ if (markdown[0].trim() === '') throw new Error('MinerU 返回的 Markdown 为空')
262
+ const path = join(outputDir, 'full.md')
263
+ await writeFile(path, markdown[0], 'utf8')
264
+ await restoreArchiveImages(markdown[0], path, archives, loadArchive, logger)
265
+ return completed(path)
266
+ }
267
+ throw new Error(errors.join('; ') || 'MinerU 返回中没有可用 Markdown')
268
+ }