@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.
- package/LICENSE +21 -0
- package/README.md +150 -2
- package/cordis.patch.yml +4 -0
- package/lib/annotate-tool.js +334 -0
- package/lib/arxiv-id.js +74 -0
- package/lib/asset-routes.js +210 -0
- package/lib/bibliography-formats.js +126 -0
- package/lib/bibliography-import.js +105 -0
- package/lib/bibliography-service.js +43 -0
- package/lib/bibliography.js +42 -0
- package/lib/block-authors.js +292 -0
- package/lib/block-cache.js +39 -0
- package/lib/blocks-markdown.js +157 -0
- package/lib/blocks-reconcile.js +218 -0
- package/lib/blocks.js +1344 -0
- package/lib/citation-metadata.js +260 -0
- package/lib/citation-styles.js +120 -0
- package/lib/client-parts/01-pure-helpers.js +2762 -0
- package/lib/client-parts/02-author-year.js +95 -0
- package/lib/client.js +10381 -0
- package/lib/code-source.js +68 -0
- package/lib/concurrency-gate.js +91 -0
- package/lib/context.js +233 -0
- package/lib/csl/SOURCES.md +10 -0
- package/lib/csl/gb-t-7714.csl +441 -0
- package/lib/csl/ieee.csl +520 -0
- package/lib/csl/locales-zh-CN.xml +438 -0
- package/lib/csl/nature.csl +190 -0
- package/lib/discussion.js +400 -0
- package/lib/documents.js +67 -0
- package/lib/export.js +848 -0
- package/lib/file-lock.js +177 -0
- package/lib/gloss.js +181 -0
- package/lib/glossary.js +279 -0
- package/lib/index.js +3862 -0
- package/lib/inline-html.js +53 -0
- package/lib/install-dependency.js +120 -0
- package/lib/item-ops.js +83 -0
- package/lib/job-facade.js +58 -0
- package/lib/json-store.js +54 -0
- package/lib/library-model.js +132 -0
- package/lib/library-service.js +180 -0
- package/lib/library-tool.js +982 -0
- package/lib/library.js +814 -0
- package/lib/markdown-assets.js +138 -0
- package/lib/markdown-literals.js +93 -0
- package/lib/metadata-enrichment.js +516 -0
- package/lib/metadata-fetch.js +146 -0
- package/lib/metadata-node.js +158 -0
- package/lib/metadata-proxy.ps1 +35 -0
- package/lib/mineru-config.js +95 -0
- package/lib/mineru-sdk-helper.py +123 -0
- package/lib/mineru-sdk.js +182 -0
- package/lib/mineru.js +268 -0
- package/lib/mirror-export.js +240 -0
- package/lib/outline.js +296 -0
- package/lib/page-image-helper.py +308 -0
- package/lib/page-image.js +454 -0
- package/lib/paper-metadata.js +242 -0
- package/lib/parse-export.js +631 -0
- package/lib/pdf-analysis-tool.js +750 -0
- package/lib/pdf-metadata-helper.py +75 -0
- package/lib/pdf-metadata.js +141 -0
- package/lib/pdf-page.js +261 -0
- package/lib/pdf-scan.js +134 -0
- package/lib/pdf-text.js +68 -0
- package/lib/picker.js +305 -0
- package/lib/portable.js +379 -0
- package/lib/purge.js +170 -0
- package/lib/read-tool.js +660 -0
- package/lib/reader-store.js +497 -0
- package/lib/reading-order.js +207 -0
- package/lib/rename-document.js +480 -0
- package/lib/rename.js +372 -0
- package/lib/renderer-status.js +161 -0
- package/lib/resolver.js +1152 -0
- package/lib/result-archive.js +157 -0
- package/lib/revisions.js +330 -0
- package/lib/search-database.js +62 -0
- package/lib/search-index.js +601 -0
- package/lib/search-scan.js +185 -0
- package/lib/search-source.js +23 -0
- package/lib/search-terms.js +539 -0
- package/lib/section-audit.js +209 -0
- package/lib/selection-message.js +332 -0
- package/lib/serial-tail.js +21 -0
- package/lib/slicing.js +425 -0
- package/lib/source-resolver.js +581 -0
- package/lib/stem-repair.js +189 -0
- package/lib/storage.js +562 -0
- package/lib/store-paths.js +253 -0
- package/lib/table-gfm.js +236 -0
- package/lib/tasks.js +270 -0
- package/lib/tex-align.js +509 -0
- package/lib/tex-blocks.js +653 -0
- package/lib/tex-fetch.js +455 -0
- package/lib/tex-figures.js +140 -0
- package/lib/tex-inline.js +166 -0
- package/lib/tex-merge.js +279 -0
- package/lib/tex-pipeline.js +242 -0
- package/lib/tex-prepare.js +746 -0
- package/lib/tex-tables.js +210 -0
- package/lib/text-similarity.js +85 -0
- package/lib/tool-contract.js +86 -0
- package/lib/tool-host.js +1058 -0
- package/lib/tool-identity.js +214 -0
- package/lib/translatable-text.js +48 -0
- package/lib/translate-prompts.js +709 -0
- package/lib/translate-queue.js +418 -0
- package/lib/translate-task.js +158 -0
- package/lib/translate.js +909 -0
- package/lib/update-check.js +438 -0
- package/lib/update-contracts.js +75 -0
- package/lib/usage.js +282 -0
- package/package.json +55 -4
package/lib/portable.js
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import { copyFile, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
4
|
+
import { readMarkdownBundle } from './markdown-assets.js'
|
|
5
|
+
import { storePathsOf } from './store-paths.js'
|
|
6
|
+
import { BIBLIOGRAPHIC_FIELDS, METADATA_FACT_FIELDS, bibliographyOf, metadataSourcesOf } from './bibliography.js'
|
|
7
|
+
|
|
8
|
+
const MANIFEST_SUFFIX = '.dsh-paper.json'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 清单里保留的**字符串字段**。
|
|
12
|
+
*
|
|
13
|
+
* 🔴 title / authors / year 必须在这里,否则冷归档时会被丢掉:sidecar 记录的
|
|
14
|
+
* `writeArchivedRecord` **只留 `{id, pdfPath, artifact}`**,所以标题/作者能挺过归档的唯一
|
|
15
|
+
* 途径就是这个 manifest。丢了它的后果是"论文被 compact 驱逐一次,改名依据就没了"。
|
|
16
|
+
*
|
|
17
|
+
* renamedBy / renamedAt 同理:粘性(用户手动改过名就不再自动改名)必须跟着记录走。
|
|
18
|
+
*/
|
|
19
|
+
const MANIFEST_STRING_KEYS = ['readyAt', 'lastUsedAt', 'title', 'year', 'renamedBy', 'renamedAt', 'sourceDir', 'sourcePdfPath', ...BIBLIOGRAPHIC_FIELDS]
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 用户(或 agent)裁定「这条冲突保持原样」的记录:`{ [字段]: { value, provider, identifier, keptAt } }`。
|
|
23
|
+
*
|
|
24
|
+
* 🔴 归一在写与读两侧都做:只留合法书目字段,字段值只当**去重键**用(与下次来源值比相等),
|
|
25
|
+
* 所以形状坏掉就整条丢,不猜。
|
|
26
|
+
*/
|
|
27
|
+
function keptMetadataOf(value) {
|
|
28
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return {}
|
|
29
|
+
const kept = {}
|
|
30
|
+
for (const [key, row] of Object.entries(value)) {
|
|
31
|
+
if (!METADATA_FACT_FIELDS.includes(key)) continue
|
|
32
|
+
if (typeof row !== 'object' || row === null || Array.isArray(row)) continue
|
|
33
|
+
const entry = {}
|
|
34
|
+
if (row.value !== undefined) entry.value = row.value
|
|
35
|
+
for (const name of ['provider', 'identifier', 'keptAt']) {
|
|
36
|
+
if (typeof row[name] === 'string' && row[name] !== '') entry[name] = row[name]
|
|
37
|
+
}
|
|
38
|
+
if (Object.keys(entry).length === 0) continue
|
|
39
|
+
kept[key] = entry
|
|
40
|
+
}
|
|
41
|
+
return kept
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function manifestMetadataOf(document) {
|
|
45
|
+
const metadata = {}
|
|
46
|
+
const bibliography = bibliographyOf(document?.bibliography, document?.metadata, document)
|
|
47
|
+
if (Object.values(bibliography).some(Boolean)) metadata.bibliography = bibliography
|
|
48
|
+
if (Number.isFinite(document?.pdfSize) && document.pdfSize >= 0) metadata.pdfSize = document.pdfSize
|
|
49
|
+
if (Number.isFinite(document?.pdfMtimeMs) && document.pdfMtimeMs >= 0) metadata.pdfMtimeMs = document.pdfMtimeMs
|
|
50
|
+
if (typeof document?.outlineTruncated === 'boolean') metadata.outlineTruncated = document.outlineTruncated
|
|
51
|
+
if (Array.isArray(document?.authors)) {
|
|
52
|
+
const authors = document.authors.filter(author => typeof author === 'string' && author.trim() !== '')
|
|
53
|
+
metadata.authors = authors
|
|
54
|
+
}
|
|
55
|
+
if (Array.isArray(document?.clearedMetadata)) metadata.clearedMetadata = document.clearedMetadata.filter(key => METADATA_FACT_FIELDS.includes(key))
|
|
56
|
+
// 🔴 写侧看**有没有这个键**,不看它是不是空的:manifest 是合并语义
|
|
57
|
+
// (`{...previous.metadata, ...manifestMetadataOf(document)}`),空的 keptMetadata 必须能
|
|
58
|
+
// 覆盖掉旧值 —— 否则「手动改了这个字段 → 保留记录该失效」那条永远删不掉。
|
|
59
|
+
// 反过来,别的写入路径(发布、改名)的记录上没有这个键,就不碰它,保留记录不会丢。
|
|
60
|
+
if (Object.hasOwn(document ?? {}, 'keptMetadata')) metadata.keptMetadata = keptMetadataOf(document.keptMetadata)
|
|
61
|
+
if (document?.metadataSources) metadata.metadataSources = metadataSourcesOf(document.metadataSources)
|
|
62
|
+
if (document?.csl && typeof document.csl === 'object' && !Array.isArray(document.csl)) metadata.csl = document.csl
|
|
63
|
+
for (const key of MANIFEST_STRING_KEYS) {
|
|
64
|
+
if (typeof document?.[key] === 'string') metadata[key] = document[key]
|
|
65
|
+
}
|
|
66
|
+
return metadata
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function readManifestMetadata(value) {
|
|
70
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return {}
|
|
71
|
+
const metadata = {}
|
|
72
|
+
const bibliography = bibliographyOf(value.bibliography, value)
|
|
73
|
+
if (Object.values(bibliography).some(Boolean)) metadata.bibliography = bibliography
|
|
74
|
+
if (Number.isFinite(value.pdfSize) && value.pdfSize >= 0) metadata.pdfSize = value.pdfSize
|
|
75
|
+
if (Number.isFinite(value.pdfMtimeMs) && value.pdfMtimeMs >= 0) metadata.pdfMtimeMs = value.pdfMtimeMs
|
|
76
|
+
if (typeof value.outlineTruncated === 'boolean') metadata.outlineTruncated = value.outlineTruncated
|
|
77
|
+
if (Array.isArray(value.authors)) {
|
|
78
|
+
const authors = value.authors.filter(author => typeof author === 'string' && author.trim() !== '')
|
|
79
|
+
metadata.authors = authors
|
|
80
|
+
}
|
|
81
|
+
if (Array.isArray(value.clearedMetadata)) metadata.clearedMetadata = value.clearedMetadata.filter(key => METADATA_FACT_FIELDS.includes(key))
|
|
82
|
+
if (Object.keys(keptMetadataOf(value.keptMetadata)).length > 0) metadata.keptMetadata = keptMetadataOf(value.keptMetadata)
|
|
83
|
+
if (value.metadataSources) metadata.metadataSources = metadataSourcesOf(value.metadataSources)
|
|
84
|
+
if (value.csl && typeof value.csl === 'object' && !Array.isArray(value.csl)) metadata.csl = value.csl
|
|
85
|
+
for (const key of MANIFEST_STRING_KEYS) {
|
|
86
|
+
if (typeof value[key] === 'string') metadata[key] = value[key]
|
|
87
|
+
}
|
|
88
|
+
return metadata
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 一篇论文的解析产物落点(D127):runtime 里 `library/<documentId>/`,不再是 PDF 旁的 `analysis/`。
|
|
93
|
+
* 输入 runtimeRoot 与 {hash, name}(入库时已算好哈希与冻结文件名)。
|
|
94
|
+
*/
|
|
95
|
+
export function analysisPathsOf(runtimeRoot, pdf) {
|
|
96
|
+
const paths = storePathsOf(runtimeRoot, { id: pdf.hash, pdfName: pdf.name })
|
|
97
|
+
return {
|
|
98
|
+
dir: paths.dir,
|
|
99
|
+
markdown: paths.markdown,
|
|
100
|
+
outline: paths.outline,
|
|
101
|
+
content: paths.content,
|
|
102
|
+
manifest: paths.manifest,
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
|
|
107
|
+
|
|
108
|
+
// 与 lib/storage.js 的 replaceStateFile 同源:Windows 上"写临时文件再 rename 覆盖"会被杀软扫描
|
|
109
|
+
// 或并发读取短暂挡住,报 EPERM/EBUSY/EACCES,重试即可。这里不直接 import 那个模块 ——
|
|
110
|
+
// storage.js 已经 import 本模块,反向引用会形成循环依赖。
|
|
111
|
+
const REPLACE_RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES'])
|
|
112
|
+
const REPLACE_ATTEMPTS = 10
|
|
113
|
+
|
|
114
|
+
async function replaceFile(temporary, path, renameFile = rename) {
|
|
115
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
116
|
+
try {
|
|
117
|
+
await renameFile(temporary, path)
|
|
118
|
+
return
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (!REPLACE_RETRY_CODES.has(error?.code) || attempt >= REPLACE_ATTEMPTS - 1) throw error
|
|
121
|
+
await wait(20 * (attempt + 1))
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function isReadable(path) {
|
|
127
|
+
if (typeof path !== 'string' || path === '') return false
|
|
128
|
+
try { await readFile(path); return true } catch { return false }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 把 MinerU 的原始块列表原样落盘到 `<主名>.content.json`。
|
|
133
|
+
* 🔴 上游是数组,所以这里**只序列化数组本身**:不包信封、不加 `schemaVersion`。
|
|
134
|
+
* 写入走临时文件 + rename,避免读者看到写了一半的 JSON。
|
|
135
|
+
*/
|
|
136
|
+
export async function writeAnalysisContent(paths, contentList) {
|
|
137
|
+
if (!Array.isArray(contentList)) throw new Error('MinerU 块列表必须是数组')
|
|
138
|
+
const path = resolve(paths.content)
|
|
139
|
+
await mkdir(dirname(path), { recursive: true })
|
|
140
|
+
const temporary = join(dirname(path), `.content.${process.pid}.${Date.now()}.tmp`)
|
|
141
|
+
await writeFile(temporary, `${JSON.stringify(contentList)}\n`, { encoding: 'utf8', mode: 0o600 })
|
|
142
|
+
await replaceFile(temporary, path)
|
|
143
|
+
return path
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 目标路径上是否已有**文件**(目录/不存在都算没有;用来决定要不要先备份)。 */
|
|
147
|
+
async function isExistingFile(path) {
|
|
148
|
+
try { return (await stat(path)).isFile() } catch { return false }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 一个落点临时文件与备份的名字。与正文同目录,rename 才是同卷原子替换。 */
|
|
152
|
+
function stagedPathsOf(path) {
|
|
153
|
+
const dir = dirname(path)
|
|
154
|
+
return { temporary: join(dir, `.parse.${randomUUID()}.tmp`), backup: join(dir, `.parse.${randomUUID()}.backup`) }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* 把一次解析的产物(正文、目录、可选块列表,以及它们引用的图片)**整批**提交。
|
|
159
|
+
*
|
|
160
|
+
* 全部先写到同目录的临时文件(正文临时文件用 `wx` 独占创建,图片用 `copyFile` 拷到临时名),
|
|
161
|
+
* 全部 stage 成功之后才逐个 rename 到正式路径;任何一步失败就把已提交的按相反顺序复原 ——
|
|
162
|
+
* 有备份的 rename 回去,没有备份的删掉。
|
|
163
|
+
*
|
|
164
|
+
* 🔴 `copies` 必须在**同一个事务**里:它们与正文是同一份结果的两种载体(见
|
|
165
|
+
* markdown-assets.planMarkdownImages 的说明)。图片单独先落盘,正文一失败就留下
|
|
166
|
+
* 「旧正文 + 新图片」的错位,而那正是这条函数存在的理由。
|
|
167
|
+
*
|
|
168
|
+
* @param {object} paths 四个落点(markdown / outline / content / 其余忽略)。
|
|
169
|
+
* @param {{markdown: string, outline: string, contentList?: unknown[]}} values 文本产物。
|
|
170
|
+
* @param {{renameFile?: Function, copies?: Array<{source: string, destination: string}>}} [options]
|
|
171
|
+
* `copies` 是「从哪拷到哪」的图片清单,与文本产物同批提交。
|
|
172
|
+
*/
|
|
173
|
+
export async function writeAnalysisBundle(paths, { markdown, outline, contentList }, { renameFile = rename, copies = [] } = {}) {
|
|
174
|
+
const values = [[paths.markdown, markdown], [paths.outline, outline]]
|
|
175
|
+
if (Array.isArray(contentList) && contentList.length > 0) values.push([paths.content, `${JSON.stringify(contentList)}\n`])
|
|
176
|
+
const files = []
|
|
177
|
+
let complete = false
|
|
178
|
+
try {
|
|
179
|
+
for (const [path, data] of values) {
|
|
180
|
+
await mkdir(dirname(path), { recursive: true })
|
|
181
|
+
let previous
|
|
182
|
+
try { previous = await readFile(path) } catch (error) { if (error?.code !== 'ENOENT') throw error }
|
|
183
|
+
const { temporary, backup } = stagedPathsOf(path)
|
|
184
|
+
const file = { path, temporary, backup: previous === undefined ? undefined : backup, committed: false }
|
|
185
|
+
files.push(file)
|
|
186
|
+
if (file.backup) await writeFile(file.backup, previous, { flag: 'wx', mode: 0o600 })
|
|
187
|
+
await writeFile(temporary, data, { encoding: 'utf8', flag: 'wx', mode: 0o600 })
|
|
188
|
+
}
|
|
189
|
+
// 图片走 copyFile 而不是读写 Buffer:一篇论文的图可以是几十 MB,没必要整份读进内存。
|
|
190
|
+
for (const copy of copies) {
|
|
191
|
+
const path = resolve(copy.destination)
|
|
192
|
+
await mkdir(dirname(path), { recursive: true })
|
|
193
|
+
const { temporary, backup } = stagedPathsOf(path)
|
|
194
|
+
const file = { path, temporary, backup: await isExistingFile(path) ? backup : undefined, committed: false }
|
|
195
|
+
files.push(file)
|
|
196
|
+
if (file.backup) await copyFile(path, file.backup)
|
|
197
|
+
await copyFile(copy.source, temporary)
|
|
198
|
+
}
|
|
199
|
+
for (const file of files) {
|
|
200
|
+
await replaceFile(file.temporary, file.path, renameFile)
|
|
201
|
+
file.committed = true
|
|
202
|
+
}
|
|
203
|
+
complete = true
|
|
204
|
+
} catch (error) {
|
|
205
|
+
const failures = []
|
|
206
|
+
for (const file of [...files].reverse()) {
|
|
207
|
+
if (!file.committed) continue
|
|
208
|
+
try {
|
|
209
|
+
if (file.backup) await replaceFile(file.backup, file.path)
|
|
210
|
+
else await rm(file.path, { force: true })
|
|
211
|
+
} catch (rollback) { failures.push(rollback) }
|
|
212
|
+
}
|
|
213
|
+
if (failures.length > 0) throw new AggregateError([error, ...failures], '解析产物写入失败且恢复未完成;备份已保留')
|
|
214
|
+
complete = true
|
|
215
|
+
throw error
|
|
216
|
+
} finally {
|
|
217
|
+
for (const file of files) {
|
|
218
|
+
await rm(file.temporary, { force: true }).catch(() => {})
|
|
219
|
+
if (complete && file.backup) await rm(file.backup, { force: true }).catch(() => {})
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function resolveRelativePath(base, value, label) {
|
|
225
|
+
if (typeof value !== 'string' || value === '' || isAbsolute(value)) throw new Error(`${label} 必须是相对路径`)
|
|
226
|
+
const path = resolve(base, value)
|
|
227
|
+
const child = relative(base, path)
|
|
228
|
+
if (child === '..' || child.startsWith(`..${sep}`) || isAbsolute(child)) throw new Error(`${label} 越出论文目录`)
|
|
229
|
+
return path
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* 文档记录里的资产路径。artifact 存**相对 pdfPath 所在目录**的相对路径(D127 后该目录在
|
|
234
|
+
* runtime 里),这里 resolve + 校验后交绝对路径;非 sidecar(老形状)回退到记录上的绝对字段。
|
|
235
|
+
*/
|
|
236
|
+
export function documentPaths(document) {
|
|
237
|
+
if (document?.artifact?.kind !== 'sidecar') {
|
|
238
|
+
return {
|
|
239
|
+
markdownPath: document?.markdownPath,
|
|
240
|
+
outlinePath: document?.outlinePath,
|
|
241
|
+
manifestPath: document?.manifestPath,
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const base = dirname(resolve(document.pdfPath))
|
|
245
|
+
// contentPath 是后加的成员,老 portable 文档没有该键。缺它不算错(该论文就是没有块列表),
|
|
246
|
+
// 但一旦存在就必须过路径校验;不返回 undefined 键,免得 hydrate 后平白多挂一个空字段。
|
|
247
|
+
const content = typeof document.artifact.contentPath === 'string' && document.artifact.contentPath !== ''
|
|
248
|
+
? { contentPath: resolveRelativePath(base, document.artifact.contentPath, '块列表路径') }
|
|
249
|
+
: {}
|
|
250
|
+
return {
|
|
251
|
+
markdownPath: resolveRelativePath(base, document.artifact.markdownPath, 'Markdown 路径'),
|
|
252
|
+
outlinePath: resolveRelativePath(base, document.artifact.outlinePath, '目录路径'),
|
|
253
|
+
manifestPath: resolveRelativePath(base, document.artifact.manifestPath, 'manifest 路径'),
|
|
254
|
+
...content,
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function hydrateDocument(document) {
|
|
259
|
+
return document ? { ...document, ...documentPaths(document) } : document
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* 把绝对落点收进 artifact(runtime 绝对路径)。D127 后不再需要相对化 ——
|
|
264
|
+
* 资产固定在 runtime,不随 PDF 搬,相对化只剩越界风险没有收益。
|
|
265
|
+
*/
|
|
266
|
+
export function portableDocument(document, pdf, paths) {
|
|
267
|
+
// 相对 pdfPath 所在目录存(D128 后 = runtime 里那篇的目录):relative 保持纯文件名,
|
|
268
|
+
// state.json 不锁死绝对路径,整个 runtime 搬家后仍能解出。校验沿用 relativePath 的越界拒绝。
|
|
269
|
+
const base = dirname(resolve(pdf.path))
|
|
270
|
+
const { markdownPath: _m, outlinePath: _o, contentPath: _c, manifestPath: _f, ...metadata } = document
|
|
271
|
+
return {
|
|
272
|
+
...metadata,
|
|
273
|
+
artifact: {
|
|
274
|
+
kind: 'sidecar',
|
|
275
|
+
base: 'pdf-directory',
|
|
276
|
+
markdownPath: relativePath(base, paths.markdownPath, 'Markdown'),
|
|
277
|
+
outlinePath: relativePath(base, paths.outlinePath, '目录'),
|
|
278
|
+
manifestPath: relativePath(base, paths.manifestPath, 'manifest'),
|
|
279
|
+
...(typeof paths.contentPath === 'string' && paths.contentPath !== ''
|
|
280
|
+
? { contentPath: relativePath(base, paths.contentPath, '块列表') }
|
|
281
|
+
: {}),
|
|
282
|
+
},
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async function readManifest(manifestPath, documentId, { validateArtifacts = true } = {}) {
|
|
287
|
+
const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
|
|
288
|
+
if (![1, 2].includes(manifest?.schemaVersion) || manifest.documentId !== documentId) return undefined
|
|
289
|
+
const base = dirname(resolve(manifestPath))
|
|
290
|
+
const markdownPath = resolveRelativePath(base, manifest.files?.markdown, 'manifest Markdown 路径')
|
|
291
|
+
const outlinePath = resolveRelativePath(base, manifest.files?.outline, 'manifest 目录路径')
|
|
292
|
+
if (validateArtifacts) await readMarkdownBundle(markdownPath)
|
|
293
|
+
const contentPath = validateArtifacts ? await optionalContentPath(base, manifest.files?.content)
|
|
294
|
+
: typeof manifest.files?.content === 'string' && manifest.files.content !== '' ? resolveRelativePath(base, manifest.files.content, 'manifest 块列表路径') : undefined
|
|
295
|
+
return {
|
|
296
|
+
dir: base,
|
|
297
|
+
markdown: markdownPath,
|
|
298
|
+
outline: outlinePath,
|
|
299
|
+
...(contentPath === undefined ? {} : { content: contentPath }),
|
|
300
|
+
manifest: resolve(manifestPath),
|
|
301
|
+
manifestReady: true,
|
|
302
|
+
pdfNameAtParse: manifest.pdfNameAtParse,
|
|
303
|
+
metadata: readManifestMetadata(manifest.metadata),
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function optionalContentPath(base, value) {
|
|
308
|
+
if (typeof value !== 'string' || value === '') return undefined
|
|
309
|
+
const path = resolveRelativePath(base, value, 'manifest 块列表路径')
|
|
310
|
+
return await isReadable(path) ? path : undefined
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function relativePath(base, target, label) {
|
|
314
|
+
const value = relative(base, resolve(target))
|
|
315
|
+
if (value === '' || value === '..' || value.startsWith(`..${sep}`) || isAbsolute(value)) throw new Error(`${label} 不在论文目录内`)
|
|
316
|
+
return value
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export async function writePortableManifest(pdf, paths, document = {}) {
|
|
320
|
+
const manifestPath = resolve(paths.manifest)
|
|
321
|
+
const base = dirname(manifestPath)
|
|
322
|
+
let previous = {}
|
|
323
|
+
try {
|
|
324
|
+
previous = JSON.parse(await readFile(manifestPath, 'utf8'))
|
|
325
|
+
if (!previous || typeof previous !== 'object' || Array.isArray(previous) || previous.documentId !== pdf.hash || ![1, 2].includes(previous.schemaVersion)) throw new Error('manifest 身份或格式无效,拒绝覆盖')
|
|
326
|
+
} catch (error) { if (error?.code !== 'ENOENT') throw error }
|
|
327
|
+
const contentPath = await isReadable(paths.content) ? paths.content : undefined
|
|
328
|
+
const metadata = { ...previous.metadata, ...manifestMetadataOf(document) }
|
|
329
|
+
for (const key of ['sourceDir', 'sourcePdfPath']) if (!Object.hasOwn(document, key)) delete metadata[key]
|
|
330
|
+
if (document.bibliography) {
|
|
331
|
+
// Canonical bibliography replaces legacy duplicate keys, including explicitly cleared values.
|
|
332
|
+
for (const key of BIBLIOGRAPHIC_FIELDS) delete metadata[key]
|
|
333
|
+
metadata.bibliography = bibliographyOf(document.bibliography)
|
|
334
|
+
}
|
|
335
|
+
const manifest = {
|
|
336
|
+
...previous,
|
|
337
|
+
schemaVersion: 2,
|
|
338
|
+
documentId: pdf.hash,
|
|
339
|
+
pdfNameAtParse: pdf.name,
|
|
340
|
+
files: {
|
|
341
|
+
markdown: relativePath(base, paths.markdown, 'Markdown'),
|
|
342
|
+
outline: relativePath(base, paths.outline, '目录'),
|
|
343
|
+
...(contentPath === undefined ? {} : { content: relativePath(base, contentPath, '块列表') }),
|
|
344
|
+
},
|
|
345
|
+
metadata,
|
|
346
|
+
updatedAt: new Date().toISOString(),
|
|
347
|
+
}
|
|
348
|
+
await mkdir(base, { recursive: true })
|
|
349
|
+
const temporary = join(base, `.${pdf.hash}.${process.pid}.${Date.now()}.tmp`)
|
|
350
|
+
await writeFile(temporary, `${JSON.stringify(manifest, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
|
|
351
|
+
await replaceFile(temporary, manifestPath)
|
|
352
|
+
return manifestPath
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export async function writeDocumentManifest(document) {
|
|
356
|
+
if (document?.artifact?.kind !== 'sidecar') return undefined
|
|
357
|
+
const paths = documentPaths(document)
|
|
358
|
+
await readMarkdownBundle(paths.markdownPath)
|
|
359
|
+
await readFile(paths.outlinePath, 'utf8')
|
|
360
|
+
return writePortableManifest(
|
|
361
|
+
{ hash: document.id, name: document.pdfName, path: document.pdfPath },
|
|
362
|
+
{ markdown: paths.markdownPath, outline: paths.outlinePath, manifest: paths.manifestPath, content: paths.contentPath },
|
|
363
|
+
document,
|
|
364
|
+
)
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export async function readDocumentManifest(document, options) {
|
|
368
|
+
if (document?.artifact?.kind !== 'sidecar') return undefined
|
|
369
|
+
const paths = documentPaths(document)
|
|
370
|
+
const found = await readManifest(paths.manifestPath, document.id, options)
|
|
371
|
+
if (!found) return undefined
|
|
372
|
+
return {
|
|
373
|
+
...document,
|
|
374
|
+
...found.metadata,
|
|
375
|
+
pdfName: typeof found.pdfNameAtParse === 'string' && found.pdfNameAtParse !== ''
|
|
376
|
+
? found.pdfNameAtParse
|
|
377
|
+
: document.pdfName,
|
|
378
|
+
}
|
|
379
|
+
}
|
package/lib/purge.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 永久删除一篇论文(D127/D128 之后的形态:所有资产都在 runtime 的一个目录里)。
|
|
3
|
+
*
|
|
4
|
+
* 🔴 **只删 runtime 里的东西**。用户论文目录**一个字节都不动** —— 包括旧版本遗留的
|
|
5
|
+
* `analysis/`(D127 已裁定「不读、不迁、不删」,那条裁定对这个功能同样有效)。
|
|
6
|
+
*
|
|
7
|
+
* 删七样(一篇论文的资产**不只有一个目录**,漏掉任何一样都是永久残留)——
|
|
8
|
+
* 编号与下面的步骤注释一一对应:
|
|
9
|
+
* 1. `library/<documentId>/` 整个目录(PDF 副本、Markdown、译文、划线、边注、条目);
|
|
10
|
+
* 2. `page-images/pages/<documentId>/` —— 页面图缓存按内容标识**另起一层**,不在 library/ 里。
|
|
11
|
+
* 一篇读满的论文这里可以有几 MB,且再无其它回收路径;
|
|
12
|
+
* 3. `documents/<hash>/` 解析 scratch(不依赖启动期的孤儿扫描,当场就清);
|
|
13
|
+
* 4. `state.json` 里的文档记录、该篇的 job 记录,以及各会话选择里的**全部**引用
|
|
14
|
+
* (documentIds / desired / delivered / deliveredUnavailable 四个字段,一个都不能漏);
|
|
15
|
+
* 5. `usage.json` 里该篇的用量记录;
|
|
16
|
+
* 6. `tasks.json` 里该篇的条目;
|
|
17
|
+
* 7. `archive/<xx>/<hash>.json` 冷记录。
|
|
18
|
+
*
|
|
19
|
+
* 🔴 **删除是幂等的**:目标不存在一律当成功(force),重复点删除不会报错。
|
|
20
|
+
* 🔴 页面图/账本/任务这三样(第 2、5、6 步)**不是致命项**:它们失败只记一行日志。
|
|
21
|
+
* 理由与留痕同一口径 —— 论文本体已经删了,这时抛错只会让调用方以为没删成,让用户再删一次。
|
|
22
|
+
*
|
|
23
|
+
* 🔴 第 1、3、4、7 步(论文本体、scratch、状态记录、冷记录)失败就抛出去,**不吞** ——
|
|
24
|
+
* 调用方据此回「失败 N 篇」而不是伪造全成功。已经删掉的部分不回滚(删了就是删了),
|
|
25
|
+
* 已发生的事实如实写进账本。
|
|
26
|
+
*/
|
|
27
|
+
import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'
|
|
28
|
+
import { join } from 'node:path'
|
|
29
|
+
import { appendTrashLog, TRASH_LOG_FILE_NAME } from './library.js'
|
|
30
|
+
import { replaceStateFile } from './storage.js'
|
|
31
|
+
import { pageImageCacheDirOf, scratchDocumentDir, storePathsOf } from './store-paths.js'
|
|
32
|
+
import { dropUsageForDocument, readUsage, usagePathOf, writeUsage } from './usage.js'
|
|
33
|
+
|
|
34
|
+
/** 目录里有多少个文件(含子目录)。数不出来就回 0 —— 只用于记账,不该让删除失败。 */
|
|
35
|
+
async function countFiles(dir) {
|
|
36
|
+
try {
|
|
37
|
+
const entries = await readdir(dir, { withFileTypes: true })
|
|
38
|
+
let total = 0
|
|
39
|
+
for (const entry of entries) {
|
|
40
|
+
total += entry.isDirectory() ? await countFiles(join(dir, entry.name)) : 1
|
|
41
|
+
}
|
|
42
|
+
return total
|
|
43
|
+
} catch { return 0 }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 执行一次永久删除。
|
|
48
|
+
*
|
|
49
|
+
* @param {{runtimeRoot: string, repository: object, logger?: object, documentId: string, pdfName?: string, tasks?: object}} deps
|
|
50
|
+
* @returns {Promise<{removedDir: string, files: number, jobs: number, usage: number, tasks: number}>}
|
|
51
|
+
*/
|
|
52
|
+
export async function purgeDocument({ runtimeRoot, repository, logger, documentId, pdfName, tasks }) {
|
|
53
|
+
const paths = storePathsOf(runtimeRoot, { id: documentId, pdfName })
|
|
54
|
+
if (!paths) throw new Error('论文 ID 无效,无法定位要删除的目录')
|
|
55
|
+
return repository.withDocumentWrite(documentId, async () => {
|
|
56
|
+
const archived = await repository.rawArchivedDocument(documentId)
|
|
57
|
+
// A cold-only paper must remain discoverable if the process stops after removing its locator.
|
|
58
|
+
if (archived && !(await repository.snapshot()).documents[documentId]) {
|
|
59
|
+
await repository.update(state => { state.documents[documentId] ??= archived })
|
|
60
|
+
}
|
|
61
|
+
// Fail before touching assets if the locator cannot be removed. Restore it if later cleanup fails.
|
|
62
|
+
await repository.removeArchivedDocument(documentId)
|
|
63
|
+
try {
|
|
64
|
+
return await purgeAssets({ runtimeRoot, repository, logger, documentId, pdfName, tasks, paths })
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (archived) {
|
|
67
|
+
try { await repository.writeArchivedRecord(archived) }
|
|
68
|
+
catch (restoreError) { logger?.warn(`dsh-paper purge: 冷记录恢复失败 ${documentId}:${String(restoreError?.message ?? restoreError)}`) }
|
|
69
|
+
}
|
|
70
|
+
throw error
|
|
71
|
+
}
|
|
72
|
+
})
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function purgeAssets({ runtimeRoot, repository, logger, documentId, pdfName, tasks, paths }) {
|
|
76
|
+
const removedDir = paths.dir
|
|
77
|
+
const files = await countFiles(removedDir)
|
|
78
|
+
|
|
79
|
+
// ① 目录本身。不存在也算成功(force)—— 重复点删除是幂等的。
|
|
80
|
+
await rm(removedDir, { recursive: true, force: true })
|
|
81
|
+
|
|
82
|
+
// ② 页面图缓存:与 library/<id>/ 同级但**不在它里面**(按内容标识单独分层)。
|
|
83
|
+
// 这里失败不抛 —— 论文本体已经删了,让整次删除报错只会让用户再删一次。
|
|
84
|
+
const cacheDir = pageImageCacheDirOf(runtimeRoot, documentId)
|
|
85
|
+
if (cacheDir !== undefined) {
|
|
86
|
+
await rm(cacheDir, { recursive: true, force: true }).catch(error => {
|
|
87
|
+
logger?.warn(`dsh-paper purge: 页面图缓存未能删除 ${documentId}:${String(error?.message ?? error)}`)
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ③ 解析 scratch:正常路径下发布时就回收了,但失败/被中断的任务会留下 `documents/<hash>/<job>/`。
|
|
92
|
+
// 删掉 job 记录之后它就再无主人(启动期的孤儿扫描才收得掉),这里当场清掉。
|
|
93
|
+
const scratchDir = scratchDocumentDir(runtimeRoot, documentId)
|
|
94
|
+
if (scratchDir !== undefined) {
|
|
95
|
+
await rm(scratchDir, { recursive: true, force: true })
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ④ 状态里的文档记录、该篇的 job 记录,以及各会话选择里的引用。
|
|
99
|
+
let jobs = 0
|
|
100
|
+
await repository.update(state => {
|
|
101
|
+
if (state.documents[documentId] !== undefined) delete state.documents[documentId]
|
|
102
|
+
for (const [jobId, job] of Object.entries(state.jobs)) {
|
|
103
|
+
if (job?.documentId !== documentId) continue
|
|
104
|
+
delete state.jobs[jobId]
|
|
105
|
+
jobs += 1
|
|
106
|
+
}
|
|
107
|
+
for (const [sessionId, selection] of Object.entries(state.selections ?? {})) {
|
|
108
|
+
if (!selection) continue
|
|
109
|
+
const strip = list => (Array.isArray(list) ? list.filter(id => id !== documentId) : list)
|
|
110
|
+
// 🔴 四个字段一个都不能漏:曾经只摘了前三个,deliveredUnavailable 里一直留着已删论文的 id
|
|
111
|
+
// (前端据此判「待取消」状态,那会指向一篇不存在的论文)。
|
|
112
|
+
state.selections[sessionId] = {
|
|
113
|
+
...selection,
|
|
114
|
+
documentIds: strip(selection.documentIds),
|
|
115
|
+
desired: strip(selection.desired),
|
|
116
|
+
delivered: strip(selection.delivered),
|
|
117
|
+
deliveredUnavailable: strip(selection.deliveredUnavailable),
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
// ⑤ 用量账本:记录里带着 documentId,留着就是对已删论文的残留引用。
|
|
123
|
+
// 账本按 jobId 键控且无上限,没有别的路径会清它。失败不抛(同第 2 步的页面图口径)。
|
|
124
|
+
let usage = 0
|
|
125
|
+
try {
|
|
126
|
+
const usageFile = usagePathOf(runtimeRoot)
|
|
127
|
+
const before = await readUsage(usageFile)
|
|
128
|
+
const { store, removed } = dropUsageForDocument(before, documentId)
|
|
129
|
+
if (removed > 0) {
|
|
130
|
+
usage = removed
|
|
131
|
+
await writeUsage(usageFile, store)
|
|
132
|
+
}
|
|
133
|
+
} catch (error) {
|
|
134
|
+
logger?.warn(`dsh-paper purge: 用量记录未能清理 ${documentId}:${String(error?.message ?? error)}`)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ⑥ 任务清单:items 上带着 documentId。没有传 tasks 依赖时跳过(老调用方仍可用)。
|
|
138
|
+
let taskCount = 0
|
|
139
|
+
if (typeof tasks?.forgetDocument === 'function') {
|
|
140
|
+
try {
|
|
141
|
+
taskCount = await tasks.forgetDocument(documentId)
|
|
142
|
+
} catch (error) {
|
|
143
|
+
logger?.warn(`dsh-paper purge: 任务清单未能清理 ${documentId}:${String(error?.message ?? error)}`)
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
await writeTrashLog(runtimeRoot, { documentId, pdfName, removedDir, files, jobs, usage, tasks: taskCount })
|
|
148
|
+
return { removedDir, files, jobs, usage, tasks: taskCount }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 往 `<runtimeRoot>/trash-log.json` 追加一条。
|
|
153
|
+
*
|
|
154
|
+
* 🔴 **记账失败绝不让删除失败**:论文已经删了,这时抛错只会让调用方以为没删成、
|
|
155
|
+
* 让用户再删一次。这里把所有异常收成一行 warn。
|
|
156
|
+
*/
|
|
157
|
+
async function writeTrashLog(runtimeRoot, entry) {
|
|
158
|
+
const path = join(runtimeRoot, TRASH_LOG_FILE_NAME)
|
|
159
|
+
try {
|
|
160
|
+
let log = {}
|
|
161
|
+
try { log = JSON.parse(await readFile(path, 'utf8')) } catch { log = {} }
|
|
162
|
+
const next = appendTrashLog(log, entry)
|
|
163
|
+
await mkdir(runtimeRoot, { recursive: true })
|
|
164
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.tmp`
|
|
165
|
+
await writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
|
|
166
|
+
await replaceStateFile(temporary, path)
|
|
167
|
+
} catch (error) {
|
|
168
|
+
console.warn(`dsh-paper purge: 留痕未写入 ${path}:${String(error?.message ?? error)}`)
|
|
169
|
+
}
|
|
170
|
+
}
|