@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.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -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 +2607 -0
  19. package/lib/client.js +9569 -0
  20. package/lib/code-source.js +68 -0
  21. package/lib/concurrency-gate.js +91 -0
  22. package/lib/context.js +233 -0
  23. package/lib/csl/SOURCES.md +10 -0
  24. package/lib/csl/gb-t-7714.csl +441 -0
  25. package/lib/csl/ieee.csl +520 -0
  26. package/lib/csl/locales-zh-CN.xml +438 -0
  27. package/lib/csl/nature.csl +190 -0
  28. package/lib/discussion.js +400 -0
  29. package/lib/documents.js +67 -0
  30. package/lib/export.js +848 -0
  31. package/lib/file-lock.js +177 -0
  32. package/lib/gloss.js +181 -0
  33. package/lib/glossary.js +279 -0
  34. package/lib/index.js +3862 -0
  35. package/lib/inline-html.js +53 -0
  36. package/lib/install-dependency.js +120 -0
  37. package/lib/item-ops.js +83 -0
  38. package/lib/job-facade.js +58 -0
  39. package/lib/json-store.js +54 -0
  40. package/lib/library-model.js +132 -0
  41. package/lib/library-service.js +180 -0
  42. package/lib/library-tool.js +982 -0
  43. package/lib/library.js +814 -0
  44. package/lib/markdown-assets.js +138 -0
  45. package/lib/markdown-literals.js +93 -0
  46. package/lib/metadata-enrichment.js +516 -0
  47. package/lib/metadata-fetch.js +146 -0
  48. package/lib/metadata-node.js +158 -0
  49. package/lib/metadata-proxy.ps1 +35 -0
  50. package/lib/mineru-config.js +95 -0
  51. package/lib/mineru-sdk-helper.py +123 -0
  52. package/lib/mineru-sdk.js +182 -0
  53. package/lib/mineru.js +268 -0
  54. package/lib/mirror-export.js +240 -0
  55. package/lib/outline.js +296 -0
  56. package/lib/page-image-helper.py +294 -0
  57. package/lib/page-image.js +454 -0
  58. package/lib/paper-metadata.js +242 -0
  59. package/lib/parse-export.js +631 -0
  60. package/lib/pdf-analysis-tool.js +750 -0
  61. package/lib/pdf-metadata-helper.py +75 -0
  62. package/lib/pdf-metadata.js +141 -0
  63. package/lib/pdf-page.js +183 -0
  64. package/lib/pdf-scan.js +134 -0
  65. package/lib/pdf-text.js +68 -0
  66. package/lib/picker.js +305 -0
  67. package/lib/portable.js +379 -0
  68. package/lib/purge.js +170 -0
  69. package/lib/read-tool.js +660 -0
  70. package/lib/reader-store.js +497 -0
  71. package/lib/reading-order.js +207 -0
  72. package/lib/rename-document.js +480 -0
  73. package/lib/rename.js +372 -0
  74. package/lib/renderer-status.js +161 -0
  75. package/lib/resolver.js +1152 -0
  76. package/lib/result-archive.js +157 -0
  77. package/lib/revisions.js +330 -0
  78. package/lib/search-database.js +62 -0
  79. package/lib/search-index.js +601 -0
  80. package/lib/search-scan.js +185 -0
  81. package/lib/search-source.js +23 -0
  82. package/lib/search-terms.js +539 -0
  83. package/lib/section-audit.js +209 -0
  84. package/lib/selection-message.js +332 -0
  85. package/lib/serial-tail.js +21 -0
  86. package/lib/slicing.js +425 -0
  87. package/lib/source-resolver.js +581 -0
  88. package/lib/stem-repair.js +189 -0
  89. package/lib/storage.js +562 -0
  90. package/lib/store-paths.js +253 -0
  91. package/lib/table-gfm.js +236 -0
  92. package/lib/tasks.js +270 -0
  93. package/lib/tex-align.js +509 -0
  94. package/lib/tex-blocks.js +653 -0
  95. package/lib/tex-fetch.js +455 -0
  96. package/lib/tex-figures.js +140 -0
  97. package/lib/tex-inline.js +166 -0
  98. package/lib/tex-merge.js +279 -0
  99. package/lib/tex-pipeline.js +242 -0
  100. package/lib/tex-prepare.js +746 -0
  101. package/lib/tex-tables.js +210 -0
  102. package/lib/text-similarity.js +85 -0
  103. package/lib/tool-contract.js +86 -0
  104. package/lib/tool-host.js +1058 -0
  105. package/lib/tool-identity.js +214 -0
  106. package/lib/translatable-text.js +48 -0
  107. package/lib/translate-prompts.js +709 -0
  108. package/lib/translate-queue.js +418 -0
  109. package/lib/translate-task.js +158 -0
  110. package/lib/translate.js +909 -0
  111. package/lib/update-check.js +438 -0
  112. package/lib/update-contracts.js +75 -0
  113. package/lib/usage.js +282 -0
  114. package/package.json +55 -4
@@ -0,0 +1,138 @@
1
+ import { copyFile, mkdir, readFile, stat, writeFile } from 'node:fs/promises'
2
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'
3
+ import { requestedFilesFromZip } from './result-archive.js'
4
+
5
+ const MARKDOWN_IMAGE = /!\[[^\]\r\n]*\]\(\s*(?:<([^>\r\n]+)>|([^\s)\r\n]+))(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|\([^\r\n)]*\)))?\s*\)/g
6
+ const URI_SCHEME = /^[a-z][a-z0-9+.-]*:/i
7
+
8
+ function decodedPath(value) {
9
+ const withoutSuffix = value.split(/[?#]/, 1)[0]
10
+ try { return decodeURIComponent(withoutSuffix) } catch { return withoutSuffix }
11
+ }
12
+
13
+ function isWithin(root, path) {
14
+ const child = relative(root, path)
15
+ return child === '' || (!isAbsolute(child) && child !== '..' && !child.startsWith(`..${sep}`))
16
+ }
17
+
18
+ export function localMarkdownImagePaths(markdown) {
19
+ const paths = new Set()
20
+ for (const match of markdown.matchAll(MARKDOWN_IMAGE)) {
21
+ const value = decodedPath(match[1] ?? match[2])
22
+ if (!value || value.startsWith('#') || isAbsolute(value) || URI_SCHEME.test(value)) continue
23
+ paths.add(value)
24
+ }
25
+ return [...paths]
26
+ }
27
+
28
+ function resolvedImagePath(markdownPath, imagePath) {
29
+ const root = dirname(resolve(markdownPath))
30
+ const path = resolve(root, imagePath)
31
+ if (!isWithin(root, path)) throw new Error(`Markdown 图片路径越出结果目录:${imagePath}`)
32
+ return path
33
+ }
34
+
35
+ async function requireImageFile(path, imagePath) {
36
+ const info = await stat(path)
37
+ if (!info.isFile()) throw new Error(`Markdown 图片不是文件:${imagePath}`)
38
+ }
39
+
40
+ async function isFile(path) {
41
+ try { return (await stat(path)).isFile() } catch { return false }
42
+ }
43
+
44
+ export async function verifyMarkdownImages(markdown, markdownPath) {
45
+ for (const imagePath of localMarkdownImagePaths(markdown)) {
46
+ await requireImageFile(resolvedImagePath(markdownPath, imagePath), imagePath)
47
+ }
48
+ }
49
+
50
+ export async function missingMarkdownImagePaths(markdown, markdownPath) {
51
+ const missing = []
52
+ for (const imagePath of localMarkdownImagePaths(markdown)) {
53
+ if (!await isFile(resolvedImagePath(markdownPath, imagePath))) missing.push(imagePath)
54
+ }
55
+ return missing
56
+ }
57
+
58
+ export async function restoreMarkdownImagesFromZip(markdown, markdownPath, archive) {
59
+ const missing = await missingMarkdownImagePaths(markdown, markdownPath)
60
+ const files = requestedFilesFromZip(archive, missing)
61
+ for (const [imagePath, content] of files) {
62
+ const destination = resolvedImagePath(markdownPath, imagePath)
63
+ await mkdir(dirname(destination), { recursive: true })
64
+ await writeFile(destination, content)
65
+ await requireImageFile(destination, imagePath)
66
+ }
67
+ return { restoredImages: [...files.keys()], missingImages: missing.filter(path => !files.has(path)) }
68
+ }
69
+
70
+ /**
71
+ * 把 Markdown 引用到的本地图片解析成一份**搬移计划**,一个字节都不写。
72
+ *
73
+ * 🔴 发布路径必须走这里,不能走 {@link copyMarkdownImages}:正文与图片是同一份结果的两种
74
+ * 载体,正文按事务写(`writeAnalysisBundle`:全部 stage 好才一起 rename,失败就回滚),而
75
+ * 图片若在此之前就直接覆盖,正文一失败就留下**旧正文 + 新图片**的错位 —— 读者看到上一版的
76
+ * 文字配这一版的图,且没有任何记录能发现这件事(文件名相同,宽度高度也常常相同)。
77
+ * 计划交给 `writeAnalysisBundle` 的 `copies` 之后,两者同批提交、同批回滚。
78
+ *
79
+ * 目标目录里由 MinerU 结果 ZIP 恢复的图片同样算有效(源侧缺失时不判为断链);
80
+ * 两边都缺失才剔除引用,避免发布断链。
81
+ *
82
+ * @param {string} markdown 原文。
83
+ * @param {string} sourceMarkdownPath 本次结果的 Markdown 路径(图片相对它解析)。
84
+ * @param {string} destinationMarkdownPath 发布目标的 Markdown 路径。
85
+ * @returns {Promise<{markdown: string, missingImages: string[], copies: Array<{source: string, destination: string, path: string}>}>}
86
+ * `markdown` 是剔除掉断链引用之后的正文;`copies` 里 `path` 是 Markdown 里写的那个相对路径(只用于日志与报错)。
87
+ */
88
+ export async function planMarkdownImages(markdown, sourceMarkdownPath, destinationMarkdownPath) {
89
+ const missing = new Set()
90
+ const copies = []
91
+ for (const imagePath of localMarkdownImagePaths(markdown)) {
92
+ const source = resolvedImagePath(sourceMarkdownPath, imagePath)
93
+ const destination = resolvedImagePath(destinationMarkdownPath, imagePath)
94
+ if (!await isFile(source)) {
95
+ if (!await isFile(destination)) missing.add(imagePath)
96
+ continue
97
+ }
98
+ if (source !== destination) copies.push({ source, destination, path: imagePath })
99
+ }
100
+ return { markdown: stripImageReferences(markdown, missing), missingImages: [...missing], copies }
101
+ }
102
+
103
+ // 把 Markdown 引用到的本地图片按原相对路径从源目录复制到目标目录。
104
+ //
105
+ // 🔴 逐张直接写盘,**不能**用于发布路径(见 {@link planMarkdownImages} 的说明):发布要把图片
106
+ // 交给正文那个事务一起提交。现在只剩两个调用方,两处都在**解析 scratch** 里:
107
+ // `mineru.materializeMineruResult` 把外部结果物化到 `documents/<hash>/<job>/`,
108
+ // 以及本模块的测试。scratch 里写坏了不影响已发布的资产。
109
+ export async function copyMarkdownImages(markdown, sourceMarkdownPath, destinationMarkdownPath) {
110
+ const plan = await planMarkdownImages(markdown, sourceMarkdownPath, destinationMarkdownPath)
111
+ for (const { source, destination, path } of plan.copies) {
112
+ await mkdir(dirname(destination), { recursive: true })
113
+ await copyFile(source, destination)
114
+ await requireImageFile(destination, path)
115
+ }
116
+ return { markdown: plan.markdown, missingImages: plan.missingImages }
117
+ }
118
+
119
+ function stripImageReferences(markdown, missing) {
120
+ if (missing.size === 0) return markdown
121
+ let stripped = ''
122
+ let cursor = 0
123
+ for (const match of markdown.matchAll(MARKDOWN_IMAGE)) {
124
+ if (!missing.has(decodedPath(match[1] ?? match[2]))) continue
125
+ stripped += markdown.slice(cursor, match.index)
126
+ cursor = match.index + match[0].length
127
+ }
128
+ stripped += markdown.slice(cursor)
129
+ // 全文只有图片引用且全部缺失时保留原文,避免把一篇文档清成空文件。
130
+ return stripped.trim() === '' ? markdown : stripped
131
+ }
132
+
133
+ export async function readMarkdownBundle(markdownPath) {
134
+ const markdown = await readFile(markdownPath, 'utf8')
135
+ if (markdown.trim() === '') throw new Error('Markdown 文件为空')
136
+ await verifyMarkdownImages(markdown, markdownPath)
137
+ return markdown
138
+ }
@@ -0,0 +1,93 @@
1
+ /** Apply prose cleanup without rewriting code blocks, code spans or delimited math. */
2
+ export function mapMarkdownProse(text, transform) {
3
+ if (!/[`~$\\]/.test(text) && !/^(?:[ \t]*>)*[ \t]*(?: {4}|\t)/m.test(text)) return transform(text)
4
+ const ranges = []
5
+ let open, indented
6
+ let previousBlank = true, previousDepth = 0
7
+ for (const match of text.matchAll(/[^\r\n]*(?:\r?\n|$)/g)) {
8
+ if (match[0] === '') break
9
+ const line = match[0].replace(/\r?\n$/, '')
10
+ const prefix = /^(?: {0,3}>[ \t]?)+/.exec(line)?.[0] ?? ''
11
+ const depth = (prefix.match(/>/g) ?? []).length
12
+ const content = line.slice(prefix.length)
13
+ const blank = content.trim() === ''
14
+ const canIndent = previousBlank || depth !== previousDepth
15
+ previousBlank = blank
16
+ previousDepth = depth
17
+ const fence = /^ {0,3}(`{3,}|~{3,})([^\r\n]*)$/.exec(content)
18
+ if (open) {
19
+ if (open.depth > depth && !blank) {
20
+ ranges.push([open.at, match.index])
21
+ open = undefined
22
+ } else {
23
+ if (fence && depth === open.depth && fence[1][0] === open.marker && fence[1].length >= open.length && fence[2].trim() === '') {
24
+ ranges.push([open.at, match.index + match[0].length])
25
+ open = undefined
26
+ previousBlank = true
27
+ }
28
+ continue
29
+ }
30
+ }
31
+ const isIndented = /^(?: {4}|\t)/.test(content)
32
+ if (indented && (depth !== indented.depth || (!isIndented && !blank))) {
33
+ ranges.push([indented.at, indented.to])
34
+ indented = undefined
35
+ }
36
+ if (indented) {
37
+ indented.to = match.index + match[0].length
38
+ continue
39
+ }
40
+ if (fence && (fence[1][0] !== '`' || !fence[2].includes('`'))) {
41
+ open = { at: match.index, marker: fence[1][0], length: fence[1].length, depth }
42
+ } else if (isIndented && canIndent) {
43
+ indented = { at: match.index, to: match.index + match[0].length, depth }
44
+ }
45
+ }
46
+ if (open) ranges.push([open.at, text.length])
47
+ if (indented) ranges.push([indented.at, indented.to])
48
+ let output = '', cursor = 0
49
+ for (const [from, to] of ranges) {
50
+ output += mapCodeSpans(text.slice(cursor, from), transform) + text.slice(from, to)
51
+ cursor = to
52
+ }
53
+ return output + mapCodeSpans(text.slice(cursor), transform)
54
+ }
55
+
56
+ function escapedAt(text, at) {
57
+ let count = 0
58
+ while (at > 0 && text[--at] === '\\') count += 1
59
+ return count % 2 === 1
60
+ }
61
+
62
+ function mapCodeSpans(text, transform) {
63
+ const ticks = [...text.matchAll(/`+/g)]
64
+ const next = new Map(), closing = new Map()
65
+ // Match complete runs, including a closing run preceded by a literal backslash.
66
+ for (let index = ticks.length - 1; index >= 0; index -= 1) {
67
+ const length = ticks[index][0].length
68
+ if (next.has(length)) closing.set(index, next.get(length))
69
+ next.set(length, index)
70
+ }
71
+ let output = '', cursor = 0
72
+ for (let index = 0; index < ticks.length; index += 1) {
73
+ if (escapedAt(text, ticks[index].index) || !closing.has(index)) continue
74
+ const end = closing.get(index)
75
+ output += mapMath(text.slice(cursor, ticks[index].index), transform)
76
+ const to = ticks[end].index + ticks[end][0].length
77
+ output += text.slice(ticks[index].index, to)
78
+ cursor = to
79
+ index = end
80
+ }
81
+ return output + mapMath(text.slice(cursor), transform)
82
+ }
83
+
84
+ function mapMath(text, transform) {
85
+ // A single-dollar closer touches its content and cannot introduce another numeric amount.
86
+ const math = /(?<!\\)(?:\$\$[\s\S]*?(?<!\\)\$\$|\$(?![\s$])(?:\\[^\r\n]|[^$\\\r\n])+(?<![\\\s])\$(?!\p{N})|\\\([\s\S]*?\\\)|\\\[[\s\S]*?\\\])/gu
87
+ let output = '', cursor = 0
88
+ for (const match of text.matchAll(math)) {
89
+ output += transform(text.slice(cursor, match.index)) + match[0]
90
+ cursor = match.index + match[0].length
91
+ }
92
+ return output + transform(text.slice(cursor))
93
+ }