@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,146 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { join } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { bypassProxy, createMetadataNodeFetch } from './metadata-node.js'
5
+
6
+ const MAX_BODY = 1024 * 1024
7
+ const PROXY_SCHEMES = new Set(['http:', 'https:', 'socks:', 'socks4:', 'socks4a:', 'socks5:', 'socks5h:'])
8
+ const fail = message => Object.assign(new Error(message), { code: 'METADATA_NETWORK' })
9
+
10
+ function environmentValue(env, name) {
11
+ return env[name.toLowerCase()] || env[name] || ''
12
+ }
13
+
14
+ function proxyAddress(value) {
15
+ if (!value) return ''
16
+ const input = String(value).trim()
17
+ try {
18
+ const url = new URL(input.includes('://') ? input : 'http://' + input)
19
+ if (!PROXY_SCHEMES.has(url.protocol) || !url.hostname || url.search || url.hash || !['', '/'].includes(url.pathname)) throw new Error()
20
+ return url.href
21
+ } catch { throw fail('代理地址或协议无效,请检查 HTTPS_PROXY、HTTP_PROXY、ALL_PROXY 或系统代理设置。') }
22
+ }
23
+
24
+ /** Proxy discovery is separate from the Node TLS transport. */
25
+ export function createMetadataFetch({ mode = 'auto', baseFetch = globalThis.fetch, platform = process.platform,
26
+ env = process.env, spawnImpl = spawn, now = Date.now } = {}) {
27
+ if (!['auto', 'direct'].includes(mode)) throw new Error('书目联网方式须为 auto 或 direct。')
28
+ const systemRoot = env.SystemRoot || env.SYSTEMROOT || process.env.SystemRoot || 'C:\\Windows'
29
+ const powershell = join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
30
+ const helper = fileURLToPath(new URL('./metadata-proxy.ps1', import.meta.url))
31
+ const proxyCache = new Map()
32
+ const controllers = new Set(), running = new Set()
33
+ let stopped = false
34
+ const nodeFetch = createMetadataNodeFetch({ env, platform, systemCertificates: async signal => {
35
+ const result = await run(powershell, ['-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', helper],
36
+ JSON.stringify({ task: 'certificates' }), signal, 8 * 1024 * 1024, 5000)
37
+ let roots
38
+ try { roots = JSON.parse(result.stdout.toString('utf8').replace(/^\uFEFF/, ''))?.certificates } catch {}
39
+ if (result.code !== 0 || !Array.isArray(roots) || !roots.every(value => typeof value === 'string')) throw fail('无法读取系统信任证书,请检查系统证书设置。')
40
+ return roots
41
+ } })
42
+
43
+ function run(command, args, input, signal, maximum, timeoutMs = 0) {
44
+ return new Promise((resolve, reject) => {
45
+ if (signal.aborted) { reject(signal.reason); return }
46
+ let child
47
+ try { child = spawnImpl(command, args, { env, windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] }) }
48
+ catch (error) { reject(Object.assign(fail('书目联网组件启动失败。'), { cause: { code: error?.code } })); return }
49
+ const chunks = []
50
+ let size = 0, failure = null
51
+ const stop = error => { if (failure) return; failure = error; child.kill() }
52
+ const abort = () => stop(signal.reason)
53
+ const timer = timeoutMs ? setTimeout(() => stop(fail('系统网络设置读取超时,请检查系统代理与证书设置后重试。')), timeoutMs) : null
54
+ signal.addEventListener('abort', abort, { once: true })
55
+ child.on('error', error => { failure ??= Object.assign(fail('书目联网组件不可用。'), { cause: { code: error?.code } }) })
56
+ child.stdin.on('error', () => stop(fail('书目联网组件未能接收请求。')))
57
+ child.stdout.on('error', () => stop(fail('书目联网组件响应读取失败。')))
58
+ child.stdout.on('data', chunk => {
59
+ if (failure) return
60
+ size += chunk.length
61
+ if (size > maximum) { stop(new Error('书目响应过大,未使用该结果。')); return }
62
+ chunks.push(chunk)
63
+ })
64
+ child.on('close', (code, terminated) => {
65
+ if (timer) clearTimeout(timer)
66
+ signal.removeEventListener('abort', abort)
67
+ if (failure) reject(failure)
68
+ else if (terminated) reject(fail('书目联网请求已中止。'))
69
+ else resolve({ code, stdout: Buffer.concat(chunks) })
70
+ })
71
+ child.stdin.end(input)
72
+ if (signal.aborted) abort()
73
+ })
74
+ }
75
+
76
+ async function systemProxy(url, signal) {
77
+ const cached = proxyCache.get(url)
78
+ if (cached && now() - cached.at < 5000) return cached.proxy
79
+ const result = await run(powershell, ['-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', helper],
80
+ JSON.stringify({ url }), signal, 16 * 1024, 5000)
81
+ let record
82
+ try { record = JSON.parse(result.stdout.toString('utf8').replace(/^\uFEFF/, '')) } catch { /* Report only the failed operation. */ }
83
+ if (result.code !== 0 || !record || !(record.proxy === null || typeof record.proxy === 'string')) throw fail('无法读取系统代理设置,请检查系统代理或设置 HTTPS_PROXY。')
84
+ const proxy = proxyAddress(record.proxy)
85
+ if (proxyCache.size >= 64) proxyCache.delete(proxyCache.keys().next().value)
86
+ proxyCache.set(url, { proxy, at: now() })
87
+ return proxy
88
+ }
89
+
90
+ async function direct(input, options, signal) {
91
+ const response = await baseFetch(input, { ...options, signal })
92
+ if (!response.body) return response
93
+ const reader = response.body.getReader(), chunks = []
94
+ let size = 0
95
+ try {
96
+ for (;;) {
97
+ const next = await reader.read()
98
+ if (next.done) break
99
+ size += next.value.byteLength
100
+ if (size > MAX_BODY) throw new Error('书目响应过大,未使用该结果。')
101
+ chunks.push(Buffer.from(next.value))
102
+ }
103
+ } catch (error) {
104
+ try { await reader.cancel() } catch { /* Preserve the read failure. */ }
105
+ throw error
106
+ } finally { reader.releaseLock() }
107
+ return new Response(Buffer.concat(chunks), { status: response.status, headers: response.headers })
108
+ }
109
+
110
+ async function perform(input, options, signal) {
111
+ if (options.method && options.method.toUpperCase() !== 'GET') throw fail('书目联网仅支持只读查询。')
112
+ if (mode === 'direct') return direct(input, options, signal)
113
+ const url = new URL(String(input))
114
+ if (!['http:', 'https:'].includes(url.protocol)) throw fail('书目联网只支持 HTTP 和 HTTPS 地址。')
115
+ const bypassAll = bypassProxy(url, environmentValue(env, 'NO_PROXY'))
116
+ const configured = url.protocol === 'https:' ? environmentValue(env, 'HTTPS_PROXY') || environmentValue(env, 'ALL_PROXY') || environmentValue(env, 'HTTP_PROXY')
117
+ : environmentValue(env, 'HTTP_PROXY') || environmentValue(env, 'ALL_PROXY')
118
+ const proxy = bypassAll ? '' : configured ? proxyAddress(configured) : platform === 'win32' ? await systemProxy(url.href, signal) : ''
119
+ return nodeFetch(url, { ...options, signal }, proxy)
120
+ }
121
+
122
+ async function fetch(input, options = {}) {
123
+ if (stopped) throw fail('论文插件已停止,书目查询已取消。')
124
+ const controller = new AbortController()
125
+ const abort = () => controller.abort(options.signal.reason)
126
+ if (options.signal?.aborted) abort()
127
+ else options.signal?.addEventListener('abort', abort, { once: true })
128
+ controllers.add(controller)
129
+ const job = perform(input, options, controller.signal)
130
+ running.add(job)
131
+ try { return await job }
132
+ finally {
133
+ options.signal?.removeEventListener('abort', abort)
134
+ controllers.delete(controller)
135
+ running.delete(job)
136
+ }
137
+ }
138
+
139
+ async function dispose() {
140
+ stopped = true
141
+ for (const controller of controllers) controller.abort(new DOMException('书目查询已取消。', 'AbortError'))
142
+ await Promise.allSettled([...running])
143
+ proxyCache.clear()
144
+ }
145
+ return { fetch, dispose }
146
+ }
@@ -0,0 +1,158 @@
1
+ import { request as httpRequest, Agent as HttpAgent } from 'node:http'
2
+ import { request as httpsRequest, Agent as HttpsAgent } from 'node:https'
3
+ import { BlockList, isIP, connect } from 'node:net'
4
+ import { lookup } from 'node:dns/promises'
5
+ import { once } from 'node:events'
6
+ import { readFile } from 'node:fs/promises'
7
+ import * as tls from 'node:tls'
8
+ import { HttpsProxyAgent } from 'https-proxy-agent'
9
+ import { SocksClient } from 'socks'
10
+
11
+ const MAX_BODY = 1024 * 1024
12
+ const networkError = message => Object.assign(new Error(message), { code: 'METADATA_NETWORK' })
13
+
14
+ function socksAgent(address, secure, ca, signal) {
15
+ const agent = secure ? new HttpsAgent() : new HttpAgent()
16
+ const pending = new Set()
17
+ const destroy = agent.destroy.bind(agent)
18
+ agent.destroy = () => { for (const socket of pending) socket.destroy(); destroy() }
19
+ agent.createConnection = (options, callback) => {
20
+ let socket
21
+ const establish = async () => {
22
+ let host = options.host
23
+ if (['socks4:', 'socks5:'].includes(address.protocol) && !isIP(host)) {
24
+ host = (await lookup(host, address.protocol === 'socks4:' ? { family: 4 } : {})).address
25
+ }
26
+ signal.throwIfAborted()
27
+ socket = connect({ host: address.hostname.replace(/^\[|\]$/g, ''), port: Number(address.port || 1080), signal })
28
+ pending.add(socket)
29
+ await once(socket, 'connect', { signal })
30
+ // Own the socket before negotiation so cancellation also interrupts an incomplete SOCKS handshake.
31
+ await SocksClient.createConnection({
32
+ command: 'connect', timeout: 20000, existing_socket: socket,
33
+ proxy: { host: address.hostname.replace(/^\[|\]$/g, ''), port: Number(address.port || 1080),
34
+ type: address.protocol.startsWith('socks4') ? 4 : 5,
35
+ userId: decodeURIComponent(address.username), password: decodeURIComponent(address.password) },
36
+ destination: { host, port: Number(options.port) },
37
+ })
38
+ signal.throwIfAborted()
39
+ const connected = secure ? tls.connect({ ...options, host: undefined, port: undefined, socket, ca, rejectUnauthorized: true,
40
+ servername: options.servername || (!isIP(options.host) ? options.host : undefined), signal }) : socket
41
+ pending.delete(socket)
42
+ callback(null, connected)
43
+ }
44
+ establish().catch(error => {
45
+ if (socket) { pending.delete(socket); socket.destroy() }
46
+ callback(signal.aborted ? signal.reason : Object.assign(networkError('SOCKS 代理连接失败,请检查代理地址、认证与网络。'), { cause: { code: error?.code } }))
47
+ })
48
+ }
49
+ return agent
50
+ }
51
+
52
+ export function bypassProxy(url, rules = '') {
53
+ const host = url.hostname.replace(/^\[|\]$/g, '').toLowerCase()
54
+ const port = url.port || (url.protocol === 'https:' ? '443' : '80')
55
+ return rules.split(/[\s,]+/).filter(Boolean).some(raw => {
56
+ if (raw === '*') return true
57
+ if (raw.includes('/')) {
58
+ const [address, bits] = raw.split('/')
59
+ if (!isIP(address) || !isIP(host) || !/^\d+$/.test(bits ?? '')) return false
60
+ try {
61
+ const list = new BlockList(), family = isIP(address) === 6 ? 'ipv6' : 'ipv4'
62
+ list.addSubnet(address, Number(bits), family)
63
+ return list.check(host, isIP(host) === 6 ? 'ipv6' : 'ipv4')
64
+ } catch { return false }
65
+ }
66
+ let entry = raw.toLowerCase(), entryPort = ''
67
+ const bracket = /^\[([^\]]+)\](?::(\d+))?$/.exec(entry)
68
+ if (bracket) { entry = bracket[1]; entryPort = bracket[2] ?? '' }
69
+ else if (!isIP(entry)) {
70
+ const match = /^(.*):(\d+)$/.exec(entry)
71
+ if (match) { entry = match[1]; entryPort = match[2] }
72
+ }
73
+ if (entryPort && entryPort !== port) return false
74
+ entry = entry.replace(/^\*?\./, '')
75
+ return host === entry || !isIP(host) && host.endsWith('.' + entry)
76
+ })
77
+ }
78
+
79
+ /** Local agents keep proxy routing and certificate trust independent of process-global fetch. */
80
+ export function createMetadataNodeFetch({ env, platform, systemCertificates }) {
81
+ let rootsPromise
82
+ const value = name => env[name.toLowerCase()] || env[name] || ''
83
+ async function certificates(signal) {
84
+ if (!rootsPromise) rootsPromise = (async () => {
85
+ const roots = [...(typeof tls.getCACertificates === 'function' ? tls.getCACertificates('default') : tls.rootCertificates)]
86
+ if (platform === 'win32') roots.push(...(typeof tls.getCACertificates === 'function'
87
+ ? tls.getCACertificates('system') : await systemCertificates(signal)))
88
+ return [...new Set(roots)]
89
+ })().catch(error => { rootsPromise = null; throw error })
90
+ const roots = [...await rootsPromise]
91
+ for (const path of new Set([value('CURL_CA_BUNDLE') || value('SSL_CERT_FILE'), value('NODE_EXTRA_CA_CERTS')].filter(Boolean))) {
92
+ try { roots.push(await readFile(path, 'utf8')) }
93
+ catch { throw Object.assign(new Error('书目查询的 CA 文件无法读取,请检查证书文件配置。'), { code: 'METADATA_TLS' }) }
94
+ }
95
+ return roots
96
+ }
97
+
98
+ return async function fetch(url, options, proxy) {
99
+ const ca = await certificates(options.signal)
100
+ options.signal?.throwIfAborted()
101
+ let agent
102
+ if (proxy) {
103
+ const address = new URL(proxy)
104
+ if (address.protocol.startsWith('socks')) {
105
+ agent = socksAgent(address, url.protocol === 'https:', ca, options.signal)
106
+ } else {
107
+ const headers = {}
108
+ if (address.username || address.password) {
109
+ headers['Proxy-Authorization'] = 'Basic ' + Buffer.from(decodeURIComponent(address.username) + ':' + decodeURIComponent(address.password)).toString('base64')
110
+ address.username = ''; address.password = ''
111
+ }
112
+ agent = new HttpsProxyAgent(address, { ca, headers, signal: options.signal, rejectUnauthorized: true })
113
+ }
114
+ }
115
+ try {
116
+ return await new Promise((resolve, reject) => {
117
+ let result, failure, ended = false
118
+ const request = (url.protocol === 'https:' ? httpsRequest : httpRequest)(url, {
119
+ method: 'GET', headers: Object.fromEntries(new Headers(options.headers)),
120
+ agent: agent ?? false, ca, signal: options.signal, rejectUnauthorized: true,
121
+ }, incoming => {
122
+ const chunks = []
123
+ let size = 0
124
+ incoming.on('data', chunk => {
125
+ size += chunk.length
126
+ if (size > MAX_BODY) { incoming.destroy(new Error('书目响应过大,未使用该结果。')); return }
127
+ chunks.push(chunk)
128
+ })
129
+ incoming.on('error', error => { failure ??= error; request.destroy(error) })
130
+ incoming.on('end', () => {
131
+ ended = true
132
+ const status = incoming.statusCode
133
+ const headers = new Headers()
134
+ for (const [name, value] of Object.entries(incoming.headers)) {
135
+ if (Array.isArray(value)) value.forEach(item => headers.append(name, item))
136
+ else if (value !== undefined) headers.set(name, value)
137
+ }
138
+ try { result = new Response([204, 205, 304].includes(status) ? null : Buffer.concat(chunks), { status, headers }) }
139
+ catch { failure = networkError('书目来源返回了无效的 HTTP 响应。') }
140
+ })
141
+ })
142
+ request.on('proxyConnect', connect => {
143
+ if (connect.statusCode !== 200) {
144
+ failure = networkError(connect.statusCode === 407 ? '代理要求认证,请核对代理认证设置。' : '代理连接失败(HTTP ' + connect.statusCode + ')。')
145
+ request.destroy(failure)
146
+ }
147
+ })
148
+ request.on('error', error => { failure ??= error })
149
+ request.on('close', () => {
150
+ if (failure) reject(failure)
151
+ else if (!ended || !result) reject(networkError('书目连接提前关闭,未使用不完整结果。'))
152
+ else resolve(result)
153
+ })
154
+ request.end()
155
+ })
156
+ } finally { agent?.destroy() }
157
+ }
158
+ }
@@ -0,0 +1,35 @@
1
+ $ErrorActionPreference = 'Stop'
2
+ [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
3
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
4
+
5
+ try {
6
+ $Request = [Console]::In.ReadToEnd() | ConvertFrom-Json
7
+ if ($Request.task -eq 'certificates') {
8
+ $Certificates = @()
9
+ foreach ($Location in @('CurrentUser', 'LocalMachine')) {
10
+ foreach ($StoreName in @('Root', 'CertificateAuthority')) {
11
+ $Store = New-Object System.Security.Cryptography.X509Certificates.X509Store($StoreName, $Location)
12
+ try {
13
+ $Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
14
+ foreach ($Certificate in $Store.Certificates) {
15
+ $Certificates += '-----BEGIN CERTIFICATE-----' + "`n" + [Convert]::ToBase64String($Certificate.RawData) + "`n-----END CERTIFICATE-----"
16
+ }
17
+ } finally { $Store.Close() }
18
+ }
19
+ }
20
+ @{ certificates = @($Certificates) } | ConvertTo-Json -Compress
21
+ exit 0
22
+ }
23
+ $Destination = [Uri]$Request.url
24
+ if ($Destination.Scheme -notin @('http', 'https')) { exit 1 }
25
+ $SystemProxy = [System.Net.WebRequest]::GetSystemWebProxy()
26
+ $ProxyAddress = $SystemProxy.GetProxy($Destination)
27
+ $Address = $null
28
+ if ($null -ne $ProxyAddress -and $ProxyAddress.AbsoluteUri -ne $Destination.AbsoluteUri) {
29
+ $Address = $ProxyAddress.AbsoluteUri
30
+ }
31
+ @{ proxy = $Address } | ConvertTo-Json -Compress
32
+ } catch {
33
+ # Configuration values and proxy authentication details stay out of diagnostics.
34
+ exit 1
35
+ }
@@ -0,0 +1,95 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
3
+ import { dirname, join } from 'node:path'
4
+ import { replaceStateFile } from './storage.js'
5
+
6
+ /**
7
+ * MinerU 令牌由插件自己保管:明文只写在 `<runtimeRoot>/mineru.json` 里,宿主日志、HTTP 响应
8
+ * 与页面一律只见打码值。此前它读的是 `$DSH_HOME/.env` 的 `MINERU_API_TOKEN`(与官方
9
+ * dsh-mcp-client 的 mineru 行共用一份),那既让插件的配置散在别人的文件里,也没法在插件详情页
10
+ * 录入。
11
+ */
12
+ export const MINERU_KEY_SCHEMA_VERSION = 1
13
+
14
+ /** 令牌长度上限:超过它的一律按坏输入拒绝,而不是写进文件再让下游解析失败。 */
15
+ export const MAX_MINERU_KEY_LENGTH = 512
16
+
17
+ const MASK = '********'
18
+
19
+ // 同一毫秒内的两次保存(连点两下)会撞出同一个临时文件名:第一个 rename 已经把临时文件搬走,
20
+ // 第二个就会以 ENOENT 变成 500。计数器让进程内永远撞不上。
21
+ let temporarySequence = 0
22
+
23
+ /** 插件自己那份令牌文件的位置。`runtimeRoot` 由 index.js 的 `runtimeRoot(config)` 给出。 */
24
+ export function mineruKeyPath(runtimeRoot) {
25
+ return join(runtimeRoot, 'mineru.json')
26
+ }
27
+
28
+ /**
29
+ * 读回令牌;任何"读不出来"的情形都当作未配置返回空串,绝不抛错。
30
+ *
31
+ * 令牌文件是用户手边的东西(可能被删、被同步工具写坏、被手工编辑成数组),而调用方是每次
32
+ * 打开插件详情页都会跑的 GET 路由:这里抛错就变成设置页上的 5xx,而不是一句"未配置"。
33
+ */
34
+ export async function readMineruKey(file) {
35
+ let value
36
+ try {
37
+ value = JSON.parse(await readFile(file, 'utf8'))
38
+ } catch {
39
+ // ENOENT(还没配过)、权限、非法 JSON 走同一条路:未配置。
40
+ return ''
41
+ }
42
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return ''
43
+ return typeof value.key === 'string' ? value.key : ''
44
+ }
45
+
46
+ /**
47
+ * {@link readMineruKey} 的同步版本,给「解析前先看一眼有没有 Key」这条同步判定用。
48
+ *
49
+ * 判定本身是个纯逻辑(`mineruSdkConfig` 收值、不收路径),把它做成 async 会让
50
+ * `describeMineru()` 也跟着变成 Promise —— 一个只读当前状态的访问器返回 Promise,调用方
51
+ * 漏一个 `await` 就会把 `[object Promise]` 送进侧栏。文件只有几十字节,同步读的代价
52
+ * 远小于这条接线的脆弱性。退化规则与异步版逐字相同:读不出来就是未配置。
53
+ */
54
+ export function readMineruKeySync(file) {
55
+ let value
56
+ try {
57
+ value = JSON.parse(readFileSync(file, 'utf8'))
58
+ } catch {
59
+ return ''
60
+ }
61
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return ''
62
+ return typeof value.key === 'string' ? value.key : ''
63
+ }
64
+
65
+ /**
66
+ * 打码值:长度 ≥ 12 时保留前 4 位与后 4 位,中间固定 8 个 `*`;更短的一律只给 8 个 `*`。
67
+ *
68
+ * 定长掩码是刻意的——掩码长度不随 Key 长度变化,否则"看到几个星号"本身就成了长度信息。
69
+ * 返回值在任何输入下都不等于完整 Key(最短的 12 位 Key 也只露出 8 位)。
70
+ */
71
+ export function maskMineruKey(key) {
72
+ const text = typeof key === 'string' ? key : ''
73
+ if (text === '') return ''
74
+ if (text.length < 12) return MASK
75
+ return `${text.slice(0, 4)}${MASK}${text.slice(-4)}`
76
+ }
77
+
78
+ /**
79
+ * 写入令牌;空串表示清除(仍落盘,写 `{schemaVersion:1,key:''}`,而不是删文件)。
80
+ *
81
+ * 走临时文件 + 原子替换,并复用 storage.js 的 {@link replaceStateFile}:Windows 上覆盖一个
82
+ * 正被读的 `mineru.json` 会被杀软扫描或并发读取短暂挡住(EPERM/EBUSY/EACCES),那边的退避
83
+ * 重试就是为这种抖动准备的。权限 0o600:这是明文凭据,别的用户不该读得到(POSIX 上生效,
84
+ * Windows 上由 ACL 决定)。
85
+ */
86
+ export async function writeMineruKey(file, key) {
87
+ const value = { schemaVersion: MINERU_KEY_SCHEMA_VERSION, key: typeof key === 'string' ? key : '' }
88
+ const directory = dirname(file)
89
+ await mkdir(directory, { recursive: true })
90
+ temporarySequence += 1
91
+ const temporary = join(directory, `.mineru.${process.pid}.${Date.now()}.${temporarySequence}.tmp`)
92
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
93
+ await replaceStateFile(temporary, file)
94
+ return value
95
+ }
@@ -0,0 +1,123 @@
1
+ """Preserve one complete MinerU SDK result without the MCP formatter or repeat downloads."""
2
+
3
+ import json
4
+ import os
5
+ import sys
6
+ import time
7
+ from pathlib import Path
8
+
9
+
10
+ RESULT_BEGIN = "DSH-PAPER-MINERU-BEGIN"
11
+ RESULT_END = "DSH-PAPER-MINERU-END"
12
+
13
+
14
+ def _pin_utf8_stdio() -> None:
15
+ """把 stdin/stdout 钉成 UTF-8(与 page-image-helper.py 同一条理由)。
16
+
17
+ 🔴 这一条影响**整篇解析**:pdfPath / outputDir 里只要有中文,stdin 按 cp936 解就会
18
+ 抛 UnicodeDecodeError,症状是「别的电脑上一加论文就失败」,而本机(ACP=65001)永不复现。
19
+ """
20
+ for stream in (sys.stdin, sys.stdout):
21
+ reconfigure = getattr(stream, "reconfigure", None)
22
+ if reconfigure is not None:
23
+ try:
24
+ reconfigure(encoding="utf-8")
25
+ except (ValueError, OSError):
26
+ pass
27
+
28
+ # Windows 上 os.replace 可能被占用句柄挡住(杀软扫描/并发读取),报 PermissionError。
29
+ # 与 Node 侧 replaceStateFile 同样的处置:退避重试;不重试的话一次抖动就丢掉整份块列表。
30
+ REPLACE_ATTEMPTS = 10
31
+
32
+
33
+ def _replace(temporary: Path, target: Path) -> None:
34
+ for attempt in range(REPLACE_ATTEMPTS):
35
+ try:
36
+ os.replace(temporary, target)
37
+ return
38
+ except PermissionError:
39
+ if attempt == REPLACE_ATTEMPTS - 1:
40
+ raise
41
+ time.sleep(0.02 * (attempt + 1))
42
+
43
+
44
+ def _save_content_list(content_list: list, output_dir: str):
45
+ """把 MinerU 的原始块列表落盘,返回它的路径。
46
+
47
+ 回传文件路径而不是内联 JSON 是有意的:Node 侧把 helper 的 stdout 上限钉在 1 MiB
48
+ (mineru-sdk.js 的 MAX_STDOUT_BYTES),而长文档的块列表本身就能顶到这个量级,
49
+ 内联会让整次解析失败。使用本次输出目录中的固定文件名,不采用远端文件路径。
50
+ """
51
+ target = Path(output_dir) / "content_list.json"
52
+ target.parent.mkdir(parents=True, exist_ok=True)
53
+ temporary = target.with_name(f".{target.name}.{os.getpid()}.tmp")
54
+ temporary.write_text(json.dumps(content_list, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
55
+ _replace(temporary, target)
56
+ return str(target)
57
+
58
+
59
+ def parse(request: dict) -> dict:
60
+ from mineru.client import MinerU
61
+
62
+ token = os.environ.get("MINERU_API_TOKEN")
63
+ if not token:
64
+ raise RuntimeError("MinerU API Key is required for structured parsing")
65
+ model = request.get("model", "vlm")
66
+ language = request.get("language", "ch")
67
+ if model not in ("vlm", "pipeline") or not isinstance(language, str) or not language.strip():
68
+ raise ValueError("Invalid MinerU model or language")
69
+ ocr = request.get("ocr", False)
70
+ if not isinstance(ocr, bool):
71
+ raise ValueError("MinerU ocr must be boolean")
72
+ timeout_ms = request.get("timeoutMs", 900000)
73
+ if not isinstance(timeout_ms, (int, float)) or isinstance(timeout_ms, bool) or timeout_ms <= 0:
74
+ raise ValueError("MinerU timeout must be positive")
75
+ with MinerU(token=token) as client:
76
+ result = client.extract(
77
+ request["pdfPath"], model=model, language=language, ocr=ocr,
78
+ formula=True, table=True, timeout=max(1, int(timeout_ms / 1000)),
79
+ )
80
+ if result.state != "done":
81
+ raise RuntimeError(f"MinerU parse failed [{result.err_code}]: {result.error or result.state}")
82
+ if not isinstance(result.markdown, str) or not result.markdown.strip():
83
+ raise RuntimeError("MinerU returned empty Markdown")
84
+ # A fresh precision parse needs its own structure; never silently publish a Markdown-only result.
85
+ if not isinstance(result.content_list, list) or not result.content_list:
86
+ raise RuntimeError("MinerU returned no structured content list")
87
+ output = Path(request["outputDir"])
88
+ output.mkdir(parents=True, exist_ok=True)
89
+ markdown_path = output / "full.md"
90
+ temporary = output / f".markdown.{os.getpid()}.tmp"
91
+ temporary.write_text(result.markdown, encoding="utf-8")
92
+ _replace(temporary, markdown_path)
93
+ payload = {
94
+ "filename": Path(request["pdfPath"]).name, "status": "success",
95
+ "extract_path": str(markdown_path),
96
+ "content_list_path": _save_content_list(result.content_list, str(output)),
97
+ }
98
+ # Node validates ZIP entries and only restores referenced assets. Do not call save_all/extractall.
99
+ archive = getattr(result, "_zip_bytes", None)
100
+ if isinstance(archive, bytes):
101
+ if len(archive) > 256 * 1024 * 1024:
102
+ raise RuntimeError("MinerU result ZIP exceeds 256 MiB")
103
+ archive_path = output / "result.zip"
104
+ temporary = output / f".archive.{os.getpid()}.tmp"
105
+ temporary.write_bytes(archive)
106
+ _replace(temporary, archive_path)
107
+ payload["archive_path"] = str(archive_path)
108
+ elif result.zip_url:
109
+ payload["zip_url"] = result.zip_url
110
+ return payload
111
+
112
+
113
+ if __name__ == "__main__":
114
+ _pin_utf8_stdio()
115
+ try:
116
+ response = {"ok": True, "result": parse(json.loads(sys.stdin.read()))}
117
+ except Exception as error:
118
+ response = {"ok": False, "error": f"{type(error).__name__}: {error}"}
119
+ print(RESULT_BEGIN)
120
+ print(json.dumps(response, ensure_ascii=False))
121
+ print(RESULT_END)
122
+ if not response["ok"]:
123
+ raise SystemExit(1)