@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,516 @@
1
+ import { arxivEntryMatches, doiMatches, parseArxivEntry } from './source-resolver.js'
2
+ import { plainInlineText } from './inline-html.js'
3
+ import { splitAuthors } from './rename.js'
4
+ import { createConcurrencyGate } from './concurrency-gate.js'
5
+ import { createMetadataFetch } from './metadata-fetch.js'
6
+
7
+ const text = value => typeof value === 'string' ? value.trim() : ''
8
+ const first = value => text(Array.isArray(value) ? value[0] : value)
9
+ const titleKey = value => plainInlineText(text(value)).normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]/gu, '')
10
+ const DOI = /^10\.\d{4,9}\/\S+$/i
11
+ const ARXIV = /^(?:\d{4}\.\d{4,5}|[a-z-]+(?:\.[A-Z]{2})?\/\d{7})(?:v\d+)?$/i
12
+ const TYPES = { 'journal-article': 'article', 'article-journal': 'article', 'proceedings-article': 'conference',
13
+ 'paper-conference': 'conference', book: 'book', 'book-chapter': 'chapter', chapter: 'chapter',
14
+ dissertation: 'thesis', report: 'report', 'posted-content': 'preprint' }
15
+ // 🔴 `doi.or.kr` 是必需的:doi.org 对**韩国 KISTI 注册的 DOI**(前缀 `10.24225` 等)不做内容协商,
16
+ // 而是 302 到 `https://doi.or.kr/data/<doi>` 才返回 CSL-JSON。少了这一条,这类 DOI 的
17
+ // Crossref 是 404、转到 doi.or.kr 又撞白名单,整篇永远报「书目来源地址不受支持」
18
+ // (实测 HEMA / Korean Journal of Artificial Intelligence)。
19
+ // 它与 doi.org、data.crosscite.org 是同一角色的注册机构协商端点,不是任意落地页。
20
+ const PROVIDER_HOSTS = new Set(['api.crossref.org', 'doi.org', 'doi.or.kr', 'data.crosscite.org', 'api.datacite.org', 'aclanthology.org', 'export.arxiv.org'])
21
+ const NETWORK_CODES = new Set(['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH',
22
+ 'ENOTFOUND', 'EAI_AGAIN', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT', 'UND_ERR_SOCKET'])
23
+ const CERTIFICATE_CODES = new Set(['SELF_SIGNED_CERT_IN_CHAIN', 'DEPTH_ZERO_SELF_SIGNED_CERT', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
24
+ 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY', 'CERT_HAS_EXPIRED', 'ERR_TLS_CERT_ALTNAME_INVALID'])
25
+ /**
26
+ * 自动采纳的题名门槛:归一化后短于这个长度就不认。
27
+ * 「A Paper」「Memory」这类短题名撞名概率太高,只作提示、不自动写入。
28
+ */
29
+ const AUTO_TITLE_MINIMUM = 20
30
+ /**
31
+ * 记录里的作者名常带注记:单位脚注(`(1)`)、邮箱、`†`/`*` 上标、`<sup>` 残留。
32
+ * 比较前剥掉 —— 否则「Olaf Ronneberger (olaf@example.org)」与登记记录的
33
+ * 「Olaf Ronneberger」会被判成两个不同的人,连正确的标识都用不了(实测 U-Net 那篇)。
34
+ * 只剥**注记**,不碰姓名本身:姓氏与名字仍然逐字比较,绑错论文的防线不动。
35
+ */
36
+ function plainAuthorName(value) {
37
+ return text(value)
38
+ .replace(/<[^>]*>/g, ' ')
39
+ .replace(/\{\{[^}]*\}\}/g, ' ')
40
+ .replace(/\([^)]*\)/g, ' ')
41
+ .replace(/\[[^\]]*\]/g, ' ')
42
+ .replace(/[\u2020\u2021*\u2217]/g, ' ')
43
+ .replace(/\s+/g, ' ')
44
+ .trim()
45
+ }
46
+
47
+ function sameAuthor(left, right) {
48
+ const parts = value => plainInlineText(text(value)).normalize('NFKD').toLowerCase()
49
+ .replace(/\p{M}/gu, '').match(/[\p{L}\p{N}]+/gu) ?? []
50
+ const a = parts(left), b = parts(right)
51
+ if (a.join(' ') === b.join(' ')) return a.length > 0
52
+ if (a.length < 2 || b.length < 2 || a.at(-1) !== b.at(-1)) return false
53
+ // Initials may abbreviate a given name; two different full names never match on surname alone.
54
+ return a.slice(0, -1).length === b.slice(0, -1).length
55
+ && a.slice(0, -1).every((name, index) => name === b[index]
56
+ || (name.length === 1 || b[index].length === 1) && name[0] === b[index][0])
57
+ }
58
+
59
+ /** Crossref 与 arXiv 两路候选的先后:exact 排最前,similar 次之,其余保持来源顺序。 */
60
+ /**
61
+ * arXiv 短语检索的退路:PDF 抽取的题名常带全大写与排版断词(`ASSIST-ANTS`),
62
+ * 完整题名作为短语查询会落空,而冒号前的主标题通常还能命中。
63
+ * 命中与否仍由 titleMatchOf 严格判定 —— 放宽的只是检索,不是采纳。
64
+ */
65
+ function searchPrefixOf(title) {
66
+ const head = text(title).split(/[::]/)[0].trim()
67
+ if (head === '' || head === text(title)) return ''
68
+ return titleKey(head).length >= 6 ? head : ''
69
+ }
70
+ const MATCH_ORDER = { exact: 0, similar: 1, '': 2 }
71
+ const sortTitleMatches = rows => [...rows].sort((left, right) =>
72
+ (MATCH_ORDER[left.match] ?? 2) - (MATCH_ORDER[right.match] ?? 2))
73
+
74
+ /**
75
+ * 一条候选与当前记录的关系。**只有 exact 允许自动采纳**。
76
+ *
77
+ * 题名先归一化(NFKC + 去非字母数字),这一步同时吸收掉 PDF 抽取的两种常见污染:
78
+ * 全大写,以及排版断词留下的连字符(`ASSIST-ANTS` 归一化后就是 `assistants`)。
79
+ * 作者只用来反驳:已知的首位作者对不上时,再相等的题名也不采纳(同名论文是真实存在的)。
80
+ */
81
+ function titleMatchOf(record, row) {
82
+ const mine = titleKey(record.title)
83
+ const theirs = titleKey(row.title)
84
+ if (mine === '' || theirs === '') return ''
85
+ if (mine === theirs) {
86
+ if (mine.length < AUTO_TITLE_MINIMUM) return 'similar'
87
+ const known = splitAuthors(record.authors)[0]
88
+ const found = text(row.authors?.[0])
89
+ if (!known || !found) return 'exact'
90
+ return sameAuthor(known, found) ? 'exact' : ''
91
+ }
92
+ return mine.startsWith(theirs) || theirs.startsWith(mine) ? 'similar' : ''
93
+ }
94
+
95
+ function canTryAnotherSource(error) {
96
+ return ['METADATA_TIMEOUT', 'METADATA_NETWORK'].includes(error?.code)
97
+ || [404, 408, 429].includes(error?.status) || error?.status >= 500
98
+ }
99
+
100
+ export function metadataIdentifier(value) {
101
+ let input = text(value)
102
+ if (!input || input.length > 2048) return null
103
+ try {
104
+ const url = new URL(input)
105
+ if (url.username || url.password || url.port) return null
106
+ if (['doi.org', 'dx.doi.org'].includes(url.hostname)) input = decodeURIComponent(url.pathname.slice(1))
107
+ else if (url.hostname === 'aclanthology.org') {
108
+ const id = url.pathname.replace(/^\/|\/$/g, '').replace(/\.(?:pdf|bib)$/, '')
109
+ if (!/^[A-Za-z0-9][A-Za-z0-9.-]*$/.test(id)) return null
110
+ input = '10.18653/v1/' + id
111
+ } else if (['arxiv.org', 'export.arxiv.org', 'www.arxiv.org'].includes(url.hostname)) {
112
+ input = url.pathname.replace(/^\/(?:abs|pdf)\//, '').replace(/\.pdf$/, '')
113
+ } else return null
114
+ } catch { /* Bare identifiers have no URL scheme. */ }
115
+ input = input.replace(/^doi:\s*/i, '').replace(/^arxiv:\s*/i, '')
116
+ if (DOI.test(input) && !/[<>"\\]/.test(input)) return { type: 'doi', id: input.toLowerCase() }
117
+ if (ARXIV.test(input)) return { type: 'arxiv', id: input }
118
+ return null
119
+ }
120
+
121
+ export function recordIdentifier(record) {
122
+ for (const value of [record?.bibliography?.doi, record?.doi, record?.bibliography?.archiveId,
123
+ record?.bibliography?.url, record?.bibliography?.sourceUrl, record?.sourceUrl]) {
124
+ const identifier = metadataIdentifier(value)
125
+ if (identifier) return identifier
126
+ }
127
+ return null
128
+ }
129
+
130
+ function publicationDate(parts) {
131
+ if (!Array.isArray(parts) || !Number.isInteger(parts[0]) || parts[0] < 1500 || parts[0] > 2200) return {}
132
+ const [year, month, day] = parts
133
+ if (parts.length > 1 && (!Number.isInteger(month) || month < 1 || month > 12)) return {}
134
+ if (parts.length > 2 && (!Number.isInteger(day) || day < 1 || day > new Date(Date.UTC(year, month, 0)).getUTCDate())) return {}
135
+ return { year: String(year), date: [year, ...(month ? [String(month).padStart(2, '0')] : []), ...(day ? [String(day).padStart(2, '0')] : [])].join('-') }
136
+ }
137
+
138
+ function fieldsOf(value) {
139
+ const entries = Object.entries(value).filter(([key, item]) => Array.isArray(item)
140
+ ? item.length > 0 && item.length <= 500 && item.every(name => typeof name === 'string' && name.length <= 1000)
141
+ : typeof item === 'string' && item !== '' && item.length <= (key === 'abstract' ? 8192 : 2048))
142
+ const fields = {}
143
+ for (const [key, item] of entries) {
144
+ if (Buffer.byteLength(JSON.stringify({ ...fields, [key]: item })) <= 16 * 1024) fields[key] = item
145
+ }
146
+ return fields
147
+ }
148
+
149
+ export function crossrefMetadata(value, expectedDoi) {
150
+ const doi = metadataIdentifier(value?.DOI)
151
+ // 与导入链路共用同一个判定:DOI 名称不区分大小写,但除此之外必须精确相同。
152
+ if (doi?.type !== 'doi' || !doiMatches(doi.id, expectedDoi)) throw new Error('登记记录的 DOI 与请求不一致,未使用该结果。')
153
+ const authors = (Array.isArray(value.author) ? value.author : []).map(row => text(row?.name) || [text(row?.given), text(row?.family)].filter(Boolean).join(' ')).filter(Boolean)
154
+ const date = [value['published-print'], value['published-online'], value.published, value.issued]
155
+ .map(row => publicationDate(row?.['date-parts']?.[0])).find(row => row.year) ?? {}
156
+ let title = plainInlineText(first(value.title))
157
+ const subtitle = plainInlineText(first(value.subtitle))
158
+ if (title && subtitle && !titleKey(title).endsWith(titleKey(subtitle))) title += ': ' + subtitle
159
+ return fieldsOf({ title, authors,
160
+ ...date, itemType: TYPES[value.type] ?? '',
161
+ publicationTitle: plainInlineText(first(value['container-title'])), publisher: text(value.publisher),
162
+ volume: text(value.volume), issue: text(value.issue), pages: text(value.page),
163
+ place: text(value['publisher-location']), language: text(value.language),
164
+ doi: doi.id, url: 'https://doi.org/' + doi.id, abstract: plainInlineText(text(value.abstract)) })
165
+ }
166
+
167
+ export function cslMetadata(value, expectedDoi) {
168
+ return crossrefMetadata({ ...value, type: value?.type, title: [value?.title],
169
+ author: Array.isArray(value?.author) ? value.author.map(row => ({ ...row, name: row?.literal })) : [],
170
+ 'container-title': [value?.['container-title']], page: value?.page, 'publisher-location': value?.['publisher-place'],
171
+ published: value?.issued, DOI: value?.DOI }, expectedDoi)
172
+ }
173
+
174
+ /** Read one BibTeX entry without evaluating macros or executable TeX. */
175
+ export function aclMetadata(bib, expectedDoi) {
176
+ const head = /^\s*@(\w+)\s*\{\s*([^,\s]+)\s*,/.exec(bib)
177
+ if (!head) throw new Error('出版方没有返回有效书目。')
178
+ let index = head[0].length
179
+ const fields = {}
180
+ while (index < bib.length) {
181
+ while (/[\s,]/.test(bib[index] ?? '') && index < bib.length) index++
182
+ if (index >= bib.length) break
183
+ if (bib[index] === '}') break
184
+ const key = /^(\w+)\s*=\s*/.exec(bib.slice(index))
185
+ if (!key) throw new Error('出版方书目字段格式无效。')
186
+ index += key[0].length
187
+ let value = ''
188
+ const opening = bib[index]
189
+ if (opening === '"' || opening === '{') {
190
+ index++
191
+ let depth = 0, closed = false
192
+ for (; index < bib.length; index++) {
193
+ const char = bib[index]
194
+ if (char === '\\') { value += char + (bib[++index] ?? ''); continue }
195
+ if (char === (opening === '"' ? '"' : '}') && depth === 0) { index++; closed = true; break }
196
+ if (char === '{') depth++
197
+ if (char === '}') depth--
198
+ if (depth < 0) throw new Error('出版方书目括号不匹配。')
199
+ value += char
200
+ }
201
+ if (!closed || depth !== 0) throw new Error('出版方书目未完整返回。')
202
+ } else {
203
+ const token = /^[^,\s}]+/.exec(bib.slice(index))
204
+ if (!token) throw new Error('出版方书目值无效。')
205
+ value = token[0]; index += value.length
206
+ }
207
+ if (Object.hasOwn(fields, key[1].toLowerCase())) throw new Error('出版方书目字段重复。')
208
+ fields[key[1].toLowerCase()] = value
209
+ }
210
+ if (bib[index] !== '}' || bib.slice(index + 1).trim() !== '') throw new Error('出版方书目不是一个完整的独立条目。')
211
+ // Remove BibTeX case-protection groups while retaining TeX math and command arguments.
212
+ // 🔴 大小写保护括号要**剥到底**,不能只剥前面不是字母的那些:ACL 的题名普遍写成
213
+ // `{P}er{LTQA}`、`{LLM}`,旧的 `(?<![A-Za-z\\])` 守卫会把 `{LTQA}`(前面是 `r`)留下来,
214
+ // 于是补全永远报一条「题名冲突」—— 两边肉眼一模一样,差别只是花括号(实测 PerLTQA)。
215
+ // 守卫本来是为了保住 TeX:改成**先保住 \$...\$ 数学段**(上面的 split 已经隔开),
216
+ // 循环到不再变化为止即可。剥不干净的只会是真正的嵌套命令参数,那种交给下一行处理。
217
+ const stripGroups = part => {
218
+ let current = part, previous
219
+ do { previous = current; current = current.replace(/\{([^{}]*)\}/g, '$1') } while (current !== previous)
220
+ return current
221
+ }
222
+ const clean = value => text(value).split(/(\$\$[\s\S]*?\$\$|\$[^$]*?\$)/g).map((part, index) => index % 2 ? part
223
+ : stripGroups(part).replace(/\\([&_#$%])/g, '$1')).join('').replace(/\s+/g, ' ')
224
+ // 🔴 **部分 ACL 卷的 BibTeX 不带 `doi` 字段**(实测 SIGHAN 各年 2021–2025 都没有;
225
+ // EMNLP / ACL / Findings / WNUT / SemEval 等都有 —— 是**按卷**而非按年份的差异)。
226
+ // 以前这里无条件比对,空值自然对不上,于是「题名、作者、页码全对」的论文一律被判成
227
+ // 「出版方书目的 DOI 与请求不一致」—— 而它不是网络错误,不会退到 Crossref
228
+ // (那里登记得好好的),整篇就永远补不了书目(实测 PerLTQA、SIGHAN 2024)。
229
+ // 身份仍由**取书目的 URL 本身**确定:它就是从 requested DOI 拼出来的,不是从 bib 里读的。
230
+ // 所以只有 bib **主动声明**了另一个 DOI 才算指错论文,没声明就照常采纳它的事实。
231
+ const declaredDoi = metadataIdentifier(clean(fields.doi))?.id
232
+ if (declaredDoi !== undefined && !doiMatches(declaredDoi, expectedDoi)) throw new Error('出版方书目的 DOI 与请求不一致。')
233
+ const authorParts = []
234
+ let author = '', depth = 0
235
+ const raw = text(fields.author)
236
+ for (let offset = 0; offset < raw.length; offset++) {
237
+ if (depth === 0 && /^\s+and\s+/i.test(raw.slice(offset))) {
238
+ authorParts.push(author); author = ''
239
+ offset += /^\s+and\s+/i.exec(raw.slice(offset))[0].length - 1
240
+ } else {
241
+ if (raw[offset] === '{') depth++
242
+ if (raw[offset] === '}') depth--
243
+ author += raw[offset]
244
+ }
245
+ }
246
+ if (author) authorParts.push(author)
247
+ // BibTeX uses "family, given" even for a single author.
248
+ const normalizedAuthors = authorParts.map(name => {
249
+ const cleaned = clean(name)
250
+ return /^\{.*\}$/.test(text(name)) ? cleaned : splitAuthors(cleaned.includes(',') ? cleaned + ';' : cleaned).join(', ')
251
+ }).filter(Boolean)
252
+ const monthName = text(fields.month).toLowerCase()
253
+ const month = /^\d{1,2}$/.test(monthName) ? Number(monthName) : ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].indexOf(monthName.slice(0, 3)) + 1
254
+ const year = /^\d{4}$/.test(clean(fields.year)) ? Number(clean(fields.year)) : NaN
255
+ return fieldsOf({ title: clean(fields.title), authors: normalizedAuthors,
256
+ ...publicationDate([year, ...(month ? [month] : [])]), itemType: head[1].toLowerCase() === 'inproceedings' ? 'conference' : '',
257
+ citationKey: head[2], publicationTitle: clean(fields.booktitle || fields.journal), publisher: clean(fields.publisher),
258
+ pages: clean(fields.pages).replace(/--/g, '-'), place: clean(fields.address), volume: clean(fields.volume), issue: clean(fields.number),
259
+ doi: expectedDoi.toLowerCase(), url: `https://aclanthology.org/${expectedDoi.slice('10.18653/v1/'.length)}/` })
260
+ }
261
+
262
+ /** Public providers only; neither local PDF paths nor PDF bytes are sent. */
263
+ export function createMetadataResolver({ fetchImpl, networkMode = 'auto', timeoutMs = 20000, cacheMs = 30 * 60 * 1000, minArxivIntervalMs = 3000 } = {}) {
264
+ const transport = fetchImpl ? null : createMetadataFetch({ mode: networkMode })
265
+ const fetch = fetchImpl ?? transport.fetch
266
+ const cache = new Map(), pending = new Map()
267
+ const gate = createConcurrencyGate(2)
268
+ let arxivTail = Promise.resolve(), nextArxiv = 0
269
+ const request = (url, accept = 'application/json') => gate.run(async () => {
270
+ if (new URL(url).hostname === 'export.arxiv.org') {
271
+ const slot = arxivTail.then(async () => {
272
+ const delay = Math.max(0, nextArxiv - Date.now())
273
+ if (delay) await new Promise(resolve => setTimeout(resolve, delay))
274
+ nextArxiv = Date.now() + minArxivIntervalMs
275
+ })
276
+ arxivTail = slot.catch(() => {})
277
+ await slot
278
+ }
279
+ const controller = new AbortController()
280
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
281
+ try {
282
+ for (let redirects = 0; redirects < 4; redirects++) {
283
+ const target = new URL(url)
284
+ if (target.protocol !== 'https:' || !PROVIDER_HOSTS.has(target.hostname) || target.username || target.password || target.port) throw new Error('书目来源地址不受支持。')
285
+ const response = await fetch(url, { headers: { Accept: accept }, signal: controller.signal, redirect: 'manual' })
286
+ if ([301,302,303,307,308].includes(response.status)) {
287
+ try { await response.body?.cancel() } catch { /* The next request owns no part of this response. */ }
288
+ url = new URL(response.headers.get('location'), url).href
289
+ continue
290
+ }
291
+ if (!response.ok) {
292
+ try { await response.body?.cancel() } catch { /* Preserve the HTTP failure. */ }
293
+ throw Object.assign(new Error('书目来源 ' + target.hostname + ' 请求失败(HTTP ' + response.status + ')。'), { status: response.status })
294
+ }
295
+ const maximum = 1024 * 1024
296
+ let body = ''
297
+ if (response.body?.getReader) {
298
+ const reader = response.body.getReader(), chunks = []
299
+ let size = 0
300
+ try {
301
+ for (;;) {
302
+ const next = await reader.read()
303
+ if (next.done) break
304
+ size += next.value.byteLength
305
+ if (size > maximum) { await reader.cancel(); throw new Error('书目响应过大,未使用该结果。') }
306
+ chunks.push(Buffer.from(next.value))
307
+ }
308
+ } finally { reader.releaseLock() }
309
+ body = Buffer.concat(chunks).toString('utf8')
310
+ } else body = await response.text()
311
+ if (Buffer.byteLength(body) > maximum) throw new Error('书目响应过大,未使用该结果。')
312
+ return body
313
+ }
314
+ throw new Error('书目来源重定向过多。')
315
+ } catch (error) {
316
+ const timedOut = controller.signal.aborted
317
+ controller.abort()
318
+ const host = new URL(url).hostname
319
+ if (timedOut) throw Object.assign(new Error('书目来源 ' + host + ' 查询超时(' + timeoutMs / 1000 + ' 秒),请检查网络或稍后重试。'), { code: 'METADATA_TIMEOUT' })
320
+ const code = error?.cause?.code ?? error?.code
321
+ if (CERTIFICATE_CODES.has(code)) throw Object.assign(new Error('书目来源 ' + host + ' 的 HTTPS 证书校验失败,请检查系统时间、代理与受信任证书。'), { code: 'METADATA_TLS' })
322
+ if (NETWORK_CODES.has(code) || error?.name === 'TypeError' && /fetch failed|terminated/i.test(error.message)) {
323
+ throw Object.assign(new Error('无法连接书目来源 ' + host + ',请检查网络或代理设置后重试。'), { code: 'METADATA_NETWORK' })
324
+ }
325
+ if (['AbortError', 'TimeoutError'].includes(error?.name)) throw Object.assign(new Error('书目来源 ' + host + ' 的请求被中止,请重试。'), { code: 'METADATA_NETWORK' })
326
+ throw error
327
+ } finally { clearTimeout(timer) }
328
+ })
329
+ async function lookupDoi(id) {
330
+ const url = 'https://api.crossref.org/works/' + encodeURIComponent(id)
331
+ try {
332
+ const body = JSON.parse(await request(url))
333
+ return { fields: crossrefMetadata(body.message, id), sources: [{ provider: 'crossref', identifier: id, url }] }
334
+ } catch (error) {
335
+ if (!canTryAnotherSource(error)) throw error
336
+ const doiUrl = 'https://doi.org/' + id.split('/').map(encodeURIComponent).join('/')
337
+ return { fields: cslMetadata(JSON.parse(await request(doiUrl, 'application/vnd.citationstyles.csl+json')), id), sources: [{ provider: 'doi', identifier: id, url: doiUrl }] }
338
+ }
339
+ }
340
+ async function cachedLookup(key, load) {
341
+ const cached = cache.get(key)
342
+ if (cached && cached.expires > Date.now()) return structuredClone(cached.value)
343
+ if (pending.has(key)) return structuredClone(await pending.get(key))
344
+ const task = Promise.resolve().then(load)
345
+ pending.set(key, task)
346
+ try {
347
+ const value = await task
348
+ if (cache.size >= 128) cache.delete(cache.keys().next().value)
349
+ cache.set(key, { expires: Date.now() + cacheMs, value })
350
+ return structuredClone(value)
351
+ } finally { pending.delete(key) }
352
+ }
353
+ function lookup(identifier) {
354
+ return cachedLookup(identifier.type + ':' + identifier.id, async () => {
355
+ const { id, type } = identifier
356
+ if (type === 'arxiv') {
357
+ const url = 'https://export.arxiv.org/api/query?id_list=' + encodeURIComponent(id)
358
+ const xml = await request(url, 'application/atom+xml')
359
+ const entry = /<entry(?:\s[^>]*)?>([\s\S]*?)<\/entry>/i.exec(xml)?.[1] ?? ''
360
+ // 与导入链路共用同一个判定:这套版本规则写两遍,正是两条路会漂移的原因。
361
+ if (!arxivEntryMatches(xml, id)) throw new Error('arXiv 返回了不同论文或版本,未使用该结果。')
362
+ const parsed = parseArxivEntry(xml)
363
+ const published = /<published>\s*(\d{4})-(\d{2})-(\d{2})/.exec(entry)
364
+ const linked = /<(?:arxiv:)?doi\b[^>]*>([^<]+)<\//i.exec(entry)?.[1]
365
+ const doi = metadataIdentifier(linked)
366
+ /** arXiv 条目自己的字段。声明了正式 DOI 时优先取正式版的,那条路失败才退回这里。 */
367
+ const ownFields = () => fieldsOf({ title: parsed.title, authors: parsed.authors,
368
+ ...publicationDate(published ? published.slice(1).map(Number) : []), itemType: 'preprint', publicationTitle: 'arXiv',
369
+ repository: 'arXiv', archiveId: id, url: 'https://arxiv.org/abs/' + id })
370
+ const arxivSource = { provider: 'arxiv', identifier: id, url: 'https://arxiv.org/abs/' + id }
371
+ if (doi?.type === 'doi') {
372
+ try {
373
+ const formal = await lookup(doi)
374
+ return { ...formal, fields: { ...formal.fields, repository: 'arXiv', archiveId: id }, sources: [...formal.sources, arxivSource] }
375
+ } catch (error) {
376
+ // 🔴 **arXiv 声明的 DOI 可能还没注册**:会议/期刊刚出版时作者已经把 DOI 填在 arXiv 页上,
377
+ // 而注册机构尚未收录 —— handle 返回 responseCode 100、Crossref 与 DataCite 都是 404
378
+ // (实测 CIKM 2026 那篇)。这时整条查询不该失败:arXiv 自己那份字段仍然可用,
379
+ // 那个 DOI 也是真的,只是暂时取不到登记元数据,原样留下供人核对。
380
+ if (!canTryAnotherSource(error)) throw error
381
+ return { fields: { ...ownFields(), doi: doi.id }, sources: [arxivSource],
382
+ warnings: ['arXiv 记录声明的 DOI ' + doi.id + ' 暂时取不到登记元数据(会议或期刊刚出版时常见),已改用 arXiv 自身字段。'] }
383
+ }
384
+ }
385
+ return { fields: ownFields(), sources: [arxivSource] }
386
+ }
387
+ if (/^10\.18653\/v1\/[a-z0-9.-]+$/i.test(id)) {
388
+ const url = `https://aclanthology.org/${id.slice('10.18653/v1/'.length)}.bib`
389
+ let body
390
+ try { body = await request(url, 'application/x-bibtex') }
391
+ catch (error) { if (canTryAnotherSource(error)) return lookupDoi(id); throw error }
392
+ return { fields: aclMetadata(body, id), sources: [{ provider: 'acl', identifier: id, url }] }
393
+ }
394
+ return lookupDoi(id)
395
+ })
396
+ }
397
+ async function searchCrossrefTitle(title) {
398
+ const url = 'https://api.crossref.org/works?rows=5&query.title=' + encodeURIComponent(title)
399
+ const rows = JSON.parse(await request(url))?.message?.items ?? []
400
+ return rows.slice(0, 5).flatMap(row => {
401
+ const id = metadataIdentifier(row.DOI)
402
+ if (!id) return []
403
+ const fields = crossrefMetadata(row, id.id)
404
+ return [{ identifier: id.id, title: fields.title ?? '', authors: (fields.authors ?? []).slice(0, 5),
405
+ year: fields.year ?? '', url: 'https://doi.org/' + id.id, source: 'crossref' }]
406
+ })
407
+ }
408
+ /**
409
+ * arXiv 原本只支持按 id 精确查询 —— 而 AI 预印本只有 arXiv 有,Crossref 是空白区
410
+ * (实测 LongMemEval / MemoryAgentBench / HippoRAG 2 / MEM1 在 Crossref 里都查不到)。
411
+ * 这里补一条按题名搜索的路,同样的 `<entry>` 解析,但不接受任何未经校验的结果。
412
+ */
413
+ async function searchArxivTitle(title) {
414
+ const url = 'https://export.arxiv.org/api/query?search_query=ti:%22' + encodeURIComponent(title) + '%22&max_results=5'
415
+ const xml = await request(url, 'application/atom+xml')
416
+ const entries = [...xml.matchAll(/<entry(?:\s[^>]*)?>[\s\S]*?<\/entry>/gi)].slice(0, 5)
417
+ return entries.flatMap(entry => {
418
+ const returned = /<id>\s*https?:\/\/arxiv.org\/abs\/([^<\s]+)\s*<\/id>/i.exec(entry[0])?.[1]
419
+ const identifier = metadataIdentifier(returned)
420
+ if (identifier?.type !== 'arxiv') return []
421
+ let parsed
422
+ try { parsed = parseArxivEntry(entry[0]) } catch { return [] }
423
+ if (text(parsed.title) === '') return []
424
+ return [{ identifier: identifier.id, title: parsed.title, authors: parsed.authors.slice(0, 5),
425
+ year: parsed.year ?? '', url: 'https://arxiv.org/abs/' + identifier.id, source: 'arxiv' }]
426
+ })
427
+ }
428
+ async function resolve(record, { identifier: supplied, search = true } = {}) {
429
+ const bound = recordIdentifier(record)
430
+ const identifier = supplied ? metadataIdentifier(supplied) : bound
431
+ if (supplied && !identifier) throw new Error('identifier 须为 DOI、arXiv 编号或其官方页面地址。')
432
+ if (identifier) {
433
+ // 判定要等 lookup 之后(见下),所以这里得自己接住失败:否则一条 404 会把
434
+ // 「你指的其实是另一篇」这个真正的原因盖掉。
435
+ const result = await lookup(identifier).catch(error => {
436
+ if (bound && supplied && (bound.type !== identifier.type || bound.id !== identifier.id))
437
+ throw Object.assign(new Error('指定标识与论文已有标识不同,且该标识取不到元数据(' + error.message + ');请先核对版本,未改动记录。'), { status: error.status, code: error.code })
438
+ throw error
439
+ })
440
+ // 🔴 **两个标识不同不等于指错了论文**:同一篇论文的 arXiv 版与正式版 DOI 天然不同,
441
+ // 而来源记录常常自己声明了另一个标识(arXiv 条目的 `<arxiv:doi>`、Crossref 的 archiveId)。
442
+ // 声明与记录上那个一致就是同一篇,放行;对不上仍然拒绝 —— 那才是「绑错论文」的信号。
443
+ // 实测(CIKM 2026 那篇):记录里已有 ACM DOI,改用它的 arXiv 编号补全会被标识不同这条挡住,
444
+ // 而那个 DOI 当时还没注册,两条路都走不通,整篇只能靠手写。
445
+ if (bound && supplied && (bound.type !== identifier.type || bound.id !== identifier.id)) {
446
+ const linked = recordIdentifier({ bibliography: result.fields })
447
+ if (!linked || linked.type !== bound.type || linked.id !== bound.id) throw new Error('指定标识与论文已有标识不同;请先核对版本,未改动记录。')
448
+ }
449
+ // lookup 自己带回来的说明(如 arXiv 声明的 DOI 还没注册)要跟着走,不能在这里丢掉。
450
+ const warnings = [...(result.warnings ?? [])]
451
+ // 🔴 显式给出的标识是**明确的意图**,题名/首位作者对不上不足以否定它:
452
+ //
453
+ // 正式发表时改标题是常态(arXiv 「Swish: a Self-Gated Activation Function」→ 后来的
454
+ // 「Searching for Activation Functions」;DeepSeek-R1 进 Nature 后标题整句重写),
455
+ // 而记录里的题名常常本身就有脏值(全大写、OCR 断词、少一个字母、被截断)。
456
+ // 过去这里一律拒绝,结果是**越是需要修的论文越修不了自己** —— 实测连着三篇
457
+ // (U-Net 作者带邮箱、Switch Transformers 的 Eficient、DeepSeek-R1 改了标题)
458
+ // 都只能用标识取不到数据,最后全靠手写。
459
+ //
460
+ // 改成:两个信号**同时**相反才拒绝(那更像指错了论文),只有一个对不上就放行,
461
+ // 但把差异记进 warnings 带出去,让预览和工具回执都能看见、由人来核对。
462
+ if (supplied && !bound) {
463
+ const sameTitle = !titleKey(record.title) || titleKey(record.title) === titleKey(result.fields.title)
464
+ // 🔴 作者仍然**严判**:它是"绑错论文"的最强信号(同姓不同名都要拦,见
465
+ // test 里 different full given names 那条)。但比较前先剥掉记录里的注记
466
+ // (邮箱、单位脚注、† 上标)—— 那不改变姓名本身,只是把脏数据还原成名字。
467
+ const known = plainAuthorName(splitAuthors(record.authors)[0])
468
+ const found = plainAuthorName(result.fields.authors?.[0])
469
+ if (known && found && !sameAuthor(known, found)) throw new Error('指定标识的首位作者与当前论文不一致,未改动记录。')
470
+ if (!sameTitle) warnings.push('题名与当前记录不同(正式发表改名很常见)')
471
+ }
472
+ return { ...result, identifier, ...(warnings.length > 0 ? { warnings } : {}) }
473
+ }
474
+ const title = text(record.title)
475
+ if (!search || !title || /^[a-z]:[\\/]|^\/|\.pdf$/i.test(title)) return { fields: {}, sources: [], candidates: [] }
476
+ // Crossref 先查:它有登记的就别浪费 arXiv 的 3 秒限速配额。任一路失败都不阻断另一路。
477
+ const failures = []
478
+ let rows = []
479
+ try { rows = await cachedLookup('title:crossref:' + title, () => searchCrossrefTitle(title)) } catch (error) { failures.push(error) }
480
+ const hasExact = () => rows.some(row => titleMatchOf(record, row) === 'exact')
481
+ if (!hasExact()) {
482
+ try { rows = rows.concat(await cachedLookup('title:arxiv:' + title, () => searchArxivTitle(title))) } catch (error) { failures.push(error) }
483
+ }
484
+ // 完整题名落空时再试一次冒号前的主标题(断词/全大写污染下它往往还能命中)。
485
+ const prefix = searchPrefixOf(title)
486
+ if (!hasExact() && prefix !== '') {
487
+ try { rows = rows.concat(await cachedLookup('title:arxiv:' + prefix, () => searchArxivTitle(prefix))) } catch (error) { failures.push(error) }
488
+ }
489
+ const seen = new Set()
490
+ rows = rows.filter(row => {
491
+ const key = row.source + ':' + row.identifier
492
+ if (seen.has(key)) return false
493
+ seen.add(key)
494
+ return true
495
+ })
496
+ if (rows.length === 0) {
497
+ if (failures.length > 0) throw failures[0]
498
+ return { fields: {}, sources: [], candidates: [] }
499
+ }
500
+ const marked = rows.map(row => ({ ...row, match: titleMatchOf(record, row) }))
501
+ // 只有「题名完全相等且唯一」才自动采纳 —— 相似度只用于排序与提示,绝不用来写入。
502
+ const exact = marked.filter(row => row.match === 'exact')
503
+ if (exact.length === 1) {
504
+ const found = metadataIdentifier(exact[0].identifier)
505
+ if (found) {
506
+ const result = await lookup(found)
507
+ // The exact record must independently pass the same title and author checks as the search hit.
508
+ if (titleMatchOf(record, result.fields) === 'exact') {
509
+ return { ...result, identifier: found, auto: true, matchedBy: exact[0].source }
510
+ }
511
+ }
512
+ }
513
+ return { fields: {}, sources: [], candidates: sortTitleMatches(marked) }
514
+ }
515
+ return { resolve, dispose: () => transport?.dispose() }
516
+ }