@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,746 @@
1
+ /**
2
+ * 预处理层:把一份 arXiv 源码包变成「干净的、宏已展开的正文」。
3
+ *
4
+ * 输入是 {@link fetchEprint} 的文件表,输出是**一段可以直接切块的文本**加上一串统计。
5
+ * 这一层做完,切块层就只需要认 LaTeX 语法,不用再关心 include、注释、自定义宏。
6
+ *
7
+ * 五件事,顺序不能换:
8
+ * 1. 找主文件(含 \documentclass 的那份);
9
+ * 2. 递归展开 \input / \include(子文件里还有注释和宏,必须并进来才算完整);
10
+ * 3. 去注释(**先于**宏收集:定义里的 \% 会吞掉后面的花括号);
11
+ * 4. 收集并删除宏定义(删除是为了不让定义本身进正文——GPT-4 的 278 条定义全留在正文里
12
+ * 会变成一堆看不懂的符号);
13
+ * 5. 展开宏调用(多轮,直到不再变化)。
14
+ *
15
+ * 纯函数:文件表由调用方读好传进来,这一层不碰磁盘、不碰网络、不看时钟。
16
+ */
17
+ import { DEGRADE_REASON } from './tex-fetch.js'
18
+
19
+ /** 正文低于这个长度就判 pdf-only:正常论文正文远大于此,Adam 那篇(只有 \includepdf)是 44 字符。 */
20
+ const MIN_BODY_CHARS = 200
21
+ /** include 递归深度上限:超过就是环或病态包。 */
22
+ const MAX_INCLUDE_DEPTH = 16
23
+ /** 宏展开轮数上限:链式定义(a 用 b、b 用 c)实测最多 4 轮收敛。 */
24
+ const MAX_EXPAND_ROUNDS = 12
25
+ /** 宏展开的嵌套深度上限:防自引用炸栈。 */
26
+ const MAX_EXPAND_DEPTH = 24
27
+ /** 未知命令占比阈值:超过就判 macros。 */
28
+ /**
29
+ * 未知命令占比上限。
30
+ *
31
+ * 这道门问的是「这份包我们是不是基本看不懂」,不是「有没有个别命令没覆盖」。实测库里
32
+ * 58 篇能拿到源码的论文,在补完标准宏包白名单、并把绘图环境排除出统计口径之后,
33
+ * 最大 4.29%、p90 2.60%、中位数 0.62% —— 取 8% 留约两倍余量。
34
+ *
35
+ * 之前定 5% 是拿「未知命令 = 危险」当假设。实测下来它主要拦的不是野生宏(那些本来
36
+ * 就由 collectMacros 收走),而是模板自带的元数据命令与绘图命令;把标准命令算成
37
+ * 「不认识」,后果是本该用源码的论文被整篇退回 OCR。
38
+ */
39
+ const MAX_UNKNOWN_RATIO = 0.08
40
+
41
+ /** 反斜杠字符本身。 */
42
+ const BACKSLASH = '\\'
43
+
44
+ /**
45
+ * 已知命令表。
46
+ *
47
+ * 这份表**不是**要穷举 LaTeX,而是回答一个具体问题:展开完宏之后,剩下的命令里有多少是
48
+ * 「标准 LaTeX 中我们认识、但暂时不渲染」的,有多少是「我们压根不认识的」。只有后者占比高
49
+ * 才说明源码里有我们没处理的东西,才值得降级。
50
+ *
51
+ * 单字符命令(\,、\%、\\ 这些)一律按已知处理,不进这张表 —— 它们是转义或间距,没有语义。
52
+ */
53
+ const KNOWN_COMMANDS = new Set([
54
+ 'documentclass', 'documentstyle', 'usepackage', 'RequirePackage', 'begin', 'end', 'input', 'include',
55
+ 'subfile', 'includeonly', 'makeatletter', 'makeatother', 'ProvidesPackage', 'DeclareOption',
56
+ 'ExecuteOptions', 'ProcessOptions', 'NeedsTeXFormat', 'LoadClass',
57
+ 'part', 'chapter', 'section', 'subsection', 'subsubsection', 'paragraph', 'subparagraph',
58
+ 'title', 'author', 'date', 'thanks', 'and', 'maketitle', 'abstract', 'appendix',
59
+ 'bibliography', 'bibliographystyle', 'cite', 'citep', 'citet', 'nocite', 'ref', 'eqref', 'pageref',
60
+ 'autoref', 'cref', 'Cref', 'label', 'footnote', 'footnotetext', 'footnotemark',
61
+ 'item', 'caption', 'centering', 'raggedright', 'raggedleft', 'newline', 'linebreak', 'pagebreak',
62
+ 'clearpage', 'cleardoublepage', 'noindent', 'indent', 'par', 'relax', 'protect', 'nobreak',
63
+ 'allowbreak', 'hfill', 'vfill', 'hspace', 'vspace', 'smallskip', 'medskip', 'bigskip',
64
+ 'textbf', 'textit', 'emph', 'texttt', 'textrm', 'textsf', 'textsc', 'textsl', 'textup',
65
+ 'textnormal', 'underline', 'sout', 'url', 'href', 'hyperref', 'hypersetup', 'textcolor',
66
+ 'color', 'colorbox', 'fcolorbox', 'definecolor', 'today',
67
+ 'includegraphics', 'includepdf', 'graphicspath', 'rotatebox', 'scalebox', 'resizebox',
68
+ 'tabular', 'tabularx', 'longtable', 'table', 'figure', 'subfigure', 'subfloat', 'wrapfigure',
69
+ 'multicols', 'minipage', 'center', 'flushleft', 'flushright', 'quote', 'quotation', 'verse',
70
+ 'verbatim', 'lstlisting', 'minted', 'alltt',
71
+ 'itemize', 'enumerate', 'description', 'thebibliography', 'bibitem',
72
+ 'hline', 'cline', 'toprule', 'midrule', 'bottomrule', 'multicolumn', 'multirow',
73
+ 'arraystretch', 'tabcolsep', 'rule', 'setlength', 'addtolength', 'setcounter', 'addtocounter',
74
+ 'newcommand', 'renewcommand', 'providecommand', 'def', 'let', 'newenvironment', 'renewenvironment',
75
+ 'DeclareMathOperator', 'newtheorem', 'theoremstyle', 'numberwithin',
76
+ 'equation', 'align', 'gather', 'multline', 'eqnarray', 'split', 'aligned', 'cases', 'array',
77
+ 'matrix', 'pmatrix', 'bmatrix', 'vmatrix', 'Vmatrix', 'smallmatrix', 'displaymath', 'math',
78
+ 'tag', 'notag', 'nonumber', 'intertext', 'shortintertext',
79
+ 'frac', 'dfrac', 'tfrac', 'cfrac', 'sqrt', 'binom', 'choose', 'atop', 'over', 'above',
80
+ 'sum', 'prod', 'coprod', 'int', 'iint', 'iiint', 'oint', 'lim', 'limsup', 'liminf',
81
+ 'log', 'ln', 'lg', 'exp', 'sin', 'cos', 'tan', 'cot', 'sec', 'csc', 'arcsin', 'arccos',
82
+ 'arctan', 'sinh', 'cosh', 'tanh', 'coth', 'min', 'max', 'arg', 'det', 'dim', 'ker',
83
+ 'deg', 'gcd', 'hom', 'sup', 'inf', 'Pr', 'mod', 'bmod', 'pmod',
84
+ 'mathbb', 'mathcal', 'mathbf', 'mathit', 'mathrm', 'mathsf', 'mathtt', 'mathnormal',
85
+ 'boldsymbol', 'bm', 'text', 'operatorname', 'displaystyle', 'textstyle', 'scriptstyle',
86
+ 'scriptscriptstyle', 'limits', 'nolimits', 'substack',
87
+ 'left', 'right', 'big', 'Big', 'bigg', 'Bigg', 'bigl', 'bigr', 'Bigl', 'Bigr',
88
+ 'biggl', 'biggr', 'Biggl', 'Biggr', 'middle',
89
+ 'cdot', 'cdots', 'ldots', 'dots', 'vdots', 'ddots', 'iddots', 'times', 'div', 'pm', 'mp',
90
+ 'ast', 'star', 'circ', 'bullet', 'oplus', 'ominus', 'otimes', 'oslash', 'odot',
91
+ 'leq', 'le', 'geq', 'ge', 'neq', 'ne', 'approx', 'sim', 'simeq', 'cong', 'equiv', 'propto',
92
+ 'll', 'gg', 'prec', 'succ', 'preceq', 'succeq', 'asymp', 'doteq',
93
+ 'in', 'notin', 'ni', 'subset', 'subseteq', 'supset', 'supseteq', 'sqsubset', 'sqsubseteq',
94
+ 'cup', 'cap', 'bigcup', 'bigcap', 'setminus', 'emptyset', 'varnothing', 'complement',
95
+ 'forall', 'exists', 'nexists', 'neg', 'lnot', 'land', 'lor', 'wedge', 'vee', 'implies',
96
+ 'iff', 'therefore', 'because',
97
+ 'to', 'rightarrow', 'leftarrow', 'Rightarrow', 'Leftarrow', 'leftrightarrow',
98
+ 'Leftrightarrow', 'mapsto', 'longmapsto', 'longrightarrow', 'longleftarrow',
99
+ 'Longrightarrow', 'hookrightarrow', 'hookleftarrow', 'uparrow', 'downarrow', 'updownarrow',
100
+ 'nearrow', 'searrow', 'swarrow', 'nwarrow', 'rightleftharpoons',
101
+ 'infty', 'partial', 'nabla', 'ell', 'hbar', 'hslash', 'Re', 'Im', 'aleph', 'wp',
102
+ 'hat', 'widehat', 'bar', 'overline', 'vec', 'overrightarrow', 'dot', 'ddot', 'tilde',
103
+ 'widetilde', 'underbrace', 'overbrace', 'underset', 'overset', 'stackrel',
104
+ 'langle', 'rangle', 'lceil', 'rceil', 'lfloor', 'rfloor', 'lbrace', 'rbrace', 'vert',
105
+ 'Vert', 'lvert', 'rvert', 'lVert', 'rVert', 'backslash', 'prime', 'angle', 'triangle',
106
+ 'quad', 'qquad', 'enspace', 'thinspace', 'negthinspace', 'colon', 'textellipsis',
107
+ 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'varepsilon', 'zeta', 'eta', 'theta',
108
+ 'vartheta', 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi', 'omicron', 'pi', 'varpi', 'rho',
109
+ 'varrho', 'sigma', 'varsigma', 'tau', 'upsilon', 'phi', 'varphi', 'chi', 'psi', 'omega',
110
+ 'Gamma', 'Delta', 'Theta', 'Lambda', 'Xi', 'Pi', 'Sigma', 'Upsilon', 'Phi', 'Psi', 'Omega',
111
+ 'copyright', 'textbackslash', 'textasciitilde', 'textasciicircum', 'textbar', 'textless',
112
+ 'textgreater', 'textendash', 'textemdash', 'dotsb', 'dotsc',
113
+ 'affiliation', 'inst', 'etal', 'eg', 'ie',
114
+ // 宏包命令:实测一篇 NeurIPS 论文里 xspace 出现 99 次、newblock 75 次、cellcolor 52 次,
115
+ // 全是标准宏包给的,把它们算成「不认识」会让整篇被误判降级(12.45% vs 实际自定义 2.3%)。
116
+ 'xspace', 'newblock', 'cellcolor', 'rowcolor', 'columncolor', 'cmidrule', 'addlinespace',
117
+ 'shortstack', 'makecell', 'tnote', 'tablenotes', 'mathbbm', 'mid', 'nameref', 'citealt',
118
+ 'citeyearpar', 'SI', 'si', 'num', 'unit', 'ang', 'qty', 'todo', 'kw', 'etal', 'etal',
119
+ // algorithm2e / algorithmic 的控制流命令:它们只在算法块里出现,不属于「不认识」。
120
+ 'State', 'For', 'EndFor', 'While', 'EndWhile', 'If', 'EndIf', 'Else', 'Return',
121
+ 'Require', 'Ensure', 'Procedure', 'EndProcedure', 'KwIn', 'KwOut', 'KwData', 'KwResult',
122
+ 'newsavebox', 'sbox', 'parbox', 'adjustbox', 'raisebox',
123
+ // 长度与尺寸:极常见,且从来不产出内容(@@textwidth 这类写在 includegraphics 的选项里)。
124
+ 'textwidth', 'linewidth', 'columnwidth', 'textheight', 'paperwidth', 'paperheight',
125
+ 'baselineskip', 'baselinestretch', 'parindent', 'parskip', 'fboxsep', 'fboxrule',
126
+ 'arrayrulewidth', 'unitlength', 'columnsep', 'abovecaptionskip', 'belowcaptionskip',
127
+ // 盒子与字号声明:渲染层不还原样式,但它们在正文里很常见,不该算「不认识」。
128
+ 'fbox', 'hbox', 'vbox', 'makebox', 'framebox', 'parbox', 'raisebox', 'strut', 'vline',
129
+ 'hrulefill', 'dotfill', 'hrule', 'small', 'footnotesize', 'scriptsize', 'tiny', 'large',
130
+ 'Large', 'LARGE', 'huge', 'Huge', 'normalsize', 'bfseries', 'itshape', 'ttfamily',
131
+ 'rmfamily', 'sffamily', 'mdseries', 'upshape', 'slshape', 'scshape', 'em', 'bf', 'it', 'tt',
132
+ // 算法宏包(algorithmicx / algpseudocode / algorithm2e):它们的命令只出现在算法块里,
133
+ // 一条 \Comment 就是一句自然语言批注,把它们算「不认识」等于按算法条数扣分。
134
+ 'Comment', 'gets', 'ElseIf', 'Function', 'EndFunction', 'Repeat', 'Until', 'Loop', 'EndLoop',
135
+ 'SetKw', 'SetKwInOut', 'SetKwFunction', 'SetKwData', 'SetKwInput', 'SetAlgoLined',
136
+ 'DontPrintSemicolon', 'BlankLine', 'tcp', 'tcc', 'nl', 'Indp', 'Indm',
137
+ 'Precondition', 'Postcondition', 'KwTo', 'KwRet', 'Break', 'Continue', 'EndIf', 'EndFor',
138
+ // 出版模板的元数据命令(ACM / Elsevier / IEEE):值落在 \author 与 CCS 块里,
139
+ // 本来就该被 preamble 截掉,正文里见到也不该算「不认识」。
140
+ 'ccsdesc', 'ccsdesc', 'institution', 'country', 'email', 'keywords', 'city', 'postcode',
141
+ 'streetaddress', 'orcid', 'conferenceInfo', 'setcopyright', 'acmDOI', 'acmISBN', 'acmYear',
142
+ 'acmConference', 'acmBooktitle', 'acmPrice', 'CopyrightYear', 'CopyrightText', 'Price',
143
+ 'received', 'documentclass', 'institute', 'affil', 'affiliationmark', 'corref', 'fnmark',
144
+ // amssymb / 常用数学符号:它们本来就在数学区里,出现在正文也不算「不认识」。
145
+ 'triangleq', 'checkmark', 'leavevmode', 'textbullet', 'square', 'blacksquare', 'Box',
146
+ 'Diamond', 'bigstar', 'blacktriangleright', 'blacktriangleleft', 'vartriangle', 'eqsim',
147
+ // booktabs 与表格宏包。
148
+ 'specialrule', 'thead', 'hhline', 'diagbox', 'arraybackslash', 'tabularnewline', 'Xhline',
149
+ 'rowfont', 'tabu', 'cmark', 'addlinespace', 'midrule', 'cmidrule', 'toprule', 'bottomrule',
150
+ // TeX 原语:只在样式与条件判断里出现。
151
+ 'unskip', 'ignorespaces', 'expandafter', 'csname', 'endcsname', 'ifnextchar', 'noalign',
152
+ 'hfil', 'vfil', 'hss', 'vss', 'kern', 'mkern', 'mskip', 'hskip', 'vskip', 'penalty',
153
+ // natbib 与 NATBib 的 .bst 生成的排版命令:实测一篇 NeurIPS 风格的论文里
154
+ // showarticletitle 出现 77 次、tempurl 72 次、urldef 36 次,全是参考文献条目里的样板。
155
+ 'showarticletitle', 'tempurl', 'urldef', 'showDOI', 'showeprint', 'doilink', 'eprint',
156
+ 'urlprefix', 'natexlab', 'bibfont', 'citenumfont', 'bibpunct', 'bibsep', 'bibhang',
157
+ 'showISBNx', 'showISBNxiii', 'showISSN', 'showCODEN', 'showLCCN', 'shownote', 'showURL',
158
+ 'texttrademark', 'mbox', 'protected@write', 'undefined',
159
+ // LaTeX2e 的 NFSS(字体选择):\fontfamily{...}\selectfont 这类调用分布在每个字体切换点。
160
+ 'fontfamily', 'selectfont', 'fontsize', 'fontshape', 'fontseries', 'usefont', 'fontencoding',
161
+ 'fontseriesdefault', 'normalfont', 'emrmdefault',
162
+ // TeX 条件原语与盒子:只控制排版分支,不产出正文。
163
+ 'ifx', 'ifnum', 'ifdim', 'ifcase', 'ifdefined', 'ifcsname', 'else', 'fi', 'or', 'expandafter',
164
+ 'noexpand', 'smash', 'vphantom', 'hphantom', 'mathrlap', 'mathllap', 'rlap', 'llap', 'clap',
165
+ 'ensuremath', 'raisebox', 'rule', 'hrule', 'vrule', 'copy', 'box',
166
+ // 图与标题的补充命令。
167
+ 'captionof', 'subcaption', 'subcaptionbox', 'captionsetup', 'captionstyle', 'floatstyle',
168
+ 'restylefloat', 'usepackage', 'RequirePackage',
169
+ // 无障碍与标签(tagpdf / LaTeX 2022+)。
170
+ 'Description', 'tagstructbegin', 'tagstructend', 'tagmcbegin', 'tagmcend', 'pdfstringdef',
171
+ // 常见说明性命令:作者在草稿里留的批注,删掉即可。
172
+ 'todo', 'todonotes', 'missingfigure', 'listoftodos',
173
+ // algorithm2e 的大写变体与其余宏包命令。
174
+ 'STATE', 'IF', 'ENDIF', 'ELSIF', 'BEGIN', 'END', 'ForAll', 'Call', 'CallLine',
175
+ // LaTeX / e-TeX 原语。
176
+ 'textsuperscript', 'textsubscript', 'begingroup', 'endgroup', 'dimexpr', 'char',
177
+ 'linenumbers', 'nolinenumbers', 'ifcolsubmission', 'ifcolfinal',
178
+ // pifont 的 dingbat 与列表标记。
179
+ 'ding', 'LEFTcircle', 'RIGHTcircle', 'CIRCLE', 'Square', 'XSolidBrush', 'Checkmark',
180
+ // longtable 的表头表尾钩子。
181
+ 'endfirsthead', 'endhead', 'endfoot', 'endlastfoot', 'lastfoot', 'extracolsep', 'extrarowheight',
182
+ // 长度与段落参数(只影响排版)。
183
+ 'hsize', 'vsize', 'leftskip', 'rightskip', 'fill', 'phantomsection', 'addtocontents',
184
+ 'newpage', 'phantom', 'texorpdfstring',
185
+ // amsmath / amssymb 的常用关系与箭头。
186
+ 'dagger', 'ddagger', 'lesssim', 'gtrsim', 'dag', 'xrightarrow', 'xleftarrow',
187
+ // natbib 的编号命令(.bst 生成)。
188
+ 'citenum',
189
+ ])
190
+
191
+ /** 前面连续反斜杠个数为奇数,说明这个字符被转义了。 */
192
+ function isEscaped(text, index) {
193
+ let count = 0
194
+ for (let cursor = index - 1; cursor >= 0 && text[cursor] === BACKSLASH; cursor -= 1) count += 1
195
+ return count % 2 === 1
196
+ }
197
+
198
+ /**
199
+ * 读一个命令名。text[index] 必须是反斜杠。
200
+ *
201
+ * 两种形态:字母串(\section、\alpha)与单个非字母字符(\%、\\、\,)。
202
+ * 返回的 end 指向名字之后(不含)。
203
+ */
204
+ export function readCommandName(text, index) {
205
+ if (text[index] !== BACKSLASH) return null
206
+ const next = text[index + 1]
207
+ if (next === undefined) return null
208
+ if (/[a-zA-Z@]/.test(next)) {
209
+ let end = index + 1
210
+ while (end < text.length && /[a-zA-Z@]/.test(text[end])) end += 1
211
+ return { name: text.slice(index + 1, end), end }
212
+ }
213
+ return { name: next, end: index + 2 }
214
+ }
215
+
216
+ /** 跳过空白(含换行)。 */
217
+ export function skipSpaces(text, index) {
218
+ let cursor = index
219
+ while (cursor < text.length && /\s/.test(text[cursor])) cursor += 1
220
+ return cursor
221
+ }
222
+
223
+ /**
224
+ * 读一个花括号组。text[index] 必须是左花括号。
225
+ *
226
+ * 必须做平衡扫描而不是找第一个右花括号:宏体里嵌套花括号是常态
227
+ * (\newcommand{\foo}{\frac{a}{b}}),按第一个右括号截断会把定义切成半截。
228
+ * 转义花括号(\{ \})不参与配对。
229
+ */
230
+ export function readGroup(text, index) {
231
+ if (text[index] !== '{') return null
232
+ let depth = 0
233
+ for (let cursor = index; cursor < text.length; cursor += 1) {
234
+ const char = text[cursor]
235
+ if (char === BACKSLASH) { cursor += 1; continue }
236
+ if (char === '{') depth += 1
237
+ else if (char === '}') {
238
+ depth -= 1
239
+ if (depth === 0) return { content: text.slice(index + 1, cursor), start: index, end: cursor + 1 }
240
+ }
241
+ }
242
+ return null
243
+ }
244
+
245
+ /** 读一个方括号可选参数。text[index] 必须是左方括号;里面的花括号不参与配对。 */
246
+ export function readOptional(text, index) {
247
+ if (text[index] !== '[') return null
248
+ let depth = 0
249
+ for (let cursor = index; cursor < text.length; cursor += 1) {
250
+ const char = text[cursor]
251
+ if (char === BACKSLASH) { cursor += 1; continue }
252
+ if (char === '{') depth += 1
253
+ else if (char === '}') depth -= 1
254
+ else if (char === ']' && depth === 0) return { content: text.slice(index + 1, cursor), start: index, end: cursor + 1 }
255
+ }
256
+ return null
257
+ }
258
+
259
+ /**
260
+ * 去注释:\% 到行尾(不含换行),但转义后的 \% 与 verbatim 类环境里的 \% 都保留。
261
+ *
262
+ * 三条规则各自对应一个真实事故:
263
+ * - **转义**:\% 在 LaTeX 里就是百分号字符,剥掉会把 90\% 变成 90;
264
+ * - **verbatim**:代码块里的 \% 是注释符号本身,剥掉会改代码语义;
265
+ * - **反斜杠个数**:判据是「前面连续反斜杠为奇数才算转义」,否则 \\% 会被误判。
266
+ */
267
+ export function stripComments(text) {
268
+ const source = typeof text === 'string' ? text : ''
269
+ let out = ''
270
+ let index = 0
271
+ let verbatim = null
272
+ while (index < source.length) {
273
+ const char = source[index]
274
+ if (char === BACKSLASH) {
275
+ const command = readCommandName(source, index)
276
+ if (command === null) { out += char; index += 1; continue }
277
+ if (command.name === 'begin' && verbatim === null) {
278
+ const env = readGroup(source, skipSpaces(source, command.end))
279
+ if (env !== null && /^(?:verbatim\*?|lstlisting|minted|alltt|comment)$/.test(env.content.trim())) {
280
+ verbatim = env.content.trim()
281
+ }
282
+ const stop = env === null ? command.end : env.end
283
+ out += source.slice(index, stop)
284
+ index = stop
285
+ continue
286
+ }
287
+ if (command.name === 'end' && verbatim !== null) {
288
+ const env = readGroup(source, skipSpaces(source, command.end))
289
+ const stop = env === null ? command.end : env.end
290
+ if (env !== null && env.content.trim() === verbatim) verbatim = null
291
+ out += source.slice(index, stop)
292
+ index = stop
293
+ continue
294
+ }
295
+ out += source.slice(index, command.end)
296
+ index = command.end
297
+ continue
298
+ }
299
+ if (char === '%' && verbatim === null && !isEscaped(source, index)) {
300
+ while (index < source.length && source[index] !== '\n') index += 1
301
+ continue
302
+ }
303
+ out += char
304
+ index += 1
305
+ }
306
+ return out
307
+ }
308
+
309
+ /**
310
+ * 找主文件:含 \documentclass 或 \documentstyle 的 .tex。
311
+ *
312
+ * 为什么「最长的那份」:实测有的包同时带 main.tex 与一份 early draft / response letter,
313
+ * 两份都有 \documentclass。正文最长的那份才是论文本体。
314
+ * 注释掉的 \documentclass 不算(先去注释再判)。
315
+ */
316
+ export function findMainFile(files) {
317
+ const texFiles = (Array.isArray(files) ? files : [])
318
+ .filter(file => file && typeof file.name === 'string' && /.tex$/i.test(file.name) && file.bytes)
319
+ let best = null
320
+ for (const file of texFiles) {
321
+ const text = file.bytes.toString('utf8')
322
+ const stripped = stripComments(text)
323
+ if (!/\\(?:documentclass|documentstyle)/.test(stripped)) continue
324
+ if (best === null || stripped.length > best.score) best = { name: file.name, text, score: stripped.length }
325
+ }
326
+ return best === null ? null : { name: best.name, text: best.text }
327
+ }
328
+
329
+ /** 把 include 目标解析成文件表里的键;找不到返回 null。 */
330
+ function resolveInclude(target, from, fileMap) {
331
+ const clean = target.replace(/\\/g, '/').trim()
332
+ if (clean === '') return null
333
+ const directory = from.includes('/') ? from.slice(0, from.lastIndexOf('/') + 1) : ''
334
+ const candidates = []
335
+ for (const base of [directory, '']) {
336
+ const relative = base + clean
337
+ candidates.push(relative, relative + '.tex')
338
+ }
339
+ for (const candidate of candidates) {
340
+ const normalized = candidate.replace(/^\.\//, '')
341
+ if (fileMap.has(normalized)) return normalized
342
+ }
343
+ return null
344
+ }
345
+
346
+ /**
347
+ * 递归展开 \input / \include / \subfile。
348
+ *
349
+ * 找不到的目标**原样保留**:\input{missing} 留在正文里至少还能被统计到,
350
+ * 换成空串就等于把「这里少了一节」这件事抹掉了。环按 visited 集合断开。
351
+ */
352
+ export function expandIncludes(main, fileMap, { maxDepth = MAX_INCLUDE_DEPTH } = {}) {
353
+ const missing = []
354
+ let found = 0
355
+ const visited = new Set([main.name])
356
+ const pattern = /\\(?:input|include|subfile)\s*\{([^}]*)\}/g
357
+ const expand = (name, text, depth) => {
358
+ if (depth > maxDepth) return text
359
+ return text.replace(pattern, (whole, target) => {
360
+ const resolved = resolveInclude(target, name, fileMap)
361
+ if (resolved === null) { missing.push(target.trim()); return whole }
362
+ if (visited.has(resolved)) return ''
363
+ visited.add(resolved)
364
+ found += 1
365
+ return expand(resolved, fileMap.get(resolved), depth + 1)
366
+ })
367
+ }
368
+ return { name: main.name, text: expand(main.name, main.text, 0), includes: { found, missing } }
369
+ }
370
+
371
+ /**
372
+ * 收集自定义宏与环境定义,并记下它们在文本里的区间(供 {@link removeSpans} 删除)。
373
+ *
374
+ * 只认四种声明:\newcommand / \renewcommand / \providecommand / \DeclareMathOperator,
375
+ * 外加零参数的 \def 与 \newenvironment(后者只记名字,不展开)。
376
+ *
377
+ * 带默认值(\newcommand{\x}[2][d]{...})的宏**不记进宏表**:它的参数个数依赖调用方,
378
+ * 第 1 批不做这套语义 —— 记进去只会按错误的位置替换参数。
379
+ */
380
+ /**
381
+ * 把 \bibliography{name} 就地换成同目录下 name.bbl 的内容。
382
+ *
383
+ * 为什么值得做:.bbl 是 bibtex 已经排版好的参考文献(含条目顺序与编号),比我们从
384
+ * \bibitem 硬啃 \bibliography 可靠得多;40 篇抽样里 8 篇带 bbl。没有 bbl 时不报错,
385
+ * 只把缺的那个名字记进 missing —— 上层据此知道这篇的参考文献只能靠 MinerU。
386
+ */
387
+ export function inlineBibliography(text, fileMap, { from = '' } = {}) {
388
+ const source = typeof text === 'string' ? text : ''
389
+ const missing = []
390
+ let inlined = 0
391
+ const pattern = /\\bibliography\s*\{([^}]*)\}/g
392
+ const result = source.replace(pattern, (whole, names) => {
393
+ const parts = []
394
+ for (const name of String(names).split(',').map(value => value.trim()).filter(value => value !== '')) {
395
+ const resolved = resolveInclude(name + '.bbl', from, fileMap) ?? resolveInclude(name, from, fileMap)
396
+ if (resolved === null) { missing.push(name); continue }
397
+ parts.push(fileMap.get(resolved))
398
+ inlined += 1
399
+ }
400
+ return parts.length === 0 ? '' : parts.join('\n')
401
+ })
402
+ return { text: result, inlined, missing }
403
+ }
404
+
405
+ export function collectMacros(text) {
406
+ const source = typeof text === 'string' ? text : ''
407
+ const macros = new Map()
408
+ const environments = new Map()
409
+ const spans = []
410
+
411
+ const newCommand = /\\(?:(re)?newcommand|providecommand)\*?\s*/g
412
+ let match
413
+ while ((match = newCommand.exec(source)) !== null) {
414
+ let cursor = match.index + match[0].length
415
+ let name = ''
416
+ if (source[cursor] === '{') {
417
+ const group = readGroup(source, cursor)
418
+ if (group === null) continue
419
+ const command = readCommandName(group.content.trim(), 0)
420
+ if (command === null) continue
421
+ name = command.name
422
+ cursor = group.end
423
+ } else {
424
+ const command = readCommandName(source, cursor)
425
+ if (command === null) continue
426
+ name = command.name
427
+ cursor = command.end
428
+ }
429
+ cursor = skipSpaces(source, cursor)
430
+ let argc = 0
431
+ const argcGroup = readOptional(source, cursor)
432
+ if (argcGroup !== null) {
433
+ argc = Number.parseInt(argcGroup.content.trim(), 10)
434
+ if (!Number.isInteger(argc) || argc < 0) argc = 0
435
+ cursor = argcGroup.end
436
+ }
437
+ cursor = skipSpaces(source, cursor)
438
+ const defaultGroup = argc > 0 ? readOptional(source, cursor) : null
439
+ if (defaultGroup !== null) cursor = defaultGroup.end
440
+ cursor = skipSpaces(source, cursor)
441
+ const body = readGroup(source, cursor)
442
+ if (body === null) continue
443
+ spans.push({ start: match.index, end: body.end })
444
+ // 带默认值的宏不进表(见注释);仍要删定义,所以 span 已经记下。
445
+ if (defaultGroup === null && !macros.has(name)) {
446
+ macros.set(name, { argc, body: body.content })
447
+ }
448
+ }
449
+
450
+ const mathOperator = /\\DeclareMathOperator\*?\s*/g
451
+ while ((match = mathOperator.exec(source)) !== null) {
452
+ let cursor = skipSpaces(source, match.index + match[0].length)
453
+ const nameGroup = readGroup(source, cursor)
454
+ if (nameGroup === null) continue
455
+ const command = readCommandName(nameGroup.content.trim(), 0)
456
+ cursor = skipSpaces(source, nameGroup.end)
457
+ const body = readGroup(source, cursor)
458
+ if (command === null || body === null) continue
459
+ spans.push({ start: match.index, end: body.end })
460
+ if (!macros.has(command.name)) {
461
+ macros.set(command.name, { argc: 0, body: '\\operatorname{' + body.content + '}' })
462
+ }
463
+ }
464
+
465
+ // 零参数 \def:\def\foo{...}。带参数的 \def 形态(\def\foo#1{...})不认,
466
+ // 定义与调用都原样留着 —— 不认识的东西宁可保留,也不要按错误位置替换。
467
+ const plainDef = /\\def\s*\\([a-zA-Z@]+)\s*\{/g
468
+ while ((match = plainDef.exec(source)) !== null) {
469
+ const bodyStart = source.indexOf('{', match.index + match[0].length - 1)
470
+ const body = readGroup(source, bodyStart)
471
+ if (body === null) continue
472
+ spans.push({ start: match.index, end: body.end })
473
+ if (!macros.has(match[1])) macros.set(match[1], { argc: 0, body: body.content })
474
+ }
475
+
476
+ const newEnvironment = /\\(?:(re)?newenvironment)\*?\s*/g
477
+ while ((match = newEnvironment.exec(source)) !== null) {
478
+ let cursor = skipSpaces(source, match.index + match[0].length)
479
+ const nameGroup = readGroup(source, cursor)
480
+ if (nameGroup === null) continue
481
+ cursor = skipSpaces(source, nameGroup.end)
482
+ const argcGroup = readOptional(source, cursor)
483
+ if (argcGroup !== null) cursor = skipSpaces(source, argcGroup.end)
484
+ const defaultGroup = readOptional(source, cursor)
485
+ if (defaultGroup !== null) cursor = skipSpaces(source, defaultGroup.end)
486
+ const begin = readGroup(source, cursor)
487
+ if (begin === null) continue
488
+ const end = readGroup(source, skipSpaces(source, begin.end))
489
+ if (end === null) continue
490
+ spans.push({ start: match.index, end: end.end })
491
+ if (!environments.has(nameGroup.content.trim())) {
492
+ environments.set(nameGroup.content.trim(), { begin: begin.content, end: end.content })
493
+ }
494
+ }
495
+
496
+ spans.sort((left, right) => left.start - right.start)
497
+ return { macros, environments, spans }
498
+ }
499
+
500
+ /** 按区间删除文本(区间允许重叠:先到的赢)。 */
501
+ export function removeSpans(text, spans) {
502
+ const source = typeof text === 'string' ? text : ''
503
+ if (!Array.isArray(spans) || spans.length === 0) return source
504
+ let out = ''
505
+ let cursor = 0
506
+ for (const span of spans) {
507
+ if (!(span.end > span.start) || span.start < cursor) continue
508
+ out += source.slice(cursor, span.start)
509
+ cursor = span.end
510
+ }
511
+ return out + source.slice(cursor)
512
+ }
513
+
514
+ /** 把宏体里的 #1..#9 换成实参;## 是字面井号,先占位再还原。 */
515
+ function applyArguments(body, args) {
516
+ const PLACEHOLDER = '\u0001'
517
+ return body
518
+ .split('##').join(PLACEHOLDER)
519
+ .replace(/#([1-9])/g, (whole, digit) => {
520
+ const value = args[Number(digit) - 1]
521
+ return value === undefined ? whole : value
522
+ })
523
+ .split(PLACEHOLDER).join('#')
524
+ }
525
+
526
+ /**
527
+ * 单趟展开:扫描全文,遇到宏调用就取参数、替换宏体、递归展开结果。
528
+ *
529
+ * 单趟而不是「每个宏做一次全文 replace」:实测 GPT-3 的包有 3713 条宏定义、正文 281KB,
530
+ * 逐宏全量替换是 O(宏数 × 正文长度),几千万次字符扫描;单趟是 O(正文长度 × 嵌套深度)。
531
+ */
532
+ function expandOnce(text, macros, depth) {
533
+ let out = ''
534
+ let index = 0
535
+ let count = 0
536
+ let unresolved = 0
537
+ while (index < text.length) {
538
+ if (text[index] !== BACKSLASH) { out += text[index]; index += 1; continue }
539
+ const command = readCommandName(text, index)
540
+ if (command === null) { out += text[index]; index += 1; continue }
541
+ const macro = macros.get(command.name)
542
+ if (macro === undefined) {
543
+ out += text.slice(index, command.end)
544
+ index = command.end
545
+ continue
546
+ }
547
+ let cursor = command.end
548
+ const args = []
549
+ let complete = true
550
+ for (let position = 0; position < macro.argc; position += 1) {
551
+ cursor = skipSpaces(text, cursor)
552
+ const group = readGroup(text, cursor)
553
+ if (group === null) { complete = false; break }
554
+ args.push(group.content)
555
+ cursor = group.end
556
+ }
557
+ if (!complete) {
558
+ // 参数不齐:原样保留调用,计入 unresolved。宁可留着让人看见,也不要替换成半截内容。
559
+ unresolved += 1
560
+ out += text.slice(index, command.end)
561
+ index = command.end
562
+ continue
563
+ }
564
+ const body = applyArguments(macro.body, args)
565
+ count += 1
566
+ out += depth > 0 ? expandOnce(body, macros, depth - 1).text : body
567
+ index = cursor
568
+ }
569
+ return { text: out, count, unresolved }
570
+ }
571
+
572
+ /**
573
+ * 展开宏调用,多轮直到不再变化。
574
+ *
575
+ * 多轮是必要的:\newcommand{\a}{\b} 与 \newcommand{\b}{x} 的收集顺序不定,
576
+ * 一轮下来 \a 可能展开成 \b 而不是 x。
577
+ */
578
+ export function expandMacros(text, macros, { maxRounds = MAX_EXPAND_ROUNDS, maxDepth = MAX_EXPAND_DEPTH } = {}) {
579
+ const source = typeof text === 'string' ? text : ''
580
+ if (!(macros instanceof Map) || macros.size === 0) return { text: source, expanded: 0, unresolved: 0 }
581
+ let current = source
582
+ let expanded = 0
583
+ let unresolved = 0
584
+ for (let round = 0; round < maxRounds; round += 1) {
585
+ const result = expandOnce(current, macros, maxDepth)
586
+ expanded += result.count
587
+ unresolved = result.unresolved
588
+ if (result.count === 0) { current = result.text; break }
589
+ current = result.text
590
+ }
591
+ return { text: current, expanded, unresolved }
592
+ }
593
+
594
+ /**
595
+ * 切出 document 环境内的正文与 preamble。
596
+ *
597
+ * 没有 \begin{document} 时(老式 \documentstyle 写法仍会有它;真没有说明包不完整)
598
+ * 全文都当正文 —— 少切一刀比切错一刀安全。
599
+ */
600
+ export function extractBody(text) {
601
+ const source = typeof text === 'string' ? text : ''
602
+ const begin = /\\begin\s*\{document\}/.exec(source)
603
+ if (begin === null) return { preamble: source, body: source, hasDocumentEnv: false }
604
+ const start = begin.index + begin[0].length
605
+ const end = /\\end\s*\{document\}/.exec(source.slice(start))
606
+ const stop = end === null ? source.length : start + end.index
607
+ return { preamble: source.slice(0, begin.index), body: source.slice(start, stop), hasDocumentEnv: true }
608
+ }
609
+
610
+ /**
611
+ * 绘图类环境(TikZ / pgfplots / pstricks)整段剥掉,**只为统计口径服务**。
612
+ *
613
+ * 这些环境里的内容本来就不进正文(切块层把它们整体跳过),但 \node、\draw、
614
+ * \pgfmathtruncatemacro 会按绘图点数计进「不认识的命令」—— 实测一篇论文里
615
+ * mix 出现 228 次、node 224 次,把 16.06% 的未知率全算在正文头上,而正文里一个都没有。
616
+ * 这种污染会让本该通过的论文被判 macros 降级。
617
+ */
618
+ const DRAWING_ENVIRONMENTS = ['tikzpicture', 'pgfpicture', 'pspicture', 'axis', 'tikzcd', 'circuitikz', 'pgfonlayer']
619
+
620
+ function stripDrawingEnvironments(text) {
621
+ let output = text
622
+ for (const name of DRAWING_ENVIRONMENTS) {
623
+ const pattern = new RegExp('\\\\begin\\{' + name + '\\}[\\s\\S]*?\\\\end\\{' + name + '\\}', 'g')
624
+ // 同名环境嵌套:反复剥到不再变化。
625
+ for (let round = 0; round < 4; round += 1) {
626
+ const next = output.replace(pattern, ' ')
627
+ if (next === output) break
628
+ output = next
629
+ }
630
+ }
631
+ return output
632
+ }
633
+
634
+ /**
635
+ * 统计命令总数与「不认识」的数量。
636
+ *
637
+ * 只统计**展开之后**还剩下的命令:展开掉的宏不算未知。这个比值是 macros 这条判定唯一的输入。
638
+ */
639
+ export function documentStats(text) {
640
+ const source = stripDrawingEnvironments(typeof text === 'string' ? text : '')
641
+ const top = new Map()
642
+ let total = 0
643
+ let unknown = 0
644
+ let index = 0
645
+ while (index < source.length) {
646
+ if (source[index] !== BACKSLASH) { index += 1; continue }
647
+ const command = readCommandName(source, index)
648
+ if (command === null) { index += 1; continue }
649
+ total += 1
650
+ // 单字符命令(\%、\\、\,)一律算认识:它们是转义或间距,没有语义可判。
651
+ const known = command.name.length === 1 || KNOWN_COMMANDS.has(command.name)
652
+ if (!known) {
653
+ unknown += 1
654
+ top.set(command.name, (top.get(command.name) ?? 0) + 1)
655
+ }
656
+ index = command.end
657
+ }
658
+ return {
659
+ total,
660
+ unknown,
661
+ ratio: total === 0 ? 0 : unknown / total,
662
+ top: [...top.entries()].sort((left, right) => right[1] - left[1]).slice(0, 10).map(([name, count]) => ({ name, count })),
663
+ }
664
+ }
665
+
666
+ /** 从主文件里读 documentclass 名(article / IEEEtran / 自研类)。取不到给空串。 */
667
+ export function documentClassOf(text) {
668
+ const match = /\\(?:documentclass|documentstyle)\s*(?:\[[^\]]*\])?\s*\{([^}]*)\}/.exec(String(text ?? ''))
669
+ return match === null ? '' : match[1].trim()
670
+ }
671
+
672
+ /**
673
+ * 预处理一份源码包,给出「能不能用」的结论。
674
+ *
675
+ * 判定顺序与原因码一一对应,**任何一条不通过都返回 degraded**,调用方据此整篇退回 MinerU:
676
+ * no-main 没有含 \documentclass 的主文件(1990 年代 LaTeX 2.09 的包、残缺包)
677
+ * pdf-only 正文不足 200 字符,或通篇只有 \includepdf(Adam 那篇)
678
+ * macros 展开后仍有超过 8% 的命令不认识
679
+ *
680
+ * @param {{files: Array<{name: string, bytes: Buffer}>}} input
681
+ */
682
+ export function prepareDocument({ files } = {}) {
683
+ const list = Array.isArray(files) ? files : []
684
+ const main = findMainFile(list)
685
+ if (main === null) {
686
+ return { state: 'degraded', reason: DEGRADE_REASON.NO_MAIN, detail: '源码包里没有含 documentclass 的主文件' }
687
+ }
688
+ const fileMap = new Map()
689
+ for (const file of list) {
690
+ if (file && typeof file.name === 'string' && file.bytes) fileMap.set(file.name, file.bytes.toString('utf8'))
691
+ }
692
+ fileMap.set(main.name, main.text)
693
+
694
+ const included = expandIncludes(main, fileMap)
695
+ const bibliography = inlineBibliography(included.text, fileMap, { from: main.name })
696
+ const uncommented = stripComments(bibliography.text)
697
+ const collected = collectMacros(uncommented)
698
+ const withoutDefinitions = removeSpans(uncommented, collected.spans)
699
+ const expanded = expandMacros(withoutDefinitions, collected.macros)
700
+ const parts = extractBody(expanded.text)
701
+ const stats = documentStats(parts.body)
702
+ const documentClass = documentClassOf(parts.preamble)
703
+
704
+ if (parts.body.length < MIN_BODY_CHARS) {
705
+ return {
706
+ state: 'degraded', reason: DEGRADE_REASON.PDF_ONLY,
707
+ detail: '源码正文不足 ' + MIN_BODY_CHARS + ' 字符',
708
+ mainFile: main.name, bodyChars: parts.body.length, documentClass, stats,
709
+ }
710
+ }
711
+ if (/\\includepdf/.test(expanded.text)) {
712
+ return {
713
+ state: 'degraded', reason: DEGRADE_REASON.PDF_ONLY,
714
+ detail: '源码用 includepdf 拼页,正文不在源码里',
715
+ mainFile: main.name, bodyChars: parts.body.length, documentClass, stats,
716
+ }
717
+ }
718
+ if (stats.ratio > MAX_UNKNOWN_RATIO) {
719
+ return {
720
+ state: 'degraded', reason: DEGRADE_REASON.MACROS,
721
+ detail: '未知命令占 ' + (stats.ratio * 100).toFixed(1) + '%(上限 ' + (MAX_UNKNOWN_RATIO * 100) + '%)',
722
+ mainFile: main.name, bodyChars: parts.body.length, documentClass, stats,
723
+ }
724
+ }
725
+
726
+ return {
727
+ state: 'ready',
728
+ mainFile: main.name,
729
+ documentClass,
730
+ hasDocumentEnv: parts.hasDocumentEnv,
731
+ preamble: parts.preamble,
732
+ body: parts.body,
733
+ text: expanded.text,
734
+ bodyChars: parts.body.length,
735
+ macros: collected.macros.size,
736
+ environments: collected.environments.size,
737
+ includes: included.includes,
738
+ bibliography: { inlined: bibliography.inlined, missing: bibliography.missing },
739
+ stats,
740
+ expandedCalls: expanded.expanded,
741
+ unresolvedCalls: expanded.unresolved,
742
+ }
743
+ }
744
+
745
+ /** 导出阈值,供测试与文档引用(避免测试里抄死字面量)。 */
746
+ export const PREPARE_LIMITS = { MIN_BODY_CHARS, MAX_INCLUDES: MAX_INCLUDE_DEPTH, MAX_EXPAND_ROUNDS, MAX_UNKNOWN_RATIO }