dsh-pdf-workbench 0.0.0-stage → 1.3.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 (277) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +162 -2
  3. package/assets/screenshot-bilingual.jpg +0 -0
  4. package/assets/screenshot-hero.jpg +0 -0
  5. package/assets/screenshot-overlay.jpg +0 -0
  6. package/assets/screenshot-qa.jpg +0 -0
  7. package/assets/screenshot-reader.jpg +0 -0
  8. package/assets/screenshot-shelf.jpg +0 -0
  9. package/client.js +13438 -0
  10. package/cordis.patch.yml +13 -0
  11. package/docs/DETAIL.md +69 -0
  12. package/docs/READER-REWRITE.md +95 -0
  13. package/docs/ROADMAP.md +172 -0
  14. package/docs/SIDE-PREVIEW.md +271 -0
  15. package/docs/TESTING.md +109 -0
  16. package/docs/TRANSLATION.md +167 -0
  17. package/icon.svg +6 -0
  18. package/index.js +192 -0
  19. package/locale/en.json +7 -0
  20. package/locale/zh.json +7 -0
  21. package/package.json +64 -6
  22. package/samples/manifest.json +52 -0
  23. package/samples/test/serre_c01_p2-3.pdf +0 -0
  24. package/samples//345/210/206/347/211/207//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206_c00_/345/211/215/347/275/256_/345/260/201/351/235/242/347/233/256/345/275/225.pdf +0 -0
  25. package/samples//345/210/206/347/211/207//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206_c01_/347/254/2540/347/253/240_/345/257/274/350/257/273.pdf +0 -0
  26. package/samples//345/210/206/347/211/207//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206_c02_/347/254/2541/347/253/240_/345/217/244/351/242/230_/345/255/231/345/255/220/347/256/227/347/273/217/345/210/260/347/247/246/344/271/235/351/237/266.pdf +0 -0
  27. package/samples//345/210/206/347/211/207//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206_c03_/347/254/2542/347/253/240_/346/225/264/346/225/260/347/211/210/346/234/254.pdf +0 -0
  28. package/samples//345/210/206/347/211/207//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206_c04_/347/254/2543/347/253/240_/347/216/257/350/256/272/347/211/210/346/234/254.pdf +0 -0
  29. package/samples//345/210/206/347/211/207//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206_c05_/347/254/2544/347/253/240_/345/244/232/351/241/271/345/274/217/347/211/210/346/234/254.pdf +0 -0
  30. package/samples//345/210/206/347/211/207//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206_c06_/347/254/2545/347/253/240_/347/276/244/350/256/272/347/211/210/346/234/254.pdf +0 -0
  31. package/samples//345/210/206/347/211/207//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206_c07_/347/254/2546/347/253/240_/347/273/237/344/270/200/347/273/223/346/236/204.pdf +0 -0
  32. package/samples//345/210/206/347/211/207//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206_c08_/347/254/2547/347/253/240_/345/233/236/346/234/233.pdf +0 -0
  33. package/samples//345/210/206/347/211/207//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206//344/270/255/345/233/275/345/211/251/344/275/231/345/256/232/347/220/206_c90_/351/231/204/345/275/225_/346/225/231/346/235/220/351/241/265/347/240/201/347/254/246/345/217/267/350/241/250/350/207/252/346/265/213.pdf +0 -0
  34. package/screenshots.json +8 -0
  35. package/src/client/viewer.js +80 -0
  36. package/src/host/annotations.js +145 -0
  37. package/src/host/artifacts.js +317 -0
  38. package/src/host/blocks.js +44 -0
  39. package/src/host/config.js +112 -0
  40. package/src/host/digest.js +156 -0
  41. package/src/host/environment.js +42 -0
  42. package/src/host/http.js +124 -0
  43. package/src/host/index-source.js +488 -0
  44. package/src/host/libraries.js +224 -0
  45. package/src/host/links.js +201 -0
  46. package/src/host/pdf-source.js +122 -0
  47. package/src/host/pending.js +166 -0
  48. package/src/host/pressure.js +137 -0
  49. package/src/host/purge.js +100 -0
  50. package/src/host/render.js +43 -0
  51. package/src/host/routes.js +1732 -0
  52. package/src/host/shelf-groups.js +109 -0
  53. package/src/host/state.js +128 -0
  54. package/src/host/toolkit.js +54 -0
  55. package/src/host/translate-blocks.js +132 -0
  56. package/src/host/translate-job.js +316 -0
  57. package/src/host/translate.js +94 -0
  58. package/src/host/update.js +134 -0
  59. package/tools/AGENTS.md +33 -0
  60. package/tools/README.md +138 -0
  61. package/tools/auto_chapters.py +122 -0
  62. package/tools/dsfile.mjs +198 -0
  63. package/tools/export_chapter.py +108 -0
  64. package/tools/export_page.py +91 -0
  65. package/tools/md2overlay.py +200 -0
  66. package/tools/md2tex.py +422 -0
  67. package/tools/pdf_blocks.py +110 -0
  68. package/tools/pdf_fontsize.py +20 -0
  69. package/tools/pdf_merge.py +15 -0
  70. package/tools/pdf_pagesizes.py +8 -0
  71. package/tools/pdf_raster.py +21 -0
  72. package/tools/pdfkit.py +896 -0
  73. package/tools/realign_overlay.py +248 -0
  74. package/tools/rebuild_overlay.py +55 -0
  75. package/tools/rename_chapters.py +93 -0
  76. package/tools//350/247/204/350/214/203/00_/345/205/261/345/220/214/347/272/246/345/256/232.md +142 -0
  77. package/tools//350/247/204/350/214/203/01_/346/226/207/346/234/254/346/217/220/345/217/226.md +204 -0
  78. package/tools//350/247/204/350/214/203/02_/347/255/224/347/226/221.md +61 -0
  79. package/tools//350/247/204/350/214/203/03_/344/271/240/351/242/230/350/247/243/347/255/224.md +77 -0
  80. package/tools//350/247/204/350/214/203/api/346/217/220/347/244/272/350/257/215_/346/217/220/345/217/226.md +11 -0
  81. package/vendor/cmaps/78-EUC-H.bcmap +0 -0
  82. package/vendor/cmaps/78-EUC-V.bcmap +0 -0
  83. package/vendor/cmaps/78-H.bcmap +0 -0
  84. package/vendor/cmaps/78-RKSJ-H.bcmap +0 -0
  85. package/vendor/cmaps/78-RKSJ-V.bcmap +0 -0
  86. package/vendor/cmaps/78-V.bcmap +0 -0
  87. package/vendor/cmaps/78ms-RKSJ-H.bcmap +0 -0
  88. package/vendor/cmaps/78ms-RKSJ-V.bcmap +0 -0
  89. package/vendor/cmaps/83pv-RKSJ-H.bcmap +0 -0
  90. package/vendor/cmaps/90ms-RKSJ-H.bcmap +0 -0
  91. package/vendor/cmaps/90ms-RKSJ-V.bcmap +0 -0
  92. package/vendor/cmaps/90msp-RKSJ-H.bcmap +0 -0
  93. package/vendor/cmaps/90msp-RKSJ-V.bcmap +0 -0
  94. package/vendor/cmaps/90pv-RKSJ-H.bcmap +0 -0
  95. package/vendor/cmaps/90pv-RKSJ-V.bcmap +0 -0
  96. package/vendor/cmaps/Add-H.bcmap +0 -0
  97. package/vendor/cmaps/Add-RKSJ-H.bcmap +0 -0
  98. package/vendor/cmaps/Add-RKSJ-V.bcmap +0 -0
  99. package/vendor/cmaps/Add-V.bcmap +0 -0
  100. package/vendor/cmaps/Adobe-CNS1-0.bcmap +0 -0
  101. package/vendor/cmaps/Adobe-CNS1-1.bcmap +0 -0
  102. package/vendor/cmaps/Adobe-CNS1-2.bcmap +0 -0
  103. package/vendor/cmaps/Adobe-CNS1-3.bcmap +0 -0
  104. package/vendor/cmaps/Adobe-CNS1-4.bcmap +0 -0
  105. package/vendor/cmaps/Adobe-CNS1-5.bcmap +0 -0
  106. package/vendor/cmaps/Adobe-CNS1-6.bcmap +0 -0
  107. package/vendor/cmaps/Adobe-CNS1-UCS2.bcmap +0 -0
  108. package/vendor/cmaps/Adobe-GB1-0.bcmap +0 -0
  109. package/vendor/cmaps/Adobe-GB1-1.bcmap +0 -0
  110. package/vendor/cmaps/Adobe-GB1-2.bcmap +0 -0
  111. package/vendor/cmaps/Adobe-GB1-3.bcmap +0 -0
  112. package/vendor/cmaps/Adobe-GB1-4.bcmap +0 -0
  113. package/vendor/cmaps/Adobe-GB1-5.bcmap +0 -0
  114. package/vendor/cmaps/Adobe-GB1-UCS2.bcmap +0 -0
  115. package/vendor/cmaps/Adobe-Japan1-0.bcmap +0 -0
  116. package/vendor/cmaps/Adobe-Japan1-1.bcmap +0 -0
  117. package/vendor/cmaps/Adobe-Japan1-2.bcmap +0 -0
  118. package/vendor/cmaps/Adobe-Japan1-3.bcmap +0 -0
  119. package/vendor/cmaps/Adobe-Japan1-4.bcmap +0 -0
  120. package/vendor/cmaps/Adobe-Japan1-5.bcmap +0 -0
  121. package/vendor/cmaps/Adobe-Japan1-6.bcmap +0 -0
  122. package/vendor/cmaps/Adobe-Japan1-UCS2.bcmap +0 -0
  123. package/vendor/cmaps/Adobe-Korea1-0.bcmap +0 -0
  124. package/vendor/cmaps/Adobe-Korea1-1.bcmap +0 -0
  125. package/vendor/cmaps/Adobe-Korea1-2.bcmap +0 -0
  126. package/vendor/cmaps/Adobe-Korea1-UCS2.bcmap +0 -0
  127. package/vendor/cmaps/B5-H.bcmap +0 -0
  128. package/vendor/cmaps/B5-V.bcmap +0 -0
  129. package/vendor/cmaps/B5pc-H.bcmap +0 -0
  130. package/vendor/cmaps/B5pc-V.bcmap +0 -0
  131. package/vendor/cmaps/CNS-EUC-H.bcmap +0 -0
  132. package/vendor/cmaps/CNS-EUC-V.bcmap +0 -0
  133. package/vendor/cmaps/CNS1-H.bcmap +0 -0
  134. package/vendor/cmaps/CNS1-V.bcmap +0 -0
  135. package/vendor/cmaps/CNS2-H.bcmap +0 -0
  136. package/vendor/cmaps/CNS2-V.bcmap +3 -0
  137. package/vendor/cmaps/ETHK-B5-H.bcmap +0 -0
  138. package/vendor/cmaps/ETHK-B5-V.bcmap +0 -0
  139. package/vendor/cmaps/ETen-B5-H.bcmap +0 -0
  140. package/vendor/cmaps/ETen-B5-V.bcmap +0 -0
  141. package/vendor/cmaps/ETenms-B5-H.bcmap +3 -0
  142. package/vendor/cmaps/ETenms-B5-V.bcmap +0 -0
  143. package/vendor/cmaps/EUC-H.bcmap +0 -0
  144. package/vendor/cmaps/EUC-V.bcmap +0 -0
  145. package/vendor/cmaps/Ext-H.bcmap +0 -0
  146. package/vendor/cmaps/Ext-RKSJ-H.bcmap +0 -0
  147. package/vendor/cmaps/Ext-RKSJ-V.bcmap +0 -0
  148. package/vendor/cmaps/Ext-V.bcmap +0 -0
  149. package/vendor/cmaps/GB-EUC-H.bcmap +0 -0
  150. package/vendor/cmaps/GB-EUC-V.bcmap +0 -0
  151. package/vendor/cmaps/GB-H.bcmap +4 -0
  152. package/vendor/cmaps/GB-V.bcmap +0 -0
  153. package/vendor/cmaps/GBK-EUC-H.bcmap +0 -0
  154. package/vendor/cmaps/GBK-EUC-V.bcmap +0 -0
  155. package/vendor/cmaps/GBK2K-H.bcmap +0 -0
  156. package/vendor/cmaps/GBK2K-V.bcmap +0 -0
  157. package/vendor/cmaps/GBKp-EUC-H.bcmap +0 -0
  158. package/vendor/cmaps/GBKp-EUC-V.bcmap +0 -0
  159. package/vendor/cmaps/GBT-EUC-H.bcmap +0 -0
  160. package/vendor/cmaps/GBT-EUC-V.bcmap +0 -0
  161. package/vendor/cmaps/GBT-H.bcmap +0 -0
  162. package/vendor/cmaps/GBT-V.bcmap +0 -0
  163. package/vendor/cmaps/GBTpc-EUC-H.bcmap +0 -0
  164. package/vendor/cmaps/GBTpc-EUC-V.bcmap +0 -0
  165. package/vendor/cmaps/GBpc-EUC-H.bcmap +0 -0
  166. package/vendor/cmaps/GBpc-EUC-V.bcmap +0 -0
  167. package/vendor/cmaps/H.bcmap +0 -0
  168. package/vendor/cmaps/HKdla-B5-H.bcmap +0 -0
  169. package/vendor/cmaps/HKdla-B5-V.bcmap +0 -0
  170. package/vendor/cmaps/HKdlb-B5-H.bcmap +0 -0
  171. package/vendor/cmaps/HKdlb-B5-V.bcmap +0 -0
  172. package/vendor/cmaps/HKgccs-B5-H.bcmap +0 -0
  173. package/vendor/cmaps/HKgccs-B5-V.bcmap +0 -0
  174. package/vendor/cmaps/HKm314-B5-H.bcmap +0 -0
  175. package/vendor/cmaps/HKm314-B5-V.bcmap +0 -0
  176. package/vendor/cmaps/HKm471-B5-H.bcmap +0 -0
  177. package/vendor/cmaps/HKm471-B5-V.bcmap +0 -0
  178. package/vendor/cmaps/HKscs-B5-H.bcmap +0 -0
  179. package/vendor/cmaps/HKscs-B5-V.bcmap +0 -0
  180. package/vendor/cmaps/Hankaku.bcmap +0 -0
  181. package/vendor/cmaps/Hiragana.bcmap +0 -0
  182. package/vendor/cmaps/KSC-EUC-H.bcmap +0 -0
  183. package/vendor/cmaps/KSC-EUC-V.bcmap +0 -0
  184. package/vendor/cmaps/KSC-H.bcmap +0 -0
  185. package/vendor/cmaps/KSC-Johab-H.bcmap +0 -0
  186. package/vendor/cmaps/KSC-Johab-V.bcmap +0 -0
  187. package/vendor/cmaps/KSC-V.bcmap +0 -0
  188. package/vendor/cmaps/KSCms-UHC-H.bcmap +0 -0
  189. package/vendor/cmaps/KSCms-UHC-HW-H.bcmap +0 -0
  190. package/vendor/cmaps/KSCms-UHC-HW-V.bcmap +0 -0
  191. package/vendor/cmaps/KSCms-UHC-V.bcmap +0 -0
  192. package/vendor/cmaps/KSCpc-EUC-H.bcmap +0 -0
  193. package/vendor/cmaps/KSCpc-EUC-V.bcmap +0 -0
  194. package/vendor/cmaps/Katakana.bcmap +0 -0
  195. package/vendor/cmaps/LICENSE.txt +36 -0
  196. package/vendor/cmaps/NWP-H.bcmap +0 -0
  197. package/vendor/cmaps/NWP-V.bcmap +0 -0
  198. package/vendor/cmaps/RKSJ-H.bcmap +0 -0
  199. package/vendor/cmaps/RKSJ-V.bcmap +0 -0
  200. package/vendor/cmaps/Roman.bcmap +0 -0
  201. package/vendor/cmaps/UniCNS-UCS2-H.bcmap +0 -0
  202. package/vendor/cmaps/UniCNS-UCS2-V.bcmap +0 -0
  203. package/vendor/cmaps/UniCNS-UTF16-H.bcmap +0 -0
  204. package/vendor/cmaps/UniCNS-UTF16-V.bcmap +0 -0
  205. package/vendor/cmaps/UniCNS-UTF32-H.bcmap +0 -0
  206. package/vendor/cmaps/UniCNS-UTF32-V.bcmap +0 -0
  207. package/vendor/cmaps/UniCNS-UTF8-H.bcmap +0 -0
  208. package/vendor/cmaps/UniCNS-UTF8-V.bcmap +0 -0
  209. package/vendor/cmaps/UniGB-UCS2-H.bcmap +0 -0
  210. package/vendor/cmaps/UniGB-UCS2-V.bcmap +0 -0
  211. package/vendor/cmaps/UniGB-UTF16-H.bcmap +0 -0
  212. package/vendor/cmaps/UniGB-UTF16-V.bcmap +0 -0
  213. package/vendor/cmaps/UniGB-UTF32-H.bcmap +0 -0
  214. package/vendor/cmaps/UniGB-UTF32-V.bcmap +0 -0
  215. package/vendor/cmaps/UniGB-UTF8-H.bcmap +0 -0
  216. package/vendor/cmaps/UniGB-UTF8-V.bcmap +0 -0
  217. package/vendor/cmaps/UniJIS-UCS2-H.bcmap +0 -0
  218. package/vendor/cmaps/UniJIS-UCS2-HW-H.bcmap +0 -0
  219. package/vendor/cmaps/UniJIS-UCS2-HW-V.bcmap +0 -0
  220. package/vendor/cmaps/UniJIS-UCS2-V.bcmap +0 -0
  221. package/vendor/cmaps/UniJIS-UTF16-H.bcmap +0 -0
  222. package/vendor/cmaps/UniJIS-UTF16-V.bcmap +0 -0
  223. package/vendor/cmaps/UniJIS-UTF32-H.bcmap +0 -0
  224. package/vendor/cmaps/UniJIS-UTF32-V.bcmap +0 -0
  225. package/vendor/cmaps/UniJIS-UTF8-H.bcmap +0 -0
  226. package/vendor/cmaps/UniJIS-UTF8-V.bcmap +0 -0
  227. package/vendor/cmaps/UniJIS2004-UTF16-H.bcmap +0 -0
  228. package/vendor/cmaps/UniJIS2004-UTF16-V.bcmap +0 -0
  229. package/vendor/cmaps/UniJIS2004-UTF32-H.bcmap +0 -0
  230. package/vendor/cmaps/UniJIS2004-UTF32-V.bcmap +0 -0
  231. package/vendor/cmaps/UniJIS2004-UTF8-H.bcmap +0 -0
  232. package/vendor/cmaps/UniJIS2004-UTF8-V.bcmap +0 -0
  233. package/vendor/cmaps/UniJISPro-UCS2-HW-V.bcmap +0 -0
  234. package/vendor/cmaps/UniJISPro-UCS2-V.bcmap +0 -0
  235. package/vendor/cmaps/UniJISPro-UTF8-V.bcmap +0 -0
  236. package/vendor/cmaps/UniJISX0213-UTF32-H.bcmap +0 -0
  237. package/vendor/cmaps/UniJISX0213-UTF32-V.bcmap +0 -0
  238. package/vendor/cmaps/UniJISX02132004-UTF32-H.bcmap +0 -0
  239. package/vendor/cmaps/UniJISX02132004-UTF32-V.bcmap +0 -0
  240. package/vendor/cmaps/UniKS-UCS2-H.bcmap +0 -0
  241. package/vendor/cmaps/UniKS-UCS2-V.bcmap +0 -0
  242. package/vendor/cmaps/UniKS-UTF16-H.bcmap +0 -0
  243. package/vendor/cmaps/UniKS-UTF16-V.bcmap +0 -0
  244. package/vendor/cmaps/UniKS-UTF32-H.bcmap +0 -0
  245. package/vendor/cmaps/UniKS-UTF32-V.bcmap +0 -0
  246. package/vendor/cmaps/UniKS-UTF8-H.bcmap +0 -0
  247. package/vendor/cmaps/UniKS-UTF8-V.bcmap +0 -0
  248. package/vendor/cmaps/V.bcmap +0 -0
  249. package/vendor/cmaps/WP-Symbol.bcmap +0 -0
  250. package/vendor/fonts/excalifont/Excalifont-Regular-349fac6ca4700ffec595a7150a0d1e1d.woff2 +0 -0
  251. package/vendor/fonts/excalifont/Excalifont-Regular-3f2c5db56cc93c5a6873b1361d730c16.woff2 +0 -0
  252. package/vendor/fonts/excalifont/Excalifont-Regular-41b173a47b57366892116a575a43e2b6.woff2 +0 -0
  253. package/vendor/fonts/excalifont/Excalifont-Regular-623ccf21b21ef6b3a0d87738f77eb071.woff2 +0 -0
  254. package/vendor/fonts/excalifont/Excalifont-Regular-a88b72a24fb54c9f94e3b5fdaa7481c9.woff2 +0 -0
  255. package/vendor/fonts/excalifont/Excalifont-Regular-b9dcf9d2e50a1eaf42fc664b50a3fd0d.woff2 +0 -0
  256. package/vendor/fonts/excalifont/Excalifont-Regular-be310b9bcd4f1a43f571c46df7809174.woff2 +0 -0
  257. package/vendor/fonts/excalifont/OFL.txt +98 -0
  258. package/vendor/fonts/zhhand/OFL.txt +99 -0
  259. package/vendor/fonts/zhhand/Xiaolai-Regular.ttf +0 -0
  260. package/vendor/pdf.min.mjs +29 -0
  261. package/vendor/pdf.worker.min.mjs +29 -0
  262. package/vendor/pdfjs-LICENSE.txt +177 -0
  263. package/vendor/rough/LICENSE +21 -0
  264. package/vendor/rough/rough.mjs +1 -0
  265. package/vendor/wasm/LICENSE_JBIG2 +196 -0
  266. package/vendor/wasm/LICENSE_OPENJPEG +39 -0
  267. package/vendor/wasm/LICENSE_PDFJS_JBIG2 +13 -0
  268. package/vendor/wasm/LICENSE_PDFJS_OPENJPEG +22 -0
  269. package/vendor/wasm/LICENSE_PDFJS_QCMS +19 -0
  270. package/vendor/wasm/LICENSE_QCMS +21 -0
  271. package/vendor/wasm/jbig2.wasm +0 -0
  272. package/vendor/wasm/jbig2_nowasm_fallback.js +15 -0
  273. package/vendor/wasm/openjpeg.wasm +0 -0
  274. package/vendor/wasm/openjpeg_nowasm_fallback.js +17 -0
  275. package/vendor/wasm/qcms_bg.wasm +0 -0
  276. package/vendor/wasm/quickjs-eval.wasm +0 -0
  277. package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +54 -0
@@ -0,0 +1,1732 @@
1
+ /**
2
+ * The `/pdfdesk/*` surface.
3
+ *
4
+ * GET /pdfdesk/bootstrap catalog + stored position + pending intents + links
5
+ * GET /pdfdesk/artifacts one chapter's produced files
6
+ * GET /pdfdesk/artifact one produced file's text, for the preview
7
+ * GET /pdfdesk/pdf one chapter's PDF, or a produced PDF, for the reader
8
+ * GET /pdfdesk/pdf-ref that PDF as a workspace-relative path
9
+ * GET /pdfdesk/cover a user-provided book cover image
10
+ * GET /pdfdesk/context how full one session's context is
11
+ * POST /pdfdesk/digest summarize a chapter's conversations
12
+ * GET /pdfdesk/vendor/<file> the reader's pdf.js build
13
+ * POST /pdfdesk/links attach an existing session to a chapter
14
+ * POST /pdfdesk/links/remove detach one chapter from a session
15
+ * PUT /pdfdesk/state persist the position
16
+ * POST /pdfdesk/pending record a created-but-unused session
17
+ * POST /pdfdesk/pending/remove forget one pending session
18
+ *
19
+ * The browser half owns no filesystem access, so every read the page needs
20
+ * arrives through `bootstrap` or one of the read routes.
21
+ *
22
+ * @module dsh-pdf-workbench/routes
23
+ */
24
+ import { execFile } from 'node:child_process'
25
+ import { existsSync } from 'node:fs'
26
+ import { copyFile, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises'
27
+ import { basename, dirname, extname, isAbsolute, join, relative } from 'node:path'
28
+
29
+ import { chapterArtifactDir, countArtifacts, listArtifacts, readArtifact, resolveChapter } from './artifacts.js'
30
+ import { pathSegment, readAnnotations, seedAnnotations, writeAnnotations } from './annotations.js'
31
+ import { PLUGIN_VERSION } from './config.js'
32
+ import { fail, isLoopback, isSameOrigin, readJson, sendBytes, sendJson } from './http.js'
33
+ import { loadCatalog } from './index-source.js'
34
+ import { readPageBlocks } from './blocks.js'
35
+ import { translatePage } from './translate.js'
36
+ import { startChapterJob } from './translate-job.js'
37
+ import { artifactPdfPath, chapterPdfPath, readPdf } from './pdf-source.js'
38
+ import { checkForUpdate } from './update.js'
39
+ import { detectEnvironment } from './environment.js'
40
+ import { renderMarkdown } from './render.js'
41
+ import { readState, writeState } from './state.js'
42
+
43
+ /** Route prefix owned by this plugin. */
44
+ export const PREFIX = '/pdfdesk'
45
+
46
+ /** The reader's pdf.js build, by relative name so a path can never escape. */
47
+ function vendorContentType(name) {
48
+ if (name === 'pdf.min.mjs' || name === 'pdf.worker.min.mjs') return 'text/javascript; charset=utf-8'
49
+ if (/^wasm\/[A-Za-z0-9._-]+\.wasm$/.test(name)) return 'application/wasm'
50
+ if (/^wasm\/[A-Za-z0-9._-]+_nowasm_fallback\.js$/.test(name)) return 'text/javascript; charset=utf-8'
51
+ if (/^cmaps\/[A-Za-z0-9._-]+\.bcmap$/.test(name)) return 'application/octet-stream'
52
+ // The hand-drawn text face, split into upstream's unicode-range subsets.
53
+ if (/^fonts\/excalifont\/Excalifont-Regular-[a-f0-9]+\.woff2$/.test(name)) return 'font/woff2'
54
+ if (name === 'fonts/excalifont/OFL.txt') return 'text/plain; charset=utf-8'
55
+ if (name === 'fonts/zhhand/Xiaolai-Regular.ttf') return 'font/ttf'
56
+ if (name === 'fonts/zhhand/OFL.txt') return 'text/plain; charset=utf-8'
57
+ if (/^rough\/[^/]+\.mjs$/.test(name)) return 'text/javascript; charset=utf-8'
58
+ if (name === 'rough/LICENSE') return 'text/plain; charset=utf-8'
59
+ return null
60
+ }
61
+
62
+ /** Cover image extensions the shelf accepts, in preference order. */
63
+ const COVER_TYPES = {
64
+ png: 'image/png',
65
+ jpg: 'image/jpeg',
66
+ jpeg: 'image/jpeg',
67
+ webp: 'image/webp',
68
+ }
69
+
70
+ /**
71
+ * Book ids that have a user-provided cover, so the shelf can skip the 404 probe.
72
+ * @param {string} dir - the active library's cover directory.
73
+ * @returns {Promise<string[]>} ids without a known solution (may be empty).
74
+ */
75
+ async function coverIds(dir) {
76
+ try {
77
+ const names = await readdir(dir)
78
+ const ids = []
79
+ for (const name of names) {
80
+ const match = /^(.+)\.(png|jpe?g|webp)$/i.exec(name)
81
+ if (match !== null) ids.push(match[1])
82
+ }
83
+ return ids
84
+ } catch {
85
+ return []
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Read the request body for a mutation.
91
+ * @param {import('node:http').IncomingMessage} request - inbound request.
92
+ * @param {import('node:http').ServerResponse} response - outbound response.
93
+ * @returns {Promise<unknown | undefined>} the body, or undefined after a failure was answered.
94
+ */
95
+ async function mutationBody(request, response) {
96
+ if (!isSameOrigin(request)) {
97
+ fail(response, 403, 'cross-origin', '拒绝跨站写入')
98
+ return undefined
99
+ }
100
+ try {
101
+ return await readJson(request)
102
+ } catch (error) {
103
+ fail(response, 400, 'invalid-body', String(error && error.message ? error.message : error))
104
+ return undefined
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Build the prefix handler for the plugin's routes.
110
+ * @param {{ libraryDir: string, fragmentDir: string, artifactDir: string, coverDir: string, indexPath: string, statePath: string, resumeRatio?: number, toolsDir?: string }} config - resolved paths and behavior (the profile's library is the fallback).
111
+ * @param {{ resolveTarget?: () => Promise<{ workspaceId: string | null, cwd: string }>, pending?: { list: () => Promise<object>, put: Function, remove: Function }, links?: { list: () => Promise<Record<string, object[]>>, add: Function, remove: Function }, contextPressure?: (sessionId: string) => Promise<object | null>, libraries?: { list: Function, active: Function, add: Function, setActive: Function, remove: Function }, installToolkit?: (libraryDir: string) => Promise<object> }} [options] - host capabilities the routes expose.
112
+ * @returns {(request: import('node:http').IncomingMessage, response: import('node:http').ServerResponse) => Promise<void>} the handler.
113
+ */
114
+ export function createHandler(config, options = {}) {
115
+ const pending = options.pending
116
+ const links = options.links
117
+ const libraries = options.libraries
118
+ // A burst of artifact reads (expand a chapter, click three files) must not
119
+ // rescan the whole library each time; a short window is enough for that and
120
+ // still refreshes on the next deliberate look.
121
+ const CATALOG_TTL_MS = 2000
122
+ let cachedCatalog = null
123
+ let cachedAt = 0
124
+ let cachedLibraryId = ''
125
+
126
+ /**
127
+ * The library every read route works on.
128
+ * @returns {Promise<object>} the active library, or the profile's fallback.
129
+ */
130
+ /**
131
+ * Locate a chapter's own PDF through the catalog (the same path the reader uses).
132
+ * @param {object} library - active library entry.
133
+ * @param {string} bookId - book id.
134
+ * @param {string} code - chapter code.
135
+ * @returns {Promise<string|null>} absolute path, or null when missing.
136
+ */
137
+ function runTool(script, args) {
138
+ const pythons = [process.env.MATH_DESK_PYTHON, 'python', 'py'].filter(Boolean)
139
+ return new Promise((resolve, reject) => {
140
+ const next = index => {
141
+ if (index >= pythons.length) {
142
+ reject(new Error('没有可用的 Python'))
143
+ return
144
+ }
145
+ execFile(pythons[index], [script, ...args], { timeout: 240000, windowsHide: true }, error => {
146
+ if (error === null) resolve()
147
+ else next(index + 1)
148
+ })
149
+ }
150
+ next(0)
151
+ })
152
+ }
153
+
154
+ /**
155
+ * Run one bundled tool and return its stdout (PDF sizes, font sizes, blocks).
156
+ * @param {string} script - absolute tool path.
157
+ * @param {string[]} args - tool arguments.
158
+ * @returns {Promise<string>} the tool's stdout.
159
+ */
160
+ function toolOutput(script, args) {
161
+ const pythons = [process.env.MATH_DESK_PYTHON, 'python', 'py'].filter(Boolean)
162
+ return new Promise((resolve, reject) => {
163
+ const next = index => {
164
+ if (index >= pythons.length) {
165
+ reject(new Error('没有可用的 Python'))
166
+ return
167
+ }
168
+ execFile(
169
+ pythons[index],
170
+ [script, ...args],
171
+ { timeout: 180000, windowsHide: true, maxBuffer: 8 * 1024 * 1024 },
172
+ (error, stdout) => {
173
+ if (error === null) resolve(stdout)
174
+ else next(index + 1)
175
+ }
176
+ )
177
+ }
178
+ next(0)
179
+ })
180
+ }
181
+
182
+ async function chapterPdf(library, bookId, code) {
183
+ const current = await catalog()
184
+ const match = resolveChapter(current, bookId, code)
185
+ if (match.ok !== true) return null
186
+ const source = chapterPdfPath(library, match.book, match.chapter)
187
+ return source.ok ? source.path : null
188
+ }
189
+
190
+ /**
191
+ * The DeepSeek key for translation: config or env first, then the stored file.
192
+ * @returns {Promise<string>} the key, or '' when none is configured.
193
+ */
194
+ async function deepseekKey() {
195
+ if (typeof config.deepseekApiKey === 'string' && config.deepseekApiKey !== '') return config.deepseekApiKey
196
+ try {
197
+ const raw = await readFile(join(config.dataDir, 'deepseek.json'), 'utf8')
198
+ const stored = JSON.parse(raw)
199
+ return typeof stored.apiKey === 'string' ? stored.apiKey : ''
200
+ } catch {
201
+ return ''
202
+ }
203
+ }
204
+
205
+ async function activeLibrary() {
206
+ if (libraries !== undefined && typeof libraries.active === 'function') {
207
+ const active = await libraries.active()
208
+ if (active !== null && active !== undefined) return active
209
+ }
210
+ return {
211
+ id: 'default',
212
+ name: '',
213
+ mode: 'math',
214
+ libraryDir: config.libraryDir,
215
+ fragmentDir: config.fragmentDir,
216
+ artifactDir: config.artifactDir,
217
+ coverDir: config.coverDir,
218
+ indexPath: config.indexPath,
219
+ }
220
+ }
221
+
222
+ /**
223
+ * The bundled sample library's manifest, when the package ships one.
224
+ * @returns {Promise<object | null>} `{ book, files }` or null.
225
+ */
226
+ async function readSampleManifest() {
227
+ try {
228
+ const manifest = JSON.parse(await readFile(join(config.samplesDir, 'manifest.json'), 'utf8'))
229
+ return manifest !== null && typeof manifest === 'object' ? manifest : null
230
+ } catch {
231
+ return null
232
+ }
233
+ }
234
+
235
+ /**
236
+ * The catalog of one library, reused for a couple of seconds; `fresh` rescans.
237
+ * @param {boolean} [fresh] - ignore the cached copy.
238
+ * @returns {Promise<Awaited<ReturnType<typeof loadCatalog>>>} the catalog.
239
+ */
240
+ async function catalog(fresh) {
241
+ const library = await activeLibrary()
242
+ if (fresh !== true && cachedCatalog !== null && cachedLibraryId === library.id && Date.now() - cachedAt < CATALOG_TTL_MS) {
243
+ return cachedCatalog
244
+ }
245
+ cachedCatalog = await loadCatalog({
246
+ fragmentDir: library.fragmentDir,
247
+ indexPath: library.indexPath,
248
+ libraryDir: library.libraryDir,
249
+ artifactDir: library.artifactDir,
250
+ coverDir: library.coverDir,
251
+ })
252
+ cachedLibraryId = library.id
253
+ cachedAt = Date.now()
254
+ return cachedCatalog
255
+ }
256
+
257
+ /**
258
+ * Resolve `book` + `code` from the query against the live catalog.
259
+ * @param {URL} url - the request URL.
260
+ * @returns {Promise<{ ok: true, book: object, chapter: object } | { ok: false, status: number, code: string, message: string }>} the match or the refusal to answer.
261
+ */
262
+ async function chapterFromQuery(url) {
263
+ const match = resolveChapter(await catalog(), url.searchParams.get('book') ?? '', (url.searchParams.get('code') ?? '').toLowerCase())
264
+ if (match.ok) return match
265
+ return { ...match, status: match.code === 'unknown-chapter' ? 404 : 400 }
266
+ }
267
+
268
+ return async function handle(request, response) {
269
+ try {
270
+ if (!isLoopback(request)) {
271
+ fail(response, 403, 'forbidden', '只接受本机请求')
272
+ return
273
+ }
274
+ const url = new URL(request.url ?? '/', 'http://localhost')
275
+ const path = url.pathname.replace(/\/+$/, '')
276
+
277
+ if (path === `${PREFIX}/qa-persona`) {
278
+ if (request.method !== 'GET') {
279
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
280
+ return
281
+ }
282
+ // The Socratic persona is a local workflow file, never shipped with the
283
+ // plugin: `~/.dsh/pdfdesk/qa-persona.md`. A missing file is simply empty.
284
+ try {
285
+ const raw = await readFile(join(config.dataDir, 'qa-persona.md'), 'utf8')
286
+ sendJson(response, 200, { ok: true, persona: raw })
287
+ } catch {
288
+ sendJson(response, 200, { ok: true, persona: '' })
289
+ }
290
+ return
291
+ }
292
+
293
+ if (path === `${PREFIX}/bootstrap`) {
294
+ if (request.method !== 'GET') {
295
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
296
+ return
297
+ }
298
+ // The Refresh button is a deliberate look: bypass the short reuse window.
299
+ // A first run may have no library yet: an unreadable catalog must still
300
+ // reach the browser so it can show the "add a library" page instead of a
301
+ // dead error screen.
302
+ let fresh
303
+ try {
304
+ fresh = await catalog(true)
305
+ } catch (error) {
306
+ fresh = {
307
+ source: 'missing',
308
+ indexIgnored: false,
309
+ problem: String(error !== null && error !== undefined && error.message ? error.message : error),
310
+ books: [],
311
+ skipped: [],
312
+ warnings: [],
313
+ }
314
+ }
315
+ const library = await activeLibrary()
316
+ const state = await readState(config.statePath)
317
+ const target = typeof options.resolveTarget === 'function'
318
+ ? await options.resolveTarget()
319
+ : { workspaceId: null, cwd: library.libraryDir }
320
+ const libraryList = libraries === undefined || typeof libraries.list !== 'function'
321
+ ? { items: [library], activeId: library.id }
322
+ : await libraries.list()
323
+ // Every chapter carries its absolute PDF path once. A new conversation's
324
+ // prompt can then name the file directly instead of paying for a search;
325
+ // an unplaceable chapter (hand-edited catalog) simply has no path.
326
+ const pdfConfig = { libraryDir: library.libraryDir, fragmentDir: library.fragmentDir }
327
+ const booksWithPaths = (Array.isArray(fresh.books) ? fresh.books : []).map(book => ({
328
+ ...book,
329
+ chapters: Array.isArray(book.chapters)
330
+ ? book.chapters.map(chapter => {
331
+ const pdf = chapterPdfPath(pdfConfig, book, chapter)
332
+ return pdf.ok ? { ...chapter, pdfPath: pdf.path } : chapter
333
+ })
334
+ : book.chapters,
335
+ }))
336
+ sendJson(response, 200, {
337
+ ok: true,
338
+ version: PLUGIN_VERSION,
339
+ source: fresh.source,
340
+ indexIgnored: fresh.indexIgnored,
341
+ problem: fresh.problem,
342
+ library: {
343
+ id: library.id,
344
+ name: library.name,
345
+ mode: library.mode,
346
+ libraryDir: library.libraryDir,
347
+ fragmentDir: library.fragmentDir,
348
+ artifactDir: library.artifactDir,
349
+ coverDir: library.coverDir,
350
+ },
351
+ libraries: libraryList,
352
+ libraryDir: library.libraryDir,
353
+ fragmentDir: library.fragmentDir,
354
+ artifactDir: library.artifactDir,
355
+ indexPath: library.indexPath,
356
+ covers: await coverIds(library.coverDir),
357
+ target,
358
+ environment: detectEnvironment(),
359
+ resumeRatio: typeof config.resumeRatio === 'number' ? config.resumeRatio : 0.85,
360
+ pending: pending === undefined ? {} : await pending.list(),
361
+ links: links === undefined ? {} : await links.list(),
362
+ shelves: options.shelves === undefined ? { hidden: [], shelves: [] } : await options.shelves.get(library.id),
363
+ books: booksWithPaths,
364
+ skipped: fresh.skipped,
365
+ warnings: fresh.warnings,
366
+ state,
367
+ })
368
+ return
369
+ }
370
+
371
+ if (path === `${PREFIX}/update`) {
372
+ if (request.method !== 'GET') {
373
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
374
+ return
375
+ }
376
+ const result = await checkForUpdate(config.updateProxy)
377
+ sendJson(response, 200, result)
378
+ return
379
+ }
380
+
381
+ if (path === `${PREFIX}/render`) {
382
+ if (request.method !== 'POST') {
383
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
384
+ return
385
+ }
386
+ try {
387
+ const body = await readJson(request)
388
+ const catalog = await loadCatalog(config)
389
+ const chapter = resolveChapter(catalog, body.book, body.code)
390
+ if (chapter === null) {
391
+ fail(response, 404, 'no-chapter', '找不到这一章')
392
+ return
393
+ }
394
+ const name = basename(String(body.name ?? ''))
395
+ if (!/\.md$/i.test(name)) {
396
+ fail(response, 400, 'bad-name', '只支持渲染 .md 文件')
397
+ return
398
+ }
399
+ const library = await activeLibrary()
400
+ const dir = join(library.libraryDir, '产物', body.book, body.code)
401
+ const source = join(dir, name)
402
+ try {
403
+ await stat(source)
404
+ } catch {
405
+ fail(response, 404, 'missing-file', '文件不存在(可能已被删除),请点「重新读取」刷新列表')
406
+ return
407
+ }
408
+ const out = `${source.slice(0, source.length - 3)}.pdf`
409
+ await renderMarkdown(options.md2texScript, source, out)
410
+ sendJson(response, 200, { ok: true, path: out })
411
+ } catch (error) {
412
+ fail(response, 503, 'render-failed', String(error && error.message ? error.message : error))
413
+ }
414
+ return
415
+ }
416
+
417
+ if (path === `${PREFIX}/deepseek-key`) {
418
+ if (request.method === 'GET') {
419
+ sendJson(response, 200, { ok: true, configured: (await deepseekKey()) !== '' })
420
+ return
421
+ }
422
+ if (request.method !== 'POST') {
423
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET 或 POST')
424
+ return
425
+ }
426
+ try {
427
+ const body = await readJson(request)
428
+ const key = typeof body.key === 'string' ? body.key.trim() : ''
429
+ if (key !== '' && !key.startsWith('sk-')) {
430
+ fail(response, 400, 'bad-key', 'API Key 应以 sk- 开头')
431
+ return
432
+ }
433
+ await mkdir(config.dataDir, { recursive: true })
434
+ await writeFile(join(config.dataDir, 'deepseek.json'), `${JSON.stringify({ apiKey: key })}\n`, { encoding: 'utf8', mode: 0o600 })
435
+ sendJson(response, 200, { ok: true, configured: key !== '' })
436
+ } catch (error) {
437
+ fail(response, 500, 'key-save-failed', String(error && error.message ? error.message : error))
438
+ }
439
+ return
440
+ }
441
+
442
+ if (path === `${PREFIX}/blocks`) {
443
+ try {
444
+ const book = url.searchParams.get('book') ?? ''
445
+ const code = (url.searchParams.get('code') ?? '').toLowerCase()
446
+ const page = Number.parseInt(url.searchParams.get('page') ?? '', 10)
447
+ if (!Number.isFinite(page) || page < 1) {
448
+ fail(response, 400, 'bad-page', '页码不合法')
449
+ return
450
+ }
451
+ const library = await activeLibrary()
452
+ const source = await chapterPdf(library, book, code)
453
+ if (source === null) {
454
+ fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
455
+ return
456
+ }
457
+ const blocks = await readPageBlocks({
458
+ script: join(config.toolsDir, 'pdf_blocks.py'),
459
+ source,
460
+ pageIndex: page,
461
+ })
462
+ sendJson(response, 200, { ok: true, blocks })
463
+ } catch (error) {
464
+ fail(response, 500, 'blocks-failed', String(error && error.message ? error.message : error))
465
+ }
466
+ return
467
+ }
468
+
469
+ if (path === `${PREFIX}/translate-chapter`) {
470
+ if (request.method !== 'POST') {
471
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
472
+ return
473
+ }
474
+ try {
475
+ const body = await readJson(request)
476
+ const target = body.target === 'zh' ? 'zh' : 'en'
477
+ // `resume` fills pages that never came back, reusing the cached
478
+ // per-page markdown instead of paying to translate them again.
479
+ const resume = body.resume === true
480
+ const library = await activeLibrary()
481
+ const source = await chapterPdf(library, body.book, body.code)
482
+ if (source === null) {
483
+ fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
484
+ return
485
+ }
486
+ const outPath = join(dirname(source), `${basename(source, '.pdf')}_translated.pdf`)
487
+ const jobId = await startChapterJob({
488
+ jobDir: join(config.dataDir, 'translate-jobs'),
489
+ cacheDir: join(config.dataDir, 'translation', body.book, body.code),
490
+ toolsDir: config.toolsDir,
491
+ overlayPath: join(dirname(source), `${basename(source, '.pdf')}_overlay.pdf`),
492
+ rasterScript: join(config.toolsDir, 'pdf_raster.py'),
493
+ md2texScript: options.md2texScript,
494
+ apiKey: await deepseekKey(),
495
+ source,
496
+ outPath,
497
+ target,
498
+ book: body.book,
499
+ code: body.code,
500
+ resume,
501
+ })
502
+ sendJson(response, 200, { ok: true, jobId })
503
+ } catch (error) {
504
+ fail(response, 502, 'translate-start-failed', String(error && error.message ? error.message : error))
505
+ }
506
+ return
507
+ }
508
+
509
+ if (path === `${PREFIX}/translate-status`) {
510
+ try {
511
+ const jobId = url.searchParams.get('job') ?? ''
512
+ if (!/^tr-[a-z0-9]+$/.test(jobId)) {
513
+ fail(response, 400, 'bad-job', '任务编号不合法')
514
+ return
515
+ }
516
+ const raw = await readFile(join(config.dataDir, 'translate-jobs', `${jobId}.json`), 'utf8')
517
+ const state = JSON.parse(raw)
518
+ sendJson(response, 200, { ...state, ok: true })
519
+ } catch (error) {
520
+ fail(response, 404, 'job-missing', String(error && error.message ? error.message : error))
521
+ }
522
+ return
523
+ }
524
+
525
+ if (path === `${PREFIX}/translate-cancel`) {
526
+ if (request.method !== 'POST') {
527
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
528
+ return
529
+ }
530
+ try {
531
+ const body = await readJson(request)
532
+ const jobId = typeof body.job === 'string' ? body.job : ''
533
+ if (!/^tr-[a-z0-9]+$/.test(jobId)) {
534
+ fail(response, 400, 'bad-job', '任务编号不合法')
535
+ return
536
+ }
537
+ await mkdir(join(config.dataDir, 'translate-jobs'), { recursive: true })
538
+ await writeFile(join(config.dataDir, 'translate-jobs', `${jobId}.cancel`), '1', 'utf8')
539
+ sendJson(response, 200, { ok: true })
540
+ } catch (error) {
541
+ fail(response, 500, 'cancel-failed', String(error && error.message ? error.message : error))
542
+ }
543
+ return
544
+ }
545
+
546
+ if (path === `${PREFIX}/annotations`) {
547
+ try {
548
+ const library = await activeLibrary()
549
+ if (request.method === 'POST') {
550
+ const body = await readJson(request)
551
+ const book = pathSegment(body.book)
552
+ const code = pathSegment(String(body.code ?? '').toLowerCase())
553
+ const page = Number.parseInt(String(body.page ?? ''), 10)
554
+ if (book === '' || code === '' || !Number.isFinite(page) || page < 1) {
555
+ fail(response, 400, 'bad-annotations-request', '书、章或页码不合法')
556
+ return
557
+ }
558
+ const result = await writeAnnotations(library.libraryDir, book, code, page, body)
559
+ sendJson(response, 200, { ok: true, updatedAt: result.updatedAt })
560
+ return
561
+ }
562
+ const book = pathSegment(url.searchParams.get('book'))
563
+ const code = pathSegment((url.searchParams.get('code') ?? '').toLowerCase())
564
+ if (book === '' || code === '') {
565
+ fail(response, 400, 'bad-annotations-request', '书或章不合法')
566
+ return
567
+ }
568
+ sendJson(response, 200, { ok: true, ...(await readAnnotations(library.libraryDir, book, code)) })
569
+ } catch (error) {
570
+ fail(response, 500, 'annotations-failed', String(error && error.message ? error.message : error))
571
+ }
572
+ return
573
+ }
574
+
575
+ if (path === `${PREFIX}/annotations-bulk`) {
576
+ if (request.method !== 'POST') {
577
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
578
+ return
579
+ }
580
+ try {
581
+ const body = await readJson(request)
582
+ const book = pathSegment(body.book)
583
+ const code = pathSegment(String(body.code ?? '').toLowerCase())
584
+ if (book === '' || code === '') {
585
+ fail(response, 400, 'bad-annotations-request', '书或章不合法')
586
+ return
587
+ }
588
+ const library = await activeLibrary()
589
+ const result = await seedAnnotations(library.libraryDir, book, code, body.pages)
590
+ sendJson(response, 200, { ok: true, added: result.added })
591
+ } catch (error) {
592
+ fail(response, 500, 'annotations-bulk-failed', String(error && error.message ? error.message : error))
593
+ }
594
+ return
595
+ }
596
+
597
+ if (path === `${PREFIX}/import-annots`) { if (request.method !== 'POST') {
598
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
599
+ return
600
+ }
601
+ try {
602
+ const body = await readJson(request)
603
+ const library = await activeLibrary()
604
+ const file = join(library.artifactDir, body.book, body.code, `${body.code}_export.annots.json`)
605
+ let spec = null
606
+ try {
607
+ spec = JSON.parse(await readFile(file, 'utf8'))
608
+ } catch {
609
+ fail(response, 404, 'no-sidecar', '没有找到标注 sidecar,请先「导出整章」')
610
+ return
611
+ }
612
+ const pages = spec !== null && Array.isArray(spec.pages) ? spec.pages : []
613
+ sendJson(response, 200, { ok: true, pages })
614
+ } catch (error) {
615
+ fail(response, 500, 'import-annots-failed', String(error && error.message ? error.message : error))
616
+ }
617
+ return
618
+ }
619
+
620
+ if (path === `${PREFIX}/export-chapter`) {
621
+ if (request.method !== 'POST') {
622
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
623
+ return
624
+ }
625
+ try {
626
+ const body = await readJson(request, 8 * 1024 * 1024)
627
+ const library = await activeLibrary()
628
+ const source = await chapterPdf(library, body.book, body.code)
629
+ if (source === null) {
630
+ fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
631
+ return
632
+ }
633
+ const pages = Array.isArray(body.pages) ? body.pages : []
634
+ const jobDir = join(config.dataDir, 'export-jobs')
635
+ await mkdir(jobDir, { recursive: true })
636
+ const jobId = `ex-${Date.now().toString(36)}`
637
+ const progressPath = join(jobDir, `${jobId}.progress.json`)
638
+ const specPath = join(jobDir, `${jobId}.spec.json`)
639
+ await writeFile(specPath, JSON.stringify({ pages }), 'utf8')
640
+ const overlayPath = join(dirname(source), `${basename(source, '.pdf')}_overlay.pdf`)
641
+ const outDir = join(library.artifactDir, body.book, body.code)
642
+ await mkdir(outDir, { recursive: true })
643
+ const outName = `${body.code}_export.pdf`
644
+ const jsonName = `${body.code}_export.annots.json`
645
+ await writeFile(join(outDir, jsonName),
646
+ JSON.stringify({ version: 1, book: body.book, code: body.code, pages }, null, 2), 'utf8')
647
+ const outPath = join(outDir, outName)
648
+ // Compose in the background and let the client poll the progress file;
649
+ // a long chapter must not hang one HTTP request.
650
+ void runTool(join(config.toolsDir, 'export_chapter.py'),
651
+ [source, overlayPath, specPath, outPath, progressPath])
652
+ .then(() => {})
653
+ .catch(() => writeFile(`${progressPath}.error`, '1', 'utf8').catch(() => {}))
654
+ sendJson(response, 200, { ok: true, jobId, pdf: outName, json: jsonName, pages: pages.length })
655
+ } catch (error) {
656
+ fail(response, 500, 'export-failed', String(error && error.message ? error.message : error))
657
+ }
658
+ return
659
+ }
660
+
661
+ if (path === `${PREFIX}/export-status`) {
662
+ try {
663
+ const jobId = url.searchParams.get('job') ?? ''
664
+ if (!/^ex-[a-z0-9]+$/.test(jobId)) {
665
+ fail(response, 400, 'bad-job', '任务编号不合法')
666
+ return
667
+ }
668
+ const progressPath = join(config.dataDir, 'export-jobs', `${jobId}.progress.json`)
669
+ let state = { status: 'running', done: 0, total: 0 }
670
+ try {
671
+ state = JSON.parse(await readFile(progressPath, 'utf8'))
672
+ } catch {
673
+ state = { status: 'running', done: 0, total: 0 }
674
+ }
675
+ if (existsSync(`${progressPath}.error`)) state = { status: 'error', error: '导出失败' }
676
+ sendJson(response, 200, { ...state, ok: true })
677
+ } catch (error) {
678
+ fail(response, 404, 'status-missing', String(error && error.message ? error.message : error))
679
+ }
680
+ return
681
+ }
682
+
683
+ if (path === `${PREFIX}/export-cancel`) {
684
+ if (request.method !== 'POST') {
685
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
686
+ return
687
+ }
688
+ try {
689
+ const body = await readJson(request)
690
+ const jobId = typeof body.job === 'string' ? body.job : ''
691
+ if (!/^ex-[a-z0-9]+$/.test(jobId)) {
692
+ fail(response, 400, 'bad-job', '任务编号不合法')
693
+ return
694
+ }
695
+ await mkdir(join(config.dataDir, 'export-jobs'), { recursive: true })
696
+ await writeFile(join(config.dataDir, 'export-jobs', `${jobId}.progress.json.cancel`), '1', 'utf8')
697
+ sendJson(response, 200, { ok: true })
698
+ } catch (error) {
699
+ fail(response, 500, 'cancel-failed', String(error && error.message ? error.message : error))
700
+ }
701
+ return
702
+ }
703
+
704
+ if (path === `${PREFIX}/export-page`) {
705
+ if (request.method !== 'POST') {
706
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
707
+ return
708
+ }
709
+ try {
710
+ const body = await readJson(request, 8 * 1024 * 1024)
711
+ const library = await activeLibrary()
712
+ const source = await chapterPdf(library, body.book, body.code)
713
+ if (source === null) {
714
+ fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
715
+ return
716
+ }
717
+ const page = Math.max(1, Math.round(Number(body.page) || 1))
718
+ const masks = Array.isArray(body.masks) ? body.masks : []
719
+ const annots = Array.isArray(body.annots) ? body.annots : []
720
+ const tmpDir = join(config.dataDir, 'tmp')
721
+ await mkdir(tmpDir, { recursive: true })
722
+ const stamp = Date.now().toString(36)
723
+ const masksPath = join(tmpDir, `export-${stamp}-masks.json`)
724
+ const annotsPath = join(tmpDir, `export-${stamp}-annots.json`)
725
+ await writeFile(masksPath, JSON.stringify(masks), 'utf8')
726
+ await writeFile(annotsPath, JSON.stringify(annots), 'utf8')
727
+ const overlayPath = join(dirname(source), `${basename(source, '.pdf')}_overlay.pdf`)
728
+ const outDir = join(library.artifactDir, body.book, body.code)
729
+ await mkdir(outDir, { recursive: true })
730
+ const outName = `${body.code}_p${String(page).padStart(3, '0')}_export.pdf`
731
+ const outPath = join(outDir, outName)
732
+ try {
733
+ await runTool(join(config.toolsDir, 'export_page.py'), [
734
+ source, overlayPath, String(page), masksPath, annotsPath, outPath,
735
+ ])
736
+ } finally {
737
+ await unlink(masksPath).catch(() => {})
738
+ await unlink(annotsPath).catch(() => {})
739
+ }
740
+ sendJson(response, 200, { ok: true, pdf: outName, page })
741
+ } catch (error) {
742
+ fail(response, 500, 'export-failed', String(error && error.message ? error.message : error))
743
+ }
744
+ return
745
+ }
746
+
747
+ if (path === `${PREFIX}/rebuild-overlay`) {
748
+ if (request.method !== 'POST') {
749
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
750
+ return
751
+ }
752
+ try {
753
+ const body = await readJson(request)
754
+ const library = await activeLibrary()
755
+ const source = await chapterPdf(library, body.book, body.code)
756
+ if (source === null) {
757
+ fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
758
+ return
759
+ }
760
+ const cacheDir = join(config.dataDir, 'translation', body.book, body.code)
761
+ const outPath = join(dirname(source), `${basename(source, '.pdf')}_overlay.pdf`)
762
+ await runTool(join(config.toolsDir, 'rebuild_overlay.py'), [source, cacheDir, outPath, config.toolsDir])
763
+ sendJson(response, 200, { ok: true, pdf: basename(outPath) })
764
+ } catch (error) {
765
+ fail(response, 500, 'rebuild-overlay-failed', String(error && error.message ? error.message : error))
766
+ }
767
+ return
768
+ }
769
+
770
+ if (path === `${PREFIX}/realign-overlay`) {
771
+ if (request.method !== 'POST') {
772
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
773
+ return
774
+ }
775
+ try {
776
+ const body = await readJson(request)
777
+ const library = await activeLibrary()
778
+ const source = await chapterPdf(library, body.book, body.code)
779
+ if (source === null) {
780
+ fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
781
+ return
782
+ }
783
+ const cacheDir = join(config.dataDir, 'translation', body.book, body.code)
784
+ let pages = []
785
+ try {
786
+ pages = (await readdir(cacheDir)).filter(name => /^page-\d+\.md$/.test(name))
787
+ } catch {
788
+ pages = []
789
+ }
790
+ if (pages.length === 0) {
791
+ fail(response, 404, 'no-cache', '还没有可复用的逐页译文,请先翻译这一章')
792
+ return
793
+ }
794
+ const outPath = join(dirname(source), `${basename(source, '.pdf')}_overlay.pdf`)
795
+ // This is an approximation built from cached text, so the overlay it
796
+ // replaces stays next to it as `.bak` instead of just vanishing.
797
+ await copyFile(outPath, `${outPath}.bak`).catch(() => {})
798
+ await runTool(join(config.toolsDir, 'realign_overlay.py'), [source, cacheDir, outPath, config.toolsDir])
799
+ sendJson(response, 200, { ok: true, pdf: basename(outPath) })
800
+ } catch (error) {
801
+ fail(response, 500, 'realign-overlay-failed', String(error && error.message ? error.message : error))
802
+ }
803
+ return
804
+ }
805
+
806
+ if (path === `${PREFIX}/rebuild-translated`) {
807
+ if (request.method !== 'POST') {
808
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
809
+ return
810
+ }
811
+ try {
812
+ const body = await readJson(request)
813
+ const library = await activeLibrary()
814
+ const source = await chapterPdf(library, body.book, body.code)
815
+ if (source === null) {
816
+ fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
817
+ return
818
+ }
819
+ const cacheDir = join(config.dataDir, 'translation', body.book, body.code)
820
+ let pages = []
821
+ try {
822
+ pages = (await readdir(cacheDir)).filter(name => /^page-\d+\.md$/.test(name)).sort()
823
+ } catch {
824
+ pages = []
825
+ }
826
+ if (pages.length === 0) {
827
+ fail(response, 404, 'no-cache', '还没有可复用的逐页译文,请先翻译这一章')
828
+ return
829
+ }
830
+ const outPath = join(dirname(source), `${basename(source, '.pdf')}_translated.pdf`)
831
+ // Re-render only when the renderer changed: the marker keeps re-opening
832
+ // bilingual mode from spending seconds in XeLaTeX every time.
833
+ const marker = join(cacheDir, '.render-version')
834
+ let rendered = ''
835
+ try {
836
+ rendered = (await readFile(marker, 'utf8')).trim()
837
+ } catch {
838
+ rendered = ''
839
+ }
840
+ if (rendered === PLUGIN_VERSION) {
841
+ sendJson(response, 200, { ok: true, skipped: true, pdf: basename(outPath) })
842
+ return
843
+ }
844
+ const chunks = []
845
+ for (const name of pages) chunks.push(await readFile(join(cacheDir, name), 'utf8'))
846
+ // Render on the source's own paper size: bilingual columns then look
847
+ // like one book instead of "chapter page next to an A4 sheet".
848
+ let paper = ''
849
+ try {
850
+ const sizes = JSON.parse(await toolOutput(join(config.toolsDir, 'pdf_pagesizes.py'), [source]))
851
+ const size = Array.isArray(sizes) ? sizes[0] : null
852
+ if (Array.isArray(size) && size.length === 2) paper = `${size[0] / 72},${size[1] / 72}`
853
+ } catch {
854
+ paper = ''
855
+ }
856
+ const draft = join(cacheDir, `.render-${PLUGIN_VERSION}.md`)
857
+ await writeFile(draft, chunks.join('\n\n\\newpage\n\n'), 'utf8')
858
+ try {
859
+ await renderMarkdown(
860
+ options.md2texScript,
861
+ draft,
862
+ outPath,
863
+ {
864
+ // No generated heading: the pages carry the book's own one.
865
+ MATH_DESK_NO_TITLE: '1',
866
+ ...(paper === '' ? {} : { MATH_DESK_PAPER: paper }),
867
+ }
868
+ )
869
+ } finally {
870
+ await unlink(draft).catch(() => {})
871
+ }
872
+ await writeFile(marker, PLUGIN_VERSION, 'utf8').catch(() => {})
873
+ sendJson(response, 200, { ok: true, pdf: basename(outPath) })
874
+ } catch (error) {
875
+ fail(response, 500, 'rebuild-translated-failed', String(error && error.message ? error.message : error))
876
+ }
877
+ return
878
+ }
879
+
880
+ if (path === `${PREFIX}/translate-page`) {
881
+ if (request.method !== 'POST') {
882
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
883
+ return
884
+ }
885
+ try {
886
+ const body = await readJson(request, 16 * 1024 * 1024)
887
+ const image = typeof body.image === 'string' ? body.image : ''
888
+ if (!image.startsWith('data:image/')) {
889
+ fail(response, 400, 'bad-image', '缺少页面图片')
890
+ return
891
+ }
892
+ if (image.length > 24 * 1024 * 1024) {
893
+ fail(response, 413, 'image-too-large', '页面图片过大,请降低渲染倍率')
894
+ return
895
+ }
896
+ const target = body.target === 'zh' ? 'zh' : 'en'
897
+ const library = await activeLibrary()
898
+ const source = await chapterPdf(library, body.book, body.code)
899
+ if (source === null) {
900
+ fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
901
+ return
902
+ }
903
+ const dir = dirname(source)
904
+ const name = basename(source)
905
+ const markdown = await translatePage({ apiKey: await deepseekKey(), image, target })
906
+ if (body.mdOnly === true) {
907
+ sendJson(response, 200, { ok: true, md: markdown })
908
+ return
909
+ }
910
+ const mdPath = join(dir, `.translate-${Date.now()}.md`)
911
+ await writeFile(mdPath, markdown, 'utf8')
912
+ const out = join(dir, `${name.slice(0, name.length - 4)}_translated.pdf`)
913
+ try {
914
+ // The translated page keeps the book's own chapter heading; a
915
+ // generated one would print the temp file name above it.
916
+ await renderMarkdown(options.md2texScript, mdPath, out, { MATH_DESK_NO_TITLE: '1' })
917
+ } finally {
918
+ await unlink(mdPath).catch(() => {})
919
+ }
920
+ sendJson(response, 200, { ok: true, pdf: basename(out) })
921
+ } catch (error) {
922
+ fail(response, 502, 'translate-failed', String(error && error.message ? error.message : error))
923
+ }
924
+ return
925
+ }
926
+
927
+ if (path === `${PREFIX}/translate-render`) {
928
+ if (request.method !== 'POST') {
929
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
930
+ return
931
+ }
932
+ try {
933
+ const body = await readJson(request, 32 * 1024 * 1024)
934
+ const markdown = typeof body.md === 'string' ? body.md : ''
935
+ if (markdown.trim() === '') {
936
+ fail(response, 400, 'bad-markdown', '译文内容为空')
937
+ return
938
+ }
939
+ const library = await activeLibrary()
940
+ const source = await chapterPdf(library, body.book, body.code)
941
+ if (source === null) {
942
+ fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
943
+ return
944
+ }
945
+ const dir = dirname(source)
946
+ const name = basename(source)
947
+ const mdPath = join(dir, `.translate-${Date.now()}.md`)
948
+ await writeFile(mdPath, markdown, 'utf8')
949
+ const out = join(dir, `${name.slice(0, name.length - 4)}_translated.pdf`)
950
+ try {
951
+ await renderMarkdown(options.md2texScript, mdPath, out, { MATH_DESK_NO_TITLE: '1' })
952
+ } finally {
953
+ await unlink(mdPath).catch(() => {})
954
+ }
955
+ sendJson(response, 200, { ok: true, pdf: basename(out) })
956
+ } catch (error) {
957
+ fail(response, 502, 'translate-render-failed', String(error && error.message ? error.message : error))
958
+ }
959
+ return
960
+ }
961
+
962
+ if (path === `${PREFIX}/translated-info`) {
963
+ try {
964
+ const book = url.searchParams.get('book') ?? ''
965
+ const name = basename(url.searchParams.get('name') ?? '')
966
+ if (!/\.pdf$/i.test(name)) {
967
+ sendJson(response, 200, { ok: true, exists: false })
968
+ return
969
+ }
970
+ const library = await activeLibrary()
971
+ const source = await chapterPdf(library, book, url.searchParams.get('code') ?? '')
972
+ if (source === null) {
973
+ sendJson(response, 200, { ok: true, exists: false })
974
+ return
975
+ }
976
+ const out = join(dirname(source), `${name.slice(0, name.length - 4)}_translated.pdf`)
977
+ let exists = false
978
+ try {
979
+ await stat(out)
980
+ exists = true
981
+ } catch {
982
+ exists = false
983
+ }
984
+ sendJson(response, 200, { ok: true, exists, pdf: basename(out) })
985
+ } catch (error) {
986
+ fail(response, 500, 'translated-info-failed', String(error && error.message ? error.message : error))
987
+ }
988
+ return
989
+ }
990
+
991
+ if (path === `${PREFIX}/trash-translated`) {
992
+ if (request.method !== 'POST') {
993
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
994
+ return
995
+ }
996
+ try {
997
+ const body = await readJson(request)
998
+ const name = basename(String(body.name ?? ''))
999
+ if (!/\.pdf$/i.test(name)) {
1000
+ fail(response, 400, 'bad-name', '只支持 PDF 章节')
1001
+ return
1002
+ }
1003
+ const library = await activeLibrary()
1004
+ const source = await chapterPdf(library, body.book, body.code)
1005
+ if (source === null) {
1006
+ fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
1007
+ return
1008
+ }
1009
+ const out = join(dirname(source), `${name.slice(0, name.length - 4)}_translated.pdf`)
1010
+ try {
1011
+ await stat(out)
1012
+ } catch {
1013
+ fail(response, 404, 'missing-file', '译文文件不存在')
1014
+ return
1015
+ }
1016
+ const trashDir = join(library.libraryDir, '回收站', '译文')
1017
+ await mkdir(trashDir, { recursive: true })
1018
+ await rename(out, join(trashDir, `${Date.now()}_${basename(out)}`))
1019
+ sendJson(response, 200, { ok: true })
1020
+ } catch (error) {
1021
+ fail(response, 500, 'trash-translated-failed', String(error && error.message ? error.message : error))
1022
+ }
1023
+ return
1024
+ }
1025
+
1026
+ if (path === `${PREFIX}/trash-book`) {
1027
+ if (request.method !== 'POST') {
1028
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1029
+ return
1030
+ }
1031
+ const body = await readJson(request)
1032
+ const book = typeof body.book === 'string' ? body.book : ''
1033
+ if (book === '' || /[\\/:*?"<>|]/.test(book)) {
1034
+ fail(response, 400, 'bad-book', '书名不合法')
1035
+ return
1036
+ }
1037
+ const library = await activeLibrary()
1038
+ const catalog = await loadCatalog(config)
1039
+ const row = catalog.books.find(item => item.id === book)
1040
+ const fragmentRoot = join(library.libraryDir, '分片')
1041
+ let source = ''
1042
+ const candidates = []
1043
+ if (row !== undefined && typeof row.dir === 'string' && row.dir !== '') candidates.push(join(fragmentRoot, row.dir))
1044
+ candidates.push(join(fragmentRoot, book))
1045
+ for (const candidate of candidates) {
1046
+ try {
1047
+ await stat(candidate)
1048
+ source = candidate
1049
+ break
1050
+ } catch {
1051
+ // try the next naming variant
1052
+ }
1053
+ }
1054
+ if (source === '') {
1055
+ // The hidden id may be a book title while the folder carries another
1056
+ // suffix: accept a single unambiguous prefix match.
1057
+ try {
1058
+ const entries = await readdir(fragmentRoot, { withFileTypes: true })
1059
+ const match = entries.find(entry => entry.isDirectory()
1060
+ && (entry.name === book || book.startsWith(entry.name) || entry.name.startsWith(book)))
1061
+ if (match !== undefined) source = join(fragmentRoot, match.name)
1062
+ } catch {
1063
+ // no fragment root at all: fall through to whole-book lookup
1064
+ }
1065
+ }
1066
+ if (source === '') {
1067
+ for (const sub of ['整本', '']) {
1068
+ try {
1069
+ const entries = await readdir(join(library.libraryDir, sub), { withFileTypes: true })
1070
+ const match = entries.find(entry => {
1071
+ if (!entry.isFile() || !/\.pdf$/i.test(entry.name)) return false
1072
+ const stem = entry.name.replace(/\.pdf$/i, '')
1073
+ return stem === book || stem.startsWith(book) || book.startsWith(stem)
1074
+ })
1075
+ if (match !== undefined) source = join(library.libraryDir, sub, match.name)
1076
+ } catch {
1077
+ // that folder does not exist
1078
+ }
1079
+ if (source !== '') break
1080
+ }
1081
+ }
1082
+ if (source === '') {
1083
+ fail(response, 404, 'missing', `找不到这本书的分片目录或整本 PDF(书 id: ${book})`)
1084
+ return
1085
+ }
1086
+ const trash = join(library.libraryDir, '回收站')
1087
+ await mkdir(trash, { recursive: true })
1088
+ const target = join(trash, `${Date.now()}-${book}`)
1089
+ await rename(source, target)
1090
+ sendJson(response, 200, { ok: true, path: target })
1091
+ return
1092
+ }
1093
+
1094
+ if (path === `${PREFIX}/trash-artifact`) {
1095
+ if (request.method !== 'POST') {
1096
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1097
+ return
1098
+ }
1099
+ const body = await readJson(request)
1100
+ const name = basename(String(body.name ?? ''))
1101
+ if (name === '') {
1102
+ fail(response, 400, 'bad-name', '文件名不能为空')
1103
+ return
1104
+ }
1105
+ const library = await activeLibrary()
1106
+ const source = join(library.libraryDir, '产物', body.book, body.code, name)
1107
+ try {
1108
+ await stat(source)
1109
+ } catch {
1110
+ fail(response, 404, 'missing', '文件不存在(可能已被删除)')
1111
+ return
1112
+ }
1113
+ const trash = join(library.libraryDir, '回收站')
1114
+ await mkdir(trash, { recursive: true })
1115
+ const target = join(trash, `${Date.now()}-${name}`)
1116
+ await rename(source, target)
1117
+ sendJson(response, 200, { ok: true, path: target })
1118
+ return
1119
+ }
1120
+
1121
+ if (path === `${PREFIX}/import`) {
1122
+ if (request.method !== 'POST') {
1123
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1124
+ return
1125
+ }
1126
+ const wanted = basename(url.searchParams.get('name') ?? '').replace(/[\\/:*?"<>|]/g, '_').slice(0, 160)
1127
+ if (wanted === '' || !/\.(md|markdown|txt|pdf)$/i.test(wanted)) {
1128
+ fail(response, 400, 'bad-name', '只接受 md / markdown / txt / pdf 文件')
1129
+ return
1130
+ }
1131
+ const library = await activeLibrary()
1132
+ const dir = join(library.libraryDir, '整本')
1133
+ await mkdir(dir, { recursive: true })
1134
+ const chunks = []
1135
+ let total = 0
1136
+ for await (const chunk of request) {
1137
+ total += chunk.length
1138
+ if (total > 64 * 1024 * 1024) {
1139
+ fail(response, 413, 'too-large', '单个文件不能超过 64 MB')
1140
+ return
1141
+ }
1142
+ chunks.push(chunk)
1143
+ }
1144
+ const extension = extname(wanted).toLowerCase()
1145
+ const stem = wanted.slice(0, wanted.length - extension.length)
1146
+ const unique = async () => {
1147
+ let target = join(dir, `${stem}.pdf`)
1148
+ for (let n = 2; n < 1000; n += 1) {
1149
+ try {
1150
+ await stat(target)
1151
+ } catch {
1152
+ return target
1153
+ }
1154
+ target = join(dir, `${stem}-${n}.pdf`)
1155
+ }
1156
+ return target
1157
+ }
1158
+ if (extension === '.pdf') {
1159
+ const target = await unique()
1160
+ await writeFile(target, Buffer.concat(chunks))
1161
+ sendJson(response, 200, { ok: true, path: target, pdf: target, bytes: total })
1162
+ return
1163
+ }
1164
+ if (options.md2texScript === undefined) {
1165
+ fail(response, 503, 'render-unavailable', '导入 md 需要 Python 与 TeX Live(xelatex)')
1166
+ return
1167
+ }
1168
+ const temporary = join(config.dataDir, 'tmp', `${Date.now()}-${wanted}`)
1169
+ await mkdir(join(config.dataDir, 'tmp'), { recursive: true })
1170
+ await writeFile(temporary, Buffer.concat(chunks))
1171
+ const target = await unique()
1172
+ try {
1173
+ await renderMarkdown(options.md2texScript, temporary, target)
1174
+ } catch (error) {
1175
+ fail(response, 503, 'render-failed', `渲染失败:${String(error && error.message ? error.message : error).slice(-400)}`)
1176
+ return
1177
+ }
1178
+ sendJson(response, 200, { ok: true, path: target, pdf: target, bytes: total })
1179
+ return
1180
+ }
1181
+
1182
+ if (path === `${PREFIX}/samples`) {
1183
+ if (request.method !== 'GET') {
1184
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
1185
+ return
1186
+ }
1187
+ const manifest = await readSampleManifest()
1188
+ if (manifest === null) {
1189
+ fail(response, 404, 'no-samples', '插件没有附带示例书')
1190
+ return
1191
+ }
1192
+ sendJson(response, 200, { ok: true, ...manifest })
1193
+ return
1194
+ }
1195
+
1196
+ if (path === `${PREFIX}/samples/install`) {
1197
+ if (request.method !== 'POST') {
1198
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1199
+ return
1200
+ }
1201
+ const manifest = await readSampleManifest()
1202
+ if (manifest === null || manifest.book === undefined) {
1203
+ fail(response, 404, 'no-samples', '插件没有附带示例书')
1204
+ return
1205
+ }
1206
+ const bookId = String(manifest.book.id ?? '')
1207
+ if (!/^[^\\/:*?"<>|]{1,120}$/.test(bookId)) {
1208
+ fail(response, 400, 'bad-sample', '示例书的书 id 不合法')
1209
+ return
1210
+ }
1211
+ const library = await activeLibrary()
1212
+ const source = join(config.samplesDir, '分片', bookId)
1213
+ const target = join(library.fragmentDir, bookId)
1214
+ await mkdir(target, { recursive: true })
1215
+ let copied = 0
1216
+ let skipped = 0
1217
+ const names = Array.isArray(manifest.files) ? manifest.files : []
1218
+ for (const entry of names) {
1219
+ const name = typeof entry === 'string' ? entry : String(entry?.name ?? '')
1220
+ if (!/^[^\\/:*?"<>|]{1,200}\.pdf$/i.test(name)) continue
1221
+ // Always refresh: the bundled sample is ours, and an older copy in the
1222
+ // library (e.g. the pre-embedded-font render) must be replaced.
1223
+ try {
1224
+ await copyFile(join(source, name), join(target, name))
1225
+ copied += 1
1226
+ } catch {
1227
+ skipped += 1
1228
+ }
1229
+ }
1230
+ sendJson(response, 200, { ok: true, book: bookId, dir: target, copied, skipped })
1231
+ return
1232
+ }
1233
+
1234
+ if (path === `${PREFIX}/shelves`) {
1235
+ if (request.method !== 'POST') {
1236
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1237
+ return
1238
+ }
1239
+ if (options.shelves === undefined) {
1240
+ fail(response, 503, 'unavailable', '书架分组存储不可用')
1241
+ return
1242
+ }
1243
+ const body = await mutationBody(request, response)
1244
+ if (body === undefined) return
1245
+ const library = await activeLibrary()
1246
+ try {
1247
+ const saved = await options.shelves.put(library.id, body)
1248
+ sendJson(response, 200, { ok: true, ...saved })
1249
+ } catch (error) {
1250
+ fail(response, 400, 'invalid-shelves', String(error && error.message ? error.message : error))
1251
+ }
1252
+ return
1253
+ }
1254
+
1255
+ if (path === `${PREFIX}/libraries`) {
1256
+ if (request.method !== 'GET') {
1257
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
1258
+ return
1259
+ }
1260
+ if (libraries === undefined) {
1261
+ fail(response, 503, 'unavailable', '书库存储不可用')
1262
+ return
1263
+ }
1264
+ sendJson(response, 200, { ok: true, ...(await libraries.list()) })
1265
+ return
1266
+ }
1267
+
1268
+ if (path === `${PREFIX}/libraries/add`) {
1269
+ if (request.method !== 'POST') {
1270
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1271
+ return
1272
+ }
1273
+ if (libraries === undefined) {
1274
+ fail(response, 503, 'unavailable', '书库存储不可用')
1275
+ return
1276
+ }
1277
+ const body = await mutationBody(request, response)
1278
+ if (body === undefined) return
1279
+ const record = body !== null && typeof body === 'object' ? body : {}
1280
+ try {
1281
+ const library = await libraries.add({
1282
+ libraryDir: typeof record.libraryDir === 'string' ? record.libraryDir : '',
1283
+ name: typeof record.name === 'string' ? record.name : '',
1284
+ })
1285
+ cachedLibraryId = ''
1286
+ sendJson(response, 200, { ok: true, library, ...(await libraries.list()) })
1287
+ } catch (error) {
1288
+ fail(response, 400, 'invalid-library', String(error && error.message ? error.message : error))
1289
+ }
1290
+ return
1291
+ }
1292
+
1293
+ if (path === `${PREFIX}/libraries/active`) {
1294
+ if (request.method !== 'POST') {
1295
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1296
+ return
1297
+ }
1298
+ if (libraries === undefined) {
1299
+ fail(response, 503, 'unavailable', '书库存储不可用')
1300
+ return
1301
+ }
1302
+ const body = await mutationBody(request, response)
1303
+ if (body === undefined) return
1304
+ const record = body !== null && typeof body === 'object' ? body : {}
1305
+ const changed = typeof record.id === 'string' && await libraries.setActive(record.id)
1306
+ if (!changed) {
1307
+ fail(response, 404, 'unknown-library', '没有这个书库')
1308
+ return
1309
+ }
1310
+ cachedLibraryId = ''
1311
+ sendJson(response, 200, { ok: true, ...(await libraries.list()) })
1312
+ return
1313
+ }
1314
+
1315
+ if (path === `${PREFIX}/libraries/remove`) {
1316
+ if (request.method !== 'POST') {
1317
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1318
+ return
1319
+ }
1320
+ if (libraries === undefined) {
1321
+ fail(response, 503, 'unavailable', '书库存储不可用')
1322
+ return
1323
+ }
1324
+ const body = await mutationBody(request, response)
1325
+ if (body === undefined) return
1326
+ const record = body !== null && typeof body === 'object' ? body : {}
1327
+ if (typeof record.id === 'string') await libraries.remove(record.id)
1328
+ cachedLibraryId = ''
1329
+ sendJson(response, 200, { ok: true, ...(await libraries.list()) })
1330
+ return
1331
+ }
1332
+
1333
+ if (path === `${PREFIX}/toolkit/install`) {
1334
+ if (request.method !== 'POST') {
1335
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1336
+ return
1337
+ }
1338
+ if (typeof options.installToolkit !== 'function') {
1339
+ fail(response, 503, 'unavailable', '工具包不可用')
1340
+ return
1341
+ }
1342
+ const library = await activeLibrary()
1343
+ try {
1344
+ const result = await options.installToolkit(library.libraryDir)
1345
+ sendJson(response, 200, { ok: true, ...result })
1346
+ } catch (error) {
1347
+ fail(response, 500, 'toolkit-failed', String(error && error.message ? error.message : error))
1348
+ }
1349
+ return
1350
+ }
1351
+
1352
+ if (path === `${PREFIX}/artifact-counts`) {
1353
+ if (request.method !== 'GET') {
1354
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
1355
+ return
1356
+ }
1357
+ const bookId = url.searchParams.get('book') ?? ''
1358
+ const current = await catalog()
1359
+ const book = Array.isArray(current.books) ? current.books.find(item => item.id === bookId) : undefined
1360
+ if (book === undefined) {
1361
+ fail(response, 404, 'unknown-book', `书库里没有 ${bookId}`)
1362
+ return
1363
+ }
1364
+ sendJson(response, 200, {
1365
+ ok: true,
1366
+ book: { id: book.id, title: book.title },
1367
+ counts: await countArtifacts(await activeLibrary(), book),
1368
+ })
1369
+ return
1370
+ }
1371
+
1372
+ if (path === `${PREFIX}/artifacts`) {
1373
+ if (request.method !== 'GET') {
1374
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
1375
+ return
1376
+ }
1377
+ const match = await chapterFromQuery(url)
1378
+ if (!match.ok) {
1379
+ fail(response, match.status, match.code, match.message)
1380
+ return
1381
+ }
1382
+ const listing = await listArtifacts(await activeLibrary(), match.book, match.chapter)
1383
+ sendJson(response, 200, {
1384
+ ok: true,
1385
+ book: { id: match.book.id, title: match.book.title },
1386
+ chapter: { code: match.chapter.code, title: match.chapter.title },
1387
+ dir: listing.dir,
1388
+ missing: listing.missing,
1389
+ truncated: listing.truncated,
1390
+ artifacts: listing.artifacts,
1391
+ })
1392
+ return
1393
+ }
1394
+
1395
+ if (path === `${PREFIX}/artifact`) {
1396
+ if (request.method !== 'GET') {
1397
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
1398
+ return
1399
+ }
1400
+ const match = await chapterFromQuery(url)
1401
+ if (!match.ok) {
1402
+ fail(response, match.status, match.code, match.message)
1403
+ return
1404
+ }
1405
+ const name = url.searchParams.get('name') ?? ''
1406
+ const preview = await readArtifact(await activeLibrary(), match.book, match.chapter, name)
1407
+ if (!preview.ok) {
1408
+ const status = preview.reason === 'not-found' ? 404 : preview.reason === 'bad-name' ? 400 : 415
1409
+ const messages = {
1410
+ 'bad-name': '文件名不合法',
1411
+ 'not-found': `这个章里没有 ${name}`,
1412
+ 'not-text': '这种文件不在页内预览里显示(PDF 阅读器还没接入)',
1413
+ binary: '看起来是二进制文件,不在页内预览里显示',
1414
+ directory: '这是一个目录,不是文件',
1415
+ }
1416
+ fail(response, status, preview.reason, messages[preview.reason] ?? '读不了这个文件')
1417
+ return
1418
+ }
1419
+ sendJson(response, 200, { ok: true, ...preview })
1420
+ return
1421
+ }
1422
+
1423
+ if (path === `${PREFIX}/pdf`) {
1424
+ if (request.method !== 'GET') {
1425
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
1426
+ return
1427
+ }
1428
+ const match = await chapterFromQuery(url)
1429
+ if (!match.ok) {
1430
+ fail(response, match.status, match.code, match.message)
1431
+ return
1432
+ }
1433
+ const name = url.searchParams.get('name') ?? ''
1434
+ const source = name === ''
1435
+ ? chapterPdfPath(await activeLibrary(), match.book, match.chapter)
1436
+ : artifactPdfPath(await activeLibrary(), match.book, match.chapter, name)
1437
+ if (!source.ok) {
1438
+ fail(response, 400, source.reason, '这个文件不能作为 PDF 打开')
1439
+ return
1440
+ }
1441
+ const variant = url.searchParams.get('variant') ?? ''
1442
+ if (variant === 'translated' || variant === 'overlay') {
1443
+ const suffix = variant === 'overlay' ? '_overlay' : '_translated'
1444
+ const target = join(dirname(source.path), `${basename(source.path, '.pdf')}${suffix}.pdf`)
1445
+ let bytes = null
1446
+ try {
1447
+ bytes = await readPdf(target)
1448
+ } catch {
1449
+ bytes = null
1450
+ }
1451
+ if (bytes === null || !bytes.ok) {
1452
+ fail(response, 404, 'missing-file', '还没有这一页/章的译文')
1453
+ return
1454
+ }
1455
+ sendBytes(response, 200, bytes.bytes, 'application/pdf')
1456
+ return
1457
+ }
1458
+ const file = await readPdf(source.path)
1459
+ if (!file.ok) {
1460
+ const status = file.reason === 'too-large' ? 413 : 404
1461
+ fail(response, status, file.reason, file.reason === 'too-large' ? '这个 PDF 太大了' : '找不到这个 PDF')
1462
+ return
1463
+ }
1464
+ sendBytes(response, 200, file.bytes, 'application/pdf')
1465
+ return
1466
+ }
1467
+
1468
+ if (path.startsWith(`${PREFIX}/vendor/`)) {
1469
+ if (request.method !== 'GET') {
1470
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
1471
+ return
1472
+ }
1473
+ const name = path.slice(`${PREFIX}/vendor/`.length)
1474
+ const contentType = vendorContentType(name)
1475
+ if (contentType === null) {
1476
+ fail(response, 404, 'not-found', '没有这个阅读器文件')
1477
+ return
1478
+ }
1479
+ try {
1480
+ const body = await readFile(join(config.vendorDir, ...name.split('/')))
1481
+ sendBytes(response, 200, body, contentType)
1482
+ } catch {
1483
+ fail(response, 404, 'missing-vendor', '阅读器文件缺失,请重新安装插件')
1484
+ }
1485
+ return
1486
+ }
1487
+
1488
+ if (path === `${PREFIX}/pdf-ref`) {
1489
+ if (request.method !== 'GET') {
1490
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
1491
+ return
1492
+ }
1493
+ const match = await chapterFromQuery(url)
1494
+ if (!match.ok) {
1495
+ fail(response, match.status, match.code, match.message)
1496
+ return
1497
+ }
1498
+ const name = url.searchParams.get('name') ?? ''
1499
+ const source = name === ''
1500
+ ? chapterPdfPath(await activeLibrary(), match.book, match.chapter)
1501
+ : artifactPdfPath(await activeLibrary(), match.book, match.chapter, name)
1502
+ if (!source.ok) {
1503
+ fail(response, 400, source.reason, '这个文件不能作为 PDF 打开')
1504
+ return
1505
+ }
1506
+ // What the host's right-pane preview needs: a path relative to the
1507
+ // session's workspace, so no absolute library path leaves the Host.
1508
+ const rel = relative((await activeLibrary()).libraryDir, source.path)
1509
+ const inside = rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)
1510
+ sendJson(response, 200, { ok: true, rel: inside ? rel.replace(/\\/g, '/') : '' })
1511
+ return
1512
+ }
1513
+
1514
+ if (path === `${PREFIX}/cover`) {
1515
+ if (request.method !== 'GET') {
1516
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
1517
+ return
1518
+ }
1519
+ const bookId = url.searchParams.get('book') ?? ''
1520
+ const current = await catalog()
1521
+ const book = Array.isArray(current.books) ? current.books.find(item => item.id === bookId) : undefined
1522
+ if (book === undefined) {
1523
+ fail(response, 404, 'unknown-book', `书库里没有 ${bookId}`)
1524
+ return
1525
+ }
1526
+ for (const [extension, contentType] of Object.entries(COVER_TYPES)) {
1527
+ try {
1528
+ const body = await readFile(join((await activeLibrary()).coverDir, `${bookId}.${extension}`))
1529
+ sendBytes(response, 200, body, contentType)
1530
+ return
1531
+ } catch {
1532
+ // Try the next extension; a missing cover is normal.
1533
+ }
1534
+ }
1535
+ fail(response, 404, 'no-cover', '这本书没有自定义封面')
1536
+ return
1537
+ }
1538
+
1539
+ if (path === `${PREFIX}/context`) {
1540
+ if (request.method !== 'GET') {
1541
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
1542
+ return
1543
+ }
1544
+ const sessionId = url.searchParams.get('session') ?? ''
1545
+ if (!/^[\w-]{1,80}$/.test(sessionId)) {
1546
+ fail(response, 400, 'invalid-session', '会话 id 不合法')
1547
+ return
1548
+ }
1549
+ const reading = typeof options.contextPressure === 'function'
1550
+ ? await options.contextPressure(sessionId)
1551
+ : null
1552
+ sendJson(response, 200, {
1553
+ ok: true,
1554
+ sessionId,
1555
+ context: reading === null ? null : {
1556
+ tokens: reading.tokens,
1557
+ window: reading.window,
1558
+ ratio: reading.ratio,
1559
+ source: reading.source,
1560
+ },
1561
+ })
1562
+ return
1563
+ }
1564
+
1565
+ if (path === `${PREFIX}/digest`) {
1566
+ if (request.method !== 'POST') {
1567
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1568
+ return
1569
+ }
1570
+ if (typeof options.digest !== 'function') {
1571
+ fail(response, 503, 'unavailable', '提纲生成不可用(缺少模型服务)')
1572
+ return
1573
+ }
1574
+ const body = await mutationBody(request, response)
1575
+ if (body === undefined) return
1576
+ const record = body !== null && typeof body === 'object' ? body : {}
1577
+ const match = resolveChapter(await catalog(), typeof record.bookId === 'string' ? record.bookId : '', String(record.code ?? '').toLowerCase())
1578
+ if (!match.ok) {
1579
+ fail(response, match.code === 'unknown-chapter' ? 404 : 400, match.code, match.message)
1580
+ return
1581
+ }
1582
+ const ids = Array.isArray(record.sessionIds)
1583
+ ? record.sessionIds.filter(id => typeof id === 'string' && /^[\w-]{1,80}$/.test(id)).slice(0, 50)
1584
+ : []
1585
+ if (ids.length === 0) {
1586
+ fail(response, 400, 'no-sessions', '这一章还没有可总结的会话')
1587
+ return
1588
+ }
1589
+ try {
1590
+ const result = await options.digest({
1591
+ book: match.book,
1592
+ chapter: match.chapter,
1593
+ sessionIds: ids,
1594
+ mode: typeof record.mode === 'string' && /^[\w-]{1,16}$/.test(record.mode) ? record.mode : 'all',
1595
+ })
1596
+ sendJson(response, 200, { ok: true, ...result })
1597
+ } catch (error) {
1598
+ fail(response, 502, 'digest-failed', String(error && error.message ? error.message : error))
1599
+ }
1600
+ return
1601
+ }
1602
+
1603
+ if (path === `${PREFIX}/links`) {
1604
+ if (request.method !== 'POST') {
1605
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1606
+ return
1607
+ }
1608
+ if (links === undefined) {
1609
+ fail(response, 503, 'unavailable', '挂载存储不可用')
1610
+ return
1611
+ }
1612
+ const body = await mutationBody(request, response)
1613
+ if (body === undefined) return
1614
+ const record = body !== null && typeof body === 'object' ? body : {}
1615
+ if (typeof record.sessionId !== 'string' || record.sessionId === '') {
1616
+ fail(response, 400, 'invalid-body', 'sessionId 缺失')
1617
+ return
1618
+ }
1619
+ // Only a chapter the catalog knows can be linked, so a typo cannot
1620
+ // create a placement the page would never render.
1621
+ const match = resolveChapter(await catalog(), typeof record.bookId === 'string' ? record.bookId : '', String(record.code ?? '').toLowerCase())
1622
+ if (!match.ok) {
1623
+ fail(response, match.code === 'unknown-chapter' ? 404 : 400, match.code, match.message)
1624
+ return
1625
+ }
1626
+ try {
1627
+ await links.add(record.sessionId, {
1628
+ bookId: match.book.id,
1629
+ code: match.chapter.code,
1630
+ mode: typeof record.mode === 'string' ? record.mode : 'qa',
1631
+ })
1632
+ } catch (error) {
1633
+ fail(response, 400, 'invalid-body', String(error && error.message ? error.message : error))
1634
+ return
1635
+ }
1636
+ sendJson(response, 200, { ok: true, links: await links.list() })
1637
+ return
1638
+ }
1639
+
1640
+ if (path === `${PREFIX}/links/remove`) {
1641
+ if (request.method !== 'POST') {
1642
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1643
+ return
1644
+ }
1645
+ const body = await mutationBody(request, response)
1646
+ if (body === undefined) return
1647
+ const record = body !== null && typeof body === 'object' ? body : {}
1648
+ if (links !== undefined && typeof record.sessionId === 'string' && record.sessionId !== '') {
1649
+ try {
1650
+ await links.remove(record.sessionId, String(record.bookId ?? ''), String(record.code ?? '').toLowerCase())
1651
+ } catch (error) {
1652
+ fail(response, 400, 'invalid-body', String(error && error.message ? error.message : error))
1653
+ return
1654
+ }
1655
+ }
1656
+ sendJson(response, 200, { ok: true, links: links === undefined ? {} : await links.list() })
1657
+ return
1658
+ }
1659
+
1660
+ if (path === `${PREFIX}/pending`) {
1661
+ if (request.method !== 'POST') {
1662
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1663
+ return
1664
+ }
1665
+ if (pending === undefined) {
1666
+ fail(response, 503, 'unavailable', 'pending 存储不可用')
1667
+ return
1668
+ }
1669
+ const body = await mutationBody(request, response)
1670
+ if (body === undefined) return
1671
+ const record = body !== null && typeof body === 'object' ? body : {}
1672
+ if (typeof record.sessionId !== 'string' || record.sessionId === '') {
1673
+ fail(response, 400, 'invalid-body', 'sessionId 缺失')
1674
+ return
1675
+ }
1676
+ try {
1677
+ await pending.put(record.sessionId, record)
1678
+ } catch (error) {
1679
+ fail(response, 400, 'invalid-body', String(error && error.message ? error.message : error))
1680
+ return
1681
+ }
1682
+ sendJson(response, 200, { ok: true, pending: await pending.list() })
1683
+ return
1684
+ }
1685
+
1686
+ if (path === `${PREFIX}/pending/remove`) {
1687
+ if (request.method !== 'POST') {
1688
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1689
+ return
1690
+ }
1691
+ const body = await mutationBody(request, response)
1692
+ if (body === undefined) return
1693
+ const record = body !== null && typeof body === 'object' ? body : {}
1694
+ if (pending !== undefined && typeof record.sessionId === 'string' && record.sessionId !== '') {
1695
+ await pending.remove(record.sessionId)
1696
+ }
1697
+ sendJson(response, 200, { ok: true, pending: pending === undefined ? {} : await pending.list() })
1698
+ return
1699
+ }
1700
+
1701
+ if (path === `${PREFIX}/purge`) {
1702
+ if (request.method !== 'POST') {
1703
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1704
+ return
1705
+ }
1706
+ if (!isSameOrigin(request)) {
1707
+ fail(response, 403, 'cross-origin', '拒绝跨站写入')
1708
+ return
1709
+ }
1710
+ const result = typeof options.purge === 'function' ? await options.purge() : { purged: 0 }
1711
+ sendJson(response, 200, { ok: true, purged: result.purged })
1712
+ return
1713
+ }
1714
+
1715
+ if (path === `${PREFIX}/state`) {
1716
+ if (request.method !== 'PUT' && request.method !== 'POST') {
1717
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 PUT')
1718
+ return
1719
+ }
1720
+ const body = await mutationBody(request, response)
1721
+ if (body === undefined) return
1722
+ const state = await writeState(config.statePath, body)
1723
+ sendJson(response, 200, { ok: true, state })
1724
+ return
1725
+ }
1726
+
1727
+ fail(response, 404, 'not-found', `没有这个接口:${path}`)
1728
+ } catch (error) {
1729
+ fail(response, 500, 'internal', String(error && error.message ? error.message : error))
1730
+ }
1731
+ }
1732
+ }