dsh-paper-workbench 1.1.2 → 1.2.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.
package/lib/arxiv.js CHANGED
@@ -12,6 +12,8 @@
12
12
  * 而不是按固定顺序匹配字符串。
13
13
  */
14
14
  import { promises as fsp } from 'node:fs'
15
+ import { createHash } from 'node:crypto'
16
+ import { AsyncLocalStorage } from 'node:async_hooks'
15
17
  import path from 'node:path'
16
18
 
17
19
  import { proxyFetch } from './net.js'
@@ -42,6 +44,60 @@ function clampInt(value, fallback, min, max) {
42
44
  return Math.min(Math.max(n, min), max)
43
45
  }
44
46
 
47
+ const PAGE_CURSOR_MAX_LENGTH = 16384
48
+ const FEED_PAGE_CONTEXT = new AsyncLocalStorage()
49
+
50
+ function redactUserInfo(value) {
51
+ return String(value || '').replace(/\b((?:https?|socks5h?):\/\/)[^/\s@]+@/gi, '$1[redacted]@')
52
+ }
53
+
54
+ function stableJson(value) {
55
+ if (Array.isArray(value)) return '[' + value.map(stableJson).join(',') + ']'
56
+ if (value && typeof value === 'object') {
57
+ return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + stableJson(value[key])).join(',') + '}'
58
+ }
59
+ const json = JSON.stringify(value)
60
+ return json === undefined ? 'null' : json
61
+ }
62
+
63
+ function openAlexCount(payload) {
64
+ const raw = payload && payload.meta && payload.meta.count
65
+ const count = Number(raw)
66
+ return raw === null || raw === undefined || !Number.isFinite(count) ? null : count
67
+ }
68
+
69
+ function fingerprint(value) {
70
+ return createHash('sha256').update(stableJson(value)).digest('hex')
71
+ }
72
+
73
+ function encodePageCursor(value) {
74
+ const cursor = 'v1.' + Buffer.from(JSON.stringify(value), 'utf8').toString('base64url')
75
+ if (cursor.length > PAGE_CURSOR_MAX_LENGTH) throw new Error('检索失败:分页状态过长,请缩小订阅范围后重试')
76
+ return cursor
77
+ }
78
+
79
+ function decodePageCursor(raw, kind) {
80
+ if (typeof raw !== 'string' || raw.length < 4 || raw.length > PAGE_CURSOR_MAX_LENGTH || !raw.startsWith('v1.')) {
81
+ throw new Error('检索失败:分页游标无效或超出长度限制,请重新检索')
82
+ }
83
+ let value
84
+ try {
85
+ const encoded = raw.slice(3)
86
+ value = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'))
87
+ if (Buffer.from(JSON.stringify(value), 'utf8').toString('base64url') !== encoded) throw new Error('bad cursor')
88
+ } catch {
89
+ throw new Error('检索失败:分页游标格式无效,请重新检索')
90
+ }
91
+ if (!value || typeof value !== 'object' || value.v !== 1 || value.kind !== kind) {
92
+ throw new Error('检索失败:分页游标版本或用途不匹配,请重新检索')
93
+ }
94
+ return value
95
+ }
96
+
97
+ function safeErrorMessage(error) {
98
+ return redactUserInfo(messageOf(error))
99
+ }
100
+
45
101
  /** arXiv 接口返回的链接仍是 http,统一升到 https,避免明文下载与多余重定向。 */
46
102
  function toHttps(url) {
47
103
  return typeof url === 'string' ? url.replace(/^http:\/\//i, 'https://') : null
@@ -245,11 +301,16 @@ export function normalizeDoi(input) {
245
301
  /** 统一的文本请求:带 UA、跟随重定向、整段(含读 body)计入超时,默认走代理感知的 proxyFetch,错误转中文。 */
246
302
  async function fetchText(
247
303
  url,
248
- { timeoutMs = DEFAULT_SEARCH_TIMEOUT, accept = '*/*', fetchImpl, networkConfig } = {},
304
+ { timeoutMs = DEFAULT_SEARCH_TIMEOUT, accept = '*/*', fetchImpl, networkConfig, signal } = {},
249
305
  ) {
250
306
  const timeout = clampInt(timeoutMs, DEFAULT_SEARCH_TIMEOUT, 1000, 600000)
251
307
  const useCustomFetch = typeof fetchImpl === 'function'
252
308
  const controller = new AbortController()
309
+ const forwardAbort = () => controller.abort(signal && signal.reason)
310
+ if (signal) {
311
+ if (signal.aborted) forwardAbort()
312
+ else signal.addEventListener('abort', forwardAbort, { once: true })
313
+ }
253
314
  let timedOut = false
254
315
  const timer = setTimeout(() => {
255
316
  timedOut = true
@@ -272,12 +333,14 @@ async function fetchText(
272
333
  if (!res.ok) throw new Error('检索失败:HTTP ' + res.status)
273
334
  return await res.text()
274
335
  } catch (error) {
275
- const message = messageOf(error)
276
- if (message.startsWith('检索失败')) throw error
336
+ if (signal && signal.aborted && !timedOut) throw new Error('检索失败:请求已取消')
337
+ const message = safeErrorMessage(error)
338
+ if (message.startsWith('检索失败')) throw new Error(message)
277
339
  if (timedOut) throw new Error('检索失败:请求超时(' + timeout + 'ms)')
278
340
  throw new Error('检索失败:网络错误(' + message + ')')
279
341
  } finally {
280
342
  clearTimeout(timer)
343
+ if (signal) signal.removeEventListener('abort', forwardAbort)
281
344
  }
282
345
  }
283
346
 
@@ -293,20 +356,24 @@ export async function searchArxiv({
293
356
  timeoutMs = DEFAULT_SEARCH_TIMEOUT,
294
357
  fetchImpl,
295
358
  networkConfig,
359
+ signal,
360
+ start,
296
361
  } = {}) {
297
362
  const max = clampInt(limit, 10, 1, 2000)
298
363
  const hasId = id !== undefined && id !== null && String(id).trim() !== ''
299
364
  const arxivId = hasId ? normalizeArxivId(id) : null
300
- if (hasId && arxivId === null) throw new Error('检索失败:无效的 arXiv ID(' + String(id) + ')')
365
+ if (hasId && arxivId === null) throw new Error('检索失败:无效的 arXiv ID(' + redactUserInfo(id) + ')')
301
366
  const keyword = typeof query === 'string' ? query.trim() : ''
302
367
  if (arxivId === null && keyword === '') throw new Error('检索失败:需要 query 或 id')
303
368
  const params =
304
369
  arxivId === null ? 'search_query=all:' + encodeURIComponent(keyword) : 'id_list=' + encodeURIComponent(arxivId)
305
- const xml = await fetchText(ARXIV_API + '?' + params + '&max_results=' + max, {
370
+ const startParam = start === undefined || start === null ? '' : '&start=' + clampInt(start, 0, 0, 2147483647)
371
+ const xml = await fetchText(ARXIV_API + '?' + params + startParam + '&max_results=' + max, {
306
372
  timeoutMs,
307
373
  accept: 'application/atom+xml, application/xml;q=0.9, */*;q=0.8',
308
374
  fetchImpl,
309
375
  networkConfig,
376
+ signal,
310
377
  })
311
378
  return { source: 'arxiv', items: parseArxivAtom(xml) }
312
379
  }
@@ -430,25 +497,33 @@ export async function searchOpenAlex({
430
497
  timeoutMs = DEFAULT_SEARCH_TIMEOUT,
431
498
  fetchImpl,
432
499
  networkConfig,
500
+ signal,
501
+ page,
502
+ includePageMetadata = false,
433
503
  } = {}) {
434
504
  const max = clampInt(limit, 10, 1, 200)
435
505
  const hasDoi = doi !== undefined && doi !== null && String(doi).trim() !== ''
436
506
  const normalizedDoi = hasDoi ? normalizeDoi(doi) : null
437
- if (hasDoi && normalizedDoi === null) throw new Error('检索失败:无效的 DOI(' + String(doi) + ')')
507
+ if (hasDoi && normalizedDoi === null) throw new Error('检索失败:无效的 DOI(' + redactUserInfo(doi) + ')')
438
508
  const keyword = typeof query === 'string' ? query.trim() : ''
439
509
  if (normalizedDoi === null && keyword === '') throw new Error('检索失败:需要 query 或 doi')
510
+ const pageParam = page === undefined || page === null ? '' : '&page=' + clampInt(page, 1, 1, 1000)
440
511
  const url =
441
512
  normalizedDoi === null
442
- ? OPENALEX_API + '/works?search=' + encodeURIComponent(keyword) + '&per-page=' + max
513
+ ? OPENALEX_API + '/works?search=' + encodeURIComponent(keyword) + '&per-page=' + max + pageParam
443
514
  : OPENALEX_API + '/works/https://doi.org/' + encodeDoiPath(normalizedDoi)
444
- const body = await fetchText(url, { timeoutMs, accept: 'application/json', fetchImpl, networkConfig })
515
+ const body = await fetchText(url, { timeoutMs, accept: 'application/json', fetchImpl, networkConfig, signal })
445
516
  let payload
446
517
  try {
447
518
  payload = JSON.parse(body)
448
519
  } catch {
449
520
  throw new Error('检索失败:OpenAlex 返回的不是合法 JSON')
450
521
  }
451
- return { source: 'openalex', items: parseOpenAlexWorks(payload) }
522
+ return {
523
+ source: 'openalex',
524
+ items: parseOpenAlexWorks(payload),
525
+ ...(includePageMetadata ? { totalCount: openAlexCount(payload) } : {}),
526
+ }
452
527
  }
453
528
 
454
529
  /** 合并去重键:标题压成小写单空格 + 年份。 */
@@ -510,6 +585,119 @@ export async function searchBoth({
510
585
  return warnings.length > 0 ? { items, warnings } : { items }
511
586
  }
512
587
 
588
+ /** 分页在线检索。游标绑定规范化查询和来源;每个来源独立推进,失败源保留位置供重试。 */
589
+ export async function searchOnlinePage({
590
+ query,
591
+ id,
592
+ doi,
593
+ source = 'both',
594
+ limit = 100,
595
+ cursor,
596
+ timeoutMs = DEFAULT_SEARCH_TIMEOUT,
597
+ signal,
598
+ fetchImpl,
599
+ networkConfig,
600
+ } = {}) {
601
+ const keyword = typeof query === 'string' ? query.trim().replace(/\s+/g, ' ') : ''
602
+ const requestedSource = String(source === undefined ? 'both' : source).trim().toLowerCase()
603
+ if (!['arxiv', 'openalex', 'both'].includes(requestedSource)) {
604
+ throw new Error('检索失败:不支持的数据源(' + redactUserInfo(requestedSource) + ')')
605
+ }
606
+ const max = clampInt(limit, 100, 1, 100)
607
+ const normalizedId = id ? normalizeArxivId(String(id)) : normalizeArxivId(keyword)
608
+ const normalizedDoi = doi ? normalizeDoi(String(doi)) : normalizeDoi(keyword)
609
+ if (id && !normalizedId) throw new Error('检索失败:无效的 arXiv ID(' + redactUserInfo(id) + ')')
610
+ if (doi && !normalizedDoi) throw new Error('检索失败:无效的 DOI(' + redactUserInfo(doi) + ')')
611
+ if (!normalizedId && !normalizedDoi && !keyword) throw new Error('检索失败:需要 query、arXiv ID 或 DOI')
612
+
613
+ const exact = Boolean(normalizedId || normalizedDoi)
614
+ const providers = normalizedDoi ? ['openalex'] : normalizedId ? ['arxiv'] : requestedSource === 'both' ? ['arxiv', 'openalex'] : [requestedSource]
615
+ const binding = fingerprint({
616
+ query: keyword.toLocaleLowerCase(),
617
+ id: normalizedId || null,
618
+ doi: normalizedDoi || null,
619
+ source: requestedSource,
620
+ providers,
621
+ })
622
+ let state
623
+ if (cursor !== undefined && cursor !== null) {
624
+ state = decodePageCursor(cursor, 'search')
625
+ if (state.binding !== binding || state.limit !== max || !state.providers || typeof state.providers !== 'object') {
626
+ throw new Error('检索失败:分页游标与当前查询/来源/每页数量不匹配,请重新检索')
627
+ }
628
+ for (const provider of providers) {
629
+ const entry = state.providers[provider]
630
+ const half = Math.ceil(max / 2)
631
+ const expectedPageSize = providers.length === 1 ? max : provider === 'arxiv' ? half : Math.max(1, max - half)
632
+ const maxPosition = provider === 'openalex' ? Math.min(1000, Math.floor(10000 / expectedPageSize)) : 2147483647
633
+ if (!entry || !Number.isInteger(entry.position) || entry.position < 0 || entry.position > maxPosition || typeof entry.done !== 'boolean' || entry.pageSize !== expectedPageSize) {
634
+ throw new Error('检索失败:分页游标位置无效,请重新检索')
635
+ }
636
+ }
637
+ } else {
638
+ const half = Math.ceil(max / 2)
639
+ state = {
640
+ v: 1,
641
+ kind: 'search',
642
+ binding,
643
+ limit: max,
644
+ providers: Object.fromEntries(providers.map((provider) => [provider, {
645
+ position: provider === 'openalex' ? 1 : 0,
646
+ done: false,
647
+ pageSize: providers.length === 1 ? max : provider === 'arxiv' ? half : Math.max(1, max - half),
648
+ }])),
649
+ }
650
+ }
651
+
652
+ const partialErrors = []
653
+ const warnings = []
654
+ const fetched = await Promise.all(providers.map(async (provider) => {
655
+ const current = state.providers[provider]
656
+ if (current.done) return { provider, items: [] }
657
+ if (signal && signal.aborted) return { provider, error: new Error('检索失败:请求已取消') }
658
+ try {
659
+ const result = provider === 'arxiv'
660
+ ? await searchArxiv({ query: keyword, id: normalizedId || undefined, limit: current.pageSize, start: current.position, timeoutMs, signal, fetchImpl, networkConfig })
661
+ : await searchOpenAlex({ query: keyword, doi: normalizedDoi || undefined, limit: current.pageSize, page: current.position, includePageMetadata: true, timeoutMs, signal, fetchImpl, networkConfig })
662
+ const count = result.items.length
663
+ if (exact || count < current.pageSize) current.done = true
664
+ else if (provider === 'arxiv') current.position += current.pageSize
665
+ else {
666
+ const nextPosition = current.position + 1
667
+ const maxPage = Math.min(1000, Math.floor(10000 / current.pageSize))
668
+ const totalCount = result.totalCount
669
+ current.done = totalCount !== null && current.position * current.pageSize >= totalCount
670
+ if (!current.done && current.position >= maxPage) {
671
+ current.done = true
672
+ warnings.push('OpenAlex 已到达分页上限(最多 1000 页/10000 条),可能仍有更多结果。')
673
+ } else if (!current.done) current.position = nextPosition
674
+ }
675
+ return { provider, items: result.items }
676
+ } catch (error) {
677
+ return { provider, error }
678
+ }
679
+ }))
680
+ const all = []
681
+ for (const result of fetched) {
682
+ if (result.error) {
683
+ const message = safeErrorMessage(result.error)
684
+ partialErrors.push({ source: result.provider, message })
685
+ warnings.push((result.provider === 'arxiv' ? 'arXiv' : 'OpenAlex') + ' 暂不可用:' + message)
686
+ } else {
687
+ all.push(...result.items.map((item) => ({ ...item, source: item.source || result.provider, sources: item.sources || [result.provider] })))
688
+ }
689
+ }
690
+ const items = mergeFeedItems(all, { limit: max })
691
+ const hasMore = !exact && providers.some((provider) => !state.providers[provider].done)
692
+ return {
693
+ items,
694
+ nextCursor: hasMore ? encodePageCursor(state) : null,
695
+ hasMore,
696
+ warnings: [...new Set(warnings)],
697
+ partialErrors,
698
+ }
699
+ }
700
+
513
701
  /** 超限提示:默认 200MB 时显示整数,非整数上限保留一位小数。 */
514
702
  function pdfTooLarge(maxBytes) {
515
703
  const mb = maxBytes / (1024 * 1024)
@@ -1201,14 +1389,17 @@ export function buildArxivLatestQuery({ categories, keywords } = {}) {
1201
1389
  }
1202
1390
 
1203
1391
  /** 构建带 submittedDate 降序排序的 arXiv API 请求 URL(纯函数)。 */
1204
- export function buildArxivLatestUrl({ categories, keywords, limit = DEFAULT_LATEST_LIMIT } = {}) {
1392
+ export function buildArxivLatestUrl({ categories, keywords, limit = DEFAULT_LATEST_LIMIT, start = 0 } = {}) {
1205
1393
  const max = clampInt(limit, DEFAULT_LATEST_LIMIT, 1, 2000)
1394
+ const offset = clampInt(start, 0, 0, 2147483647)
1206
1395
  const searchQuery = buildArxivLatestQuery({ categories, keywords })
1207
1396
  return (
1208
1397
  ARXIV_API +
1209
1398
  '?search_query=' +
1210
1399
  encodeURIComponent(searchQuery) +
1211
- '&sortBy=submittedDate&sortOrder=descending&max_results=' +
1400
+ '&sortBy=submittedDate&sortOrder=descending&start=' +
1401
+ offset +
1402
+ '&max_results=' +
1212
1403
  max
1213
1404
  )
1214
1405
  }
@@ -1239,6 +1430,7 @@ export function buildOpenAlexLatestUrl({
1239
1430
  limit = DEFAULT_LATEST_LIMIT,
1240
1431
  days = DEFAULT_OPENALEX_WINDOW_DAYS,
1241
1432
  now = Date.now(),
1433
+ page,
1242
1434
  } = {}) {
1243
1435
  const max = clampInt(limit, DEFAULT_LATEST_LIMIT, 1, 200)
1244
1436
  const windowDays = clampInt(days, DEFAULT_OPENALEX_WINDOW_DAYS, 1, 3650)
@@ -1253,7 +1445,8 @@ export function buildOpenAlexLatestUrl({
1253
1445
  '&filter=from_publication_date:' +
1254
1446
  sinceDate +
1255
1447
  '&sort=publication_date:desc&per-page=' +
1256
- max
1448
+ max +
1449
+ (page === undefined || page === null ? '' : '&page=' + clampInt(page, 1, 1, 1000))
1257
1450
  )
1258
1451
  }
1259
1452
 
@@ -1524,13 +1717,22 @@ export async function searchArxivLatest({
1524
1717
  now,
1525
1718
  fetchImpl,
1526
1719
  networkConfig,
1720
+ start,
1721
+ signal,
1527
1722
  } = {}) {
1528
- const url = buildArxivLatestUrl({ categories, keywords, limit })
1723
+ const pageContext = FEED_PAGE_CONTEXT.getStore()
1724
+ if (pageContext) {
1725
+ limit = pageContext.pageSize
1726
+ start = pageContext.position
1727
+ signal = pageContext.signal
1728
+ }
1729
+ const url = buildArxivLatestUrl({ categories, keywords, limit, start })
1529
1730
  const xml = await fetchText(url, {
1530
1731
  timeoutMs,
1531
1732
  accept: 'application/atom+xml, application/xml;q=0.9, */*;q=0.8',
1532
1733
  fetchImpl,
1533
1734
  networkConfig,
1735
+ signal,
1534
1736
  })
1535
1737
  const items = sortFeedItems(parseArxivAtom(xml))
1536
1738
  return { source: 'arxiv', items, fetchedAt: isoNow(now) }
@@ -1546,13 +1748,22 @@ export async function searchOpenAlexLatest({
1546
1748
  now,
1547
1749
  fetchImpl,
1548
1750
  networkConfig,
1751
+ page,
1752
+ signal,
1549
1753
  } = {}) {
1550
- const url = buildOpenAlexLatestUrl({ keywords, topicQueries, limit, days, now })
1754
+ const pageContext = FEED_PAGE_CONTEXT.getStore()
1755
+ if (pageContext) {
1756
+ limit = pageContext.pageSize
1757
+ page = pageContext.position
1758
+ signal = pageContext.signal
1759
+ }
1760
+ const url = buildOpenAlexLatestUrl({ keywords, topicQueries, limit, days, now, page })
1551
1761
  const body = await fetchText(url, {
1552
1762
  timeoutMs,
1553
1763
  accept: 'application/json',
1554
1764
  fetchImpl,
1555
1765
  networkConfig,
1766
+ signal,
1556
1767
  })
1557
1768
  let payload
1558
1769
  try {
@@ -1561,7 +1772,10 @@ export async function searchOpenAlexLatest({
1561
1772
  throw new Error('检索失败:OpenAlex 返回的不是合法 JSON')
1562
1773
  }
1563
1774
  const items = sortFeedItems(parseOpenAlexWorks(payload))
1564
- return { source: 'openalex', items, fetchedAt: isoNow(now) }
1775
+ const pageMeta = FEED_PAGE_CONTEXT.getStore() ? {
1776
+ totalCount: openAlexCount(payload),
1777
+ } : {}
1778
+ return { source: 'openalex', items, fetchedAt: isoNow(now), ...pageMeta }
1565
1779
  }
1566
1780
 
1567
1781
  async function mapSettledWithConcurrency(items, concurrency, worker) {
@@ -1611,6 +1825,7 @@ export async function fetchTopicFeed({
1611
1825
  now,
1612
1826
  fetchImpl,
1613
1827
  networkConfig,
1828
+ _pageRequest,
1614
1829
  } = {}) {
1615
1830
  const rawSrc =
1616
1831
  source !== undefined && source !== null && String(source).trim() !== ''
@@ -1626,7 +1841,7 @@ export async function fetchTopicFeed({
1626
1841
  throw new Error('订阅拉取失败:不支持的数据源(' + src + ')')
1627
1842
  }
1628
1843
 
1629
- const max = clampInt(limit, DEFAULT_FEED_LIMIT, 1, 200)
1844
+ const max = clampInt(limit, DEFAULT_FEED_LIMIT, 1, _pageRequest ? 100 : 200)
1630
1845
  const fetchedAt = isoNow(now)
1631
1846
  const partialErrors = []
1632
1847
  const topics = []
@@ -1639,43 +1854,133 @@ export async function fetchTopicFeed({
1639
1854
  source: taskSource,
1640
1855
  topicId: taskTopicId,
1641
1856
  label,
1642
- run: async () => {
1643
- const res = await runSearch()
1644
- return res.items.map((item) => ({
1857
+ run: async (pageState) => {
1858
+ const execute = () => runSearch()
1859
+ const res = pageState ? await FEED_PAGE_CONTEXT.run(pageState, execute) : await execute()
1860
+ const items = res.items.map((item) => ({
1645
1861
  ...item,
1646
1862
  source: taskSource,
1647
1863
  sources: [taskSource],
1648
1864
  topics: resolveTopics(item),
1649
1865
  }))
1866
+ return pageState ? { items, count: res.items.length, totalCount: res.totalCount } : items
1650
1867
  },
1651
1868
  })
1652
1869
  }
1653
1870
 
1654
1871
  const executeTasks = async () => {
1655
1872
  if (tasks.length === 0) {
1656
- return { topics, items: [], fetchedAt, partialErrors }
1873
+ return { topics, items: [], fetchedAt, partialErrors, ...( _pageRequest ? { nextCursor: null, hasMore: false, warnings: [] } : {}) }
1874
+ }
1875
+ if (!_pageRequest) {
1876
+ const settled = await mapSettledWithConcurrency(tasks, 3, (task) => task.run())
1877
+ const collected = []
1878
+ for (let i = 0; i < settled.length; i += 1) {
1879
+ const result = settled[i]
1880
+ const task = tasks[i]
1881
+ if (result.status === 'fulfilled') {
1882
+ collected.push(...result.value)
1883
+ } else {
1884
+ partialErrors.push({
1885
+ source: task.source,
1886
+ topicId: task.topicId,
1887
+ label: task.label,
1888
+ message: safeErrorMessage(result.reason),
1889
+ })
1890
+ }
1891
+ }
1892
+ return {
1893
+ topics,
1894
+ items: mergeFeedItems(collected, { limit: max }),
1895
+ fetchedAt,
1896
+ partialErrors,
1897
+ }
1898
+ }
1899
+
1900
+ const taskKeys = tasks.map((task, index) => `${index}:${task.source}`)
1901
+ let pageState
1902
+ if (_pageRequest.cursor) {
1903
+ pageState = decodePageCursor(_pageRequest.cursor, 'feed')
1904
+ if (pageState.binding !== _pageRequest.binding || pageState.limit !== max || typeof pageState.anchorNow !== 'number' || !Number.isFinite(pageState.anchorNow) || !Array.isArray(pageState.tasks) || pageState.tasks.length !== tasks.length || pageState.tasks.some((entry, index) => entry.key !== taskKeys[index])) {
1905
+ throw new Error('订阅分页失败:游标与当前主题、来源或每页数量不匹配,请重新拉取')
1906
+ }
1907
+ for (const [index, entry] of pageState.tasks.entries()) {
1908
+ const expectedPageSize = tasks.length > max ? 1 : Math.floor(max / tasks.length) + (index < max % tasks.length ? 1 : 0)
1909
+ const maxPosition = tasks[index].source === 'openalex' ? Math.min(1000, Math.floor(10000 / expectedPageSize)) : 2147483647
1910
+ if (!Number.isInteger(entry.position) || entry.position < 0 || entry.position > maxPosition || entry.pageSize !== expectedPageSize || typeof entry.done !== 'boolean') {
1911
+ throw new Error('订阅分页失败:游标位置无效,请重新拉取')
1912
+ }
1913
+ }
1914
+ if (!Number.isInteger(pageState.nextTask) || pageState.nextTask < 0 || pageState.nextTask >= tasks.length) {
1915
+ throw new Error('订阅分页失败:游标任务队列无效,请重新拉取')
1916
+ }
1917
+ } else {
1918
+ const base = Math.floor(max / tasks.length)
1919
+ const remainder = max % tasks.length
1920
+ pageState = {
1921
+ v: 1,
1922
+ kind: 'feed',
1923
+ binding: _pageRequest.binding,
1924
+ anchorNow: _pageRequest.anchorNow,
1925
+ limit: max,
1926
+ nextTask: 0,
1927
+ tasks: tasks.map((task, index) => ({
1928
+ key: taskKeys[index],
1929
+ position: task.source === 'openalex' ? 1 : 0,
1930
+ pageSize: tasks.length <= max ? base + (index < remainder ? 1 : 0) : 1,
1931
+ done: false,
1932
+ })),
1933
+ }
1657
1934
  }
1658
- const settled = await mapSettledWithConcurrency(tasks, 3, (task) => task.run())
1935
+
1936
+ const warnings = []
1937
+ const activeIndexes = []
1938
+ for (let checked = 0; checked < tasks.length && activeIndexes.length < max; checked += 1) {
1939
+ const index = pageState.nextTask
1940
+ pageState.nextTask = (index + 1) % tasks.length
1941
+ if (!pageState.tasks[index].done) activeIndexes.push(index)
1942
+ }
1943
+ const settled = await mapSettledWithConcurrency(activeIndexes, 3, (index) => {
1944
+ const task = tasks[index]
1945
+ const state = pageState.tasks[index]
1946
+ return task.run({ position: state.position, pageSize: state.pageSize, signal: _pageRequest.signal })
1947
+ })
1659
1948
  const collected = []
1660
1949
  for (let i = 0; i < settled.length; i += 1) {
1950
+ const index = activeIndexes[i]
1661
1951
  const result = settled[i]
1662
- const task = tasks[i]
1663
- if (result.status === 'fulfilled') {
1664
- collected.push(...result.value)
1952
+ const task = tasks[index]
1953
+ const state = pageState.tasks[index]
1954
+ if (result.status === 'rejected') {
1955
+ const message = safeErrorMessage(result.reason)
1956
+ partialErrors.push({ source: task.source, topicId: task.topicId, label: task.label, message })
1957
+ warnings.push((task.source === 'arxiv' ? 'arXiv' : 'OpenAlex') + ' 暂不可用:' + message)
1958
+ continue
1959
+ }
1960
+ collected.push(...result.value.items)
1961
+ const { count, totalCount } = result.value
1962
+ if (count < state.pageSize) {
1963
+ state.done = true
1964
+ } else if (task.source === 'openalex') {
1965
+ const maxPage = Math.min(1000, Math.floor(10000 / state.pageSize))
1966
+ if (totalCount !== null && totalCount !== undefined) state.done = state.position * state.pageSize >= totalCount
1967
+ if (!state.done && state.position >= maxPage) {
1968
+ state.done = true
1969
+ warnings.push('OpenAlex 已到达 10000 条分页边界,可能仍有更多结果。')
1970
+ } else if (!state.done) state.position += 1
1665
1971
  } else {
1666
- partialErrors.push({
1667
- source: task.source,
1668
- topicId: task.topicId,
1669
- label: task.label,
1670
- message: messageOf(result.reason),
1671
- })
1972
+ state.position += state.pageSize
1672
1973
  }
1673
1974
  }
1975
+ const hasMore = pageState.tasks.some((entry) => !entry.done)
1674
1976
  return {
1675
1977
  topics,
1676
1978
  items: mergeFeedItems(collected, { limit: max }),
1677
1979
  fetchedAt,
1678
1980
  partialErrors,
1981
+ nextCursor: hasMore ? encodePageCursor(pageState) : null,
1982
+ hasMore,
1983
+ warnings,
1679
1984
  }
1680
1985
  }
1681
1986
 
@@ -1726,7 +2031,7 @@ export async function fetchTopicFeed({
1726
2031
  () => [topicKey],
1727
2032
  )
1728
2033
  }
1729
- if (src === 'openalex') {
2034
+ if (useOpenAlex) {
1730
2035
  pushTask(
1731
2036
  'openalex',
1732
2037
  topicKey,
@@ -1781,7 +2086,7 @@ export async function fetchTopicFeed({
1781
2086
  () => [topicKey],
1782
2087
  )
1783
2088
  }
1784
- if (src === 'openalex') {
2089
+ if (useOpenAlex) {
1785
2090
  pushTask(
1786
2091
  'openalex',
1787
2092
  topicKey,
@@ -1930,7 +2235,7 @@ export async function fetchTopicFeed({
1930
2235
  )
1931
2236
  const activeTopics = resolveSubscribedTopics(normCfg)
1932
2237
  if (activeTopics.length === 0) {
1933
- return { topics: [], items: [], fetchedAt, partialErrors }
2238
+ return executeTasks()
1934
2239
  }
1935
2240
 
1936
2241
  const structuredItems = activeTopics.filter((t) => t.kind !== 'customKeyword')
@@ -2095,7 +2400,7 @@ export async function fetchTopicFeed({
2095
2400
  }
2096
2401
 
2097
2402
  if (presets.length === 0 && customKeywords.length === 0 && customObjects.length === 0) {
2098
- return { topics, items: [], fetchedAt, partialErrors }
2403
+ return executeTasks()
2099
2404
  }
2100
2405
 
2101
2406
  const unitCount = presets.length + (customKeywords.length > 0 ? 1 : 0) + customObjects.length
@@ -2214,3 +2519,62 @@ export async function fetchTopicFeed({
2214
2519
 
2215
2520
  return executeTasks()
2216
2521
  }
2522
+
2523
+ /** 分页科研 Feed;每个主题/来源任务用固定容量与独立位置续拉。 */
2524
+ export async function fetchTopicFeedPage(options = {}) {
2525
+ const input = options && typeof options === 'object' ? options : {}
2526
+ const limit = clampInt(input.limit, 100, 1, 100)
2527
+ const configuredSource = input.topicsConfig && input.topicsConfig.feedSource
2528
+ const requestedSource = String(
2529
+ input.source !== undefined && input.source !== null
2530
+ ? input.source
2531
+ : input.feedSource !== undefined && input.feedSource !== null
2532
+ ? input.feedSource
2533
+ : configuredSource || 'arxiv',
2534
+ ).trim()
2535
+ if (!['arxiv', 'openalex', 'both'].includes(requestedSource)) {
2536
+ throw new Error('订阅拉取失败:不支持的数据源(' + redactUserInfo(requestedSource) + ')')
2537
+ }
2538
+ const filters = {
2539
+ subscribed: input.subscribed,
2540
+ custom: input.custom,
2541
+ customKeywords: input.customKeywords,
2542
+ items: input.items,
2543
+ topicsConfig: input.topicsConfig,
2544
+ topicId: input.topicId,
2545
+ domainId: input.domainId,
2546
+ category: input.category,
2547
+ source: requestedSource,
2548
+ days: input.days === undefined ? DEFAULT_OPENALEX_WINDOW_DAYS : input.days,
2549
+ }
2550
+ let anchorNow = input.now === undefined ? Date.now() : input.now
2551
+ if (input.cursor !== undefined && input.cursor !== null) {
2552
+ const prior = decodePageCursor(input.cursor, 'feed')
2553
+ if (typeof prior.anchorNow !== 'number' || !Number.isFinite(prior.anchorNow)) {
2554
+ throw new Error('订阅分页失败:游标时间锚点无效,请重新拉取')
2555
+ }
2556
+ if (input.now !== undefined && prior.anchorNow !== input.now) {
2557
+ throw new Error('订阅分页失败:游标与当前时间范围不匹配,请重新拉取')
2558
+ }
2559
+ anchorNow = prior.anchorNow
2560
+ }
2561
+ const binding = fingerprint(filters)
2562
+ try {
2563
+ const result = await fetchTopicFeed({
2564
+ ...input,
2565
+ limit,
2566
+ now: anchorNow,
2567
+ _pageRequest: { cursor: input.cursor, binding, signal: input.signal, anchorNow },
2568
+ })
2569
+ result.partialErrors = result.partialErrors.map((error) => ({
2570
+ ...error,
2571
+ ...(error.topicId ? { topicId: redactUserInfo(error.topicId) } : {}),
2572
+ ...(error.label ? { label: redactUserInfo(error.label) } : {}),
2573
+ ...(error.message ? { message: redactUserInfo(error.message) } : {}),
2574
+ }))
2575
+ result.warnings = result.warnings.map(redactUserInfo)
2576
+ return result
2577
+ } catch (error) {
2578
+ throw new Error(safeErrorMessage(error))
2579
+ }
2580
+ }